@deepagents/experimental 6.1.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +151 -10
  2. package/dist/coding-agent-reminders/types.d.ts.map +1 -1
  3. package/dist/index.js +3084 -1206
  4. package/dist/index.js.map +4 -4
  5. package/dist/providers/claude/index.d.ts +4 -0
  6. package/dist/providers/claude/index.d.ts.map +1 -0
  7. package/dist/providers/claude/index.js +196 -0
  8. package/dist/providers/claude/index.js.map +7 -0
  9. package/dist/providers/claude/local-credentials.d.ts +3 -0
  10. package/dist/providers/claude/local-credentials.d.ts.map +1 -0
  11. package/dist/providers/codex/generate-via-stream.d.ts +8 -0
  12. package/dist/providers/codex/generate-via-stream.d.ts.map +1 -0
  13. package/dist/providers/codex/index.d.ts +4 -0
  14. package/dist/providers/codex/index.d.ts.map +1 -0
  15. package/dist/providers/codex/index.js +358 -0
  16. package/dist/providers/codex/index.js.map +7 -0
  17. package/dist/providers/codex/local-credentials.d.ts +4 -0
  18. package/dist/providers/codex/local-credentials.d.ts.map +1 -0
  19. package/dist/providers/language-model-provider.d.ts +5 -0
  20. package/dist/providers/language-model-provider.d.ts.map +1 -0
  21. package/dist/zukhruf/agent.d.ts +17 -2
  22. package/dist/zukhruf/agent.d.ts.map +1 -1
  23. package/dist/zukhruf/collaboration/agent-tool-context.d.ts +2 -2
  24. package/dist/zukhruf/collaboration/agent-tool-context.d.ts.map +1 -1
  25. package/dist/zukhruf/collaboration/collaboration-tools.d.ts +1807 -3
  26. package/dist/zukhruf/collaboration/collaboration-tools.d.ts.map +1 -1
  27. package/dist/zukhruf/collaboration/spawn-agent.d.ts.map +1 -1
  28. package/dist/zukhruf/collaboration/wait-agent.d.ts.map +1 -1
  29. package/dist/zukhruf/control-plane/agent-control-plane.d.ts +6 -7
  30. package/dist/zukhruf/control-plane/agent-control-plane.d.ts.map +1 -1
  31. package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts +1 -0
  32. package/dist/zukhruf/control-plane/agent-declaration-registry.d.ts.map +1 -1
  33. package/dist/zukhruf/control-plane/agent-status-projector.d.ts +6 -3
  34. package/dist/zukhruf/control-plane/agent-status-projector.d.ts.map +1 -1
  35. package/dist/zukhruf/control-plane/agent-thread.d.ts.map +1 -1
  36. package/dist/zukhruf/index.d.ts +7 -3
  37. package/dist/zukhruf/index.d.ts.map +1 -1
  38. package/dist/zukhruf/index.js +3085 -1207
  39. package/dist/zukhruf/index.js.map +4 -4
  40. package/dist/zukhruf/{multi-agent-v2-config.d.ts → multi-agent-config.d.ts} +14 -9
  41. package/dist/zukhruf/multi-agent-config.d.ts.map +1 -0
  42. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts +76 -0
  43. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -0
  44. package/dist/zukhruf/plugins/conversation-scheduling/index.d.ts +13 -0
  45. package/dist/zukhruf/plugins/conversation-scheduling/index.d.ts.map +1 -0
  46. package/dist/zukhruf/plugins/conversation-scheduling/index.js +999 -0
  47. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +7 -0
  48. package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts +19 -0
  49. package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts.map +1 -0
  50. package/dist/zukhruf/plugins/conversation-scheduling/tools.d.ts +1305 -0
  51. package/dist/zukhruf/plugins/conversation-scheduling/tools.d.ts.map +1 -0
  52. package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts +12 -0
  53. package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts.map +1 -0
  54. package/dist/zukhruf/plugins/http/index.d.ts +50 -0
  55. package/dist/zukhruf/plugins/http/index.d.ts.map +1 -0
  56. package/dist/zukhruf/plugins/http/index.js +618 -0
  57. package/dist/zukhruf/plugins/http/index.js.map +7 -0
  58. package/dist/zukhruf/plugins/http/parse.d.ts +3 -0
  59. package/dist/zukhruf/plugins/http/parse.d.ts.map +1 -0
  60. package/dist/zukhruf/plugins/http/validator.d.ts +64 -0
  61. package/dist/zukhruf/plugins/http/validator.d.ts.map +1 -0
  62. package/dist/zukhruf/plugins/mcp/index.d.ts +8 -0
  63. package/dist/zukhruf/plugins/mcp/index.d.ts.map +1 -0
  64. package/dist/zukhruf/plugins/mcp/index.js +25 -0
  65. package/dist/zukhruf/plugins/mcp/index.js.map +7 -0
  66. package/dist/zukhruf/plugins/schedules/http.d.ts +45 -0
  67. package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -0
  68. package/dist/zukhruf/plugins/schedules/http.js +528 -0
  69. package/dist/zukhruf/plugins/schedules/http.js.map +7 -0
  70. package/dist/zukhruf/plugins/schedules/index.d.ts +35 -0
  71. package/dist/zukhruf/plugins/schedules/index.d.ts.map +1 -0
  72. package/dist/zukhruf/plugins/schedules/index.js +1873 -0
  73. package/dist/zukhruf/plugins/schedules/index.js.map +7 -0
  74. package/dist/zukhruf/plugins/schedules/schedule-files.d.ts +6 -0
  75. package/dist/zukhruf/plugins/schedules/schedule-files.d.ts.map +1 -0
  76. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts +157 -0
  77. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -0
  78. package/dist/zukhruf/plugins/uploads/http.d.ts +27 -0
  79. package/dist/zukhruf/plugins/uploads/http.d.ts.map +1 -0
  80. package/dist/zukhruf/plugins/uploads/http.js +426 -0
  81. package/dist/zukhruf/plugins/uploads/http.js.map +7 -0
  82. package/dist/zukhruf/plugins/uploads/index.d.ts +73 -0
  83. package/dist/zukhruf/plugins/uploads/index.d.ts.map +1 -0
  84. package/dist/zukhruf/plugins/uploads/index.js +247 -0
  85. package/dist/zukhruf/plugins/uploads/index.js.map +7 -0
  86. package/dist/zukhruf/queue/pg-boss-notifications.d.ts +10 -0
  87. package/dist/zukhruf/queue/pg-boss-notifications.d.ts.map +1 -0
  88. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +8 -11
  89. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  90. package/dist/zukhruf/queue/turn-queue.d.ts +43 -38
  91. package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
  92. package/dist/zukhruf/runtime/agent-runtime.d.ts +163 -43
  93. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
  94. package/dist/zukhruf/runtime/agent-turn-executor.d.ts +9 -2
  95. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -1
  96. package/dist/zukhruf/runtime/approval-controller.d.ts +10 -25
  97. package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -1
  98. package/dist/zukhruf/runtime/compaction.d.ts +47 -0
  99. package/dist/zukhruf/runtime/compaction.d.ts.map +1 -0
  100. package/dist/zukhruf/runtime/conversation-status/change-source.d.ts +19 -0
  101. package/dist/zukhruf/runtime/conversation-status/change-source.d.ts.map +1 -0
  102. package/dist/zukhruf/runtime/conversation-status/child-progress.d.ts +84 -0
  103. package/dist/zukhruf/runtime/conversation-status/child-progress.d.ts.map +1 -0
  104. package/dist/zukhruf/runtime/conversation-status/pg-boss-change-source.d.ts +22 -0
  105. package/dist/zukhruf/runtime/conversation-status/pg-boss-change-source.d.ts.map +1 -0
  106. package/dist/zukhruf/runtime/conversation-status/projector.d.ts +62 -0
  107. package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -0
  108. package/dist/zukhruf/runtime/conversation-status/status-publishing-turn-queue.d.ts +20 -0
  109. package/dist/zukhruf/runtime/conversation-status/status-publishing-turn-queue.d.ts.map +1 -0
  110. package/dist/zukhruf/runtime/plugin/agent-skills.d.ts +22 -0
  111. package/dist/zukhruf/runtime/plugin/agent-skills.d.ts.map +1 -0
  112. package/dist/zukhruf/runtime/plugin/plugin-agents.d.ts +14 -0
  113. package/dist/zukhruf/runtime/plugin/plugin-agents.d.ts.map +1 -0
  114. package/dist/zukhruf/runtime/plugin/plugin-bindings.d.ts +8 -0
  115. package/dist/zukhruf/runtime/plugin/plugin-bindings.d.ts.map +1 -0
  116. package/dist/zukhruf/runtime/plugin/plugin-context-composition.d.ts +7 -0
  117. package/dist/zukhruf/runtime/plugin/plugin-context-composition.d.ts.map +1 -0
  118. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts +38 -0
  119. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -0
  120. package/dist/zukhruf/runtime/plugin/plugin-tool-composition.d.ts +10 -0
  121. package/dist/zukhruf/runtime/plugin/plugin-tool-composition.d.ts.map +1 -0
  122. package/dist/zukhruf/tool.d.ts +5 -1
  123. package/dist/zukhruf/tool.d.ts.map +1 -1
  124. package/package.json +74 -6
  125. package/dist/zukhruf/multi-agent-v2-config.d.ts.map +0 -1
  126. package/dist/zukhruf/runtime/agent-skills.d.ts +0 -9
  127. package/dist/zukhruf/runtime/agent-skills.d.ts.map +0 -1
  128. package/dist/zukhruf/runtime/approval-job-id.d.ts +0 -3
  129. package/dist/zukhruf/runtime/approval-job-id.d.ts.map +0 -1
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/zukhruf/plugins/uploads/http.ts", "../../../../src/zukhruf/plugins/http/index.ts", "../../../../src/zukhruf/plugins/http/validator.ts", "../../../../src/zukhruf/plugins/http/parse.ts", "../../../../src/zukhruf/plugins/uploads/index.ts"],
4
+ "sourcesContent": ["import { safeParse as parseContentType } from 'fast-content-type-parse';\nimport { Hono } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\nimport type { AgentPluginDefinition } from '../../runtime/agent-runtime.ts';\nimport {\n type HttpEnv,\n type HttpProjection,\n mountPath,\n projectHttp,\n} from '../http/index.ts';\nimport { validate } from '../http/validator.ts';\nimport {\n UPLOAD_MEDIA_TYPES,\n type UploadMediaType,\n type Uploads,\n isUploadMediaType,\n} from './index.ts';\n\nexport const UPLOAD_FILENAME_HEADER = 'x-upload-filename';\n\nconst SESSION_UPLOADS_ROUTE_PATH = '/session/:sessionId/uploads';\nconst SESSION_UPLOAD_ROUTE_PATH = `${SESSION_UPLOADS_ROUTE_PATH}/:fileId`;\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst IMMUTABLE = {\n 'cache-control': 'private, max-age=31536000, immutable',\n} as const;\nconst sessionIdSchema = z.uuid();\nconst uploadFilenameSchema = z\n .string()\n .min(1)\n .transform((encoded, context) => {\n try {\n return decodeURIComponent(encoded);\n } catch {\n context.addIssue({\n code: 'custom',\n message: `${UPLOAD_FILENAME_HEADER} must be URI-encoded`,\n });\n return z.NEVER;\n }\n });\n\n/**\n * What `POST /session/:sessionId/uploads` answers. The composer keeps it and\n * sends it back under `message.metadata.uploads` on the turn that attaches it.\n */\nexport interface UploadReceipt {\n /** Absolute sandbox path the model reads with the sandbox read tool. */\n path: string;\n /** Client file name from the `x-upload-filename` header. */\n name: string;\n mediaType: UploadMediaType;\n /** Byte length of the stored file. */\n size: number;\n /** `GET` route serving the bytes for rendering. */\n url: string;\n}\n\n/**\n * Per-session upload and retrieval bound to one `uploads()` definition.\n * The caller must choose the maximum accepted upload size in bytes.\n */\nexport function uploadsHttp(\n definition: AgentPluginDefinition<Uploads>,\n { maxBytes }: { maxBytes: number },\n): HttpProjection {\n if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) {\n throw new TypeError(\n 'uploadsHttp: maxBytes must be a positive safe integer',\n );\n }\n return projectHttp(definition, (plugin) => ({\n capabilities: {\n uploads: { path: '/session', mediaTypes: UPLOAD_MEDIA_TYPES },\n },\n authenticatedRoutes: uploadRoutes(plugin, maxBytes),\n }));\n}\n\nfunction uploadRoutes(uploads: Uploads, maxBytes: number) {\n const app = new Hono<HttpEnv>();\n app.post(\n SESSION_UPLOADS_ROUTE_PATH,\n bodyLimit({\n maxSize: maxBytes,\n onError: () => {\n throw new HTTPException(413, {\n message: 'Upload is too large',\n cause: {\n code: 'api/payload-too-large',\n detail: `Upload exceeds ${maxBytes} bytes`,\n },\n });\n },\n }),\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n name: {\n select: payload.headers[UPLOAD_FILENAME_HEADER],\n against: uploadFilenameSchema,\n },\n })),\n async (context) => {\n const { sessionId, name } = context.var.input;\n const contentType = context.req.header('content-type');\n const mediaType =\n contentType === undefined\n ? undefined\n : parseContentType(contentType).type;\n if (mediaType === undefined || !isUploadMediaType(mediaType)) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'zukhruf/unsupported-media-type',\n detail: `Uploads must be one of ${UPLOAD_MEDIA_TYPES.join(', ')}`,\n },\n });\n }\n const data = new Uint8Array(await context.req.arrayBuffer());\n const { fileId, path } = await uploads.write(\n { userId: context.get('userId'), sessionId },\n { data, mediaType },\n );\n const url = new URL(\n `${mountPath(context)}/session/${sessionId}/uploads/${fileId}`,\n context.req.url,\n ).href;\n return context.json(\n {\n path,\n name,\n mediaType,\n size: data.byteLength,\n url,\n } satisfies UploadReceipt,\n 201,\n NO_STORE,\n );\n },\n );\n app.all(SESSION_UPLOADS_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.on(\n ['GET', 'HEAD'],\n SESSION_UPLOAD_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const fileId = context.req.param('fileId');\n const upload = await uploads.read(\n { userId: context.get('userId'), sessionId },\n fileId,\n );\n if (!upload) {\n throw new HTTPException(404, {\n message: 'Upload not found',\n cause: {\n code: 'zukhruf/upload-not-found',\n detail: `Upload ${fileId} does not exist in session ${sessionId}`,\n },\n });\n }\n // Byte ranges let <video>/<audio> seek and let Safari play at all; the\n // whole file is already in memory, so a range is a plain subarray.\n const total = upload.data.byteLength;\n const headers = {\n 'content-type': upload.mediaType,\n 'accept-ranges': 'bytes',\n ...IMMUTABLE,\n };\n const rangeHeader = context.req.header('range');\n const head = context.req.method === 'HEAD';\n if (rangeHeader === undefined) {\n const full = { ...headers, 'content-length': String(total) };\n return head\n ? context.body(null, 200, full)\n : context.body(upload.data, 200, full);\n }\n const range = parseByteRange(rangeHeader, total);\n if (range === undefined) {\n return context.body(null, 416, {\n ...headers,\n 'content-range': `bytes */${total}`,\n });\n }\n const partial = {\n ...headers,\n 'content-range': `bytes ${range.start}-${range.end}/${total}`,\n 'content-length': String(range.end - range.start + 1),\n };\n return head\n ? context.body(null, 206, partial)\n : context.body(\n upload.data.subarray(range.start, range.end + 1),\n 206,\n partial,\n );\n },\n );\n app.all(SESSION_UPLOAD_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n return app;\n}\n\n/**\n * One `bytes=` range (RFC 9110 \u00A714.1.2): `a-b`, `a-`, or `-n`; `undefined`\n * when the header is malformed, multi-range, or unsatisfiable.\n */\nfunction parseByteRange(\n header: string,\n total: number,\n): { start: number; end: number } | undefined {\n const match = /^bytes=(\\d*)-(\\d*)$/.exec(header.trim());\n if (match === null || total === 0) return undefined;\n const [, first, last] = match;\n if (first === '' && last === '') return undefined;\n if (first === '') {\n const suffix = Number(last);\n if (suffix === 0) return undefined;\n return { start: Math.max(total - suffix, 0), end: total - 1 };\n }\n const start = Number(first);\n const end = last === '' ? total - 1 : Math.min(Number(last), total - 1);\n if (start > end || start >= total) return undefined;\n return { start, end };\n}\n\nfunction methodNotAllowed(\n context: { header(name: string, value: string): void },\n allow: string,\n): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import {\n type JSONSchema7,\n type UIMessage,\n createUIMessageStreamResponse,\n safeValidateUIMessages,\n} from 'ai';\nimport { type Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport { basePath } from 'hono/route';\nimport { streamSSE } from 'hono/streaming';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport { elementsSchema } from '@deepagents/elements';\n\nimport type { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInstance,\n} from '../../runtime/agent-runtime.ts';\nimport { validate } from './validator.ts';\n\nexport type HttpEnv = { Variables: { userId: string } };\n\nexport type OwnerEvent =\n | { readonly type: 'ready' }\n | {\n readonly type: 'change';\n readonly resource: string;\n readonly id: string;\n readonly [key: string]: unknown;\n };\n\ntype OwnerEventNotification =\n Exclude<OwnerEvent, { type: 'ready' }> | { readonly type: 'reset' };\n\nexport type OwnerEventSource = (\n userId: string,\n signal: AbortSignal,\n) => Promise<AsyncIterable<OwnerEventNotification>>;\n\n/** A discoverable feature: its route under the mount plus any detail the client needs to use it. */\nexport interface HttpCapability {\n readonly path: string;\n readonly [detail: string]: unknown;\n}\n\nexport interface HttpContribution {\n readonly capabilities: Readonly<Record<string, HttpCapability>>;\n readonly publicRoutes?: Hono<HttpEnv>;\n readonly authenticatedRoutes?: Hono<HttpEnv>;\n readonly events?: OwnerEventSource;\n}\n\nexport interface HttpProjection {\n project(runtime: HttpRuntime): HttpContribution;\n}\n\nexport function projectHttp<Instance extends object>(\n definition: AgentPluginDefinition<Instance>,\n project: (\n plugin: AgentPluginInstance & Instance,\n runtime: HttpRuntime,\n ) => HttpContribution,\n): HttpProjection {\n return {\n project(runtime) {\n return project(runtime.plugin(definition), runtime);\n },\n };\n}\n\nconst SESSION_ROUTE_PATH = '/session/:sessionId';\nconst SESSION_CANCEL_ROUTE_PATH = '/session/:sessionId/cancel';\nconst SESSION_STREAM_ROUTE_PATH = '/session/:sessionId/stream';\nconst EVENTS_ROUTE_PATH = '/events';\nconst SESSION_TURN_ROUTE_PATH = '/session/:sessionId/turn/:turnId';\nconst SESSION_TURN_CANCEL_ROUTE_PATH =\n '/session/:sessionId/turn/:turnId/cancel';\nconst HISTORY_ROUTE_PATH = '/history';\nconst INFO_ROUTE_PATH = '/info';\nconst HEALTH_ROUTE_PATH = '/health';\nexport const ZUKHRUF_SESSION_ID_HEADER = 'x-zukhruf-session-id';\nexport const ZUKHRUF_TURN_ID_HEADER = 'x-zukhruf-turn-id';\n\n/** Where the host mounted this API, without a trailing slash; empty at `/`. */\nexport function mountPath(context: Context): string {\n return basePath(context).replace(/\\/$/, '');\n}\n\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst sessionIdSchema = z.string().refine(validateUuid);\nconst jsonSchema = z.custom<JSONSchema7>(\n (value) =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n);\nconst clientToolsSchema = z\n .record(\n z.string().min(1),\n z.strictObject({\n inputSchema: jsonSchema,\n description: z.string().min(1),\n }),\n )\n .optional();\nconst turnBodySchema = z.strictObject({\n sessionId: sessionIdSchema,\n message: z.unknown(),\n trigger: z.enum(['submit-message', 'regenerate-message']),\n tools: clientToolsSchema,\n elements: elementsSchema,\n});\n\nexport interface HttpRuntime extends Pick<\n AgentHost,\n | 'createSession'\n | 'enqueue'\n | 'info'\n | 'listHistory'\n | 'plugin'\n | 'sessionExists'\n | 'subscribeConversationStatus'\n> {\n observe(conversation: ConversationId): Pick<\n AgentObservation,\n 'cancel' | 'resume' | 'status'\n > & {\n engine: Pick<AgentObservation['engine'], 'getMessages'>;\n };\n}\n\n/** Mount at the host-selected path with `app.route(path, http(runtime))`. */\nexport function http(\n runtime: HttpRuntime,\n ...projections: readonly HttpProjection[]\n) {\n const contributions = projections.map((projection) =>\n projection.project(runtime),\n );\n const capabilities: Record<string, HttpCapability> = {\n history: { path: HISTORY_ROUTE_PATH },\n chat: { path: '/session' },\n events: { path: EVENTS_ROUTE_PATH },\n };\n for (const { capabilities: contributed } of contributions) {\n for (const [name, capability] of Object.entries(contributed)) {\n if (!name.trim() || name !== name.trim()) {\n throw new Error(\n `http: capability name \"${name}\" must be non-empty without surrounding whitespace`,\n );\n }\n if (!capability.path.startsWith('/')) {\n throw new Error(`http: capability \"${name}\" must use an absolute path`);\n }\n if (Object.hasOwn(capabilities, name)) {\n throw new Error(`http: duplicate capability \"${name}\"`);\n }\n capabilities[name] = capability;\n }\n }\n const app = new Hono<HttpEnv>();\n app.onError((error, context) => {\n if (error instanceof HTTPException) {\n return context.json(\n { cause: error.cause, error: error.message },\n error.status,\n NO_STORE,\n );\n }\n throw error;\n });\n\n app.on(['GET', 'HEAD'], HEALTH_ROUTE_PATH, (context) =>\n context.req.method === 'HEAD'\n ? context.body(null, 200, NO_STORE)\n : context.json({ ok: true }, 200, NO_STORE),\n );\n app.all(HEALTH_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n for (const { publicRoutes } of contributions) {\n if (publicRoutes) app.route('/', publicRoutes);\n }\n\n app.use('*', async (context, next) => {\n if (!context.get('userId')?.trim()) {\n throw new HTTPException(401, {\n message: 'Authentication required',\n cause: {\n code: 'api/unauthenticated',\n detail: 'Authentication required to access Zukhruf',\n },\n });\n }\n await next();\n });\n\n app.get(INFO_ROUTE_PATH, (context) => {\n const mount = mountPath(context);\n return context.json(\n {\n ...runtime.info,\n capabilities: Object.fromEntries(\n Object.entries(capabilities).map(([name, { path, ...detail }]) => [\n name,\n { href: `${mount}${path}`, ...detail },\n ]),\n ),\n },\n 200,\n NO_STORE,\n );\n });\n app.all(INFO_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(HISTORY_ROUTE_PATH, async (context) =>\n context.json(\n await runtime.listHistory(context.get('userId')),\n 200,\n NO_STORE,\n ),\n );\n app.all(HISTORY_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n return context.json(\n {\n sessionId,\n messages: await runtime.observe(conversation).engine.getMessages(),\n },\n 200,\n NO_STORE,\n );\n },\n );\n app.post(\n SESSION_ROUTE_PATH,\n validate('application/json', (payload) => ({\n body: {\n select: payload.body,\n against: turnBodySchema,\n },\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { body, sessionId } = context.var.input;\n if (body.sessionId !== sessionId) {\n throw invalidSessionId('Route and body session IDs must match');\n }\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n const request = await validateTurnRequest(body);\n if (!(await runtime.sessionExists(conversation))) {\n if (request.message.role !== 'user') {\n throw invalidMessage('A new session must start with a user message');\n }\n if (request.trigger !== 'submit-message') {\n throw invalidMessage('A new session cannot regenerate a response');\n }\n await runtime.createSession(conversation);\n }\n const turn = await runtime.enqueue(conversation, request);\n\n return accepted(context, sessionId, turn.id);\n },\n );\n app.all(SESSION_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, POST'),\n );\n\n app.get(\n SESSION_TURN_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const status = await runtime.observe(conversation).status(turnId);\n if (!status) {\n throw new HTTPException(404, {\n message: 'Session turn not found',\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${turnId} does not exist in session ${sessionId}`,\n },\n });\n }\n return context.json({ sessionId, turnId, ...status }, 200, NO_STORE);\n },\n );\n app.all(SESSION_TURN_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n app.post(\n SESSION_TURN_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel(turnId);\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_TURN_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.post(\n SESSION_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel();\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n const eventSources: OwnerEventSource[] = [\n async (userId, signal) => {\n const events = await runtime.subscribeConversationStatus(signal);\n return {\n async *[Symbol.asyncIterator]() {\n for await (const event of events) {\n if (event.type === 'reset') {\n yield event;\n } else if (event.conversation.userId === userId) {\n yield {\n type: 'change',\n resource: 'conversation',\n id: event.conversation.chatId,\n status: event.status,\n ...(event.child ? { child: event.child } : {}),\n } satisfies OwnerEvent;\n }\n }\n },\n };\n },\n ...contributions.flatMap(({ events }) => (events ? [events] : [])),\n ];\n\n app.get(EVENTS_ROUTE_PATH, (context) => {\n const userId = context.get('userId');\n const abort = new AbortController();\n const requestSignal = context.req.raw.signal;\n const abortRequest = () => abort.abort();\n requestSignal.addEventListener('abort', abortRequest, { once: true });\n context.header('cache-control', 'no-store');\n return streamSSE(context, async (stream) => {\n stream.onAbort(abortRequest);\n let lastWrite: Promise<unknown> = Promise.resolve();\n const write = (event: OwnerEvent) => {\n const next = lastWrite.then(() =>\n stream.writeSSE({ data: JSON.stringify(event) }),\n );\n lastWrite = next.catch(() => {});\n return next;\n };\n const heartbeat = setInterval(() => {\n const next = lastWrite.then(async () => {\n await stream.write(': heartbeat\\n\\n');\n });\n lastWrite = next.catch(() => {});\n }, 15_000);\n try {\n const subscriptions = await Promise.all(\n eventSources.map((subscribe) => subscribe(userId, abort.signal)),\n );\n await write({ type: 'ready' });\n await Promise.all(\n subscriptions.map(async (events) => {\n for await (const event of events) {\n await write(event.type === 'reset' ? { type: 'ready' } : event);\n }\n }),\n );\n } catch (error) {\n if (!(error instanceof Error && error.name === 'AbortError')) {\n throw error;\n }\n } finally {\n clearInterval(heartbeat);\n abort.abort();\n requestSignal.removeEventListener('abort', abortRequest);\n }\n });\n });\n app.all(EVENTS_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_STREAM_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const stream = await runtime.observe(conversation).resume();\n if (!stream) {\n throw new HTTPException(404, {\n message: 'Session stream not found',\n cause: {\n code: 'zukhruf/session-stream-not-found',\n detail: `No durable stream exists for session ${sessionId}`,\n },\n });\n }\n\n return createUIMessageStreamResponse({\n headers: NO_STORE,\n stream,\n });\n },\n );\n app.all(SESSION_STREAM_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n for (const { authenticatedRoutes } of contributions) {\n if (authenticatedRoutes) app.route('/', authenticatedRoutes);\n }\n\n return app;\n}\n\nfunction accepted<Env extends HttpEnv>(\n context: Context<Env>,\n sessionId: string,\n turnId: string,\n) {\n return context.json({ ok: true, sessionId, turnId }, 202, {\n ...NO_STORE,\n [ZUKHRUF_SESSION_ID_HEADER]: sessionId,\n [ZUKHRUF_TURN_ID_HEADER]: turnId,\n });\n}\n\nasync function validateTurnMessage(\n value: unknown,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]['message']> {\n const result = await safeValidateUIMessages({ messages: [value] });\n if (!result.success) throw invalidMessage(result.error.message);\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw invalidMessage('System messages are not accepted');\n return message;\n}\n\nasync function validateTurnRequest(\n body: z.infer<typeof turnBodySchema>,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]> {\n const message = await validateTurnMessage(body.message);\n const tools = body.tools === undefined ? {} : { tools: body.tools };\n const elements =\n body.elements === undefined ? {} : { elements: body.elements };\n if (message.role === 'assistant') {\n if (body.trigger === 'regenerate-message') {\n throw invalidMessage(\n 'Regeneration requires the user message preceding the assistant response',\n );\n }\n return { message, trigger: 'submit-message', ...tools, ...elements };\n }\n return { message, trigger: body.trigger, ...tools, ...elements };\n}\n\nfunction isTurnMessage(\n message: UIMessage,\n): message is Parameters<HttpRuntime['enqueue']>[1]['message'] {\n return message.role === 'user' || message.role === 'assistant';\n}\n\nfunction invalidMessage(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nfunction invalidSessionId(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid session ID',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nasync function requireSession(\n runtime: HttpRuntime,\n conversation: ConversationId,\n): Promise<void> {\n if (await runtime.sessionExists(conversation)) return;\n throw new HTTPException(404, {\n message: 'Session not found',\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${conversation.chatId} does not exist`,\n },\n });\n}\n\nfunction methodNotAllowed(context: Context<HttpEnv>, allow: string): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { parse as parseContentType } from 'fast-content-type-parse';\nimport type { Context, MiddlewareHandler, ValidationTargets } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\nimport { parse } from './parse.ts';\n\ntype ContentType =\n | 'application/json'\n | 'application/x-www-form-urlencoded'\n | 'multipart/form-data'\n | 'text/plain';\n\ntype ValidatorConfig = Record<\n string,\n { select: unknown; against: z.ZodTypeAny }\n>;\n\ntype ExtractInput<T extends ValidatorConfig> = {\n [K in keyof T]: z.infer<T[K]['against']>;\n};\n\ntype HasUndefined<T> = undefined extends T ? true : false;\n\ntype InferTarget<\n T extends ValidatorConfig,\n S,\n Target extends keyof ValidationTargets,\n> = {\n [K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<\n z.infer<T[K]['against']>\n > extends true\n ? z.infer<T[K]['against']> | undefined\n : z.infer<T[K]['against']> extends ValidationTargets[Target]\n ? z.infer<T[K]['against']>\n : z.infer<T[K]['against']>;\n};\n\ntype InferIn<T extends ValidatorConfig> = (keyof InferTarget<\n T,\n QuerySelect | QueriesSelect,\n 'query'\n> extends never\n ? never\n : { query: InferTarget<T, QuerySelect | QueriesSelect, 'query'> }) &\n (keyof InferTarget<T, BodySelect, 'json'> extends never\n ? never\n : { json: InferTarget<T, BodySelect, 'json'> }) &\n (keyof InferTarget<T, ParamsSelect, 'param'> extends never\n ? never\n : { param: InferTarget<T, ParamsSelect, 'param'> }) &\n (keyof InferTarget<T, HeadersSelect, 'header'> extends never\n ? never\n : { header: InferTarget<T, HeadersSelect, 'header'> }) &\n (keyof InferTarget<T, CookieSelect, 'cookie'> extends never\n ? never\n : { cookie: InferTarget<T, CookieSelect, 'cookie'> });\n\n// Marker classes\nclass BodySelect {\n #private = 0;\n}\nclass QuerySelect {\n #private = 0;\n}\nclass QueriesSelect {\n #private = 0;\n}\nclass ParamsSelect {\n #private = 0;\n}\nclass HeadersSelect {\n #private = 0;\n}\nclass CookieSelect {\n #private = 0;\n}\n\ntype SelectorFn<T> = (payload: {\n body: Record<string, BodySelect>;\n query: Record<string, QuerySelect>;\n queries: Record<string, QueriesSelect>;\n params: Record<string, ParamsSelect>;\n headers: Record<string, HeadersSelect>;\n}) => T;\ntype ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<\n {\n Variables: {\n input: ExtractInput<T>;\n };\n },\n string,\n { in: InferIn<T> }\n>;\n\nexport function validate<T extends ValidatorConfig>(\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType,\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType | SelectorFn<T>,\n selector?: SelectorFn<T>,\n): ValidateMiddleware<T> {\n const expectedContentType =\n typeof expectedContentTypeOrSelector === 'string'\n ? expectedContentTypeOrSelector\n : undefined;\n const _selector =\n typeof expectedContentTypeOrSelector === 'function'\n ? expectedContentTypeOrSelector\n : selector;\n void _selector;\n if (!_selector) {\n throw new Error('Selector function is required');\n }\n\n return createMiddleware(async (c, next) => {\n const ct = c.req.header('content-type');\n if (c.req.method === 'GET' && ct) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `GET requests cannot have a content type header`,\n },\n });\n }\n if (expectedContentType) {\n void verifyContentType(ct, expectedContentType);\n }\n\n const contentType = ct ? parseContentType(ct) : null;\n let body: unknown = null;\n\n switch (contentType?.type) {\n case 'application/json':\n body = await parseJson(c);\n break;\n case 'application/x-www-form-urlencoded':\n case 'multipart/form-data':\n body = await c.req.parseBody();\n break;\n default:\n body = {};\n }\n\n const payload = {\n body,\n query: parseQueryParams(c.req.query()),\n queries: parseQueriesParams(c.req.queries()),\n params: c.req.param(),\n headers: c.req.header(),\n };\n\n const config = _selector(payload as never);\n const schema = z.object(\n Object.entries(config).reduce<Record<string, z.ZodTypeAny>>(\n (acc, [key, value]) => {\n acc[key] = value.against;\n return acc;\n },\n {},\n ),\n );\n\n const input = Object.entries(config).reduce<Record<string, unknown>>(\n (acc, [key, value]) => {\n acc[key] = value.select;\n return acc;\n },\n {},\n );\n\n const parsed = await parse(schema, input);\n c.set('input', parsed as ExtractInput<T>);\n await next();\n });\n}\n\nexport const openapi = validate;\n\nexport const consume = (contentType: ContentType) => {\n return createMiddleware(async (context, next) => {\n verifyContentType(context.req.header('content-type'), contentType);\n await next();\n });\n};\n\nexport function verifyContentType(\n actual: string | undefined,\n expected: ContentType,\n): asserts actual is ContentType {\n if (!actual) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: 'Missing content type header',\n },\n });\n }\n const { type: incomingContentType } = parseContentType(actual);\n if (incomingContentType !== expected) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `Expected content type: ${expected}, but got: ${incomingContentType}`,\n },\n });\n }\n}\n\nasync function parseJson(context: Context) {\n try {\n return await context.req.json();\n } catch (error) {\n throw new HTTPException(400, {\n message: 'The request body is not valid JSON',\n cause: {\n code: 'api/invalid-json',\n detail: error instanceof Error ? error.message : String(error),\n },\n });\n }\n}\n\nfunction parseQueryParams(\n queryParams: Record<string, string | undefined>,\n): Record<string, string | null | undefined> {\n return Object.fromEntries(\n Object.entries(queryParams).map(([key, value]) => [\n key,\n value === 'null' ? null : value,\n ]),\n );\n}\n\nfunction parseQueriesParams(\n queriesParams: Record<string, string[]>,\n): Record<string, (string | null)[]> {\n return Object.fromEntries(\n Object.entries(queriesParams).map(([key, values]) => [\n key,\n values.map((value) => (value === 'null' ? null : value)),\n ]),\n );\n}\n", "import { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\ninterface ValidationIssue {\n message: string;\n code: string;\n path: string;\n}\n\nexport async function parse<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n input: unknown,\n) {\n const result = await schema.safeParseAsync(input);\n if (!result.success) {\n const errors: z.inferFlattenedErrors<\n z.ZodObject<T>,\n ValidationIssue\n >['fieldErrors'] = result.error.flatten((issue) => ({\n message: issue.message,\n code: issue.code,\n path: issue.path.join('.'),\n })).fieldErrors;\n\n throw new HTTPException(400, {\n message: 'Validation failed',\n cause: {\n code: 'api/validation-failed',\n detail: 'The input data is invalid',\n errors,\n },\n });\n }\n return result.data;\n}\n", "import { type UIMessage, tool } from 'ai';\nimport { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport z from 'zod';\n\nimport { reminder } from '@deepagents/context';\n\nimport type { AgentDeclaration, ZukhrufSandbox } from '../../agent.ts';\nimport type {\n AgentPluginDefinition,\n AgentPluginHost,\n AgentPluginInstance,\n AgentPluginToolContext,\n} from '../../runtime/agent-runtime.ts';\n\nconst extensionByMediaType = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/mp4': 'm4a',\n 'audio/wav': 'wav',\n} as const;\n\nexport type UploadMediaType = keyof typeof extensionByMediaType;\n\nexport const UPLOAD_MEDIA_TYPES = Object.keys(\n extensionByMediaType,\n) as readonly UploadMediaType[];\n\n/** Every extension the store writes, plus the `jpeg` spelling it accepts on read. */\nconst mediaTypeByExtension: Readonly<Record<string, UploadMediaType>> = {\n ...Object.fromEntries(\n Object.entries(extensionByMediaType).map(([mediaType, extension]) => [\n extension,\n mediaType,\n ]),\n ),\n jpeg: 'image/jpeg',\n};\n\n/** `<uuid>.<ext>` is the only file name this store writes or reads. */\nconst UPLOAD_FILE_ID_PATTERN = new RegExp(\n `^[0-9a-f-]{36}\\\\.(${Object.keys(mediaTypeByExtension).join('|')})$`,\n);\n\nexport interface UploadScope {\n userId: string;\n sessionId: string;\n}\n\nexport interface StoredUpload {\n data: Uint8Array<ArrayBuffer>;\n mediaType: UploadMediaType;\n}\n\nexport interface WrittenUpload {\n fileId: string;\n /** Absolute sandbox path of the stored file. */\n path: string;\n}\n\nexport interface PublishRequest {\n /** Absolute sandbox path of a file below the session's uploads directory. */\n path: string;\n /** Display name for the user; defaults to the file's basename. */\n name?: string;\n}\n\nexport interface PublishedUpload extends WrittenUpload {\n mediaType: UploadMediaType;\n name: string;\n /** `GET` route relative to the mounted `http()` app that serves the bytes. */\n href: string;\n /** Absolute URL when the plugin knows its public mount (`publicUrl`). */\n url?: string;\n}\n\n/** One entry of `message.metadata.uploads`: the upload receipt the composer sends back. */\ninterface AttachedUpload {\n path: string;\n name: string;\n mediaType: string;\n size: number;\n}\n\nexport interface UploadsOptions {\n /** Absolute sandbox directory that receives `<userId>/<sessionId>/<fileId>` files. */\n directory: string;\n /**\n * Absolute URL where the host mounts `http(runtime, uploadsHttp(...))`, for\n * example `http://127.0.0.1:4317/zukhruf/v1`. When set, `publish_upload`\n * returns an absolute `url` the model can hand to the user verbatim.\n */\n publicUrl?: string;\n}\n\nexport interface Uploads extends AgentPluginInstance {\n /** Stores one file in the session's sandbox. */\n write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;\n read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;\n /**\n * Adopts a file the agent wrote below the session's uploads directory: it\n * is renamed to a stable `<uuid>.<ext>` id so the `GET` route can serve it.\n */\n publish(\n scope: UploadScope,\n request: PublishRequest,\n ): Promise<PublishedUpload>;\n}\n\nexport function isUploadMediaType(\n mediaType: string,\n): mediaType is UploadMediaType {\n return Object.hasOwn(extensionByMediaType, mediaType);\n}\n\n/**\n * Keep composer uploads (images, video, audio) in the conversation sandbox,\n * tell the model where the files a turn attaches under\n * `message.metadata.uploads` live, and let any agent in the tree publish a\n * file it produced so the user can open or download it.\n */\nexport function uploads({\n directory,\n publicUrl,\n}: UploadsOptions): AgentPluginDefinition<Uploads> {\n if (typeof directory !== 'string' || !posix.isAbsolute(directory)) {\n throw new Error(\n `uploads: directory must be an absolute sandbox path, received ${JSON.stringify(directory)}`,\n );\n }\n const resolvedPublicUrl = normalizePublicUrl(publicUrl);\n return {\n name: 'uploads',\n create: () => new UploadsPlugin(directory, resolvedPublicUrl),\n };\n}\n\nconst publishInputSchema = z.object({\n path: z\n .string()\n .startsWith('/')\n .describe(\n \"Absolute sandbox path of the file to publish; it must be inside this session's uploads directory (the directory the attached files live in, subdirectories included).\",\n ),\n name: z\n .string()\n .min(1)\n .optional()\n .describe('Display name shown to the user; defaults to the file name.'),\n});\n\nclass UploadsPlugin implements Uploads {\n readonly #directory: string;\n readonly #publicUrl: string | undefined;\n #host: AgentPluginHost | undefined;\n\n readonly tools = {\n publish_upload: tool<\n z.infer<typeof publishInputSchema>,\n PublishedUpload,\n AgentPluginToolContext\n >({\n description:\n \"Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.\",\n inputSchema: publishInputSchema,\n execute: (input, { context }) =>\n this.publish(\n { userId: context.conversation.userId, sessionId: context.treeId },\n input,\n ),\n }),\n };\n\n constructor(directory: string, publicUrl: string | undefined) {\n this.#directory = directory;\n this.#publicUrl = publicUrl;\n }\n\n configure(root: AgentDeclaration): AgentDeclaration {\n return {\n ...root,\n instructions: [...root.instructions, this.#attachedUploadsReminder()],\n };\n }\n\n initialize(host: AgentPluginHost): Promise<void> {\n this.#host = host;\n return Promise.resolve();\n }\n\n async write(\n scope: UploadScope,\n { data, mediaType }: StoredUpload,\n ): Promise<WrittenUpload> {\n const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const path = this.#pathFor(scope, fileId);\n const sandbox = await this.#sandboxFor(scope);\n await sandbox.sandbox.writeFiles([{ path, content: Buffer.from(data) }]);\n return { fileId, path };\n }\n\n async read(\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n return this.#readFrom(await this.#sandboxFor(scope), scope, fileId);\n }\n\n async publish(\n scope: UploadScope,\n { path, name }: PublishRequest,\n ): Promise<PublishedUpload> {\n const root = this.#scopeFor(scope);\n if (!isBelow(root, path)) {\n throw new Error(\n `publish_upload: ${path} is outside this session's uploads directory ${root}`,\n );\n }\n const extension = posix.extname(path).slice(1).toLowerCase();\n const mediaType = mediaTypeByExtension[extension];\n if (mediaType === undefined) {\n throw new Error(\n `publish_upload: unsupported file extension \"${extension}\"; publishable extensions are ${Object.keys(mediaTypeByExtension).join(', ')}`,\n );\n }\n const sandbox = await this.#sandboxFor(scope);\n if (!(await sandbox.sandbox.exists(path))) {\n throw new Error(`publish_upload: ${path} does not exist in the sandbox`);\n }\n const basename = posix.basename(path);\n const alreadyPublished =\n posix.dirname(path) === root && UPLOAD_FILE_ID_PATTERN.test(basename);\n const fileId = alreadyPublished\n ? basename\n : `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const target = this.#pathFor(scope, fileId);\n if (target !== path) {\n const moved = await sandbox.sandbox.executeCommand(\n `mv -- ${shellQuote(path)} ${shellQuote(target)}`,\n );\n if (moved.exitCode !== 0) {\n throw new Error(\n `publish_upload: could not move ${path}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`,\n );\n }\n }\n const href = `/session/${scope.sessionId}/uploads/${fileId}`;\n return {\n fileId,\n path: target,\n mediaType,\n name: name ?? basename,\n href,\n ...(this.#publicUrl === undefined\n ? {}\n : { url: `${this.#publicUrl}${href}` }),\n };\n }\n\n /**\n * Lists the turn's attachments for the model. The engine folds it into the\n * user message being saved and hands over that chat, so only files uploaded\n * for this chat by its owner are listed.\n */\n #attachedUploadsReminder() {\n return reminder(\n ({ currentMessage, chat }) => {\n if (currentMessage === undefined || chat === undefined) {\n throw new Error(\n 'uploads: the user reminder context must carry currentMessage and chat',\n );\n }\n const scope = this.#scopeFor({\n userId: chat.userId,\n sessionId: chat.id,\n });\n const attached = attachedUploads(currentMessage).filter(({ path }) =>\n isBelow(scope, path),\n );\n if (attached.length === 0) return '';\n return [\n 'The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.',\n ...attached.map(\n ({ path, name, mediaType, size }) =>\n `- ${path} (${name}, ${mediaType}, ${size} bytes)`,\n ),\n ].join('\\n');\n },\n { asPart: true },\n );\n }\n\n #sandboxFor(scope: UploadScope): Promise<ZukhrufSandbox> {\n if (this.#host === undefined) {\n throw new Error(\n 'uploads plugin must be initialized before storing or reading uploads',\n );\n }\n return this.#host.sandbox({\n chatId: scope.sessionId,\n userId: scope.userId,\n });\n }\n\n async #readFrom(\n sandbox: ZukhrufSandbox,\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n const extension = UPLOAD_FILE_ID_PATTERN.exec(fileId)?.[1];\n const mediaType =\n extension === undefined ? undefined : mediaTypeByExtension[extension];\n if (mediaType === undefined) return undefined;\n const path = this.#pathFor(scope, fileId);\n if (!(await sandbox.sandbox.exists(path))) return undefined;\n const bytes = await sandbox.sandbox.readFile(path, { encoding: 'binary' });\n return { data: new Uint8Array(bytes), mediaType };\n }\n\n /** `<directory>/<userId>/<sessionId>`; both identifiers must be one path segment. */\n #scopeFor({ userId, sessionId }: UploadScope): string {\n assertPathSegment('userId', userId);\n assertPathSegment('sessionId', sessionId);\n return posix.join(this.#directory, userId, sessionId);\n }\n\n #pathFor(scope: UploadScope, fileId: string): string {\n return posix.join(this.#scopeFor(scope), fileId);\n }\n}\n\nfunction normalizePublicUrl(publicUrl: string | undefined): string | undefined {\n if (publicUrl === undefined) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(publicUrl);\n } catch {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n return parsed.href.replace(/\\/+$/, '');\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction assertPathSegment(name: string, value: string): void {\n if (\n value.length === 0 ||\n value === '.' ||\n value === '..' ||\n value.includes('/')\n ) {\n throw new Error(\n `uploads: ${name} must be a single path segment, received \"${value}\"`,\n );\n }\n}\n\nfunction attachedUploads(message: UIMessage): AttachedUpload[] {\n if (!isRecord(message.metadata) || !Array.isArray(message.metadata.uploads)) {\n return [];\n }\n return message.metadata.uploads.filter(isAttachedUpload);\n}\n\nfunction isAttachedUpload(value: unknown): value is AttachedUpload {\n return (\n isRecord(value) &&\n typeof value.path === 'string' &&\n typeof value.name === 'string' &&\n typeof value.mediaType === 'string' &&\n typeof value.size === 'number'\n );\n}\n\n/** `path` is already normalized (no `.`/`..` segments) and names something below `scope`. */\nfunction isBelow(scope: string, path: string): boolean {\n return posix.normalize(path) === path && path.startsWith(`${scope}/`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"],
5
+ "mappings": ";AAAA,SAAS,aAAaA,yBAAwB;AAC9C,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACJd;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,YAAY;AACnC,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,YAAY,oBAAoB;AACzC,OAAOC,QAAO;AAEd,SAAS,sBAAsB;;;ACb/B,SAAS,SAAS,wBAAwB;AAE1C,SAAS,wBAAwB;AACjC,SAAS,iBAAAC,sBAAqB;AAC9B,OAAOC,QAAO;;;ACJd,SAAS,qBAAqB;AAC9B,OAAc;AAQd,eAAsB,MACpB,QACA,OACA;AACA,QAAM,SAAS,MAAM,OAAO,eAAe,KAAK;AAChD,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,SAGa,OAAO,MAAM,QAAQ,CAAC,WAAW;AAAA,MAClD,SAAS,MAAM;AAAA,MACf,MAAM,MAAM;AAAA,MACZ,MAAM,MAAM,KAAK,KA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AI;AACxB,MAAI,UAAU,MAAM,SAAS,GAAI,QAAO;AACxC,MAAI,UAAU,IAAI;AAChB,UAAM,SAAS,OAAO,IAAI;AAC1B,QAAI,WAAW,EAAG,QAAO;AACzB,WAAO,EAAE,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC,GAAG,KAAK,QAAQ,EAAE;AAAA,EAC9D;AACA,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM,MAAM,SAAS,KAAK,QAAQ,IAAI,KAAK,IAAI,OAAO,IAAI,GAAG,QAAQ,CAAC;AACtE,MAAI,QAAQ,OAAO,SAAS,MAAO,QAAO;AAC1C,SAAO,EAAE,OAAO,IAAI;AACtB;AAEA,SAAS,iBACP,SACA,OACO;AACP,UAAQ,OAAO,SAAS,KAAK;AAC7B,QAAM,IAAIA,eAAc,KAAK;AAAA,IAC3B,SAAS;AAAA,IACT,OAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ,8BAA8B,KAAK;AAAA,IAC7C;AAAA,EACF,CAAC;AACH;",
6
+ "names": ["parseContentType", "Hono", "HTTPException", "z", "HTTPException", "z", "HTTPException", "z", "HTTPException", "z", "HTTPException", "z", "z", "z", "sessionIdSchema", "z", "Hono", "HTTPException", "parseContentType"]
7
+ }
@@ -0,0 +1,73 @@
1
+ import type { AgentPluginDefinition, AgentPluginInstance } from '../../runtime/agent-runtime.ts';
2
+ declare const extensionByMediaType: {
3
+ readonly 'image/png': "png";
4
+ readonly 'image/jpeg': "jpg";
5
+ readonly 'image/webp': "webp";
6
+ readonly 'image/gif': "gif";
7
+ readonly 'image/heic': "heic";
8
+ readonly 'image/heif': "heif";
9
+ readonly 'video/mp4': "mp4";
10
+ readonly 'video/quicktime': "mov";
11
+ readonly 'audio/mpeg': "mp3";
12
+ readonly 'audio/mp4': "m4a";
13
+ readonly 'audio/wav': "wav";
14
+ };
15
+ export type UploadMediaType = keyof typeof extensionByMediaType;
16
+ export declare const UPLOAD_MEDIA_TYPES: readonly UploadMediaType[];
17
+ export interface UploadScope {
18
+ userId: string;
19
+ sessionId: string;
20
+ }
21
+ export interface StoredUpload {
22
+ data: Uint8Array<ArrayBuffer>;
23
+ mediaType: UploadMediaType;
24
+ }
25
+ export interface WrittenUpload {
26
+ fileId: string;
27
+ /** Absolute sandbox path of the stored file. */
28
+ path: string;
29
+ }
30
+ export interface PublishRequest {
31
+ /** Absolute sandbox path of a file below the session's uploads directory. */
32
+ path: string;
33
+ /** Display name for the user; defaults to the file's basename. */
34
+ name?: string;
35
+ }
36
+ export interface PublishedUpload extends WrittenUpload {
37
+ mediaType: UploadMediaType;
38
+ name: string;
39
+ /** `GET` route relative to the mounted `http()` app that serves the bytes. */
40
+ href: string;
41
+ /** Absolute URL when the plugin knows its public mount (`publicUrl`). */
42
+ url?: string;
43
+ }
44
+ export interface UploadsOptions {
45
+ /** Absolute sandbox directory that receives `<userId>/<sessionId>/<fileId>` files. */
46
+ directory: string;
47
+ /**
48
+ * Absolute URL where the host mounts `http(runtime, uploadsHttp(...))`, for
49
+ * example `http://127.0.0.1:4317/zukhruf/v1`. When set, `publish_upload`
50
+ * returns an absolute `url` the model can hand to the user verbatim.
51
+ */
52
+ publicUrl?: string;
53
+ }
54
+ export interface Uploads extends AgentPluginInstance {
55
+ /** Stores one file in the session's sandbox. */
56
+ write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;
57
+ read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;
58
+ /**
59
+ * Adopts a file the agent wrote below the session's uploads directory: it
60
+ * is renamed to a stable `<uuid>.<ext>` id so the `GET` route can serve it.
61
+ */
62
+ publish(scope: UploadScope, request: PublishRequest): Promise<PublishedUpload>;
63
+ }
64
+ export declare function isUploadMediaType(mediaType: string): mediaType is UploadMediaType;
65
+ /**
66
+ * Keep composer uploads (images, video, audio) in the conversation sandbox,
67
+ * tell the model where the files a turn attaches under
68
+ * `message.metadata.uploads` live, and let any agent in the tree publish a
69
+ * file it produced so the user can open or download it.
70
+ */
71
+ export declare function uploads({ directory, publicUrl, }: UploadsOptions): AgentPluginDefinition<Uploads>;
72
+ export {};
73
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/zukhruf/plugins/uploads/index.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,qBAAqB,EAErB,mBAAmB,EAEpB,MAAM,gCAAgC,CAAC;AAExC,QAAA,MAAM,oBAAoB;;;;;;;;;;;;CAYhB,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG,MAAM,OAAO,oBAAoB,CAAC;AAEhE,eAAO,MAAM,kBAAkB,EAE1B,SAAS,eAAe,EAAE,CAAC;AAkBhC,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IAC9B,SAAS,EAAE,eAAe,CAAC;CAC5B;AAED,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,cAAc;IAC7B,6EAA6E;IAC7E,IAAI,EAAE,MAAM,CAAC;IACb,kEAAkE;IAClE,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,eAAgB,SAAQ,aAAa;IACpD,SAAS,EAAE,eAAe,CAAC;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,8EAA8E;IAC9E,IAAI,EAAE,MAAM,CAAC;IACb,yEAAyE;IACzE,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAUD,MAAM,WAAW,cAAc;IAC7B,sFAAsF;IACtF,SAAS,EAAE,MAAM,CAAC;IAClB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,OAAQ,SAAQ,mBAAmB;IAClD,gDAAgD;IAChD,KAAK,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;IACxE,IAAI,CAAC,KAAK,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CAAC;IAC5E;;;OAGG;IACH,OAAO,CACL,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,eAAe,CAAC,CAAC;CAC7B;AAED,wBAAgB,iBAAiB,CAC/B,SAAS,EAAE,MAAM,GAChB,SAAS,IAAI,eAAe,CAE9B;AAED;;;;;GAKG;AACH,wBAAgB,OAAO,CAAC,EACtB,SAAS,EACT,SAAS,GACV,EAAE,cAAc,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAWjD"}
@@ -0,0 +1,247 @@
1
+ // packages/experimental/src/zukhruf/plugins/uploads/index.ts
2
+ import { tool } from "ai";
3
+ import { randomUUID } from "node:crypto";
4
+ import { posix } from "node:path";
5
+ import z from "zod";
6
+ import { reminder } from "@deepagents/context";
7
+ var extensionByMediaType = {
8
+ "image/png": "png",
9
+ "image/jpeg": "jpg",
10
+ "image/webp": "webp",
11
+ "image/gif": "gif",
12
+ "image/heic": "heic",
13
+ "image/heif": "heif",
14
+ "video/mp4": "mp4",
15
+ "video/quicktime": "mov",
16
+ "audio/mpeg": "mp3",
17
+ "audio/mp4": "m4a",
18
+ "audio/wav": "wav"
19
+ };
20
+ var UPLOAD_MEDIA_TYPES = Object.keys(
21
+ extensionByMediaType
22
+ );
23
+ var mediaTypeByExtension = {
24
+ ...Object.fromEntries(
25
+ Object.entries(extensionByMediaType).map(([mediaType, extension]) => [
26
+ extension,
27
+ mediaType
28
+ ])
29
+ ),
30
+ jpeg: "image/jpeg"
31
+ };
32
+ var UPLOAD_FILE_ID_PATTERN = new RegExp(
33
+ `^[0-9a-f-]{36}\\.(${Object.keys(mediaTypeByExtension).join("|")})$`
34
+ );
35
+ function isUploadMediaType(mediaType) {
36
+ return Object.hasOwn(extensionByMediaType, mediaType);
37
+ }
38
+ function uploads({
39
+ directory,
40
+ publicUrl
41
+ }) {
42
+ if (typeof directory !== "string" || !posix.isAbsolute(directory)) {
43
+ throw new Error(
44
+ `uploads: directory must be an absolute sandbox path, received ${JSON.stringify(directory)}`
45
+ );
46
+ }
47
+ const resolvedPublicUrl = normalizePublicUrl(publicUrl);
48
+ return {
49
+ name: "uploads",
50
+ create: () => new UploadsPlugin(directory, resolvedPublicUrl)
51
+ };
52
+ }
53
+ var publishInputSchema = z.object({
54
+ path: z.string().startsWith("/").describe(
55
+ "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)."
56
+ ),
57
+ name: z.string().min(1).optional().describe("Display name shown to the user; defaults to the file name.")
58
+ });
59
+ var UploadsPlugin = class {
60
+ #directory;
61
+ #publicUrl;
62
+ #host;
63
+ tools = {
64
+ publish_upload: tool({
65
+ description: "Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.",
66
+ inputSchema: publishInputSchema,
67
+ execute: (input, { context }) => this.publish(
68
+ { userId: context.conversation.userId, sessionId: context.treeId },
69
+ input
70
+ )
71
+ })
72
+ };
73
+ constructor(directory, publicUrl) {
74
+ this.#directory = directory;
75
+ this.#publicUrl = publicUrl;
76
+ }
77
+ configure(root) {
78
+ return {
79
+ ...root,
80
+ instructions: [...root.instructions, this.#attachedUploadsReminder()]
81
+ };
82
+ }
83
+ initialize(host) {
84
+ this.#host = host;
85
+ return Promise.resolve();
86
+ }
87
+ async write(scope, { data, mediaType }) {
88
+ const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;
89
+ const path = this.#pathFor(scope, fileId);
90
+ const sandbox = await this.#sandboxFor(scope);
91
+ await sandbox.sandbox.writeFiles([{ path, content: Buffer.from(data) }]);
92
+ return { fileId, path };
93
+ }
94
+ async read(scope, fileId) {
95
+ return this.#readFrom(await this.#sandboxFor(scope), scope, fileId);
96
+ }
97
+ async publish(scope, { path, name }) {
98
+ const root = this.#scopeFor(scope);
99
+ if (!isBelow(root, path)) {
100
+ throw new Error(
101
+ `publish_upload: ${path} is outside this session's uploads directory ${root}`
102
+ );
103
+ }
104
+ const extension = posix.extname(path).slice(1).toLowerCase();
105
+ const mediaType = mediaTypeByExtension[extension];
106
+ if (mediaType === void 0) {
107
+ throw new Error(
108
+ `publish_upload: unsupported file extension "${extension}"; publishable extensions are ${Object.keys(mediaTypeByExtension).join(", ")}`
109
+ );
110
+ }
111
+ const sandbox = await this.#sandboxFor(scope);
112
+ if (!await sandbox.sandbox.exists(path)) {
113
+ throw new Error(`publish_upload: ${path} does not exist in the sandbox`);
114
+ }
115
+ const basename = posix.basename(path);
116
+ const alreadyPublished = posix.dirname(path) === root && UPLOAD_FILE_ID_PATTERN.test(basename);
117
+ const fileId = alreadyPublished ? basename : `${randomUUID()}.${extensionByMediaType[mediaType]}`;
118
+ const target = this.#pathFor(scope, fileId);
119
+ if (target !== path) {
120
+ const moved = await sandbox.sandbox.executeCommand(
121
+ `mv -- ${shellQuote(path)} ${shellQuote(target)}`
122
+ );
123
+ if (moved.exitCode !== 0) {
124
+ throw new Error(
125
+ `publish_upload: could not move ${path}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`
126
+ );
127
+ }
128
+ }
129
+ const href = `/session/${scope.sessionId}/uploads/${fileId}`;
130
+ return {
131
+ fileId,
132
+ path: target,
133
+ mediaType,
134
+ name: name ?? basename,
135
+ href,
136
+ ...this.#publicUrl === void 0 ? {} : { url: `${this.#publicUrl}${href}` }
137
+ };
138
+ }
139
+ /**
140
+ * Lists the turn's attachments for the model. The engine folds it into the
141
+ * user message being saved and hands over that chat, so only files uploaded
142
+ * for this chat by its owner are listed.
143
+ */
144
+ #attachedUploadsReminder() {
145
+ return reminder(
146
+ ({ currentMessage, chat }) => {
147
+ if (currentMessage === void 0 || chat === void 0) {
148
+ throw new Error(
149
+ "uploads: the user reminder context must carry currentMessage and chat"
150
+ );
151
+ }
152
+ const scope = this.#scopeFor({
153
+ userId: chat.userId,
154
+ sessionId: chat.id
155
+ });
156
+ const attached = attachedUploads(currentMessage).filter(
157
+ ({ path }) => isBelow(scope, path)
158
+ );
159
+ if (attached.length === 0) return "";
160
+ return [
161
+ "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.",
162
+ ...attached.map(
163
+ ({ path, name, mediaType, size }) => `- ${path} (${name}, ${mediaType}, ${size} bytes)`
164
+ )
165
+ ].join("\n");
166
+ },
167
+ { asPart: true }
168
+ );
169
+ }
170
+ #sandboxFor(scope) {
171
+ if (this.#host === void 0) {
172
+ throw new Error(
173
+ "uploads plugin must be initialized before storing or reading uploads"
174
+ );
175
+ }
176
+ return this.#host.sandbox({
177
+ chatId: scope.sessionId,
178
+ userId: scope.userId
179
+ });
180
+ }
181
+ async #readFrom(sandbox, scope, fileId) {
182
+ const extension = UPLOAD_FILE_ID_PATTERN.exec(fileId)?.[1];
183
+ const mediaType = extension === void 0 ? void 0 : mediaTypeByExtension[extension];
184
+ if (mediaType === void 0) return void 0;
185
+ const path = this.#pathFor(scope, fileId);
186
+ if (!await sandbox.sandbox.exists(path)) return void 0;
187
+ const bytes = await sandbox.sandbox.readFile(path, { encoding: "binary" });
188
+ return { data: new Uint8Array(bytes), mediaType };
189
+ }
190
+ /** `<directory>/<userId>/<sessionId>`; both identifiers must be one path segment. */
191
+ #scopeFor({ userId, sessionId }) {
192
+ assertPathSegment("userId", userId);
193
+ assertPathSegment("sessionId", sessionId);
194
+ return posix.join(this.#directory, userId, sessionId);
195
+ }
196
+ #pathFor(scope, fileId) {
197
+ return posix.join(this.#scopeFor(scope), fileId);
198
+ }
199
+ };
200
+ function normalizePublicUrl(publicUrl) {
201
+ if (publicUrl === void 0) return void 0;
202
+ let parsed;
203
+ try {
204
+ parsed = new URL(publicUrl);
205
+ } catch {
206
+ throw new Error(
207
+ `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`
208
+ );
209
+ }
210
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
211
+ throw new Error(
212
+ `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`
213
+ );
214
+ }
215
+ return parsed.href.replace(/\/+$/, "");
216
+ }
217
+ function shellQuote(value) {
218
+ return `'${value.replaceAll("'", "'\\''")}'`;
219
+ }
220
+ function assertPathSegment(name, value) {
221
+ if (value.length === 0 || value === "." || value === ".." || value.includes("/")) {
222
+ throw new Error(
223
+ `uploads: ${name} must be a single path segment, received "${value}"`
224
+ );
225
+ }
226
+ }
227
+ function attachedUploads(message) {
228
+ if (!isRecord(message.metadata) || !Array.isArray(message.metadata.uploads)) {
229
+ return [];
230
+ }
231
+ return message.metadata.uploads.filter(isAttachedUpload);
232
+ }
233
+ function isAttachedUpload(value) {
234
+ return isRecord(value) && typeof value.path === "string" && typeof value.name === "string" && typeof value.mediaType === "string" && typeof value.size === "number";
235
+ }
236
+ function isBelow(scope, path) {
237
+ return posix.normalize(path) === path && path.startsWith(`${scope}/`);
238
+ }
239
+ function isRecord(value) {
240
+ return typeof value === "object" && value !== null && !Array.isArray(value);
241
+ }
242
+ export {
243
+ UPLOAD_MEDIA_TYPES,
244
+ isUploadMediaType,
245
+ uploads
246
+ };
247
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/zukhruf/plugins/uploads/index.ts"],
4
+ "sourcesContent": ["import { type UIMessage, tool } from 'ai';\nimport { randomUUID } from 'node:crypto';\nimport { posix } from 'node:path';\nimport z from 'zod';\n\nimport { reminder } from '@deepagents/context';\n\nimport type { AgentDeclaration, ZukhrufSandbox } from '../../agent.ts';\nimport type {\n AgentPluginDefinition,\n AgentPluginHost,\n AgentPluginInstance,\n AgentPluginToolContext,\n} from '../../runtime/agent-runtime.ts';\n\nconst extensionByMediaType = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/webp': 'webp',\n 'image/gif': 'gif',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'video/mp4': 'mp4',\n 'video/quicktime': 'mov',\n 'audio/mpeg': 'mp3',\n 'audio/mp4': 'm4a',\n 'audio/wav': 'wav',\n} as const;\n\nexport type UploadMediaType = keyof typeof extensionByMediaType;\n\nexport const UPLOAD_MEDIA_TYPES = Object.keys(\n extensionByMediaType,\n) as readonly UploadMediaType[];\n\n/** Every extension the store writes, plus the `jpeg` spelling it accepts on read. */\nconst mediaTypeByExtension: Readonly<Record<string, UploadMediaType>> = {\n ...Object.fromEntries(\n Object.entries(extensionByMediaType).map(([mediaType, extension]) => [\n extension,\n mediaType,\n ]),\n ),\n jpeg: 'image/jpeg',\n};\n\n/** `<uuid>.<ext>` is the only file name this store writes or reads. */\nconst UPLOAD_FILE_ID_PATTERN = new RegExp(\n `^[0-9a-f-]{36}\\\\.(${Object.keys(mediaTypeByExtension).join('|')})$`,\n);\n\nexport interface UploadScope {\n userId: string;\n sessionId: string;\n}\n\nexport interface StoredUpload {\n data: Uint8Array<ArrayBuffer>;\n mediaType: UploadMediaType;\n}\n\nexport interface WrittenUpload {\n fileId: string;\n /** Absolute sandbox path of the stored file. */\n path: string;\n}\n\nexport interface PublishRequest {\n /** Absolute sandbox path of a file below the session's uploads directory. */\n path: string;\n /** Display name for the user; defaults to the file's basename. */\n name?: string;\n}\n\nexport interface PublishedUpload extends WrittenUpload {\n mediaType: UploadMediaType;\n name: string;\n /** `GET` route relative to the mounted `http()` app that serves the bytes. */\n href: string;\n /** Absolute URL when the plugin knows its public mount (`publicUrl`). */\n url?: string;\n}\n\n/** One entry of `message.metadata.uploads`: the upload receipt the composer sends back. */\ninterface AttachedUpload {\n path: string;\n name: string;\n mediaType: string;\n size: number;\n}\n\nexport interface UploadsOptions {\n /** Absolute sandbox directory that receives `<userId>/<sessionId>/<fileId>` files. */\n directory: string;\n /**\n * Absolute URL where the host mounts `http(runtime, uploadsHttp(...))`, for\n * example `http://127.0.0.1:4317/zukhruf/v1`. When set, `publish_upload`\n * returns an absolute `url` the model can hand to the user verbatim.\n */\n publicUrl?: string;\n}\n\nexport interface Uploads extends AgentPluginInstance {\n /** Stores one file in the session's sandbox. */\n write(scope: UploadScope, upload: StoredUpload): Promise<WrittenUpload>;\n read(scope: UploadScope, fileId: string): Promise<StoredUpload | undefined>;\n /**\n * Adopts a file the agent wrote below the session's uploads directory: it\n * is renamed to a stable `<uuid>.<ext>` id so the `GET` route can serve it.\n */\n publish(\n scope: UploadScope,\n request: PublishRequest,\n ): Promise<PublishedUpload>;\n}\n\nexport function isUploadMediaType(\n mediaType: string,\n): mediaType is UploadMediaType {\n return Object.hasOwn(extensionByMediaType, mediaType);\n}\n\n/**\n * Keep composer uploads (images, video, audio) in the conversation sandbox,\n * tell the model where the files a turn attaches under\n * `message.metadata.uploads` live, and let any agent in the tree publish a\n * file it produced so the user can open or download it.\n */\nexport function uploads({\n directory,\n publicUrl,\n}: UploadsOptions): AgentPluginDefinition<Uploads> {\n if (typeof directory !== 'string' || !posix.isAbsolute(directory)) {\n throw new Error(\n `uploads: directory must be an absolute sandbox path, received ${JSON.stringify(directory)}`,\n );\n }\n const resolvedPublicUrl = normalizePublicUrl(publicUrl);\n return {\n name: 'uploads',\n create: () => new UploadsPlugin(directory, resolvedPublicUrl),\n };\n}\n\nconst publishInputSchema = z.object({\n path: z\n .string()\n .startsWith('/')\n .describe(\n \"Absolute sandbox path of the file to publish; it must be inside this session's uploads directory (the directory the attached files live in, subdirectories included).\",\n ),\n name: z\n .string()\n .min(1)\n .optional()\n .describe('Display name shown to the user; defaults to the file name.'),\n});\n\nclass UploadsPlugin implements Uploads {\n readonly #directory: string;\n readonly #publicUrl: string | undefined;\n #host: AgentPluginHost | undefined;\n\n readonly tools = {\n publish_upload: tool<\n z.infer<typeof publishInputSchema>,\n PublishedUpload,\n AgentPluginToolContext\n >({\n description:\n \"Publish a file you produced in the sandbox so the user can open or download it. The path must be inside this session's uploads directory; the file is renamed to a stable id and the returned url (or href relative to the API) is what the user opens.\",\n inputSchema: publishInputSchema,\n execute: (input, { context }) =>\n this.publish(\n { userId: context.conversation.userId, sessionId: context.treeId },\n input,\n ),\n }),\n };\n\n constructor(directory: string, publicUrl: string | undefined) {\n this.#directory = directory;\n this.#publicUrl = publicUrl;\n }\n\n configure(root: AgentDeclaration): AgentDeclaration {\n return {\n ...root,\n instructions: [...root.instructions, this.#attachedUploadsReminder()],\n };\n }\n\n initialize(host: AgentPluginHost): Promise<void> {\n this.#host = host;\n return Promise.resolve();\n }\n\n async write(\n scope: UploadScope,\n { data, mediaType }: StoredUpload,\n ): Promise<WrittenUpload> {\n const fileId = `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const path = this.#pathFor(scope, fileId);\n const sandbox = await this.#sandboxFor(scope);\n await sandbox.sandbox.writeFiles([{ path, content: Buffer.from(data) }]);\n return { fileId, path };\n }\n\n async read(\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n return this.#readFrom(await this.#sandboxFor(scope), scope, fileId);\n }\n\n async publish(\n scope: UploadScope,\n { path, name }: PublishRequest,\n ): Promise<PublishedUpload> {\n const root = this.#scopeFor(scope);\n if (!isBelow(root, path)) {\n throw new Error(\n `publish_upload: ${path} is outside this session's uploads directory ${root}`,\n );\n }\n const extension = posix.extname(path).slice(1).toLowerCase();\n const mediaType = mediaTypeByExtension[extension];\n if (mediaType === undefined) {\n throw new Error(\n `publish_upload: unsupported file extension \"${extension}\"; publishable extensions are ${Object.keys(mediaTypeByExtension).join(', ')}`,\n );\n }\n const sandbox = await this.#sandboxFor(scope);\n if (!(await sandbox.sandbox.exists(path))) {\n throw new Error(`publish_upload: ${path} does not exist in the sandbox`);\n }\n const basename = posix.basename(path);\n const alreadyPublished =\n posix.dirname(path) === root && UPLOAD_FILE_ID_PATTERN.test(basename);\n const fileId = alreadyPublished\n ? basename\n : `${randomUUID()}.${extensionByMediaType[mediaType]}`;\n const target = this.#pathFor(scope, fileId);\n if (target !== path) {\n const moved = await sandbox.sandbox.executeCommand(\n `mv -- ${shellQuote(path)} ${shellQuote(target)}`,\n );\n if (moved.exitCode !== 0) {\n throw new Error(\n `publish_upload: could not move ${path}: ${moved.stderr.trim() || `exit ${moved.exitCode}`}`,\n );\n }\n }\n const href = `/session/${scope.sessionId}/uploads/${fileId}`;\n return {\n fileId,\n path: target,\n mediaType,\n name: name ?? basename,\n href,\n ...(this.#publicUrl === undefined\n ? {}\n : { url: `${this.#publicUrl}${href}` }),\n };\n }\n\n /**\n * Lists the turn's attachments for the model. The engine folds it into the\n * user message being saved and hands over that chat, so only files uploaded\n * for this chat by its owner are listed.\n */\n #attachedUploadsReminder() {\n return reminder(\n ({ currentMessage, chat }) => {\n if (currentMessage === undefined || chat === undefined) {\n throw new Error(\n 'uploads: the user reminder context must carry currentMessage and chat',\n );\n }\n const scope = this.#scopeFor({\n userId: chat.userId,\n sessionId: chat.id,\n });\n const attached = attachedUploads(currentMessage).filter(({ path }) =>\n isBelow(scope, path),\n );\n if (attached.length === 0) return '';\n return [\n 'The user attached the files listed below for this turn; read images by path with the readFile tool when needed (convert HEIC and extract video frames with sandbox commands first), and [Image #N], [Video #N], or [Audio #N] in the message refers to the Nth listed file.',\n ...attached.map(\n ({ path, name, mediaType, size }) =>\n `- ${path} (${name}, ${mediaType}, ${size} bytes)`,\n ),\n ].join('\\n');\n },\n { asPart: true },\n );\n }\n\n #sandboxFor(scope: UploadScope): Promise<ZukhrufSandbox> {\n if (this.#host === undefined) {\n throw new Error(\n 'uploads plugin must be initialized before storing or reading uploads',\n );\n }\n return this.#host.sandbox({\n chatId: scope.sessionId,\n userId: scope.userId,\n });\n }\n\n async #readFrom(\n sandbox: ZukhrufSandbox,\n scope: UploadScope,\n fileId: string,\n ): Promise<StoredUpload | undefined> {\n const extension = UPLOAD_FILE_ID_PATTERN.exec(fileId)?.[1];\n const mediaType =\n extension === undefined ? undefined : mediaTypeByExtension[extension];\n if (mediaType === undefined) return undefined;\n const path = this.#pathFor(scope, fileId);\n if (!(await sandbox.sandbox.exists(path))) return undefined;\n const bytes = await sandbox.sandbox.readFile(path, { encoding: 'binary' });\n return { data: new Uint8Array(bytes), mediaType };\n }\n\n /** `<directory>/<userId>/<sessionId>`; both identifiers must be one path segment. */\n #scopeFor({ userId, sessionId }: UploadScope): string {\n assertPathSegment('userId', userId);\n assertPathSegment('sessionId', sessionId);\n return posix.join(this.#directory, userId, sessionId);\n }\n\n #pathFor(scope: UploadScope, fileId: string): string {\n return posix.join(this.#scopeFor(scope), fileId);\n }\n}\n\nfunction normalizePublicUrl(publicUrl: string | undefined): string | undefined {\n if (publicUrl === undefined) return undefined;\n let parsed: URL;\n try {\n parsed = new URL(publicUrl);\n } catch {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(\n `uploads: publicUrl must be an absolute http(s) URL, received ${JSON.stringify(publicUrl)}`,\n );\n }\n return parsed.href.replace(/\\/+$/, '');\n}\n\nfunction shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n}\n\nfunction assertPathSegment(name: string, value: string): void {\n if (\n value.length === 0 ||\n value === '.' ||\n value === '..' ||\n value.includes('/')\n ) {\n throw new Error(\n `uploads: ${name} must be a single path segment, received \"${value}\"`,\n );\n }\n}\n\nfunction attachedUploads(message: UIMessage): AttachedUpload[] {\n if (!isRecord(message.metadata) || !Array.isArray(message.metadata.uploads)) {\n return [];\n }\n return message.metadata.uploads.filter(isAttachedUpload);\n}\n\nfunction isAttachedUpload(value: unknown): value is AttachedUpload {\n return (\n isRecord(value) &&\n typeof value.path === 'string' &&\n typeof value.name === 'string' &&\n typeof value.mediaType === 'string' &&\n typeof value.size === 'number'\n );\n}\n\n/** `path` is already normalized (no `.`/`..` segments) and names something below `scope`. */\nfunction isBelow(scope: string, path: string): boolean {\n return posix.normalize(path) === path && path.startsWith(`${scope}/`);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n"],
5
+ "mappings": ";AAAA,SAAyB,YAAY;AACrC,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,OAAO,OAAO;AAEd,SAAS,gBAAgB;AAUzB,IAAM,uBAAuB;AAAA,EAC3B,aAAa;AAAA,EACb,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,cAAc;AAAA,EACd,cAAc;AAAA,EACd,aAAa;AAAA,EACb,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,aAAa;AAAA,EACb,aAAa;AACf;AAIO,IAAM,qBAAqB,OAAO;AAAA,EACvC;AACF;AAGA,IAAM,uBAAkE;AAAA,EACtE,GAAG,OAAO;AAAA,IACR,OAAO,QAAQ,oBAAoB,EAAE,IAAI,CAAC,CAAC,WAAW,SAAS,MAAM;AAAA,MACnE;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EACA,MAAM;AACR;AAGA,IAAM,yBAAyB,IAAI;AAAA,EACjC,qBAAqB,OAAO,KAAK,oBAAoB,EAAE,KAAK,GAAG,CAAC;AAClE;AAmEO,SAAS,kBACd,WAC8B;AAC9B,SAAO,OAAO,OAAO,sBAAsB,SAAS;AACtD;AAQO,SAAS,QAAQ;AAAA,EACtB;AAAA,EACA;AACF,GAAmD;AACjD,MAAI,OAAO,cAAc,YAAY,CAAC,MAAM,WAAW,SAAS,GAAG;AACjE,UAAM,IAAI;AAAA,MACR,iEAAiE,KAAK,UAAU,SAAS,CAAC;AAAA,IAC5F;AAAA,EACF;AACA,QAAM,oBAAoB,mBAAmB,SAAS;AACtD,SAAO;AAAA,IACL,MAAM;AAAA,IACN,QAAQ,MAAM,IAA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AAA,EACF;AACF;AAEA,SAAS,gBAAgB,SAAsC;AAC7D,MAAI,CAAC,SAAS,QAAQ,QAAQ,KAAK,CAAC,MAAM,QAAQ,QAAQ,SAAS,OAAO,GAAG;AAC3E,WAAO,CAAC;AAAA,EACV;AACA,SAAO,QAAQ,SAAS,QAAQ,OAAO,gBAAgB;AACzD;AAEA,SAAS,iBAAiB,OAAyC;AACjE,SACE,SAAS,KAAK,KACd,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,SAAS,YACtB,OAAO,MAAM,cAAc,YAC3B,OAAO,MAAM,SAAS;AAE1B;AAGA,SAAS,QAAQ,OAAe,MAAuB;AACrD,SAAO,MAAM,UAAU,IAAI,MAAM,QAAQ,KAAK,WAAW,GAAG,KAAK,GAAG;AACtE;AAEA,SAAS,SAAS,OAAkD;AAClE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;",
6
+ "names": []
7
+ }
@@ -0,0 +1,10 @@
1
+ import type { PgBoss } from 'pg-boss';
2
+ export type PgBossNotification<Value> = {
3
+ type: 'change';
4
+ value: Value;
5
+ } | {
6
+ type: 'reset';
7
+ };
8
+ /** A LISTEN subscription that is live before it is returned. */
9
+ export declare function pgBossNotifications<Value>(boss: PgBoss, channel: string, parse: (payload: string) => Value | undefined, signal: AbortSignal): Promise<AsyncIterable<PgBossNotification<Value>>>;
10
+ //# sourceMappingURL=pg-boss-notifications.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pg-boss-notifications.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/pg-boss-notifications.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AAEtC,MAAM,MAAM,kBAAkB,CAAC,KAAK,IAClC;IAAE,IAAI,EAAE,QAAQ,CAAC;IAAC,KAAK,EAAE,KAAK,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,CAAC;AAEvD,gEAAgE;AAChE,wBAAsB,mBAAmB,CAAC,KAAK,EAC7C,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,KAAK,GAAG,SAAS,EAC7C,MAAM,EAAE,WAAW,GAClB,OAAO,CAAC,aAAa,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC,CAAC,CAwCnD"}
@@ -1,5 +1,5 @@
1
1
  import type { PgBoss } from 'pg-boss';
