@deepagents/experimental 7.10.0 → 7.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -4
- package/dist/index.js +878 -666
- package/dist/index.js.map +4 -4
- package/dist/zukhruf/collaboration/capability.d.ts +22 -0
- package/dist/zukhruf/collaboration/capability.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/code-mode-tools.d.ts +13 -0
- package/dist/zukhruf/collaboration/code-mode-tools.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/direct-messaging.d.ts +466 -0
- package/dist/zukhruf/collaboration/direct-messaging.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/direct-tools.d.ts +14 -0
- package/dist/zukhruf/collaboration/direct-tools.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/spawn-agent.d.ts +26 -26
- package/dist/zukhruf/collaboration/spawning.d.ts +325 -0
- package/dist/zukhruf/collaboration/spawning.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/supervision.d.ts +478 -0
- package/dist/zukhruf/collaboration/supervision.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/team.d.ts +1549 -0
- package/dist/zukhruf/collaboration/team.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/tool-exposure.d.ts +29 -0
- package/dist/zukhruf/collaboration/tool-exposure.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/tool-namespace.d.ts +7 -0
- package/dist/zukhruf/collaboration/tool-namespace.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/wait-bounds.d.ts +12 -0
- package/dist/zukhruf/collaboration/wait-bounds.d.ts.map +1 -0
- package/dist/zukhruf/collaboration/waiting.d.ts +262 -0
- package/dist/zukhruf/collaboration/waiting.d.ts.map +1 -0
- package/dist/zukhruf/control-plane/agent-history-forker.d.ts.map +1 -1
- package/dist/zukhruf/control-plane/fork-turns.d.ts +4 -3
- package/dist/zukhruf/control-plane/fork-turns.d.ts.map +1 -1
- package/dist/zukhruf/index.d.ts +11 -1
- package/dist/zukhruf/index.d.ts.map +1 -1
- package/dist/zukhruf/index.js +861 -649
- package/dist/zukhruf/index.js.map +4 -4
- package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/index.js +144 -140
- package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +4 -4
- package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts.map +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts +1 -1
- package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts.map +1 -1
- package/dist/zukhruf/plugins/schedules/index.js +143 -139
- package/dist/zukhruf/plugins/schedules/index.js.map +4 -4
- package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts +1 -1
- package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -1
- package/dist/zukhruf/plugins/uploads/http.js +2 -9
- package/dist/zukhruf/plugins/uploads/http.js.map +2 -2
- package/dist/zukhruf/queue/turn-queue.d.ts +2 -2
- package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
- package/dist/zukhruf/runtime/agent-runtime.d.ts +5 -4
- package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/zukhruf/runtime/agent-turn-executor.d.ts +3 -3
- package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -1
- package/dist/zukhruf/runtime/approval-controller.d.ts +3 -3
- package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -1
- package/dist/zukhruf/runtime/conversation-sandboxes.d.ts +2 -1
- package/dist/zukhruf/runtime/conversation-sandboxes.d.ts.map +1 -1
- package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
- package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts +3 -5
- package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -1
- package/package.json +5 -4
- package/dist/zukhruf/collaboration/collaboration-tools.d.ts +0 -1832
- package/dist/zukhruf/collaboration/collaboration-tools.d.ts.map +0 -1
- package/dist/zukhruf/multi-agent-config.d.ts +0 -37
- package/dist/zukhruf/multi-agent-config.d.ts.map +0 -1
|
@@ -155,6 +155,6 @@ export declare class ScheduledTasks<ExecutionConfig extends object> {
|
|
|
155
155
|
cancelRun(ownerId: string, runId: string): Promise<ScheduledRun<ExecutionConfig>>;
|
|
156
156
|
markReviewed(ownerId: string, runId: string): Promise<ScheduledRun<ExecutionConfig>>;
|
|
157
157
|
archiveRun(ownerId: string, runId: string): Promise<ScheduledRun<ExecutionConfig>>;
|
|
158
|
-
work(options?: JobPollingOptions
|
|
158
|
+
work(options?: JobPollingOptions): Promise<AsyncDisposable>;
|
|
159
159
|
}
|
|
160
160
|
//# sourceMappingURL=scheduled-tasks.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduled-tasks.d.ts","sources":["../../../../src/zukhruf/plugins/schedules/scheduled-tasks.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,EAAE,EACF,iBAAiB,EAEjB,MAAM,EACN,KAAK,EACN,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAQxB,eAAO,MAAM,wBAAwB,6BAA6B,CAAC;AAsGnE,MAAM,MAAM,mBAAmB,GAC7B,QAAQ,GAAG,QAAQ,GAAG,WAAW,GAAG,UAAU,CAAC;AACjD,MAAM,MAAM,kBAAkB,GAC5B,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AACnE,MAAM,MAAM,wBAAwB,GAClC,gBAAgB,GAAG,UAAU,GAAG,UAAU,CAAC;AAE7C,MAAM,MAAM,uBAAuB,GACjC,eAAe,GAAG,WA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AAc,EAAE,MAAM,GACrB,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,CAiDxC;IAEK,OAAO,CACX,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,CAAC,CAmBzC;IAEK,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAwC1D;IAEK,SAAS,CACb,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,CA+CxC;IAEK,YAAY,CAChB,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,CAExC;IAEK,UAAU,CACd,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,MAAM,GACZ,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,CAExC;IAEK,IAAI,CAAC,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,eAAe,CAAC,CAiBhE;CA2eF"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// packages/experimental/src/zukhruf/plugins/uploads/http.ts
|
|
2
2
|
import { validate as validate2 } from "@sdk-it/hono/runtime";
|
|
3
|
+
import { safeParse } from "fast-content-type-parse";
|
|
3
4
|
import { Hono as Hono2 } from "hono";
|
|
4
5
|
import { bodyLimit } from "hono/body-limit";
|
|
5
6
|
import { HTTPException as HTTPException2 } from "hono/http-exception";
|
|
6
|
-
import { MIMEType } from "node:util";
|
|
7
7
|
import z4 from "zod";
|
|
8
8
|
|
|
9
9
|
// packages/experimental/src/zukhruf/plugins/http/index.ts
|
|
@@ -287,14 +287,7 @@ function essenceOf(contentType) {
|
|
|
287
287
|
if (contentType === void 0) {
|
|
288
288
|
return void 0;
|
|
289
289
|
}
|
|
290
|
-
|
|
291
|
-
return new MIMEType(contentType).essence;
|
|
292
|
-
} catch (error) {
|
|
293
|
-
if (error instanceof TypeError && "code" in error && error.code === "ERR_INVALID_MIME_SYNTAX") {
|
|
294
|
-
return void 0;
|
|
295
|
-
}
|
|
296
|
-
throw error;
|
|
297
|
-
}
|
|
290
|
+
return safeParse(contentType).type || void 0;
|
|
298
291
|
}
|
|
299
292
|
export {
|
|
300
293
|
UPLOAD_FILENAME_HEADER,
|
|
@@ -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/control-plane/agent-turn-id.ts", "../../../../src/zukhruf/plugins/uploads/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { validate } from '@sdk-it/hono/runtime';\nimport { Hono } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { HTTPException } from 'hono/http-exception';\nimport { MIMEType } from 'node:util';\nimport z from 'zod';\n\nimport type { AgentPluginDefinition } from '../../runtime/agent-runtime.ts';\nimport {\n type HttpEnv,\n type HttpProjection,\n mountPath,\n projectHttp,\n} from '../http/index.ts';\nimport {\n UPLOAD_MEDIA_TYPES,\n type UploadMediaType,\n type Uploads,\n isUploadMediaType,\n} from './index.ts';\n\nexport const UPLOAD_FILENAME_HEADER = 'x-upload-filename';\n\nconst SESSION_UPLOADS_ROUTE_PATH = '/session/:sessionId/uploads';\nconst SESSION_UPLOAD_ROUTE_PATH = `${SESSION_UPLOADS_ROUTE_PATH}/:fileId`;\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst IMMUTABLE = {\n 'cache-control': 'private, max-age=31536000, immutable',\n} as const;\nconst sessionIdSchema = z.uuid();\nconst uploadFilenameSchema = z\n .string()\n .min(1)\n .transform((encoded, context) => {\n try {\n return decodeURIComponent(encoded);\n } catch {\n context.addIssue({\n code: 'custom',\n message: `${UPLOAD_FILENAME_HEADER} must be URI-encoded`,\n });\n return z.NEVER;\n }\n });\n\n/**\n * What `POST /session/:sessionId/uploads` answers. The composer keeps it and\n * sends it back under `message.metadata.uploads` on the turn that attaches it.\n */\nexport interface UploadReceipt {\n /** Absolute sandbox path the model reads with the sandbox read tool. */\n path: string;\n /** Client file name from the `x-upload-filename` header. */\n name: string;\n mediaType: UploadMediaType;\n /** Byte length of the stored file. */\n size: number;\n /** `GET` route serving the bytes for rendering. */\n url: string;\n}\n\n/**\n * Per-session upload and retrieval bound to one `uploads()` definition.\n * The caller must choose the maximum accepted upload size in bytes.\n */\nexport function uploadsHttp(\n definition: AgentPluginDefinition<Uploads>,\n { maxBytes }: { maxBytes: number },\n): HttpProjection {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new TypeError(\n 'uploadsHttp: maxBytes must be a positive safe integer',\n );\n }\n return projectHttp(definition, (plugin) => ({\n capabilities: {\n uploads: { path: '/session', mediaTypes: UPLOAD_MEDIA_TYPES },\n },\n authenticatedRoutes: uploadRoutes(plugin, maxBytes),\n }));\n}\n\nfunction uploadRoutes(uploads: Uploads, maxBytes: number) {\n const app = new Hono<HttpEnv>();\n app.post(\n SESSION_UPLOADS_ROUTE_PATH,\n bodyLimit({\n maxSize: maxBytes,\n onError: () => {\n throw new HTTPException(413, {\n message: 'Upload is too large',\n cause: {\n code: 'api/payload-too-large',\n detail: `Upload exceeds ${maxBytes} bytes`,\n },\n });\n },\n }),\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n name: {\n select: payload.headers[UPLOAD_FILENAME_HEADER],\n against: uploadFilenameSchema,\n },\n })),\n async (context) => {\n const { sessionId, name } = context.var.input;\n const mediaType = essenceOf(context.req.header('content-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\nfunction essenceOf(contentType: string | undefined): string | undefined {\n if (contentType === undefined) {\n return undefined;\n }\n try {\n return new MIMEType(contentType).essence;\n } catch (error) {\n if (\n error instanceof TypeError &&\n 'code' in error &&\n error.code === 'ERR_INVALID_MIME_SYNTAX'\n ) {\n return undefined;\n }\n throw error;\n }\n}\n", "import { validate } from '@sdk-it/hono/runtime';\nimport {\n type JSONSchema7,\n type UIMessage,\n createUIMessageStreamResponse,\n safeValidateUIMessages,\n} from 'ai';\nimport { type Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport { basePath } from 'hono/route';\nimport { streamSSE } from 'hono/streaming';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport { elementsSchema } from '@deepagents/elements';\n\nimport type { AgentThreadLimitError } from '../../control-plane/agent-thread-limit-error.ts';\nimport { agentTurnIdSchema } from '../../control-plane/agent-turn-id.ts';\nimport type { ConversationNotFoundError } from '../../control-plane/conversation-not-found-error.ts';\nimport type { StaleTurnError } from '../../control-plane/stale-turn-error.ts';\nimport type { TurnNotFoundError } from '../../control-plane/turn-not-found-error.ts';\nimport { isNamedError } from '../../is-named-error.ts';\nimport type { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInitialization,\n} from '../../runtime/agent-runtime.ts';\n\nexport type HttpEnv = { Variables: { userId: string } };\n\nexport type OwnerEvent =\n | { readonly type: 'ready' }\n | {\n readonly type: 'change';\n readonly resource: string;\n readonly id: string;\n readonly [key: string]: unknown;\n };\n\ntype OwnerEventNotification =\n Exclude<OwnerEvent, { type: 'ready' }> | { readonly type: 'reset' };\n\nexport type OwnerEventSource = (\n userId: string,\n signal: AbortSignal,\n) => Promise<AsyncIterable<OwnerEventNotification>>;\n\n/** A discoverable feature: its route under the mount plus any detail the client needs to use it. */\nexport interface HttpCapability {\n readonly path: string;\n readonly [detail: string]: unknown;\n}\n\nexport interface HttpContribution {\n readonly capabilities: Readonly<Record<string, HttpCapability>>;\n readonly publicRoutes?: Hono<HttpEnv>;\n readonly authenticatedRoutes?: Hono<HttpEnv>;\n readonly events?: OwnerEventSource;\n}\n\nexport interface HttpProjection {\n project(runtime: HttpRuntime): HttpContribution;\n}\n\nexport function projectHttp<Running extends object>(\n definition: AgentPluginDefinition<Running>,\n project: (\n plugin: AgentPluginInitialization & Running,\n runtime: HttpRuntime,\n ) => HttpContribution,\n): HttpProjection {\n return {\n project(runtime) {\n return project(runtime.plugin(definition), runtime);\n },\n };\n}\n\nconst SESSION_ROUTE_PATH = '/session/:sessionId';\nconst SESSION_CANCEL_ROUTE_PATH = '/session/:sessionId/cancel';\nconst SESSION_STREAM_ROUTE_PATH = '/session/:sessionId/stream';\nconst EVENTS_ROUTE_PATH = '/events';\nconst SESSION_TURN_ROUTE_PATH = '/session/:sessionId/turn/:turnId';\nconst SESSION_TURN_CANCEL_ROUTE_PATH =\n '/session/:sessionId/turn/:turnId/cancel';\nconst HISTORY_ROUTE_PATH = '/history';\nconst INFO_ROUTE_PATH = '/info';\nconst HEALTH_ROUTE_PATH = '/health';\nexport const ZUKHRUF_SESSION_ID_HEADER = 'x-zukhruf-session-id';\nexport const ZUKHRUF_TURN_ID_HEADER = 'x-zukhruf-turn-id';\n\n/** Where the host mounted this API, without a trailing slash; empty at `/`. */\nexport function mountPath(context: Context): string {\n return basePath(context).replace(/\\/$/, '');\n}\n\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst sessionIdSchema = z.string().refine(validateUuid);\nconst jsonSchema = z.custom<JSONSchema7>(\n (value) =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n);\nconst clientToolsSchema = z\n .record(\n z.string().min(1),\n z.strictObject({\n inputSchema: jsonSchema,\n description: z.string().min(1),\n }),\n )\n .optional();\nconst turnBodySchema = z.strictObject({\n sessionId: sessionIdSchema,\n message: z.unknown(),\n trigger: z.enum(['submit-message', 'regenerate-message']),\n tools: clientToolsSchema,\n elements: elementsSchema,\n});\n\nexport interface HttpRuntime extends Pick<\n AgentHost,\n | 'createSession'\n | 'enqueue'\n | 'info'\n | 'listHistory'\n | 'plugin'\n | 'sessionExists'\n | 'subscribeConversationStatus'\n> {\n observe(conversation: ConversationId): Pick<\n AgentObservation,\n 'cancel' | 'resume' | 'status'\n > & {\n engine: Pick<AgentObservation['engine'], 'getMessages'>;\n };\n}\n\n/** Mount at the host-selected path with `app.route(path, http(runtime))`. */\nexport function http(\n runtime: HttpRuntime,\n ...projections: readonly HttpProjection[]\n) {\n const contributions = projections.map((projection) =>\n projection.project(runtime),\n );\n const capabilities: Record<string, HttpCapability> = {\n history: { path: HISTORY_ROUTE_PATH },\n chat: { path: '/session' },\n events: { path: EVENTS_ROUTE_PATH },\n };\n for (const { capabilities: contributed } of contributions) {\n for (const [name, capability] of Object.entries(contributed)) {\n if (!name.trim() || name !== name.trim()) {\n throw new Error(\n `http: capability name \"${name}\" must be non-empty without surrounding whitespace`,\n );\n }\n if (!capability.path.startsWith('/')) {\n throw new Error(`http: capability \"${name}\" must use an absolute path`);\n }\n if (Object.hasOwn(capabilities, name)) {\n throw new Error(`http: duplicate capability \"${name}\"`);\n }\n capabilities[name] = capability;\n }\n }\n const app = new Hono<HttpEnv>();\n app.onError((error, context) => {\n if (error instanceof HTTPException) {\n return context.json(\n { cause: error.cause, error: error.message },\n error.status,\n NO_STORE,\n );\n }\n if (\n isNamedError<ConversationNotFoundError>(\n error,\n 'ConversationNotFoundError',\n )\n ) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${error.chatId} does not exist`,\n },\n error: 'Session not found',\n },\n 404,\n NO_STORE,\n );\n }\n if (isNamedError<TurnNotFoundError>(error, 'TurnNotFoundError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${error.turnId} does not exist in session ${context.req.param('sessionId')}`,\n },\n error: 'Session turn not found',\n },\n 404,\n NO_STORE,\n );\n }\n if (isNamedError<StaleTurnError>(error, 'StaleTurnError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-turn-stale',\n detail: `Turn ${error.turnId} is not the latest turn of session ${context.req.param('sessionId')}`,\n },\n error: 'Session turn is stale',\n },\n 409,\n NO_STORE,\n );\n }\n if (isNamedError<AgentThreadLimitError>(error, 'AgentThreadLimitError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/agent-thread-limit',\n detail: `Every agent slot of session ${context.req.param('sessionId')}'s tree is busy; retry when one finishes`,\n },\n error: 'Agent thread limit reached',\n },\n 429,\n NO_STORE,\n );\n }\n throw error;\n });\n\n app.on(['GET', 'HEAD'], HEALTH_ROUTE_PATH, (context) =>\n context.req.method === 'HEAD'\n ? context.body(null, 200, NO_STORE)\n : context.json({ ok: true }, 200, NO_STORE),\n );\n app.all(HEALTH_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n for (const { publicRoutes } of contributions) {\n if (publicRoutes) app.route('/', publicRoutes);\n }\n\n app.use('*', async (context, next) => {\n if (!context.get('userId')?.trim()) {\n throw new HTTPException(401, {\n message: 'Authentication required',\n cause: {\n code: 'api/unauthenticated',\n detail: 'Authentication required to access Zukhruf',\n },\n });\n }\n await next();\n });\n\n app.get(INFO_ROUTE_PATH, (context) => {\n const mount = mountPath(context);\n return context.json(\n {\n ...runtime.info,\n capabilities: Object.fromEntries(\n Object.entries(capabilities).map(([name, { path, ...detail }]) => [\n name,\n { href: `${mount}${path}`, ...detail },\n ]),\n ),\n },\n 200,\n NO_STORE,\n );\n });\n app.all(INFO_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(HISTORY_ROUTE_PATH, async (context) =>\n context.json(\n await runtime.listHistory(context.get('userId')),\n 200,\n NO_STORE,\n ),\n );\n app.all(HISTORY_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n return context.json(\n {\n sessionId,\n messages: await runtime.observe(conversation).engine.getMessages(),\n },\n 200,\n NO_STORE,\n );\n },\n );\n app.post(\n SESSION_ROUTE_PATH,\n validate('application/json', (payload) => ({\n body: {\n select: payload.body,\n against: turnBodySchema,\n },\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { body, sessionId } = context.var.input;\n if (body.sessionId !== sessionId) {\n throw new HTTPException(400, {\n message: 'Invalid session ID',\n cause: {\n code: 'api/validation-failed',\n detail: 'Route and body session IDs must match',\n },\n });\n }\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n const request = await validateTurnRequest(body);\n if (!(await runtime.sessionExists(conversation))) {\n if (request.message.role !== 'user') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session must start with a user message',\n },\n });\n }\n if (request.trigger !== 'submit-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session cannot regenerate a response',\n },\n });\n }\n await runtime.createSession(conversation);\n }\n const turn = await runtime.enqueue(conversation, request);\n\n return accepted(context, sessionId, turn.id);\n },\n );\n app.all(SESSION_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, POST'),\n );\n\n app.get(\n SESSION_TURN_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: agentTurnIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const status = await runtime.observe(conversation).status(turnId);\n if (!status) {\n throw new HTTPException(404, {\n message: 'Session turn not found',\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${turnId} does not exist in session ${sessionId}`,\n },\n });\n }\n return context.json({ sessionId, turnId, ...status }, 200, NO_STORE);\n },\n );\n app.all(SESSION_TURN_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n app.post(\n SESSION_TURN_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: agentTurnIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel(turnId);\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_TURN_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.post(\n SESSION_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel();\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n const eventSources: OwnerEventSource[] = [\n async (userId, signal) => {\n const events = await runtime.subscribeConversationStatus(signal);\n return {\n async *[Symbol.asyncIterator]() {\n for await (const event of events) {\n if (event.type === 'reset') {\n yield event;\n } else if (event.conversation.userId === userId) {\n yield {\n type: 'change',\n resource: 'conversation',\n id: event.conversation.chatId,\n status: event.status,\n ...(event.child ? { child: event.child } : {}),\n } satisfies OwnerEvent;\n }\n }\n },\n };\n },\n ...contributions.flatMap(({ events }) => (events ? [events] : [])),\n ];\n\n app.get(EVENTS_ROUTE_PATH, (context) => {\n const userId = context.get('userId');\n const abort = new AbortController();\n const requestSignal = context.req.raw.signal;\n const abortRequest = () => abort.abort();\n requestSignal.addEventListener('abort', abortRequest, { once: true });\n context.header('cache-control', 'no-store');\n return streamSSE(context, async (stream) => {\n stream.onAbort(abortRequest);\n const write = (event: OwnerEvent) =>\n stream.writeSSE({ data: JSON.stringify(event) });\n const heartbeat = setInterval(() => {\n void stream.write(': heartbeat\\n\\n');\n }, 15_000);\n try {\n const subscriptions = await Promise.all(\n eventSources.map((subscribe) => subscribe(userId, abort.signal)),\n );\n await write({ type: 'ready' });\n await Promise.all(\n subscriptions.map(async (events) => {\n for await (const event of events) {\n await write(event.type === 'reset' ? { type: 'ready' } : event);\n }\n }),\n );\n } catch (error) {\n if (!(Error.isError(error) && error.name === 'AbortError')) {\n throw error;\n }\n } finally {\n clearInterval(heartbeat);\n abort.abort();\n requestSignal.removeEventListener('abort', abortRequest);\n }\n });\n });\n app.all(EVENTS_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_STREAM_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const stream = await runtime.observe(conversation).resume();\n if (!stream) {\n throw new HTTPException(404, {\n message: 'Session stream not found',\n cause: {\n code: 'zukhruf/session-stream-not-found',\n detail: `No durable stream exists for session ${sessionId}`,\n },\n });\n }\n\n return createUIMessageStreamResponse({\n headers: NO_STORE,\n stream,\n });\n },\n );\n app.all(SESSION_STREAM_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n for (const { authenticatedRoutes } of contributions) {\n if (authenticatedRoutes) app.route('/', authenticatedRoutes);\n }\n\n return app;\n}\n\nfunction accepted<Env extends HttpEnv>(\n context: Context<Env>,\n sessionId: string,\n turnId: string,\n) {\n return context.json({ ok: true, sessionId, turnId }, 202, {\n ...NO_STORE,\n [ZUKHRUF_SESSION_ID_HEADER]: sessionId,\n [ZUKHRUF_TURN_ID_HEADER]: turnId,\n });\n}\n\nasync function validateTurnMessage(\n value: unknown,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]['message']> {\n const result = await safeValidateUIMessages({ messages: [value] });\n if (!result.success)\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail: result.error.message },\n });\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'System messages are not accepted',\n },\n });\n return message;\n}\n\nasync function validateTurnRequest(\n body: z.infer<typeof turnBodySchema>,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]> {\n const message = await validateTurnMessage(body.message);\n const tools = body.tools === undefined ? {} : { tools: body.tools };\n const elements =\n body.elements === undefined ? {} : { elements: body.elements };\n if (message.role === 'assistant') {\n if (body.trigger === 'regenerate-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail:\n 'Regeneration requires the user message preceding the assistant response',\n },\n });\n }\n return { message, trigger: 'submit-message', ...tools, ...elements };\n }\n return { message, trigger: body.trigger, ...tools, ...elements };\n}\n\nfunction isTurnMessage(\n message: UIMessage,\n): message is Parameters<HttpRuntime['enqueue']>[1]['message'] {\n return message.role === 'user' || message.role === 'assistant';\n}\n\nasync function requireSession(\n runtime: HttpRuntime,\n conversation: ConversationId,\n): Promise<void> {\n if (await runtime.sessionExists(conversation)) return;\n throw new HTTPException(404, {\n message: 'Session not found',\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${conversation.chatId} does not exist`,\n },\n });\n}\n\nfunction methodNotAllowed(context: Context<HttpEnv>, allow: string): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { v5 as uuidv5, validate as validateUuid } from 'uuid';\nimport { z } from 'zod';\n\nimport type { ConversationId } from '../mailbox/types.ts';\nimport { TurnNotFoundError } from './turn-not-found-error.ts';\n\nconst prefix = 'zukhruf-turn';\n\n/** The shape of every AgentTurnId string; AgentTurnId.assertOwner checks whose it is. */\nexport const agentTurnIdSchema = z.string().refine((value) => {\n const [head, scope, turn, ...rest] = value.split(':');\n return (\n head === prefix &&\n rest.length === 0 &&\n validateUuid(scope) &&\n validateUuid(turn)\n );\n});\n\n/** Conversation-scoped durable identity for one caller-supplied turn key. */\nexport class AgentTurnId {\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static fromRequest(\n conversation: ConversationId,\n requestId: string,\n ): AgentTurnId {\n if (!requestId.trim()) {\n throw new Error('turn id cannot be empty');\n }\n const scope = conversationNamespace(conversation);\n return new AgentTurnId(`${prefix}:${scope}:${uuidv5(requestId, scope)}`);\n }\n\n static random(conversation: ConversationId): AgentTurnId {\n return AgentTurnId.fromRequest(conversation, crypto.randomUUID());\n }\n\n static assertOwner(conversation: ConversationId, streamId: string): void {\n const expectedPrefix = `${prefix}:${conversationNamespace(conversation)}:`;\n if (!streamId.startsWith(expectedPrefix)) {\n throw new TurnNotFoundError(streamId);\n }\n }\n\n toString(): string {\n return this.#value;\n }\n}\n\nexport function conversationNamespace(conversation: ConversationId): string {\n if (!conversation.chatId.trim() || !conversation.userId.trim()) {\n throw new Error('conversation requires non-empty chatId and userId');\n }\n return uuidv5(\n JSON.stringify([conversation.userId, conversation.chatId]),\n uuidv5.URL,\n );\n}\n", "import { type UIMessage, tool } from 'ai';\nimport { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport z from 'zod';\n\nimport { isRecord, reminder, shellQuote } from '@deepagents/context';\n\nimport type { ZukhrufSandbox } from '../../agent.ts';\nimport type {\n AgentPluginDefinition,\n AgentPluginHost,\n AgentPluginInitialization,\n AgentPluginToolContext,\n} from '../../runtime/agent-runtime.ts';\n\nconst extensionByMediaType = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/mp4': 'm4a',\n 'audio/wav': 'wav',\n} as const;\n\nexport type UploadMediaType = keyof typeof extensionByMediaType;\n\nexport const UPLOAD_MEDIA_TYPES: readonly UploadMediaType[] =\n Object.keys(extensionByMediaType).filter(isUploadMediaType);\n\n/** Every extension the store writes, plus the `jpeg` spelling it accepts on read. */\nconst mediaTypeByExtension: Readonly<Record<string, UploadMediaType>> = {\n ...Object.fromEntries(\n Object.entries(extensionByMediaType).map(([mediaType, extension]) => [\n extension,\n mediaType,\n ]),\n ),\n jpeg: 'image/jpeg',\n};\n\n/** `<uuid>.<ext>` is the only file name this store writes or reads. */\nconst UPLOAD_FILE_ID_PATTERN = new RegExp(\n `^[0-9a-f-]{36}\\\\.(${Object.keys(mediaTypeByExtension).join('|')})$`,\n);\n\nexport interface UploadScope {\n userId: string;\n sessionId: string;\n}\n\nexport interface StoredUpload {\n data: Uint8Array<ArrayBuffer>;\n mediaType: UploadMediaType;\n}\n\nexport interface WrittenUpload {\n fileId: string;\n /** Absolute sandbox path of the stored file. */\n path: string;\n}\n\nexport interface PublishRequest {\n /** Absolute sandbox path of a file below the session's uploads directory. */\n path: string;\n /** Display name for the user; defaults to the file's basename. */\n name?: string;\n}\n\nexport interface PublishedUpload extends WrittenUpload {\n mediaType: UploadMediaType;\n name: string;\n /** `GET` route relative to the mounted `http()` app that serves the bytes. */\n href: string;\n /** Absolute URL when the plugin knows its public mount (`publicUrl`). */\n url?: string;\n}\n\n/** One entry of `message.metadata.uploads`: the upload receipt the composer sends back. */\ninterface AttachedUpload {\n path: string;\n name: string;\n mediaType: string;\n size: number;\n}\n\nexport interface UploadsOptions {\n /** Absolute sandbox directory that receives `<userId>/<sessionId>/<fileId>` files. */\n directory: string;\n /**\n * Absolute URL where the host mounts `http(runtime, uploadsHttp(...))`, for\n * example `http://127.0.0.1:4317/zukhruf/v1`. When set, `publish_upload`\n * returns an absolute `url` the model can hand to the user verbatim.\n */\n publicUrl?: string;\n}\n\nexport interface Uploads extends AgentPluginInitialization {\n /** Stores one file in the session's sandbox. */\n write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;\n read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;\n /**\n * Adopts a file the agent wrote below the session's uploads directory: it\n * is renamed to a stable `<uuid>.<ext>` id so the `GET` route can serve it.\n */\n publish(\n scope: UploadScope,\n request: PublishRequest,\n ): Promise<PublishedUpload>;\n}\n\nexport function isUploadMediaType(\n mediaType: string,\n): mediaType is UploadMediaType {\n return Object.hasOwn(extensionByMediaType, mediaType);\n}\n\n/**\n * Keep composer uploads (images, video, audio) in the conversation sandbox,\n * tell the model where the files a turn attaches under\n * `message.metadata.uploads` live, and let any agent in the tree publish a\n * file it produced so the user can open or download it.\n */\nexport function uploads({\n directory,\n publicUrl,\n}: UploadsOptions): AgentPluginDefinition<Uploads> {\n if (typeof directory !== 'string' || !posix.isAbsolute(directory)) {\n throw new Error(\n `uploads: directory must be an absolute sandbox path, received ${JSON.stringify(directory)}`,\n );\n }\n const resolvedPublicUrl = normalizePublicUrl(publicUrl);\n return {\n name: 'uploads',\n create: () => ({\n configure: (root) => ({\n ...root,\n instructions: [\n ...root.instructions,\n attachedUploadsReminder(directory),\n ],\n }),\n initialize: async (host) =>\n new RunningUploads(host, directory, resolvedPublicUrl),\n }),\n };\n}\n\nconst publishInputSchema = z.object({\n path: z\n .string()\n .startsWith('/')\n .describe(\n \"Absolute sandbox path of the file to publish; it must be inside this session's uploads directory (the directory the attached files live in, subdirectories included).\",\n ),\n name: z\n .string()\n .min(1)\n .optional()\n .describe('Display name shown to the user; defaults to the file name.'),\n});\n\nclass RunningUploads implements Uploads {\n readonly #host: AgentPluginHost;\n readonly #directory: string;\n readonly #publicUrl: string | undefined;\n\n readonly tools = {\n publish_upload: tool<\n z.infer<typeof publishInputSchema>,\n PublishedUpload,\n AgentPluginToolContext\n >({\n description:\n \"Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.\",\n inputSchema: publishInputSchema,\n execute: (input, { context }) =>\n this.publish(\n { userId: context.conversation.userId, sessionId: context.treeId },\n input,\n ),\n }),\n };\n\n constructor(\n host: AgentPluginHost,\n directory: string,\n publicUrl: string | undefined,\n ) {\n this.#host = host;\n this.#directory = directory;\n this.#publicUrl = publicUrl;\n }\n\n async write(\n scope: UploadScope,\n { data, mediaType }: StoredUpload,\n ): Promise<WrittenUpload> {\n const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const path = this.#pathFor(scope, fileId);\n const sandbox = await this.#sandboxFor(scope);\n await sandbox.sandbox.writeBinaryFile({ path, content: data });\n return { fileId, path };\n }\n\n async read(\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n return this.#readFrom(await this.#sandboxFor(scope), scope, fileId);\n }\n\n async publish(\n scope: UploadScope,\n { path, name }: PublishRequest,\n ): Promise<PublishedUpload> {\n const root = this.#scopeFor(scope);\n if (!isBelow(root, path)) {\n throw new Error(\n `publish_upload: ${path} is outside this session's uploads directory ${root}`,\n );\n }\n const extension = posix.extname(path).slice(1).toLowerCase();\n const mediaType = mediaTypeByExtension[extension];\n if (mediaType === undefined) {\n throw new Error(\n `publish_upload: unsupported file extension \"${extension}\"; publishable extensions are ${Object.keys(mediaTypeByExtension).join(', ')}`,\n );\n }\n const sandbox = await this.#sandboxFor(scope);\n if ((await sandbox.sandbox.stat({ path })) === null) {\n throw new Error(`publish_upload: ${path} does not exist in the sandbox`);\n }\n const basename = posix.basename(path);\n const alreadyPublished =\n posix.dirname(path) === root && UPLOAD_FILE_ID_PATTERN.test(basename);\n const fileId = alreadyPublished\n ? basename\n : `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const target = this.#pathFor(scope, fileId);\n if (target !== path) {\n const moved = await sandbox.sandbox.run({\n command: `mv -- ${shellQuote(path)} ${shellQuote(target)}`,\n });\n if (moved.exitCode !== 0) {\n throw new Error(\n `publish_upload: could not move ${path}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`,\n );\n }\n }\n const href = `/session/${scope.sessionId}/uploads/${fileId}`;\n return {\n fileId,\n path: target,\n mediaType,\n name: name ?? basename,\n href,\n ...(this.#publicUrl === undefined\n ? {}\n : { url: `${this.#publicUrl}${href}` }),\n };\n }\n\n #sandboxFor(scope: UploadScope): Promise<ZukhrufSandbox> {\n return this.#host.sandbox({\n chatId: scope.sessionId,\n userId: scope.userId,\n });\n }\n\n async #readFrom(\n sandbox: ZukhrufSandbox,\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n const extension = UPLOAD_FILE_ID_PATTERN.exec(fileId)?.[1];\n const mediaType =\n extension === undefined ? undefined : mediaTypeByExtension[extension];\n if (mediaType === undefined) return undefined;\n const path = this.#pathFor(scope, fileId);\n const bytes = await sandbox.sandbox.readBinaryFile({ path });\n if (bytes === null) return undefined;\n return { data: new Uint8Array(bytes), mediaType };\n }\n\n #scopeFor(scope: UploadScope): string {\n return scopeFor(this.#directory, scope);\n }\n\n #pathFor(scope: UploadScope, fileId: string): string {\n return posix.join(this.#scopeFor(scope), fileId);\n }\n}\n\n/**\n * Lists the turn's attachments for the model. The engine folds it into the\n * user message being saved and hands over that chat, so only files uploaded\n * for this chat by its owner are listed.\n */\nfunction attachedUploadsReminder(directory: string) {\n return reminder(\n ({ currentMessage, chat }) => {\n if (currentMessage === undefined || chat === undefined) {\n throw new Error(\n 'uploads: the user reminder context must carry currentMessage and chat',\n );\n }\n const scope = scopeFor(directory, {\n userId: chat.userId,\n sessionId: chat.id,\n });\n const attached = attachedUploads(currentMessage).filter(({ path }) =>\n isBelow(scope, path),\n );\n if (attached.length === 0) return '';\n return [\n 'The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.',\n ...attached.map(\n ({ path, name, mediaType, size }) =>\n `- ${path} (${name}, ${mediaType}, ${size} bytes)`,\n ),\n ].join('\\n');\n },\n { asPart: true },\n );\n}\n\n/** `<directory>/<userId>/<sessionId>`; both identifiers must be one path segment. */\nfunction scopeFor(\n directory: string,\n { userId, sessionId }: UploadScope,\n): string {\n assertPathSegment('userId', userId);\n assertPathSegment('sessionId', sessionId);\n return posix.join(directory, userId, sessionId);\n}\n\nfunction normalizePublicUrl(publicUrl: string | undefined): string | undefined {\n if (publicUrl === undefined) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(publicUrl);\n } catch {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n return parsed.href.replace(/\\/+$/, '');\n}\n\nfunction 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"],
|
|
5
|
-
"mappings": ";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,
|
|
4
|
+
"sourcesContent": ["import { validate } from '@sdk-it/hono/runtime';\nimport { safeParse } from 'fast-content-type-parse';\nimport { Hono } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\nimport type { AgentPluginDefinition } from '../../runtime/agent-runtime.ts';\nimport {\n type HttpEnv,\n type HttpProjection,\n mountPath,\n projectHttp,\n} from '../http/index.ts';\nimport {\n UPLOAD_MEDIA_TYPES,\n type UploadMediaType,\n type Uploads,\n isUploadMediaType,\n} from './index.ts';\n\nexport const UPLOAD_FILENAME_HEADER = 'x-upload-filename';\n\nconst SESSION_UPLOADS_ROUTE_PATH = '/session/:sessionId/uploads';\nconst SESSION_UPLOAD_ROUTE_PATH = `${SESSION_UPLOADS_ROUTE_PATH}/:fileId`;\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst IMMUTABLE = {\n 'cache-control': 'private, max-age=31536000, immutable',\n} as const;\nconst sessionIdSchema = z.uuid();\nconst uploadFilenameSchema = z\n .string()\n .min(1)\n .transform((encoded, context) => {\n try {\n return decodeURIComponent(encoded);\n } catch {\n context.addIssue({\n code: 'custom',\n message: `${UPLOAD_FILENAME_HEADER} must be URI-encoded`,\n });\n return z.NEVER;\n }\n });\n\n/**\n * What `POST /session/:sessionId/uploads` answers. The composer keeps it and\n * sends it back under `message.metadata.uploads` on the turn that attaches it.\n */\nexport interface UploadReceipt {\n /** Absolute sandbox path the model reads with the sandbox read tool. */\n path: string;\n /** Client file name from the `x-upload-filename` header. */\n name: string;\n mediaType: UploadMediaType;\n /** Byte length of the stored file. */\n size: number;\n /** `GET` route serving the bytes for rendering. */\n url: string;\n}\n\n/**\n * Per-session upload and retrieval bound to one `uploads()` definition.\n * The caller must choose the maximum accepted upload size in bytes.\n */\nexport function uploadsHttp(\n definition: AgentPluginDefinition<Uploads>,\n { maxBytes }: { maxBytes: number },\n): HttpProjection {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new TypeError(\n 'uploadsHttp: maxBytes must be a positive safe integer',\n );\n }\n return projectHttp(definition, (plugin) => ({\n capabilities: {\n uploads: { path: '/session', mediaTypes: UPLOAD_MEDIA_TYPES },\n },\n authenticatedRoutes: uploadRoutes(plugin, maxBytes),\n }));\n}\n\nfunction uploadRoutes(uploads: Uploads, maxBytes: number) {\n const app = new Hono<HttpEnv>();\n app.post(\n SESSION_UPLOADS_ROUTE_PATH,\n bodyLimit({\n maxSize: maxBytes,\n onError: () => {\n throw new HTTPException(413, {\n message: 'Upload is too large',\n cause: {\n code: 'api/payload-too-large',\n detail: `Upload exceeds ${maxBytes} bytes`,\n },\n });\n },\n }),\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n name: {\n select: payload.headers[UPLOAD_FILENAME_HEADER],\n against: uploadFilenameSchema,\n },\n })),\n async (context) => {\n const { sessionId, name } = context.var.input;\n const mediaType = essenceOf(context.req.header('content-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\nfunction essenceOf(contentType: string | undefined): string | undefined {\n if (contentType === undefined) {\n return undefined;\n }\n return safeParse(contentType).type || undefined;\n}\n", "import { validate } from '@sdk-it/hono/runtime';\nimport {\n type JSONSchema7,\n type UIMessage,\n createUIMessageStreamResponse,\n safeValidateUIMessages,\n} from 'ai';\nimport { type Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport { basePath } from 'hono/route';\nimport { streamSSE } from 'hono/streaming';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport { elementsSchema } from '@deepagents/elements';\n\nimport type { AgentThreadLimitError } from '../../control-plane/agent-thread-limit-error.ts';\nimport { agentTurnIdSchema } from '../../control-plane/agent-turn-id.ts';\nimport type { ConversationNotFoundError } from '../../control-plane/conversation-not-found-error.ts';\nimport type { StaleTurnError } from '../../control-plane/stale-turn-error.ts';\nimport type { TurnNotFoundError } from '../../control-plane/turn-not-found-error.ts';\nimport { isNamedError } from '../../is-named-error.ts';\nimport type { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInitialization,\n} from '../../runtime/agent-runtime.ts';\n\nexport type HttpEnv = { Variables: { userId: string } };\n\nexport type OwnerEvent =\n | { readonly type: 'ready' }\n | {\n readonly type: 'change';\n readonly resource: string;\n readonly id: string;\n readonly [key: string]: unknown;\n };\n\ntype OwnerEventNotification =\n Exclude<OwnerEvent, { type: 'ready' }> | { readonly type: 'reset' };\n\nexport type OwnerEventSource = (\n userId: string,\n signal: AbortSignal,\n) => Promise<AsyncIterable<OwnerEventNotification>>;\n\n/** A discoverable feature: its route under the mount plus any detail the client needs to use it. */\nexport interface HttpCapability {\n readonly path: string;\n readonly [detail: string]: unknown;\n}\n\nexport interface HttpContribution {\n readonly capabilities: Readonly<Record<string, HttpCapability>>;\n readonly publicRoutes?: Hono<HttpEnv>;\n readonly authenticatedRoutes?: Hono<HttpEnv>;\n readonly events?: OwnerEventSource;\n}\n\nexport interface HttpProjection {\n project(runtime: HttpRuntime): HttpContribution;\n}\n\nexport function projectHttp<Running extends object>(\n definition: AgentPluginDefinition<Running>,\n project: (\n plugin: AgentPluginInitialization & Running,\n runtime: HttpRuntime,\n ) => HttpContribution,\n): HttpProjection {\n return {\n project(runtime) {\n return project(runtime.plugin(definition), runtime);\n },\n };\n}\n\nconst SESSION_ROUTE_PATH = '/session/:sessionId';\nconst SESSION_CANCEL_ROUTE_PATH = '/session/:sessionId/cancel';\nconst SESSION_STREAM_ROUTE_PATH = '/session/:sessionId/stream';\nconst EVENTS_ROUTE_PATH = '/events';\nconst SESSION_TURN_ROUTE_PATH = '/session/:sessionId/turn/:turnId';\nconst SESSION_TURN_CANCEL_ROUTE_PATH =\n '/session/:sessionId/turn/:turnId/cancel';\nconst HISTORY_ROUTE_PATH = '/history';\nconst INFO_ROUTE_PATH = '/info';\nconst HEALTH_ROUTE_PATH = '/health';\nexport const ZUKHRUF_SESSION_ID_HEADER = 'x-zukhruf-session-id';\nexport const ZUKHRUF_TURN_ID_HEADER = 'x-zukhruf-turn-id';\n\n/** Where the host mounted this API, without a trailing slash; empty at `/`. */\nexport function mountPath(context: Context): string {\n return basePath(context).replace(/\\/$/, '');\n}\n\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst sessionIdSchema = z.string().refine(validateUuid);\nconst jsonSchema = z.custom<JSONSchema7>(\n (value) =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n);\nconst clientToolsSchema = z\n .record(\n z.string().min(1),\n z.strictObject({\n inputSchema: jsonSchema,\n description: z.string().min(1),\n }),\n )\n .optional();\nconst turnBodySchema = z.strictObject({\n sessionId: sessionIdSchema,\n message: z.unknown(),\n trigger: z.enum(['submit-message', 'regenerate-message']),\n tools: clientToolsSchema,\n elements: elementsSchema,\n});\n\nexport interface HttpRuntime extends Pick<\n AgentHost,\n | 'createSession'\n | 'enqueue'\n | 'info'\n | 'listHistory'\n | 'plugin'\n | 'sessionExists'\n | 'subscribeConversationStatus'\n> {\n observe(conversation: ConversationId): Pick<\n AgentObservation,\n 'cancel' | 'resume' | 'status'\n > & {\n engine: Pick<AgentObservation['engine'], 'getMessages'>;\n };\n}\n\n/** Mount at the host-selected path with `app.route(path, http(runtime))`. */\nexport function http(\n runtime: HttpRuntime,\n ...projections: readonly HttpProjection[]\n) {\n const contributions = projections.map((projection) =>\n projection.project(runtime),\n );\n const capabilities: Record<string, HttpCapability> = {\n history: { path: HISTORY_ROUTE_PATH },\n chat: { path: '/session' },\n events: { path: EVENTS_ROUTE_PATH },\n };\n for (const { capabilities: contributed } of contributions) {\n for (const [name, capability] of Object.entries(contributed)) {\n if (!name.trim() || name !== name.trim()) {\n throw new Error(\n `http: capability name \"${name}\" must be non-empty without surrounding whitespace`,\n );\n }\n if (!capability.path.startsWith('/')) {\n throw new Error(`http: capability \"${name}\" must use an absolute path`);\n }\n if (Object.hasOwn(capabilities, name)) {\n throw new Error(`http: duplicate capability \"${name}\"`);\n }\n capabilities[name] = capability;\n }\n }\n const app = new Hono<HttpEnv>();\n app.onError((error, context) => {\n if (error instanceof HTTPException) {\n return context.json(\n { cause: error.cause, error: error.message },\n error.status,\n NO_STORE,\n );\n }\n if (\n isNamedError<ConversationNotFoundError>(\n error,\n 'ConversationNotFoundError',\n )\n ) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${error.chatId} does not exist`,\n },\n error: 'Session not found',\n },\n 404,\n NO_STORE,\n );\n }\n if (isNamedError<TurnNotFoundError>(error, 'TurnNotFoundError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${error.turnId} does not exist in session ${context.req.param('sessionId')}`,\n },\n error: 'Session turn not found',\n },\n 404,\n NO_STORE,\n );\n }\n if (isNamedError<StaleTurnError>(error, 'StaleTurnError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/session-turn-stale',\n detail: `Turn ${error.turnId} is not the latest turn of session ${context.req.param('sessionId')}`,\n },\n error: 'Session turn is stale',\n },\n 409,\n NO_STORE,\n );\n }\n if (isNamedError<AgentThreadLimitError>(error, 'AgentThreadLimitError')) {\n return context.json(\n {\n cause: {\n code: 'zukhruf/agent-thread-limit',\n detail: `Every agent slot of session ${context.req.param('sessionId')}'s tree is busy; retry when one finishes`,\n },\n error: 'Agent thread limit reached',\n },\n 429,\n NO_STORE,\n );\n }\n throw error;\n });\n\n app.on(['GET', 'HEAD'], HEALTH_ROUTE_PATH, (context) =>\n context.req.method === 'HEAD'\n ? context.body(null, 200, NO_STORE)\n : context.json({ ok: true }, 200, NO_STORE),\n );\n app.all(HEALTH_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n for (const { publicRoutes } of contributions) {\n if (publicRoutes) app.route('/', publicRoutes);\n }\n\n app.use('*', async (context, next) => {\n if (!context.get('userId')?.trim()) {\n throw new HTTPException(401, {\n message: 'Authentication required',\n cause: {\n code: 'api/unauthenticated',\n detail: 'Authentication required to access Zukhruf',\n },\n });\n }\n await next();\n });\n\n app.get(INFO_ROUTE_PATH, (context) => {\n const mount = mountPath(context);\n return context.json(\n {\n ...runtime.info,\n capabilities: Object.fromEntries(\n Object.entries(capabilities).map(([name, { path, ...detail }]) => [\n name,\n { href: `${mount}${path}`, ...detail },\n ]),\n ),\n },\n 200,\n NO_STORE,\n );\n });\n app.all(INFO_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(HISTORY_ROUTE_PATH, async (context) =>\n context.json(\n await runtime.listHistory(context.get('userId')),\n 200,\n NO_STORE,\n ),\n );\n app.all(HISTORY_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n return context.json(\n {\n sessionId,\n messages: await runtime.observe(conversation).engine.getMessages(),\n },\n 200,\n NO_STORE,\n );\n },\n );\n app.post(\n SESSION_ROUTE_PATH,\n validate('application/json', (payload) => ({\n body: {\n select: payload.body,\n against: turnBodySchema,\n },\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { body, sessionId } = context.var.input;\n if (body.sessionId !== sessionId) {\n throw new HTTPException(400, {\n message: 'Invalid session ID',\n cause: {\n code: 'api/validation-failed',\n detail: 'Route and body session IDs must match',\n },\n });\n }\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n const request = await validateTurnRequest(body);\n if (!(await runtime.sessionExists(conversation))) {\n if (request.message.role !== 'user') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session must start with a user message',\n },\n });\n }\n if (request.trigger !== 'submit-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'A new session cannot regenerate a response',\n },\n });\n }\n await runtime.createSession(conversation);\n }\n const turn = await runtime.enqueue(conversation, request);\n\n return accepted(context, sessionId, turn.id);\n },\n );\n app.all(SESSION_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, POST'),\n );\n\n app.get(\n SESSION_TURN_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: agentTurnIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const status = await runtime.observe(conversation).status(turnId);\n if (!status) {\n throw new HTTPException(404, {\n message: 'Session turn not found',\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${turnId} does not exist in session ${sessionId}`,\n },\n });\n }\n return context.json({ sessionId, turnId, ...status }, 200, NO_STORE);\n },\n );\n app.all(SESSION_TURN_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n app.post(\n SESSION_TURN_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: agentTurnIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel(turnId);\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_TURN_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.post(\n SESSION_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel();\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n const eventSources: OwnerEventSource[] = [\n async (userId, signal) => {\n const events = await runtime.subscribeConversationStatus(signal);\n return {\n async *[Symbol.asyncIterator]() {\n for await (const event of events) {\n if (event.type === 'reset') {\n yield event;\n } else if (event.conversation.userId === userId) {\n yield {\n type: 'change',\n resource: 'conversation',\n id: event.conversation.chatId,\n status: event.status,\n ...(event.child ? { child: event.child } : {}),\n } satisfies OwnerEvent;\n }\n }\n },\n };\n },\n ...contributions.flatMap(({ events }) => (events ? [events] : [])),\n ];\n\n app.get(EVENTS_ROUTE_PATH, (context) => {\n const userId = context.get('userId');\n const abort = new AbortController();\n const requestSignal = context.req.raw.signal;\n const abortRequest = () => abort.abort();\n requestSignal.addEventListener('abort', abortRequest, { once: true });\n context.header('cache-control', 'no-store');\n return streamSSE(context, async (stream) => {\n stream.onAbort(abortRequest);\n const write = (event: OwnerEvent) =>\n stream.writeSSE({ data: JSON.stringify(event) });\n const heartbeat = setInterval(() => {\n void stream.write(': heartbeat\\n\\n');\n }, 15_000);\n try {\n const subscriptions = await Promise.all(\n eventSources.map((subscribe) => subscribe(userId, abort.signal)),\n );\n await write({ type: 'ready' });\n await Promise.all(\n subscriptions.map(async (events) => {\n for await (const event of events) {\n await write(event.type === 'reset' ? { type: 'ready' } : event);\n }\n }),\n );\n } catch (error) {\n if (!(Error.isError(error) && error.name === 'AbortError')) {\n throw error;\n }\n } finally {\n clearInterval(heartbeat);\n abort.abort();\n requestSignal.removeEventListener('abort', abortRequest);\n }\n });\n });\n app.all(EVENTS_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_STREAM_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const stream = await runtime.observe(conversation).resume();\n if (!stream) {\n throw new HTTPException(404, {\n message: 'Session stream not found',\n cause: {\n code: 'zukhruf/session-stream-not-found',\n detail: `No durable stream exists for session ${sessionId}`,\n },\n });\n }\n\n return createUIMessageStreamResponse({\n headers: NO_STORE,\n stream,\n });\n },\n );\n app.all(SESSION_STREAM_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n for (const { authenticatedRoutes } of contributions) {\n if (authenticatedRoutes) app.route('/', authenticatedRoutes);\n }\n\n return app;\n}\n\nfunction accepted<Env extends HttpEnv>(\n context: Context<Env>,\n sessionId: string,\n turnId: string,\n) {\n return context.json({ ok: true, sessionId, turnId }, 202, {\n ...NO_STORE,\n [ZUKHRUF_SESSION_ID_HEADER]: sessionId,\n [ZUKHRUF_TURN_ID_HEADER]: turnId,\n });\n}\n\nasync function validateTurnMessage(\n value: unknown,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]['message']> {\n const result = await safeValidateUIMessages({ messages: [value] });\n if (!result.success)\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail: result.error.message },\n });\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail: 'System messages are not accepted',\n },\n });\n return message;\n}\n\nasync function validateTurnRequest(\n body: z.infer<typeof turnBodySchema>,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]> {\n const message = await validateTurnMessage(body.message);\n const tools = body.tools === undefined ? {} : { tools: body.tools };\n const elements =\n body.elements === undefined ? {} : { elements: body.elements };\n if (message.role === 'assistant') {\n if (body.trigger === 'regenerate-message') {\n throw new HTTPException(400, {\n message: 'Invalid message',\n cause: {\n code: 'api/validation-failed',\n detail:\n 'Regeneration requires the user message preceding the assistant response',\n },\n });\n }\n return { message, trigger: 'submit-message', ...tools, ...elements };\n }\n return { message, trigger: body.trigger, ...tools, ...elements };\n}\n\nfunction isTurnMessage(\n message: UIMessage,\n): message is Parameters<HttpRuntime['enqueue']>[1]['message'] {\n return message.role === 'user' || message.role === 'assistant';\n}\n\nasync function requireSession(\n runtime: HttpRuntime,\n conversation: ConversationId,\n): Promise<void> {\n if (await runtime.sessionExists(conversation)) return;\n throw new HTTPException(404, {\n message: 'Session not found',\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${conversation.chatId} does not exist`,\n },\n });\n}\n\nfunction methodNotAllowed(context: Context<HttpEnv>, allow: string): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { v5 as uuidv5, validate as validateUuid } from 'uuid';\nimport { z } from 'zod';\n\nimport type { ConversationId } from '../mailbox/types.ts';\nimport { TurnNotFoundError } from './turn-not-found-error.ts';\n\nconst prefix = 'zukhruf-turn';\n\n/** The shape of every AgentTurnId string; AgentTurnId.assertOwner checks whose it is. */\nexport const agentTurnIdSchema = z.string().refine((value) => {\n const [head, scope, turn, ...rest] = value.split(':');\n return (\n head === prefix &&\n rest.length === 0 &&\n validateUuid(scope) &&\n validateUuid(turn)\n );\n});\n\n/** Conversation-scoped durable identity for one caller-supplied turn key. */\nexport class AgentTurnId {\n readonly #value: string;\n\n private constructor(value: string) {\n this.#value = value;\n }\n\n static fromRequest(\n conversation: ConversationId,\n requestId: string,\n ): AgentTurnId {\n if (!requestId.trim()) {\n throw new Error('turn id cannot be empty');\n }\n const scope = conversationNamespace(conversation);\n return new AgentTurnId(`${prefix}:${scope}:${uuidv5(requestId, scope)}`);\n }\n\n static random(conversation: ConversationId): AgentTurnId {\n return AgentTurnId.fromRequest(conversation, crypto.randomUUID());\n }\n\n static assertOwner(conversation: ConversationId, streamId: string): void {\n const expectedPrefix = `${prefix}:${conversationNamespace(conversation)}:`;\n if (!streamId.startsWith(expectedPrefix)) {\n throw new TurnNotFoundError(streamId);\n }\n }\n\n toString(): string {\n return this.#value;\n }\n}\n\nexport function conversationNamespace(conversation: ConversationId): string {\n if (!conversation.chatId.trim() || !conversation.userId.trim()) {\n throw new Error('conversation requires non-empty chatId and userId');\n }\n return uuidv5(\n JSON.stringify([conversation.userId, conversation.chatId]),\n uuidv5.URL,\n );\n}\n", "import { type UIMessage, tool } from 'ai';\nimport { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport z from 'zod';\n\nimport { isRecord, reminder, shellQuote } from '@deepagents/context';\n\nimport type { ZukhrufSandbox } from '../../agent.ts';\nimport type {\n AgentPluginDefinition,\n AgentPluginHost,\n AgentPluginInitialization,\n AgentPluginToolContext,\n} from '../../runtime/agent-runtime.ts';\n\nconst extensionByMediaType = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/mp4': 'm4a',\n 'audio/wav': 'wav',\n} as const;\n\nexport type UploadMediaType = keyof typeof extensionByMediaType;\n\nexport const UPLOAD_MEDIA_TYPES: readonly UploadMediaType[] =\n Object.keys(extensionByMediaType).filter(isUploadMediaType);\n\n/** Every extension the store writes, plus the `jpeg` spelling it accepts on read. */\nconst mediaTypeByExtension: Readonly<Record<string, UploadMediaType>> = {\n ...Object.fromEntries(\n Object.entries(extensionByMediaType).map(([mediaType, extension]) => [\n extension,\n mediaType,\n ]),\n ),\n jpeg: 'image/jpeg',\n};\n\n/** `<uuid>.<ext>` is the only file name this store writes or reads. */\nconst UPLOAD_FILE_ID_PATTERN = new RegExp(\n `^[0-9a-f-]{36}\\\\.(${Object.keys(mediaTypeByExtension).join('|')})$`,\n);\n\nexport interface UploadScope {\n userId: string;\n sessionId: string;\n}\n\nexport interface StoredUpload {\n data: Uint8Array<ArrayBuffer>;\n mediaType: UploadMediaType;\n}\n\nexport interface WrittenUpload {\n fileId: string;\n /** Absolute sandbox path of the stored file. */\n path: string;\n}\n\nexport interface PublishRequest {\n /** Absolute sandbox path of a file below the session's uploads directory. */\n path: string;\n /** Display name for the user; defaults to the file's basename. */\n name?: string;\n}\n\nexport interface PublishedUpload extends WrittenUpload {\n mediaType: UploadMediaType;\n name: string;\n /** `GET` route relative to the mounted `http()` app that serves the bytes. */\n href: string;\n /** Absolute URL when the plugin knows its public mount (`publicUrl`). */\n url?: string;\n}\n\n/** One entry of `message.metadata.uploads`: the upload receipt the composer sends back. */\ninterface AttachedUpload {\n path: string;\n name: string;\n mediaType: string;\n size: number;\n}\n\nexport interface UploadsOptions {\n /** Absolute sandbox directory that receives `<userId>/<sessionId>/<fileId>` files. */\n directory: string;\n /**\n * Absolute URL where the host mounts `http(runtime, uploadsHttp(...))`, for\n * example `http://127.0.0.1:4317/zukhruf/v1`. When set, `publish_upload`\n * returns an absolute `url` the model can hand to the user verbatim.\n */\n publicUrl?: string;\n}\n\nexport interface Uploads extends AgentPluginInitialization {\n /** Stores one file in the session's sandbox. */\n write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;\n read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;\n /**\n * Adopts a file the agent wrote below the session's uploads directory: it\n * is renamed to a stable `<uuid>.<ext>` id so the `GET` route can serve it.\n */\n publish(\n scope: UploadScope,\n request: PublishRequest,\n ): Promise<PublishedUpload>;\n}\n\nexport function isUploadMediaType(\n mediaType: string,\n): mediaType is UploadMediaType {\n return Object.hasOwn(extensionByMediaType, mediaType);\n}\n\n/**\n * Keep composer uploads (images, video, audio) in the conversation sandbox,\n * tell the model where the files a turn attaches under\n * `message.metadata.uploads` live, and let any agent in the tree publish a\n * file it produced so the user can open or download it.\n */\nexport function uploads({\n directory,\n publicUrl,\n}: UploadsOptions): AgentPluginDefinition<Uploads> {\n if (typeof directory !== 'string' || !posix.isAbsolute(directory)) {\n throw new Error(\n `uploads: directory must be an absolute sandbox path, received ${JSON.stringify(directory)}`,\n );\n }\n const resolvedPublicUrl = normalizePublicUrl(publicUrl);\n return {\n name: 'uploads',\n create: () => ({\n configure: (root) => ({\n ...root,\n instructions: [\n ...root.instructions,\n attachedUploadsReminder(directory),\n ],\n }),\n initialize: async (host) =>\n new RunningUploads(host, directory, resolvedPublicUrl),\n }),\n };\n}\n\nconst publishInputSchema = z.object({\n path: z\n .string()\n .startsWith('/')\n .describe(\n \"Absolute sandbox path of the file to publish; it must be inside this session's uploads directory (the directory the attached files live in, subdirectories included).\",\n ),\n name: z\n .string()\n .min(1)\n .optional()\n .describe('Display name shown to the user; defaults to the file name.'),\n});\n\nclass RunningUploads implements Uploads {\n readonly #host: AgentPluginHost;\n readonly #directory: string;\n readonly #publicUrl: string | undefined;\n\n readonly tools = {\n publish_upload: tool<\n z.infer<typeof publishInputSchema>,\n PublishedUpload,\n AgentPluginToolContext\n >({\n description:\n \"Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.\",\n inputSchema: publishInputSchema,\n execute: (input, { context }) =>\n this.publish(\n { userId: context.conversation.userId, sessionId: context.treeId },\n input,\n ),\n }),\n };\n\n constructor(\n host: AgentPluginHost,\n directory: string,\n publicUrl: string | undefined,\n ) {\n this.#host = host;\n this.#directory = directory;\n this.#publicUrl = publicUrl;\n }\n\n async write(\n scope: UploadScope,\n { data, mediaType }: StoredUpload,\n ): Promise<WrittenUpload> {\n const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const path = this.#pathFor(scope, fileId);\n const sandbox = await this.#sandboxFor(scope);\n await sandbox.sandbox.writeBinaryFile({ path, content: data });\n return { fileId, path };\n }\n\n async read(\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n return this.#readFrom(await this.#sandboxFor(scope), scope, fileId);\n }\n\n async publish(\n scope: UploadScope,\n { path, name }: PublishRequest,\n ): Promise<PublishedUpload> {\n const root = this.#scopeFor(scope);\n if (!isBelow(root, path)) {\n throw new Error(\n `publish_upload: ${path} is outside this session's uploads directory ${root}`,\n );\n }\n const extension = posix.extname(path).slice(1).toLowerCase();\n const mediaType = mediaTypeByExtension[extension];\n if (mediaType === undefined) {\n throw new Error(\n `publish_upload: unsupported file extension \"${extension}\"; publishable extensions are ${Object.keys(mediaTypeByExtension).join(', ')}`,\n );\n }\n const sandbox = await this.#sandboxFor(scope);\n if ((await sandbox.sandbox.stat({ path })) === null) {\n throw new Error(`publish_upload: ${path} does not exist in the sandbox`);\n }\n const basename = posix.basename(path);\n const alreadyPublished =\n posix.dirname(path) === root && UPLOAD_FILE_ID_PATTERN.test(basename);\n const fileId = alreadyPublished\n ? basename\n : `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const target = this.#pathFor(scope, fileId);\n if (target !== path) {\n const moved = await sandbox.sandbox.run({\n command: `mv -- ${shellQuote(path)} ${shellQuote(target)}`,\n });\n if (moved.exitCode !== 0) {\n throw new Error(\n `publish_upload: could not move ${path}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`,\n );\n }\n }\n const href = `/session/${scope.sessionId}/uploads/${fileId}`;\n return {\n fileId,\n path: target,\n mediaType,\n name: name ?? basename,\n href,\n ...(this.#publicUrl === undefined\n ? {}\n : { url: `${this.#publicUrl}${href}` }),\n };\n }\n\n #sandboxFor(scope: UploadScope): Promise<ZukhrufSandbox> {\n return this.#host.sandbox({\n chatId: scope.sessionId,\n userId: scope.userId,\n });\n }\n\n async #readFrom(\n sandbox: ZukhrufSandbox,\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n const extension = UPLOAD_FILE_ID_PATTERN.exec(fileId)?.[1];\n const mediaType =\n extension === undefined ? undefined : mediaTypeByExtension[extension];\n if (mediaType === undefined) return undefined;\n const path = this.#pathFor(scope, fileId);\n const bytes = await sandbox.sandbox.readBinaryFile({ path });\n if (bytes === null) return undefined;\n return { data: new Uint8Array(bytes), mediaType };\n }\n\n #scopeFor(scope: UploadScope): string {\n return scopeFor(this.#directory, scope);\n }\n\n #pathFor(scope: UploadScope, fileId: string): string {\n return posix.join(this.#scopeFor(scope), fileId);\n }\n}\n\n/**\n * Lists the turn's attachments for the model. The engine folds it into the\n * user message being saved and hands over that chat, so only files uploaded\n * for this chat by its owner are listed.\n */\nfunction attachedUploadsReminder(directory: string) {\n return reminder(\n ({ currentMessage, chat }) => {\n if (currentMessage === undefined || chat === undefined) {\n throw new Error(\n 'uploads: the user reminder context must carry currentMessage and chat',\n );\n }\n const scope = scopeFor(directory, {\n userId: chat.userId,\n sessionId: chat.id,\n });\n const attached = attachedUploads(currentMessage).filter(({ path }) =>\n isBelow(scope, path),\n );\n if (attached.length === 0) return '';\n return [\n 'The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.',\n ...attached.map(\n ({ path, name, mediaType, size }) =>\n `- ${path} (${name}, ${mediaType}, ${size} bytes)`,\n ),\n ].join('\\n');\n },\n { asPart: true },\n );\n}\n\n/** `<directory>/<userId>/<sessionId>`; both identifiers must be one path segment. */\nfunction scopeFor(\n directory: string,\n { userId, sessionId }: UploadScope,\n): string {\n assertPathSegment('userId', userId);\n assertPathSegment('sessionId', sessionId);\n return posix.join(directory, userId, sessionId);\n}\n\nfunction normalizePublicUrl(publicUrl: string | undefined): string | undefined {\n if (publicUrl === undefined) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(publicUrl);\n } catch {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n return parsed.href.replace(/\\/+$/, '');\n}\n\nfunction 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"],
|
|
5
|
+
"mappings": ";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACLd,SAAS,gBAAgB;AACzB;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,YAAY;AACnC,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,YAAYC,qBAAoB;AACzC,OAAOC,QAAO;AAEd,SAAS,sBAAsB;;;ACd/B,SAAS,MAAM,QAAQ,YAAY,oBAAoB;AACvD,SAAS,SAAS;AAK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AQ,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;AAEA,SAAS,UAAU,aAAqD;AACtE,MAAI,gBAAgB,QAAW;AAC7B,WAAO;AAAA,EACT;AACA,SAAO,UAAU,WAAW,EAAE,QAAQ;AACxC;",
|
|
6
6
|
"names": ["validate", "Hono", "HTTPException", "z", "validateUuid", "z", "z", "validateUuid", "z", "z", "sessionIdSchema", "z", "Hono", "HTTPException", "validate"]
|
|
7
7
|
}
|
|
@@ -54,8 +54,6 @@ export interface ConsumeContext {
|
|
|
54
54
|
export interface ConsumeOptions {
|
|
55
55
|
/** Max turns processed concurrently by this consumer (across chats). */
|
|
56
56
|
concurrency?: number;
|
|
57
|
-
/** Wait for active handlers and settlement on disposal; otherwise only stop new claims. */
|
|
58
|
-
waitForActive?: boolean;
|
|
59
57
|
/**
|
|
60
58
|
* Fires for a turn whose handler crashed or whose worker died mid-turn.
|
|
61
59
|
* After it resolves, the turn's chat is unblocked and its next queued
|
|
@@ -85,6 +83,8 @@ export type TurnActivity = 'idle' | 'queued' | 'running';
|
|
|
85
83
|
* - After a non-parked job releases its FIFO ownership, `consume` invokes the
|
|
86
84
|
* optional `onSettled` hook before considering that delivery complete.
|
|
87
85
|
* - Turns from different chats may run concurrently.
|
|
86
|
+
* - Disposing a consumer stops new claims and resolves only after every
|
|
87
|
+
* handler it is running has exited and settled.
|
|
88
88
|
* - `getTurnActivity` distinguishes queued from active scheduler work for
|
|
89
89
|
* status inspection; adapters must not silently fall back to stale history.
|
|
90
90
|
* - `getCurrentTurn` returns the active turn, or otherwise the oldest eligible
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"turn-queue.d.ts","sources":["../../../src/zukhruf/queue/turn-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAEpC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,MAAM,MAAM,WAAW,GAAG;IACxB,iFAAiF;IACjF,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,iBAAiB,EAAE,CAAC;CAChC,GAAG,CACA;IACE,OAAO,EAAE,SAAS,GAAG;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACtC,OAAO,EAAE,gBAAgB,GAAG,oBAAoB,CAAC;CAClD,GACD;IACE,OAAO,EAAE,SAAS,GAAG;QAAE,IAAI,EAAE,WAAW,CAAA;KAAE,CAAC;IAC3C,OAAO,EAAE,gBAAgB,CAAC;CAC3B,CACJ,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,CACA,CAAC;IACC,IAAI,EAAE,SAAS,CAAC;CAQjB,GAAG,WAAW,CAAC,GAChB;IACE;;;OAGG;IACH,IAAI,EAAE,UAAU,CAAC;IACjB,IAAI,EAAE,SAAS,GAAG,YAAY,CAAC;CAChC,GACD;IACE;;;OAGG;IACH,IAAI,EAAE,SAAS,CAAC;CACjB,CACJ,CAAC;AAEF,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,WAAW,CA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AC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACtD;AAED,iFAAiF;AACjF,MAAM,MAAM,sBAAsB,GAAG,IAAI,CACvC,SAAS,EACT,MAAM,GAAG,iBAAiB,CAC3B,CAAC"}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { Telemetry } from 'ai';
|
|
2
2
|
import { ContextEngine, type ContextStore, type StreamManager, type StreamPart, type StreamStatus } from '@deepagents/context';
|
|
3
3
|
import type { AgentDeclaration, ZukhrufSandbox } from '../agent.ts';
|
|
4
|
+
import { Team } from '../collaboration/team.ts';
|
|
4
5
|
import { AgentDirectory } from '../control-plane/agent-directory.ts';
|
|
5
6
|
import type { ConversationId, InterAgentCommunication, MessageDeliveryMode } from '../mailbox/types.ts';
|
|
6
|
-
import { type MultiAgentHostConfig } from '../multi-agent-config.ts';
|
|
7
7
|
import type { TurnQueue, TurnRequest } from '../queue/turn-queue.ts';
|
|
8
8
|
import type { AgentStorage } from '../storage/agent-storage.ts';
|
|
9
9
|
import type { ZukhrufToolSet } from '../tool.ts';
|
|
@@ -63,7 +63,7 @@ export interface AgentPluginBindings {
|
|
|
63
63
|
export interface AgentPluginInitialization extends Partial<AsyncDisposable> {
|
|
64
64
|
readonly tools?: ZukhrufToolSet;
|
|
65
65
|
/** Hosts wait for active plugin work before releasing infrastructure. */
|
|
66
|
-
work?(
|
|
66
|
+
work?(): Promise<AsyncDisposable>;
|
|
67
67
|
conversationAvailable?(conversation: ConversationId): Promise<void>;
|
|
68
68
|
}
|
|
69
69
|
/**
|
|
@@ -143,8 +143,8 @@ export type AgentStack = (resources: AsyncDisposableStack) => Promise<{
|
|
|
143
143
|
* borrows it: register a storage the host should close on `resources`.
|
|
144
144
|
*/
|
|
145
145
|
storage: AgentStorage;
|
|
146
|
-
/**
|
|
147
|
-
multiAgent?:
|
|
146
|
+
/** The collaboration tools and guidance every agent gets. Defaults to `Team.codex()`. */
|
|
147
|
+
multiAgent?: Team;
|
|
148
148
|
/** Host implementations for capabilities required by root-owned plugins. */
|
|
149
149
|
bindings?: readonly AgentPluginBinding[];
|
|
150
150
|
/**
|
|
@@ -172,6 +172,7 @@ declare class RuntimeHost implements AsyncDisposable {
|
|
|
172
172
|
[Symbol.asyncDispose](): Promise<void>;
|
|
173
173
|
/** The running phase `initialize(host)` returned for `definition`. */
|
|
174
174
|
plugin<Running extends object>(definition: AgentPluginDefinition<Running>): AgentPluginInitialization & Running;
|
|
175
|
+
/** Creates the root chat, or keeps a chat of a tree this runtime owns (its root or a sub-agent); any other chat reads as absent. */
|
|
175
176
|
createSession(conversation: ConversationId): Promise<void>;
|
|
176
177
|
sessionExists(conversation: ConversationId): Promise<boolean>;
|
|
177
178
|
enqueue(conversation: ConversationId, turn: TurnRequest): Promise<{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runtime.d.ts","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;
|
|
1
|
+
{"version":3,"file":"agent-runtime.d.ts","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;AACpE,OAAO,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;A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ents/context';
|
|
2
|
+
import type { Team } from '../collaboration/team.ts';
|
|
2
3
|
import type { AgentControlPlane } from '../control-plane/agent-control-plane.ts';
|
|
3
4
|
import type { MailboxCoordinator } from '../mailbox/coordinator.ts';
|
|
4
5
|
import type { ConversationId } from '../mailbox/types.ts';
|
|
5
|
-
import type { ResolvedMultiAgentHostConfig } from '../multi-agent-config.ts';
|
|
6
6
|
import type { ConsumeContext, TurnRef } from '../queue/turn-queue.ts';
|
|
7
7
|
import type { ApprovalController } from './approval-controller.ts';
|
|
8
8
|
import type { ConversationSandboxes } from './conversation-sandboxes.ts';
|
|
9
9
|
import type { PluginManager } from './plugin/plugin-manager.ts';
|
|
10
|
-
type TurnPlugins = Pick<PluginManager, '
|
|
10
|
+
type TurnPlugins = Pick<PluginManager, 'tools' | 'skillsByAgent' | 'runtimeContext' | 'configureTelemetry'>;
|
|
11
11
|
export interface AgentTurnExecutorOptions {
|
|
12
12
|
store: ContextStore;
|
|
13
13
|
streams: StreamManager;
|
|
14
14
|
controlPlane: AgentControlPlane;
|
|
15
15
|
mailbox: MailboxCoordinator;
|
|
16
16
|
approvals: ApprovalController;
|
|
17
|
-
|
|
17
|
+
team: Team;
|
|
18
18
|
plugins: TurnPlugins;
|
|
19
19
|
/** The sandbox of each conversation, which a turn borrows. */
|
|
20
20
|
sandboxes: ConversationSandboxes;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-turn-executor.d.ts","sources":["../../../src/zukhruf/runtime/agent-turn-executor.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"agent-turn-executor.d.ts","sources":["../../../src/zukhruf/runtime/agent-turn-executor.ts"],"names":[],"mappings":"AASA,OAAO,EAGL,KAAK,YAAY,EACjB,KAAK,aAAa,EAOnB,MAAM,qBAAqB,CAAC;AAS7B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,0BAA0B,CAAC;AACrD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AACjF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,KAAK,EACV,cAAc,EAEf,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AAEtE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAEnE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,6BAA6B,CAAC;AAMzE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAEhE,KAAK,WAAW,GAAG,IAAI,CACrB,aAAa,EACb,OAAO,GAAG,eAAe,GAAG,gBAAgB,GAAG,oBAAoB,CACpE,CAAC;AAEF,MAAM,WAAW,wBAAwB;IACvC,KAAK,EAAE,YAAY,CAAC;IACpB,OAAO,EAAE,aAAa,CAAC;IACvB,YAAY,EAAE,iBAAiB,CAAC;IAChC,OAAO,EAAE,kBAAkB,CAAC;IAC5B,SAAS,EAAE,kBAAkB,CAAC;IAC9B,IAAI,EAAE,IAAI,CAAC;IACX,OAAO,EAAE,WAAW,CAAC;IACrB,8DAA8D;IAC9D,SAAS,EAAE,qBAAqB,CAAC;IACjC,8EAA8E;IAC9E,yBAAyB,EAAE,CAAC,YAAY,EAAE,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAC5E;AAMD,+EAA+E;AAC/E,qBAAa,iBAAiB;;IAW5B,YAAY,OAAO,EAAE,wBAAwB,EAU5C;IAEK,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAsBnE;CAsaF"}
|
|
@@ -13,8 +13,9 @@ export interface ApprovalControllerOptions {
|
|
|
13
13
|
export declare function hasUnansweredApprovals(message: UIMessage): boolean;
|
|
14
14
|
/**
|
|
15
15
|
* The head assistant message holds a tool call whose output must come from
|
|
16
|
-
* outside the runtime.
|
|
17
|
-
*
|
|
16
|
+
* outside the runtime. A turn writes its assistant message at each step's
|
|
17
|
+
* end, after the step's server-side tools executed, so `input-available` at
|
|
18
|
+
* a head whose turn is not running is a client tool.
|
|
18
19
|
*/
|
|
19
20
|
export declare function hasPendingClientInput(message: UIMessage): boolean;
|
|
20
21
|
/** The head is an assistant message with a tool call that has not settled: it waits on the host or a client. */
|
|
@@ -24,7 +25,6 @@ export declare class ApprovalController {
|
|
|
24
25
|
#private;
|
|
25
26
|
constructor(options: ApprovalControllerOptions);
|
|
26
27
|
isPaused(message: UIMessage | undefined): boolean;
|
|
27
|
-
isConversationPaused(conversation: ConversationId): Promise<boolean>;
|
|
28
28
|
settleDeniedApprovals(conversation: ConversationId, streamId: string): Promise<void>;
|
|
29
29
|
settleFailedApprovals(conversation: ConversationId, streamId: string, error: string): Promise<void>;
|
|
30
30
|
reconcileTerminalContinuation(conversation: ConversationId, streamId: string, status: 'completed' | 'failed' | 'cancelled', error?: string | null): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"approval-controller.d.ts","sources":["../../../src/zukhruf/runtime/approval-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,SAAS,EAGf,MAAM,IAAI,CAAC;AAEZ,OAAO,EAEL,KAAK,YAAY,EAElB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qCAAqC,CAAC;AAE1E,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC1D,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,YAAY,CAAC;IACpB,KAAK,EAAE,SAAS,CAAC;IACjB,SAAS,EAAE,cAAc,CAAC;CAC3B;AAID,wFAAwF;AACxF,wBAAgB,sBAAsB,CA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AEK,6BAA6B,CACjC,YAAY,EAAE,cAAc,EAC5B,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,WAAW,GAAG,QAAQ,GAAG,WAAW,EAC5C,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,GACpB,OAAO,CAAC,IAAI,CAAC,CAWf;IAEK,2BAA2B,CAC/B,YAAY,EAAE,cAAc,EAC5B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC,OAAO,CAAC,CA2BlB;IAEK,4BAA4B,CAChC,IAAI,EAAE,OAAO,EACb,QAAQ,EAAE,MAAM,GACf,OAAO,CAAC,OAAO,CAAC,CAqBlB;CAgBF"}
|
|
@@ -6,7 +6,8 @@ import type { AgentDeclaration, SandboxContext, ZukhrufSandbox } from '../agent.
|
|
|
6
6
|
* the host disposes it when the host ends. A handle can hold a connection
|
|
7
7
|
* (a Microsandbox microVM refuses every connect after about 107 open ones),
|
|
8
8
|
* and disposing it can end the environment (a container sandbox stops its
|
|
9
|
-
* container), so neither a turn nor a plugin disposes it.
|
|
9
|
+
* container), so neither a turn nor a plugin disposes it. A handle whose
|
|
10
|
+
* environment was removed outside it is disposed and acquired again by name.
|
|
10
11
|
*/
|
|
11
12
|
export declare class ConversationSandboxes implements AsyncDisposable {
|
|
12
13
|
#private;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"conversation-sandboxes.d.ts","sources":["../../../src/zukhruf/runtime/conversation-sandboxes.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"conversation-sandboxes.d.ts","sources":["../../../src/zukhruf/runtime/conversation-sandboxes.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,cAAc,EACf,MAAM,aAAa,CAAC;AAErB;;;;;;;;;GASG;AACH,qBAAa,qBAAsB,YAAW,eAAe;;IAI3D,OAAO,CACL,WAAW,EAAE,gBAAgB,EAC7B,OAAO,EAAE,cAAc,GACtB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|
3
|
-
import {
|
|
3
|
+
import type { Team } from '../../collaboration/team.ts';
|
|
4
4
|
import type { AgentDeclarationRegistry } from '../../control-plane/agent-declaration-registry.ts';
|
|
5
5
|
import type { ConversationId } from '../../mailbox/types.ts';
|
|
6
|
-
import type { ResolvedMultiAgentHostConfig } from '../../multi-agent-config.ts';
|
|
7
6
|
import type { ZukhrufToolSet } from '../../tool.ts';
|
|
8
7
|
import type { AgentPluginBinding, AgentPluginDefinition, AgentPluginHost, AgentPluginInitialization, AgentPluginToolContext } from '../agent-runtime.ts';
|
|
9
8
|
import { type PluginSkills } from './agent-skills.ts';
|
|
10
9
|
/** Owns plugin instances, their composed contributions, and initialization resources. */
|
|
11
10
|
export declare class PluginManager implements AsyncDisposable {
|
|
12
11
|
#private;
|
|
13
|
-
readonly collaborationTools: ReturnType<typeof createCollaborationTools>;
|
|
14
12
|
readonly declarations: AgentDeclarationRegistry;
|
|
15
13
|
readonly agentOwners: ReadonlyMap<string, string>;
|
|
16
14
|
readonly tools: ZukhrufToolSet;
|
|
17
15
|
readonly skillsByAgent: ReadonlyMap<string, PluginSkills>;
|
|
18
16
|
readonly runtimeContext: Readonly<Record<string, unknown>>;
|
|
19
|
-
constructor(root: AgentDeclaration, bindings: readonly AgentPluginBinding[] | undefined,
|
|
17
|
+
constructor(root: AgentDeclaration, bindings: readonly AgentPluginBinding[] | undefined, team: Team);
|
|
20
18
|
[Symbol.asyncDispose](): Promise<void>;
|
|
21
19
|
get<Running extends object>(definition: AgentPluginDefinition<Running>): AgentPluginInitialization & Running;
|
|
22
20
|
configureTelemetry(context: AgentPluginToolContext, telemetry: AgentDeclaration['telemetry']): Omit<import("ai").TelemetryOptions, "integrations"> | {
|
|
@@ -31,7 +29,7 @@ export declare class PluginManager implements AsyncDisposable {
|
|
|
31
29
|
integrations: Telemetry[];
|
|
32
30
|
} | undefined;
|
|
33
31
|
get reconcilesAvailability(): boolean;
|
|
34
|
-
startWorkers(workers: AsyncDisposableStack
|
|
32
|
+
startWorkers(workers: AsyncDisposableStack): Promise<void>;
|
|
35
33
|
initialize(host: AgentPluginHost): Promise<void>;
|
|
36
34
|
conversationAvailable(conversation: ConversationId): Promise<void>;
|
|
37
35
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-manager.d.ts","sources":["../../../../src/zukhruf/runtime/plugin/plugin-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAEpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"plugin-manager.d.ts","sources":["../../../../src/zukhruf/runtime/plugin/plugin-manager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,IAAI,CAAC;AAEpC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACvD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,6BAA6B,CAAC;AACxD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,mDAAmD,CAAC;AAClG,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EACV,kBAAkB,EAClB,qBAAqB,EACrB,eAAe,EACf,yBAAyB,EAEzB,sBAAsB,EACvB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAA0B,KAAK,YAAY,EAAE,MAAM,mBAAmB,CAAC;AA6B9E,yFAAyF;AACzF,qBAAa,aAAc,YAAW,eAAe;;IACnD,QAAQ,CAAC,YAAY,EAAE,wBAAwB,CAAC;IAChD,QAAQ,CAAC,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClD,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAC/B,QAAQ,CAAC,aAAa,EAAE,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