@deepagents/experimental 7.0.1 → 7.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/dist/coding-agent-reminders/evaluate.d.ts.map +1 -1
- package/dist/coding-agent-reminders/index.js +2 -2
- package/dist/coding-agent-reminders/index.js.map +2 -2
- package/dist/index.js +230 -172
- package/dist/index.js.map +3 -3
- package/dist/providers/account-tokens.d.ts +47 -0
- package/dist/providers/account-tokens.d.ts.map +1 -0
- package/dist/providers/claude/accounts.d.ts +59 -0
- package/dist/providers/claude/accounts.d.ts.map +1 -0
- package/dist/providers/claude/errors.d.ts +7 -0
- package/dist/providers/claude/errors.d.ts.map +1 -0
- package/dist/providers/claude/index.d.ts +2 -0
- package/dist/providers/claude/index.d.ts.map +1 -1
- package/dist/providers/claude/index.js +550 -43
- package/dist/providers/claude/index.js.map +4 -4
- package/dist/providers/claude/local-credentials.d.ts.map +1 -1
- package/dist/providers/claude/oauth.d.ts +3 -0
- package/dist/providers/claude/oauth.d.ts.map +1 -0
- package/dist/providers/claude/provider.d.ts +4 -0
- package/dist/providers/claude/provider.d.ts.map +1 -0
- package/dist/providers/codex/accounts.d.ts +39 -0
- package/dist/providers/codex/accounts.d.ts.map +1 -0
- package/dist/providers/codex/errors.d.ts +7 -0
- package/dist/providers/codex/errors.d.ts.map +1 -0
- package/dist/providers/codex/index.d.ts +2 -0
- package/dist/providers/codex/index.d.ts.map +1 -1
- package/dist/providers/codex/index.js +482 -159
- package/dist/providers/codex/index.js.map +4 -4
- package/dist/providers/codex/provider.d.ts +3 -0
- package/dist/providers/codex/provider.d.ts.map +1 -0
- package/dist/providers/request-signal.d.ts +2 -0
- package/dist/providers/request-signal.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/collaboration-tools.d.ts +24 -0
- package/dist/zukhruf/collaboration/collaboration-tools.d.ts.map +1 -1
- package/dist/zukhruf/collaboration/interrupt-agent.d.ts +4 -0
- package/dist/zukhruf/collaboration/interrupt-agent.d.ts.map +1 -1
- package/dist/zukhruf/collaboration/list-agents.d.ts +4 -0
- package/dist/zukhruf/collaboration/list-agents.d.ts.map +1 -1
- package/dist/zukhruf/collaboration/message-tools.d.ts +8 -0
- package/dist/zukhruf/collaboration/message-tools.d.ts.map +1 -1
- package/dist/zukhruf/collaboration/spawn-agent.d.ts +4 -0
- package/dist/zukhruf/collaboration/spawn-agent.d.ts.map +1 -1
- package/dist/zukhruf/collaboration/wait-agent.d.ts +4 -0
- package/dist/zukhruf/collaboration/wait-agent.d.ts.map +1 -1
- package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -1
- package/dist/zukhruf/control-plane/agent-history-forker.d.ts.map +1 -1
- package/dist/zukhruf/index.js +228 -170
- package/dist/zukhruf/index.js.map +3 -3
- package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
- package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -1
- package/dist/zukhruf/mailbox/types.d.ts +4 -4
- package/dist/zukhruf/mailbox/types.d.ts.map +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/index.js +17 -2
- package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +2 -2
- package/dist/zukhruf/plugins/conversation-scheduling/tools.d.ts +16 -0
- package/dist/zukhruf/plugins/conversation-scheduling/tools.d.ts.map +1 -1
- package/dist/zukhruf/plugins/http/index.js +16 -17
- package/dist/zukhruf/plugins/http/index.js.map +3 -3
- package/dist/zukhruf/plugins/http/validator.d.ts +14 -44
- package/dist/zukhruf/plugins/http/validator.d.ts.map +1 -1
- package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -1
- package/dist/zukhruf/plugins/schedules/http.js +22 -22
- package/dist/zukhruf/plugins/schedules/http.js.map +3 -3
- package/dist/zukhruf/plugins/schedules/index.d.ts.map +1 -1
- package/dist/zukhruf/plugins/schedules/index.js +172 -51
- package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
- package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts +3 -0
- package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -1
- package/dist/zukhruf/plugins/uploads/http.js +17 -20
- package/dist/zukhruf/plugins/uploads/http.js.map +3 -3
- package/dist/zukhruf/plugins/uploads/index.d.ts.map +1 -1
- package/dist/zukhruf/plugins/uploads/index.js +1 -3
- package/dist/zukhruf/plugins/uploads/index.js.map +2 -2
- package/dist/zukhruf/queue/pg-boss-notifications.d.ts.map +1 -1
- package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/render-turn.d.ts.map +1 -1
- package/dist/zukhruf/runtime/agent-runtime.d.ts +3 -0
- package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -1
- package/dist/zukhruf/runtime/compaction.d.ts +4 -4
- package/dist/zukhruf/runtime/compaction.d.ts.map +1 -1
- package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
- package/dist/zukhruf/runtime/plugin/plugin-bindings.d.ts.map +1 -1
- package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -1
- package/dist/zukhruf/tool.d.ts +1 -1
- package/dist/zukhruf/tool.d.ts.map +1 -1
- package/package.json +14 -13
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Db, JobPollingOptions, PgBoss, Queue } from 'pg-boss';
|
|
2
|
+
import { z } from 'zod';
|
|
2
3
|
export declare const SCHEDULE_CHANGES_CHANNEL = "zukhruf_schedule_changes";
|
|
3
4
|
export type ScheduledTaskStatus = 'active' | 'paused' | 'completed' | 'archived';
|
|
4
5
|
export type ScheduledRunStatus = 'dispatching' | 'running' | 'completed' | 'failed' | 'cancelled';
|
|
@@ -120,6 +121,8 @@ export interface ScheduledTaskTransaction {
|
|
|
120
121
|
}
|
|
121
122
|
export interface ScheduledTasksOptions<ExecutionConfig extends object> {
|
|
122
123
|
boss: PgBoss;
|
|
124
|
+
/** Reads each persisted execution config back from its stored JSON. */
|
|
125
|
+
executionConfigSchema: z.ZodType<ExecutionConfig>;
|
|
123
126
|
queue: string;
|
|
124
127
|
queueOptions?: Omit<Queue, 'name'>;
|
|
125
128
|
reconciliationIntervalMs: number;
|
|
@@ -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;
|
|
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;AAMxB,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,MAAM,GAAG,KAAK,CAAC;AAEpD,6EAA6E;AAC7E,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,SAAkB,IAAI,yBAAyB;IAC/C,QAAQ,CAAC,IAAI,EAAE,uBAAuB,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AAC,CAAC;IA2BpC,MAAM,CACV,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;IA+CpC,MAAM,CACV,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,wBAAwB,CAAC,eAAe,CAAC,GAC/C,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;IAyFpC,MAAM,CACV,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,cAAc,EAAE,MAAM,GACrB,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC;IAmDnC,OAAO,CACX,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC;IAqBpC,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA0CrD,SAAS,CACb,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC;IAiDnC,YAAY,CAChB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC;IAInC,UAAU,CACd,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC;IAInC,IAAI,CACR,OAAO,CAAC,EAAE,iBAAiB,EAC3B,aAAa,CAAC,EAAE,OAAO,GACtB,OAAO,CAAC,eAAe,CAAC;CA4f5B"}
|
|
@@ -48,6 +48,19 @@ async function parse(schema, input) {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
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
|
+
}
|
|
51
64
|
function validate(expectedContentTypeOrSelector, selector) {
|
|
52
65
|
const expectedContentType = typeof expectedContentTypeOrSelector === "string" ? expectedContentTypeOrSelector : void 0;
|
|
53
66
|
const _selector = typeof expectedContentTypeOrSelector === "function" ? expectedContentTypeOrSelector : selector;
|
|
@@ -90,24 +103,10 @@ function validate(expectedContentTypeOrSelector, selector) {
|
|
|
90
103
|
headers: c.req.header()
|
|
91
104
|
};
|
|
92
105
|
const config = _selector(payload);
|
|
93
|
-
const
|
|
94
|
-
Object.entries(config).
|
|
95
|
-
(acc, [key, value]) => {
|
|
96
|
-
acc[key] = value.against;
|
|
97
|
-
return acc;
|
|
98
|
-
},
|
|
99
|
-
{}
|
|
100
|
-
)
|
|
101
|
-
);
|
|
102
|
-
const input = Object.entries(config).reduce(
|
|
103
|
-
(acc, [key, value]) => {
|
|
104
|
-
acc[key] = value.select;
|
|
105
|
-
return acc;
|
|
106
|
-
},
|
|
107
|
-
{}
|
|
106
|
+
const input = Object.fromEntries(
|
|
107
|
+
Object.entries(config).map(([key, { select }]) => [key, select])
|
|
108
108
|
);
|
|
109
|
-
|
|
110
|
-
c.set("input", parsed);
|
|
109
|
+
c.set("input", await parse(inputSchema(config), input));
|
|
111
110
|
await next();
|
|
112
111
|
});
|
|
113
112
|
}
|
|
@@ -209,9 +208,7 @@ var extensionByMediaType = {
|
|
|
209
208
|
"audio/mp4": "m4a",
|
|
210
209
|
"audio/wav": "wav"
|
|
211
210
|
};
|
|
212
|
-
var UPLOAD_MEDIA_TYPES = Object.keys(
|
|
213
|
-
extensionByMediaType
|
|
214
|
-
);
|
|
211
|
+
var UPLOAD_MEDIA_TYPES = Object.keys(extensionByMediaType).filter(isUploadMediaType);
|
|
215
212
|
var mediaTypeByExtension = {
|
|
216
213
|
...Object.fromEntries(
|
|
217
214
|
Object.entries(extensionByMediaType).map(([mediaType, extension]) => [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/zukhruf/plugins/uploads/http.ts", "../../../../src/zukhruf/plugins/http/index.ts", "../../../../src/zukhruf/plugins/http/validator.ts", "../../../../src/zukhruf/plugins/http/parse.ts", "../../../../src/zukhruf/plugins/uploads/index.ts"],
|
|
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, ValidationTargets } 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\ntype ExtractInput<T extends ValidatorConfig> = {\n [K in keyof T]: z.infer<T[K]['against']>;\n};\n\ntype HasUndefined<T> = undefined extends T ? true : false;\n\ntype InferTarget<\n T extends ValidatorConfig,\n S,\n Target extends keyof ValidationTargets,\n> = {\n [K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<\n z.infer<T[K]['against']>\n > extends true\n ? z.infer<T[K]['against']> | undefined\n : z.infer<T[K]['against']> extends ValidationTargets[Target]\n ? z.infer<T[K]['against']>\n : z.infer<T[K]['against']>;\n};\n\ntype InferIn<T extends ValidatorConfig> = (keyof InferTarget<\n T,\n QuerySelect | QueriesSelect,\n 'query'\n> extends never\n ? never\n : { query: InferTarget<T, QuerySelect | QueriesSelect, 'query'> }) &\n (keyof InferTarget<T, BodySelect, 'json'> extends never\n ? never\n : { json: InferTarget<T, BodySelect, 'json'> }) &\n (keyof InferTarget<T, ParamsSelect, 'param'> extends never\n ? never\n : { param: InferTarget<T, ParamsSelect, 'param'> }) &\n (keyof InferTarget<T, HeadersSelect, 'header'> extends never\n ? never\n : { header: InferTarget<T, HeadersSelect, 'header'> }) &\n (keyof InferTarget<T, CookieSelect, 'cookie'> extends never\n ? never\n : { cookie: InferTarget<T, CookieSelect, 'cookie'> });\n\n// Marker classes\nclass BodySelect {\n #private = 0;\n}\nclass QuerySelect {\n #private = 0;\n}\nclass QueriesSelect {\n #private = 0;\n}\nclass ParamsSelect {\n #private = 0;\n}\nclass HeadersSelect {\n #private = 0;\n}\nclass CookieSelect {\n #private = 0;\n}\n\ntype SelectorFn<T> = (payload: {\n body: Record<string, BodySelect>;\n query: Record<string, QuerySelect>;\n queries: Record<string, QueriesSelect>;\n params: Record<string, ParamsSelect>;\n headers: Record<string, HeadersSelect>;\n}) => T;\ntype ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<\n {\n Variables: {\n input: ExtractInput<T>;\n };\n },\n string,\n { in: InferIn<T> }\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 = {\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 as never);\n const schema = z.object(\n Object.entries(config).reduce<Record<string, z.ZodTypeAny>>(\n (acc, [key, value]) => {\n acc[key] = value.against;\n return acc;\n },\n {},\n ),\n );\n\n const input = Object.entries(config).reduce<Record<string, unknown>>(\n (acc, [key, value]) => {\n acc[key] = value.select;\n return acc;\n },\n {},\n );\n\n const parsed = await parse(schema, input);\n c.set('input', parsed as ExtractInput<T>);\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 = Object.keys(\n extensionByMediaType,\n) as readonly UploadMediaType[];\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,aAAaA,yBAAwB;AAC9C,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACJd;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,YAAY;AACnC,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,YAAY,oBAAoB;AACzC,OAAOC,QAAO;AAEd,SAAS,sBAAsB;;;ACb/B,SAAS,SAAS,wBAAwB;AAE1C,SAAS,wBAAwB;AACjC,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACJd,SAAS,qBAAqB;AAC9B,OAAc;AAQd,eAAsB,MACpB,QACA,OACA;AACA,QAAM,SAAS,MAAM,OAAO,eAAe,KAAK;AAChD,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,SAGa,OAAO,MAAM,QAAQ,CAAC,WAAW;AAAA,MAClD,SAAS,MAAM;AAAA,MACf,MAAM,MAAM;AAAA,MACZ,MAAM,MAAM,KAAK,KAAK,GAAG;AAAA,IAC3B,EAAE,EAAE;AAEJ,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,SAAS;AAAA,MACT,OAAO;AAAA,QACL,MAAM;AAAA,QACN,QAAQ;AAAA,QACR;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,OAAO;AAChB;;;
|
|
6
|
-
"names": ["parseContentType", "Hono", "HTTPException", "z", "HTTPException", "z", "HTTPException", "z", "
|
|
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,aAAaA,yBAAwB;AAC9C,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACJd;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,YAAY;AACnC,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,YAAY,oBAAoB;AACzC,OAAOC,QAAO;AAEd,SAAS,sBAAsB;;;ACb/B,SAAS,SAAS,wBAAwB;AAE1C,SAAS,wBAAwB;AACjC,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACJd,SAAS,qBAAqB;AAC9B,OAAc;AAQd,eAAsB,MACpB,QACA,OACA;AACA,QAAM,SAAS,MAAM,OAAO,eAAe,KAAK;AAChD,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,SAGa,OAAO,MAAM,QAAQ,CAAC,WAAW;AAAA,MAClD,SAAS,MAAM;AAAA,MACf,MAAM,MAAM;AAAA,MACZ,MAAM,MAAM,KAAK,KAAK,GAAG;AAAA,IAC3B,EAAE,EAAE;AAEJ,UAAM,IAAI,cAAc,KAAK;AAAA,MAC3B,SAAS;AAAA,MACT,OAAO;AAAA,QACL,MAAM;AAAA,QACN,QAAQ;AAAA,QACR;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACA,SAAO,OAAO;AAChB;;;ADUA,SAAS,YAAuC,QAAW;AACzD,QAAM,QAAQ,OAAO;AAAA,IACnB,OAAO,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,KAAK,OAAO,CAAC;AAAA,EACnE;AACA,mBAAiB,OAAO,MAAM;AAC9B,SA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AAI,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": ["parseContentType", "Hono", "HTTPException", "z", "HTTPException", "z", "HTTPException", "z", "z", "HTTPException", "HTTPException", "z", "z", "z", "sessionIdSchema", "z", "Hono", "HTTPException", "parseContentType"]
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/uploads/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,qBAAqB,EAErB,mBAAmB,EAEpB,MAAM,gCAAgC,CAAC;AAExC,QAAA,MAAM,oBAAoB;;;;;;;;;;;;CAYhB,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG,MAAM,OAAO,oBAAoB,CAAC;AAEhE,eAAO,MAAM,kBAAkB,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/uploads/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,qBAAqB,EAErB,mBAAmB,EAEpB,MAAM,gCAAgC,CAAC;AAExC,QAAA,MAAM,oBAAoB;;;;;;;;;;;;CAYhB,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG,MAAM,OAAO,oBAAoB,CAAC;A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AChB,SAAS,IAAI,eAAe,CAE9B;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,EACtB,SAAS,EACT,SAAS,GACV,EAAE,cAAc,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAWjD"}
|
|
@@ -17,9 +17,7 @@ var extensionByMediaType = {
|
|
|
17
17
|
"audio/mp4": "m4a",
|
|
18
18
|
"audio/wav": "wav"
|
|
19
19
|
};
|
|
20
|
-
var UPLOAD_MEDIA_TYPES = Object.keys(
|
|
21
|
-
extensionByMediaType
|
|
22
|
-
);
|
|
20
|
+
var UPLOAD_MEDIA_TYPES = Object.keys(extensionByMediaType).filter(isUploadMediaType);
|
|
23
21
|
var mediaTypeByExtension = {
|
|
24
22
|
...Object.fromEntries(
|
|
25
23
|
Object.entries(extensionByMediaType).map(([mediaType, extension]) => [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/zukhruf/plugins/uploads/index.ts"],
|
|
4
|
-
"sourcesContent": ["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 = Object.keys(\n extensionByMediaType,\n) as readonly UploadMediaType[];\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,SAAyB,YAAY;AACrC,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,OAAO,OAAO;AAEd,SAAS,gBAAgB;AAUzB,IAAM,uBAAuB;AAAA,EAC3B,aAAa;AAAA,EACb,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,aAAa;AAAA,EACb,aAAa;AACf;AAIO,IAAM,
|
|
4
|
+
"sourcesContent": ["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,SAAyB,YAAY;AACrC,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,OAAO,OAAO;AAEd,SAAS,gBAAgB;AAUzB,IAAM,uBAAuB;AAAA,EAC3B,aAAa;AAAA,EACb,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,aAAa;AAAA,EACb,aAAa;AACf;AAIO,IAAM,qBACX,OAAO,KAAK,oBAAoB,EAAE,OAAO,iBAAiB;AAG5D,IAAM,uBAAkE;AAAA,EACtE,GAAG,OAAO;AAAA,IACR,OAAO,QAAQ,oBAAoB,EAAE,IAAI,CAAC,CAAC,WAAW,SAAS,MAAM;AAAA,MACnE;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EACA,MAAM;AACR;AAGA,IAAM,yBAAyB,IAAI;AAAA,EACjC,qBA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WAAW,OAAO,aAAa,UAAU;AAC/D,UAAM,IAAI;AAAA,MACR,gEAAgE,KAAK,UAAU,SAAS,CAAC;AAAA,IAC3F;AAAA,EACF;AACA,SAAO,OAAO,KAAK,QAAQ,QAAQ,EAAE;AACvC;AAEA,SAAS,WAAW,OAAuB;AACzC,SAAO,IAAI,MAAM,WAAW,KAAK,OAAO,CAAC;AAC3C;AAEA,SAAS,kBAAkB,MAAc,OAAqB;AAC5D,MACE,MAAM,WAAW,KACjB,UAAU,OACV,UAAU,QACV,MAAM,SAAS,GAAG,GAClB;AACA,UAAM,IAAI;AAAA,MACR,YAAY,IAAI,6CAA6C,KAAK;AAAA,IACpE;AAAA,EACF;AACF;AAEA,SAAS,gBAAgB,SAAsC;AAC7D,MAAI,CAAC,SAAS,QAAQ,QAAQ,KAAK,CAAC,MAAM,QAAQ,QAAQ,SAAS,OAAO,GAAG;AAC3E,WAAO,CAAC;AAAA,EACV;AACA,SAAO,QAAQ,SAAS,QAAQ,OAAO,gBAAgB;AACzD;AAEA,SAAS,iBAAiB,OAAyC;AACjE,SACE,SAAS,KAAK,KACd,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,cAAc,YAC3B,OAAO,MAAM,SAAS;AAE1B;AAGA,SAAS,QAAQ,OAAe,MAAuB;AACrD,SAAO,MAAM,UAAU,IAAI,MAAM,QAAQ,KAAK,WAAW,GAAG,KAAK,GAAG;AACtE;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pg-boss-notifications.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/pg-boss-notifications.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"pg-boss-notifications.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/pg-boss-notifications.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAItC,MAAM,MAAM,kBAAkB,CAAC,KAAK,IAClC;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAEvD,gEAAgE;AAChE,wBAAsB,mBAAmB,CAAC,KAAK,EAC7C,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,KAAK,GAAG,SAAS,EAC7C,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,aAAa,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CA6CnD"}
|
|
@@ -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;
|
|
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;AAOD;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,qBAAa,eAAgB,SAAQ,SAAS;;gBAchC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,sBAA2B;IAqC9D,IAAI,KAAK,IAAI,MAAM,CAElB;IAED,IAAI,eAAe,IAAI,MAAM,CAE5B;IAEK,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IA+C3B,IAAI,CAAC,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC;IAczB,eAAe,CAC5B,YAAY,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,GAAG,QAAQ,CAAC,GAC/C,OAAO,CAAC,YAAY,CAAC;IAiBT,cAAc,CAC3B,YAAY,EAAE,IAAI,CAAC,OAAO,EAAE,QAAQ,GAAG,QAAQ,CAAC,GAC/C,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC;IAehB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA4BhD,OAAO,CACX,OAAO,EAAE,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,EAClE,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC;IA0FrB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAkIlD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render-turn.d.ts","sourceRoot":"","sources":["../../src/zukhruf/render-turn.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"render-turn.d.ts","sourceRoot":"","sources":["../../src/zukhruf/render-turn.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,IAAI,CAAC;AA+BzC;;;;;GAKG;AACH,wBAAsB,UAAU,CAC9B,MAAM,EAAE,cAAc,CAAC,cAAc,CAAC,GACrC,OAAO,CAAC,IAAI,CAAC,CAgDf"}
|
|
@@ -46,9 +46,12 @@ export interface AgentPluginBinding {
|
|
|
46
46
|
readonly value: unknown;
|
|
47
47
|
}
|
|
48
48
|
export declare class AgentPluginCapability<Value> {
|
|
49
|
+
#private;
|
|
49
50
|
readonly name: string;
|
|
50
51
|
constructor(name: string);
|
|
51
52
|
bind(value: Value): AgentPluginBinding;
|
|
53
|
+
/** Reads the value of a binding this capability created with `bind`. */
|
|
54
|
+
read(binding: AgentPluginBinding): Value;
|
|
52
55
|
}
|
|
53
56
|
export interface AgentPluginBindings {
|
|
54
57
|
get<Value>(capability: AgentPluginCapability<Value>): Value;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runtime.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/runtime/agent-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAEpC,OAAO,EACL,aAAa,EACb,KAAK,YAAY,EACjB,KAAK,aAAa,EAClB,KAAK,UAAU,EACf,KAAK,YAAY,EAClB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAEpE,OAAO,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAMrE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,KAAK,EACV,cAAc,EACd,uBAAuB,EACvB,mBAAmB,EACpB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,KAAK,oBAAoB,EAE1B,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,SAAS,EAAW,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,KAAK,EAAE,cAAc,EAAE,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