2
- import { type ConsumeContext, type ConsumeOptions, type TurnActivity, type TurnPushResult, TurnQueue, type TurnRef } from './turn-queue.ts';
2
+ import { type ConsumeContext, type ConsumeOptions, type TurnActivity, TurnQueue, type TurnRef } from './turn-queue.ts';
3
3
  export interface PgBossTurnQueueOptions {
4
4
  queue?: string;
5
5
  /** Required for custom DB adapters; must match the PgBoss schema. */
@@ -13,12 +13,10 @@ export interface PgBossTurnQueueOptions {
13
13
  /**
14
14
  * TurnQueue on pg-boss.
15
15
  *
16
- * - `key_strict_fifo` policy with `singletonKey = chatId` gives the per-chat
17
- * serialization contract structurally: one active turn per chat and strict
18
- * push order.
19
- * - `group.id = chatId` with global `groupConcurrency: 1` excludes an active
20
- * chat before pg-boss selects the next job, so its queued successor cannot
21
- * block ready turns from other chats.
16
+ * - `key_strict_fifo` policy with `singletonKey = chatId` expresses the
17
+ * per-chat serialization contract: one active turn per chat and strict push
18
+ * order. An active/retrying/failed key blocks only its own successors, so
19
+ * ready turns from other chats remain fetchable.
22
20
  * - `retryLimit: 0` — a crashed turn is never silently re-run (its bash
23
21
  * already executed). It dead-letters instead.
24
22
  * - A failed job blocks its chat's key until acknowledged; the dead-letter
@@ -29,9 +27,8 @@ export interface PgBossTurnQueueOptions {
29
27
  * awaits its approval for as long as it takes, with no retention deadline.
30
28
  * Cleanup is commit-driven instead — `consume` deletes a job the moment its
31
29
  * turn runs and commits to the chain — so completed jobs don't accumulate.
32
- * (`retentionSeconds`, which governs still-`created` jobs, can't be 0; its
33
- * default 14d is never approached because a queued turn only waits behind one
34
- * running turn.)
30
+ * (`retentionSeconds`, which governs still-`created` jobs, can't be 0; the
31
+ * remaining deep-backlog orphan case is tracked for startup reconciliation.)
35
32
  * - Interrupting an active turn aborts the adapter-local handler but leaves its
36
33
  * pg-boss row `active` until that handler exits. Cancelling the row itself
37
34
  * would surrender the strict-FIFO key early and let the successor overlap.
@@ -46,7 +43,7 @@ export declare class PgBossTurnQueue extends TurnQueue {
46
43
  get queue(): string;
47
44
  get deadLetterQueue(): string;
48
45
  initialize(): Promise<void>;
49
- push(turn: TurnRef): Promise<TurnPushResult>;
46
+ push(turn: TurnRef): Promise<void>;
50
47
  getTurnActivity(conversation: Pick<TurnRef, 'chatId' | 'userId'>): Promise<TurnActivity>;
51
48
  getCurrentTurn(conversation: Pick<TurnRef, 'chatId' | 'userId'>): Promise<TurnRef | undefined>;
52
49
  cancel(streamId: string): Promise<void>;
@@ -1 +1 @@
1
- {"version":3,"file":"pg-boss.turn-queue.d.ts","sourceRoot":"","sources":["../../../src/zukhruf/queue/pg-boss.turn-queue.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAmB,MAAM,EAAE,MAAM,SAAS,CAAC;AAIvD,OAAO,EACL,KAAK,cAAc,EACnB,KAAK,cAAc,EACnB,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,SAAS,EACT,KAAK,OAAO,EACb,MAAM,iBAAiB,CAAC;AAEzB,MAAM,WAAW,sBAAsB;IACrC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,qEAAqE;IACrE,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,wEAAwE;IACxE,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC;AAID;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,qBAAa,eAAgB,SAAQ,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