@deepagents/experimental 7.1.1 → 7.1.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.
Files changed (41) hide show
  1. package/README.md +0 -1
  2. package/dist/index.js +183 -224
  3. package/dist/index.js.map +4 -4
  4. package/dist/providers/account-tokens.d.ts.map +1 -1
  5. package/dist/providers/claude/index.js +59 -51
  6. package/dist/providers/claude/index.js.map +2 -2
  7. package/dist/providers/claude/local-credentials.d.ts +1 -1
  8. package/dist/providers/claude/local-credentials.d.ts.map +1 -1
  9. package/dist/providers/codex/index.js +57 -49
  10. package/dist/providers/codex/index.js.map +2 -2
  11. package/dist/providers/codex/local-credentials.d.ts +1 -1
  12. package/dist/providers/codex/local-credentials.d.ts.map +1 -1
  13. package/dist/zukhruf/index.d.ts +0 -1
  14. package/dist/zukhruf/index.d.ts.map +1 -1
  15. package/dist/zukhruf/index.js +183 -224
  16. package/dist/zukhruf/index.js.map +4 -4
  17. package/dist/zukhruf/mailbox/coordinator.d.ts.map +1 -1
  18. package/dist/zukhruf/mailbox/sqlite.store.d.ts.map +1 -1
  19. package/dist/zukhruf/plugins/conversation-scheduling/index.js +12 -0
  20. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +3 -3
  21. package/dist/zukhruf/plugins/http/index.d.ts.map +1 -1
  22. package/dist/zukhruf/plugins/http/index.js +20 -164
  23. package/dist/zukhruf/plugins/http/index.js.map +4 -4
  24. package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -1
  25. package/dist/zukhruf/plugins/schedules/http.js +37 -180
  26. package/dist/zukhruf/plugins/schedules/http.js.map +4 -4
  27. package/dist/zukhruf/plugins/schedules/index.js +12 -0
  28. package/dist/zukhruf/plugins/schedules/index.js.map +3 -3
  29. package/dist/zukhruf/plugins/uploads/http.d.ts.map +1 -1
  30. package/dist/zukhruf/plugins/uploads/http.js +30 -173
  31. package/dist/zukhruf/plugins/uploads/http.js.map +4 -4
  32. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +6 -2
  33. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  34. package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -1
  35. package/package.json +20 -5
  36. package/dist/zukhruf/plugins/http/parse.d.ts +0 -3
  37. package/dist/zukhruf/plugins/http/parse.d.ts.map +0 -1
  38. package/dist/zukhruf/plugins/http/validator.d.ts +0 -34
  39. package/dist/zukhruf/plugins/http/validator.d.ts.map +0 -1
  40. package/dist/zukhruf/render-turn.d.ts +0 -9
  41. package/dist/zukhruf/render-turn.d.ts.map +0 -1
@@ -1,167 +1,24 @@
1
1
  // packages/experimental/src/zukhruf/plugins/schedules/http.ts
2
+ import { validate as validate2 } from "@sdk-it/hono/runtime";
2
3
  import { Hono as Hono2 } from "hono";
3
4
  import { bodyLimit } from "hono/body-limit";
4
- import { HTTPException as HTTPException4 } from "hono/http-exception";
5
+ import { HTTPException as HTTPException2 } from "hono/http-exception";
5
6
  import { validate as validateUuid2 } from "uuid";
6
- import z4 from "zod";
7
+ import z2 from "zod";
7
8
 
8
9
  // packages/experimental/src/zukhruf/plugins/http/index.ts
10
+ import { validate } from "@sdk-it/hono/runtime";
9
11
  import {
10
12
  createUIMessageStreamResponse,
11
13
  safeValidateUIMessages
12
14
  } from "ai";
13
15
  import { Hono } from "hono";
14
- import { HTTPException as HTTPException3 } from "hono/http-exception";
16
+ import { HTTPException } from "hono/http-exception";
15
17
  import { basePath } from "hono/route";
16
18
  import { streamSSE } from "hono/streaming";
17
19
  import { validate as validateUuid } from "uuid";
18
- import z3 from "zod";
20
+ import z from "zod";
19
21
  import { elementsSchema } from "@deepagents/elements";
20
-
21
- // packages/experimental/src/zukhruf/plugins/http/validator.ts
22
- import { parse as parseContentType } from "fast-content-type-parse";
23
- import { createMiddleware } from "hono/factory";
24
- import { HTTPException as HTTPException2 } from "hono/http-exception";
25
- import z2 from "zod";
26
-
27
- // packages/experimental/src/zukhruf/plugins/http/parse.ts
28
- import { HTTPException } from "hono/http-exception";
29
- import "zod";
30
- async function parse(schema, input) {
31
- const result = await schema.safeParseAsync(input);
32
- if (!result.success) {
33
- const errors = result.error.flatten((issue) => ({
34
- message: issue.message,
35
- code: issue.code,
36
- path: issue.path.join(".")
37
- })).fieldErrors;
38
- throw new HTTPException(400, {
39
- message: "Validation failed",
40
- cause: {
41
- code: "api/validation-failed",
42
- detail: "The input data is invalid",
43
- errors
44
- }
45
- });
46
- }
47
- return result.data;
48
- }
49
-
50
- // packages/experimental/src/zukhruf/plugins/http/validator.ts
51
- function inputSchema(config) {
52
- const shape = Object.fromEntries(
53
- Object.entries(config).map(([key, { against }]) => [key, against])
54
- );
55
- assertInputShape(shape, config);
56
- return z2.object(shape);
57
- }
58
- function assertInputShape(shape, config) {
59
- const keys = Object.keys(config);
60
- if (Object.keys(shape).length !== keys.length || keys.some((key) => shape[key] !== config[key]?.against)) {
61
- throw new Error("The input schema does not match its selectors");
62
- }
63
- }
64
- function validate(expectedContentTypeOrSelector, selector) {
65
- const expectedContentType = typeof expectedContentTypeOrSelector === "string" ? expectedContentTypeOrSelector : void 0;
66
- const _selector = typeof expectedContentTypeOrSelector === "function" ? expectedContentTypeOrSelector : selector;
67
- void _selector;
68
- if (!_selector) {
69
- throw new Error("Selector function is required");
70
- }
71
- return createMiddleware(async (c, next) => {
72
- const ct = c.req.header("content-type");
73
- if (c.req.method === "GET" && ct) {
74
- throw new HTTPException2(415, {
75
- message: "Unsupported Media Type",
76
- cause: {
77
- code: "api/unsupported-media-type",
78
- detail: `GET requests cannot have a content type header`
79
- }
80
- });
81
- }
82
- if (expectedContentType) {
83
- void verifyContentType(ct, expectedContentType);
84
- }
85
- const contentType = ct ? parseContentType(ct) : null;
86
- let body = null;
87
- switch (contentType?.type) {
88
- case "application/json":
89
- body = await parseJson(c);
90
- break;
91
- case "application/x-www-form-urlencoded":
92
- case "multipart/form-data":
93
- body = await c.req.parseBody();
94
- break;
95
- default:
96
- body = {};
97
- }
98
- const payload = {
99
- body,
100
- query: parseQueryParams(c.req.query()),
101
- queries: parseQueriesParams(c.req.queries()),
102
- params: c.req.param(),
103
- headers: c.req.header()
104
- };
105
- const config = _selector(payload);
106
- const input = Object.fromEntries(
107
- Object.entries(config).map(([key, { select }]) => [key, select])
108
- );
109
- c.set("input", await parse(inputSchema(config), input));
110
- await next();
111
- });
112
- }
113
- function verifyContentType(actual, expected) {
114
- if (!actual) {
115
- throw new HTTPException2(415, {
116
- message: "Unsupported Media Type",
117
- cause: {
118
- code: "api/unsupported-media-type",
119
- detail: "Missing content type header"
120
- }
121
- });
122
- }
123
- const { type: incomingContentType } = parseContentType(actual);
124
- if (incomingContentType !== expected) {
125
- throw new HTTPException2(415, {
126
- message: "Unsupported Media Type",
127
- cause: {
128
- code: "api/unsupported-media-type",
129
- detail: `Expected content type: ${expected}, but got: ${incomingContentType}`
130
- }
131
- });
132
- }
133
- }
134
- async function parseJson(context) {
135
- try {
136
- return await context.req.json();
137
- } catch (error) {
138
- throw new HTTPException2(400, {
139
- message: "The request body is not valid JSON",
140
- cause: {
141
- code: "api/invalid-json",
142
- detail: error instanceof Error ? error.message : String(error)
143
- }
144
- });
145
- }
146
- }
147
- function parseQueryParams(queryParams) {
148
- return Object.fromEntries(
149
- Object.entries(queryParams).map(([key, value]) => [
150
- key,
151
- value === "null" ? null : value
152
- ])
153
- );
154
- }
155
- function parseQueriesParams(queriesParams) {
156
- return Object.fromEntries(
157
- Object.entries(queriesParams).map(([key, values]) => [
158
- key,
159
- values.map((value) => value === "null" ? null : value)
160
- ])
161
- );
162
- }
163
-
164
- // packages/experimental/src/zukhruf/plugins/http/index.ts
165
22
  function projectHttp(definition, project) {
166
23
  return {
167
24
  project(runtime) {
@@ -169,21 +26,21 @@ function projectHttp(definition, project) {
169
26
  }
170
27
  };
171
28
  }
172
- var sessionIdSchema = z3.string().refine(validateUuid);
173
- var jsonSchema = z3.custom(
29
+ var sessionIdSchema = z.string().refine(validateUuid);
30
+ var jsonSchema = z.custom(
174
31
  (value) => typeof value === "object" && value !== null && !Array.isArray(value)
175
32
  );
176
- var clientToolsSchema = z3.record(
177
- z3.string().min(1),
178
- z3.strictObject({
33
+ var clientToolsSchema = z.record(
34
+ z.string().min(1),
35
+ z.strictObject({
179
36
  inputSchema: jsonSchema,
180
- description: z3.string().min(1)
37
+ description: z.string().min(1)
181
38
  })
182
39
  ).optional();
183
- var turnBodySchema = z3.strictObject({
40
+ var turnBodySchema = z.strictObject({
184
41
  sessionId: sessionIdSchema,
185
- message: z3.unknown(),
186
- trigger: z3.enum(["submit-message", "regenerate-message"]),
42
+ message: z.unknown(),
43
+ trigger: z.enum(["submit-message", "regenerate-message"]),
187
44
  tools: clientToolsSchema,
188
45
  elements: elementsSchema
189
46
  });
@@ -204,24 +61,24 @@ var MAX_TIMEZONE_LENGTH = 100;
204
61
  var MAX_CHAT_ID_LENGTH = 200;
205
62
  var MAX_IDEMPOTENCY_KEY_LENGTH = 200;
206
63
  var NO_STORE = { "cache-control": "no-store" };
207
- var scheduleIdSchema = z4.string().refine(validateUuid2);
208
- var idempotencyKeySchema = z4.string().trim().min(1).max(MAX_IDEMPOTENCY_KEY_LENGTH);
209
- var targetSchema = z4.discriminatedUnion("kind", [
210
- z4.strictObject({ kind: z4.literal("new-conversation") }),
211
- z4.strictObject({
212
- kind: z4.literal("existing-conversation"),
213
- chatId: z4.string().trim().min(1).max(MAX_CHAT_ID_LENGTH)
64
+ var scheduleIdSchema = z2.string().refine(validateUuid2);
65
+ var idempotencyKeySchema = z2.string().trim().min(1).max(MAX_IDEMPOTENCY_KEY_LENGTH);
66
+ var targetSchema = z2.discriminatedUnion("kind", [
67
+ z2.strictObject({ kind: z2.literal("new-conversation") }),
68
+ z2.strictObject({
69
+ kind: z2.literal("existing-conversation"),
70
+ chatId: z2.string().trim().min(1).max(MAX_CHAT_ID_LENGTH)
214
71
  })
215
72
  ]);
216
73
  var definitionSchema = {
217
- name: z4.string().trim().min(1).max(MAX_NAME_LENGTH),
218
- prompt: z4.string().trim().min(1).max(MAX_PROMPT_LENGTH),
219
- recurrence: z4.string().trim().min(1).max(MAX_RECURRENCE_LENGTH),
220
- timezone: z4.string().trim().min(1).max(MAX_TIMEZONE_LENGTH),
74
+ name: z2.string().trim().min(1).max(MAX_NAME_LENGTH),
75
+ prompt: z2.string().trim().min(1).max(MAX_PROMPT_LENGTH),
76
+ recurrence: z2.string().trim().min(1).max(MAX_RECURRENCE_LENGTH),
77
+ timezone: z2.string().trim().min(1).max(MAX_TIMEZONE_LENGTH),
221
78
  target: targetSchema
222
79
  };
223
- var createBodySchema = z4.strictObject(definitionSchema);
224
- var updateBodySchema = z4.strictObject({
80
+ var createBodySchema = z2.strictObject(definitionSchema);
81
+ var updateBodySchema = z2.strictObject({
225
82
  name: definitionSchema.name.optional(),
226
83
  prompt: definitionSchema.prompt.optional(),
227
84
  recurrence: definitionSchema.recurrence.optional(),
@@ -233,7 +90,7 @@ var updateBodySchema = z4.strictObject({
233
90
  var limitBody = bodyLimit({
234
91
  maxSize: MAX_BODY_BYTES,
235
92
  onError: () => {
236
- throw new HTTPException4(413, {
93
+ throw new HTTPException2(413, {
237
94
  message: "Request body is too large",
238
95
  cause: {
239
96
  code: "api/payload-too-large",
@@ -262,7 +119,7 @@ function scheduleRoutes(schedules) {
262
119
  app.post(
263
120
  TASKS_PATH,
264
121
  limitBody,
265
- validate("application/json", (payload) => ({
122
+ validate2("application/json", (payload) => ({
266
123
  body: { select: payload.body, against: createBodySchema },
267
124
  idempotencyKey: {
268
125
  select: payload.headers["idempotency-key"],
@@ -324,7 +181,7 @@ function scheduleRoutes(schedules) {
324
181
  }
325
182
  app.post(
326
183
  `${TASK_PATH}/run`,
327
- validate((payload) => ({
184
+ validate2((payload) => ({
328
185
  taskId: { select: payload.params.taskId, against: scheduleIdSchema },
329
186
  idempotencyKey: {
330
187
  select: payload.headers["idempotency-key"],
@@ -356,7 +213,7 @@ function scheduleRoutes(schedules) {
356
213
  app.patch(
357
214
  TASK_PATH,
358
215
  limitBody,
359
- validate("application/json", (payload) => ({
216
+ validate2("application/json", (payload) => ({
360
217
  body: { select: payload.body, against: updateBodySchema },
361
218
  taskId: { select: payload.params.taskId, against: scheduleIdSchema }
362
219
  })),
@@ -435,10 +292,10 @@ function scheduleRoutes(schedules) {
435
292
  app.all(RUN_PATH, (context) => methodNotAllowed(context, "GET"));
436
293
  return app;
437
294
  }
438
- var taskIdInput = validate((payload) => ({
295
+ var taskIdInput = validate2((payload) => ({
439
296
  taskId: { select: payload.params.taskId, against: scheduleIdSchema }
440
297
  }));
441
- var runIdInput = validate((payload) => ({
298
+ var runIdInput = validate2((payload) => ({
442
299
  runId: { select: payload.params.runId, against: scheduleIdSchema }
443
300
  }));
444
301
  function toExecutionConfig(target) {
@@ -495,7 +352,7 @@ function isScheduledTasksError(error) {
495
352
  function rethrowAsHttp(error) {
496
353
  if (!isScheduledTasksError(error)) throw error;
497
354
  if (error.code === "not-found") {
498
- throw new HTTPException4(404, {
355
+ throw new HTTPException2(404, {
499
356
  message: "Scheduled resource not found",
500
357
  cause: {
501
358
  code: "schedules/not-found",
@@ -503,7 +360,7 @@ function rethrowAsHttp(error) {
503
360
  }
504
361
  });
505
362
  }
506
- throw new HTTPException4(error.code === "invalid-input" ? 400 : 409, {
363
+ throw new HTTPException2(error.code === "invalid-input" ? 400 : 409, {
507
364
  message: error.message,
508
365
  cause: {
509
366
  code: `schedules/${error.code}`,
@@ -514,7 +371,7 @@ function rethrowAsHttp(error) {
514
371
  }
515
372
  function methodNotAllowed(context, allow) {
516
373
  context.header("Allow", allow);
517
- throw new HTTPException4(405, {
374
+ throw new HTTPException2(405, {
518
375
  message: "Method not allowed",
519
376
  cause: {
520
377
  code: "api/method-not-allowed",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../../../src/zukhruf/plugins/schedules/http.ts", "../../../../src/zukhruf/plugins/http/index.ts", "../../../../src/zukhruf/plugins/http/validator.ts", "../../../../src/zukhruf/plugins/http/parse.ts"],
4
- "sourcesContent": ["import { Hono } from 'hono';\nimport { bodyLimit } from 'hono/body-limit';\nimport { HTTPException } from 'hono/http-exception';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport type { AgentPluginDefinition } from '../../runtime/agent-runtime.ts';\nimport {\n type HttpEnv,\n type HttpProjection,\n projectHttp,\n} from '../http/index.ts';\nimport { validate } from '../http/validator.ts';\nimport type {\n ScheduleExecutionConfig,\n ScheduleTarget,\n Schedules,\n} from './index.ts';\nimport type {\n ScheduledRun,\n ScheduledRunReviewStatus,\n ScheduledRunStatus,\n ScheduledTask,\n ScheduledTaskStatus,\n ScheduledTasksError,\n ScheduledTasksErrorCode,\n ScheduledTasksResource,\n} from './scheduled-tasks.ts';\n\nconst SCHEDULES_PATH = '/schedules';\nconst TASKS_PATH = `${SCHEDULES_PATH}/tasks`;\nconst TASK_PATH = `${TASKS_PATH}/:taskId`;\nconst TASK_RUNS_PATH = `${TASK_PATH}/runs`;\nconst RUNS_PATH = `${SCHEDULES_PATH}/runs`;\nconst INBOX_PATH = `${RUNS_PATH}/inbox`;\nconst RUN_PATH = `${RUNS_PATH}/:runId`;\n\nconst MAX_BODY_BYTES = 10 * 1024;\nconst MAX_NAME_LENGTH = 200;\nconst MAX_PROMPT_LENGTH = 8_000;\nconst MAX_RECURRENCE_LENGTH = 1_000;\nconst MAX_TIMEZONE_LENGTH = 100;\nconst MAX_CHAT_ID_LENGTH = 200;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 200;\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\n\n/** Browser-safe Scheduled Task projection. Owner and scheduler bookkeeping stay server-side. */\nexport interface ScheduledTaskView {\n id: string;\n name: string;\n prompt: string;\n recurrence: string;\n timezone: string;\n target: ScheduleTarget;\n status: ScheduledTaskStatus;\n nextRunAt: number | null;\n createdAt: number;\n updatedAt: number;\n archivedAt: number | null;\n}\n\n/** Browser-safe Scheduled Run projection with its exact conversation reference. */\nexport interface ScheduledRunView {\n id: string;\n taskId: string;\n trigger: 'scheduled' | 'manual';\n occurrenceAt: number;\n prompt: string;\n target: ScheduleTarget;\n status: ScheduledRunStatus;\n reviewStatus: ScheduledRunReviewStatus | null;\n conversation: { chatId: string; turnId: string } | null;\n startedAt: number | null;\n finishedAt: number | null;\n error: string | null;\n createdAt: number;\n updatedAt: number;\n}\n\nconst scheduleIdSchema = z.string().refine(validateUuid);\nconst idempotencyKeySchema = z\n .string()\n .trim()\n .min(1)\n .max(MAX_IDEMPOTENCY_KEY_LENGTH);\nconst targetSchema = z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('new-conversation') }),\n z.strictObject({\n kind: z.literal('existing-conversation'),\n chatId: z.string().trim().min(1).max(MAX_CHAT_ID_LENGTH),\n }),\n]);\nconst definitionSchema = {\n name: z.string().trim().min(1).max(MAX_NAME_LENGTH),\n prompt: z.string().trim().min(1).max(MAX_PROMPT_LENGTH),\n recurrence: z.string().trim().min(1).max(MAX_RECURRENCE_LENGTH),\n timezone: z.string().trim().min(1).max(MAX_TIMEZONE_LENGTH),\n target: targetSchema,\n};\nconst createBodySchema = z.strictObject(definitionSchema);\nconst updateBodySchema = z\n .strictObject({\n name: definitionSchema.name.optional(),\n prompt: definitionSchema.prompt.optional(),\n recurrence: definitionSchema.recurrence.optional(),\n timezone: definitionSchema.timezone.optional(),\n target: targetSchema.optional(),\n })\n .refine((body) => Object.values(body).some((value) => value !== undefined), {\n message: 'At least one field must be provided',\n });\n\nconst limitBody = bodyLimit({\n maxSize: MAX_BODY_BYTES,\n onError: () => {\n throw new HTTPException(413, {\n message: 'Request body is too large',\n cause: {\n code: 'api/payload-too-large',\n detail: `Request body exceeds ${MAX_BODY_BYTES} bytes`,\n },\n });\n },\n});\n\n/**\n * Optional Scheduled Tasks capability bound to one `schedules()` definition.\n * Compose with `http(runtime, schedulesHttp(scheduled))`; omitting it removes\n * the capability from discovery so DevTool hides Scheduled navigation.\n */\nexport function schedulesHttp(\n definition: AgentPluginDefinition<Schedules>,\n): HttpProjection {\n return projectHttp(definition, (plugin) => ({\n capabilities: { schedules: { path: SCHEDULES_PATH } },\n authenticatedRoutes: scheduleRoutes(plugin),\n events: (userId, signal) => plugin.subscribeChanges(userId, signal),\n }));\n}\n\nfunction scheduleRoutes(schedules: Schedules) {\n const app = new Hono<HttpEnv>();\n\n app.get(TASKS_PATH, async (context) =>\n context.json(\n (await domain(schedules.list(context.get('userId')))).map(toTaskView),\n 200,\n NO_STORE,\n ),\n );\n app.post(\n TASKS_PATH,\n limitBody,\n validate('application/json', (payload) => ({\n body: { select: payload.body, against: createBodySchema },\n idempotencyKey: {\n select: payload.headers['idempotency-key'],\n against: idempotencyKeySchema,\n },\n })),\n async (context) => {\n const { body, idempotencyKey } = context.var.input;\n const task = await domain(\n schedules.create(context.get('userId'), {\n idempotencyKey,\n name: body.name,\n prompt: body.prompt,\n recurrence: body.recurrence,\n timezone: body.timezone,\n executionConfig: toExecutionConfig(body.target),\n }),\n );\n return context.json(toTaskView(task), 200, NO_STORE);\n },\n );\n app.all(TASKS_PATH, (context) => methodNotAllowed(context, 'GET, POST'));\n\n app.get(TASK_RUNS_PATH, taskIdInput, async (context) =>\n context.json(\n (\n await domain(\n schedules.listRuns(context.get('userId'), context.var.input.taskId),\n )\n ).map(toRunView),\n 200,\n NO_STORE,\n ),\n );\n app.all(TASK_RUNS_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n for (const [action, operation] of [\n ['pause', schedules.pause],\n ['resume', schedules.resume],\n ['archive', schedules.archive],\n ] as const) {\n const path = `${TASK_PATH}/${action}`;\n app.post(path, taskIdInput, async (context) =>\n context.json(\n toTaskView(\n await domain(\n operation.call(\n schedules,\n context.get('userId'),\n context.var.input.taskId,\n ),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(path, (context) => methodNotAllowed(context, 'POST'));\n }\n\n app.post(\n `${TASK_PATH}/run`,\n validate((payload) => ({\n taskId: { select: payload.params.taskId, against: scheduleIdSchema },\n idempotencyKey: {\n select: payload.headers['idempotency-key'],\n against: idempotencyKeySchema,\n },\n })),\n async (context) => {\n const { idempotencyKey, taskId } = context.var.input;\n const run = await domain(\n schedules.runNow(context.get('userId'), taskId, idempotencyKey),\n );\n return context.json(toRunView(run), 202, NO_STORE);\n },\n );\n app.all(`${TASK_PATH}/run`, (context) => methodNotAllowed(context, 'POST'));\n\n app.get(TASK_PATH, taskIdInput, async (context) =>\n context.json(\n toTaskView(\n await domain(\n schedules.get(context.get('userId'), context.var.input.taskId),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.patch(\n TASK_PATH,\n limitBody,\n validate('application/json', (payload) => ({\n body: { select: payload.body, against: updateBodySchema },\n taskId: { select: payload.params.taskId, against: scheduleIdSchema },\n })),\n async (context) => {\n const { body, taskId } = context.var.input;\n const task = await domain(\n schedules.update(context.get('userId'), taskId, {\n name: body.name,\n prompt: body.prompt,\n recurrence: body.recurrence,\n timezone: body.timezone,\n executionConfig: body.target && toExecutionConfig(body.target),\n }),\n );\n return context.json(toTaskView(task), 200, NO_STORE);\n },\n );\n app.delete(TASK_PATH, taskIdInput, async (context) => {\n await domain(\n schedules.purge(context.get('userId'), context.var.input.taskId),\n );\n return context.body(null, 204, NO_STORE);\n });\n app.all(TASK_PATH, (context) =>\n methodNotAllowed(context, 'GET, PATCH, DELETE'),\n );\n\n app.get(INBOX_PATH, async (context) =>\n context.json(\n (await domain(schedules.listPendingReview(context.get('userId')))).map(\n toRunView,\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(INBOX_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n for (const [action, operation] of [\n ['cancel', schedules.cancelRun],\n ['review', schedules.markReviewed],\n ] as const) {\n const path = `${RUN_PATH}/${action}`;\n app.post(path, runIdInput, async (context) =>\n context.json(\n toRunView(\n await domain(\n operation.call(\n schedules,\n context.get('userId'),\n context.var.input.runId,\n ),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(path, (context) => methodNotAllowed(context, 'POST'));\n }\n\n app.get(RUN_PATH, runIdInput, async (context) =>\n context.json(\n toRunView(\n await domain(\n schedules.getRun(context.get('userId'), context.var.input.runId),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(RUN_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n return app;\n}\n\nconst taskIdInput = validate((payload) => ({\n taskId: { select: payload.params.taskId, against: scheduleIdSchema },\n}));\n\nconst runIdInput = validate((payload) => ({\n runId: { select: payload.params.runId, against: scheduleIdSchema },\n}));\n\nfunction toExecutionConfig(target: ScheduleTarget): ScheduleExecutionConfig {\n return target.kind === 'new-conversation' ? {} : { target };\n}\n\nfunction toTaskView(\n task: ScheduledTask<ScheduleExecutionConfig>,\n): ScheduledTaskView {\n return {\n id: task.id,\n name: task.name,\n prompt: task.prompt,\n recurrence: task.recurrence,\n timezone: task.timezone,\n target: viewTarget(task.executionConfig),\n status: task.status,\n nextRunAt: task.nextRunAt,\n createdAt: task.createdAt,\n updatedAt: task.updatedAt,\n archivedAt: task.archivedAt,\n };\n}\n\nfunction toRunView(\n run: ScheduledRun<ScheduleExecutionConfig>,\n): ScheduledRunView {\n const target = viewTarget(run.executionConfig);\n return {\n id: run.id,\n taskId: run.taskId,\n trigger: run.trigger,\n occurrenceAt: run.occurrenceAt,\n prompt: run.prompt,\n target,\n status: run.status,\n reviewStatus: run.reviewStatus,\n conversation: run.externalExecutionId\n ? {\n chatId:\n target.kind === 'existing-conversation' ? target.chatId : run.id,\n turnId: run.externalExecutionId,\n }\n : null,\n startedAt: run.startedAt,\n finishedAt: run.finishedAt,\n error: run.error,\n createdAt: run.createdAt,\n updatedAt: run.updatedAt,\n };\n}\n\nfunction viewTarget(config: ScheduleExecutionConfig): ScheduleTarget {\n return config.target ?? { kind: 'new-conversation' };\n}\n\n/** Hono resolves handler errors at the innermost dispatch frame, so every\n * domain call converts its own rejection instead of relying on middleware. */\nfunction domain<T>(result: Promise<T>): Promise<T> {\n return result.catch(rethrowAsHttp);\n}\n\nconst scheduledTasksErrorCodes: ReadonlySet<unknown> =\n new Set<ScheduledTasksErrorCode>(['invalid-input', 'not-found', 'conflict']);\nconst scheduledTasksResources: ReadonlySet<unknown> =\n new Set<ScheduledTasksResource>(['task', 'run']);\n\n/**\n * `name` rather than `instanceof`: this subpath is its own build entry point, so\n * a value import of the domain would bundle a second copy of the class and every\n * `instanceof` check against it would fail.\n */\nfunction isScheduledTasksError(\n error: unknown,\n): error is Pick<\n ScheduledTasksError,\n 'name' | 'message' | 'code' | 'resource'\n> {\n return (\n error instanceof Error &&\n error.name === 'ScheduledTasksError' &&\n 'code' in error &&\n scheduledTasksErrorCodes.has(error.code) &&\n 'resource' in error &&\n scheduledTasksResources.has(error.resource)\n );\n}\n\nfunction rethrowAsHttp(error: unknown): never {\n if (!isScheduledTasksError(error)) throw error;\n if (error.code === 'not-found') {\n throw new HTTPException(404, {\n message: 'Scheduled resource not found',\n cause: {\n code: 'schedules/not-found',\n detail: 'The requested scheduled resource does not exist',\n },\n });\n }\n throw new HTTPException(error.code === 'invalid-input' ? 400 : 409, {\n message: error.message,\n cause: {\n code: `schedules/${error.code}`,\n detail: error.message,\n resource: error.resource,\n },\n });\n}\n\nfunction methodNotAllowed(\n context: { header(name: string, value: string): void },\n allow: string,\n): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import {\n type JSONSchema7,\n type UIMessage,\n createUIMessageStreamResponse,\n safeValidateUIMessages,\n} from 'ai';\nimport { type Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport { basePath } from 'hono/route';\nimport { streamSSE } from 'hono/streaming';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport { elementsSchema } from '@deepagents/elements';\n\nimport type { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInstance,\n} from '../../runtime/agent-runtime.ts';\nimport { validate } from './validator.ts';\n\nexport type HttpEnv = { Variables: { userId: string } };\n\nexport type OwnerEvent =\n | { readonly type: 'ready' }\n | {\n readonly type: 'change';\n readonly resource: string;\n readonly id: string;\n readonly [key: string]: unknown;\n };\n\ntype OwnerEventNotification =\n Exclude<OwnerEvent, { type: 'ready' }> | { readonly type: 'reset' };\n\nexport type OwnerEventSource = (\n userId: string,\n signal: AbortSignal,\n) => Promise<AsyncIterable<OwnerEventNotification>>;\n\n/** A discoverable feature: its route under the mount plus any detail the client needs to use it. */\nexport interface HttpCapability {\n readonly path: string;\n readonly [detail: string]: unknown;\n}\n\nexport interface HttpContribution {\n readonly capabilities: Readonly<Record<string, HttpCapability>>;\n readonly publicRoutes?: Hono<HttpEnv>;\n readonly authenticatedRoutes?: Hono<HttpEnv>;\n readonly events?: OwnerEventSource;\n}\n\nexport interface HttpProjection {\n project(runtime: HttpRuntime): HttpContribution;\n}\n\nexport function projectHttp<Instance extends object>(\n definition: AgentPluginDefinition<Instance>,\n project: (\n plugin: AgentPluginInstance & Instance,\n runtime: HttpRuntime,\n ) => HttpContribution,\n): HttpProjection {\n return {\n project(runtime) {\n return project(runtime.plugin(definition), runtime);\n },\n };\n}\n\nconst SESSION_ROUTE_PATH = '/session/:sessionId';\nconst SESSION_CANCEL_ROUTE_PATH = '/session/:sessionId/cancel';\nconst SESSION_STREAM_ROUTE_PATH = '/session/:sessionId/stream';\nconst EVENTS_ROUTE_PATH = '/events';\nconst SESSION_TURN_ROUTE_PATH = '/session/:sessionId/turn/:turnId';\nconst SESSION_TURN_CANCEL_ROUTE_PATH =\n '/session/:sessionId/turn/:turnId/cancel';\nconst HISTORY_ROUTE_PATH = '/history';\nconst INFO_ROUTE_PATH = '/info';\nconst HEALTH_ROUTE_PATH = '/health';\nexport const ZUKHRUF_SESSION_ID_HEADER = 'x-zukhruf-session-id';\nexport const ZUKHRUF_TURN_ID_HEADER = 'x-zukhruf-turn-id';\n\n/** Where the host mounted this API, without a trailing slash; empty at `/`. */\nexport function mountPath(context: Context): string {\n return basePath(context).replace(/\\/$/, '');\n}\n\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst sessionIdSchema = z.string().refine(validateUuid);\nconst jsonSchema = z.custom<JSONSchema7>(\n (value) =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n);\nconst clientToolsSchema = z\n .record(\n z.string().min(1),\n z.strictObject({\n inputSchema: jsonSchema,\n description: z.string().min(1),\n }),\n )\n .optional();\nconst turnBodySchema = z.strictObject({\n sessionId: sessionIdSchema,\n message: z.unknown(),\n trigger: z.enum(['submit-message', 'regenerate-message']),\n tools: clientToolsSchema,\n elements: elementsSchema,\n});\n\nexport interface HttpRuntime extends Pick<\n AgentHost,\n | 'createSession'\n | 'enqueue'\n | 'info'\n | 'listHistory'\n | 'plugin'\n | 'sessionExists'\n | 'subscribeConversationStatus'\n> {\n observe(conversation: ConversationId): Pick<\n AgentObservation,\n 'cancel' | 'resume' | 'status'\n > & {\n engine: Pick<AgentObservation['engine'], 'getMessages'>;\n };\n}\n\n/** Mount at the host-selected path with `app.route(path, http(runtime))`. */\nexport function http(\n runtime: HttpRuntime,\n ...projections: readonly HttpProjection[]\n) {\n const contributions = projections.map((projection) =>\n projection.project(runtime),\n );\n const capabilities: Record<string, HttpCapability> = {\n history: { path: HISTORY_ROUTE_PATH },\n chat: { path: '/session' },\n events: { path: EVENTS_ROUTE_PATH },\n };\n for (const { capabilities: contributed } of contributions) {\n for (const [name, capability] of Object.entries(contributed)) {\n if (!name.trim() || name !== name.trim()) {\n throw new Error(\n `http: capability name \"${name}\" must be non-empty without surrounding whitespace`,\n );\n }\n if (!capability.path.startsWith('/')) {\n throw new Error(`http: capability \"${name}\" must use an absolute path`);\n }\n if (Object.hasOwn(capabilities, name)) {\n throw new Error(`http: duplicate capability \"${name}\"`);\n }\n capabilities[name] = capability;\n }\n }\n const app = new Hono<HttpEnv>();\n app.onError((error, context) => {\n if (error instanceof HTTPException) {\n return context.json(\n { cause: error.cause, error: error.message },\n error.status,\n NO_STORE,\n );\n }\n throw error;\n });\n\n app.on(['GET', 'HEAD'], HEALTH_ROUTE_PATH, (context) =>\n context.req.method === 'HEAD'\n ? context.body(null, 200, NO_STORE)\n : context.json({ ok: true }, 200, NO_STORE),\n );\n app.all(HEALTH_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n for (const { publicRoutes } of contributions) {\n if (publicRoutes) app.route('/', publicRoutes);\n }\n\n app.use('*', async (context, next) => {\n if (!context.get('userId')?.trim()) {\n throw new HTTPException(401, {\n message: 'Authentication required',\n cause: {\n code: 'api/unauthenticated',\n detail: 'Authentication required to access Zukhruf',\n },\n });\n }\n await next();\n });\n\n app.get(INFO_ROUTE_PATH, (context) => {\n const mount = mountPath(context);\n return context.json(\n {\n ...runtime.info,\n capabilities: Object.fromEntries(\n Object.entries(capabilities).map(([name, { path, ...detail }]) => [\n name,\n { href: `${mount}${path}`, ...detail },\n ]),\n ),\n },\n 200,\n NO_STORE,\n );\n });\n app.all(INFO_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(HISTORY_ROUTE_PATH, async (context) =>\n context.json(\n await runtime.listHistory(context.get('userId')),\n 200,\n NO_STORE,\n ),\n );\n app.all(HISTORY_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n return context.json(\n {\n sessionId,\n messages: await runtime.observe(conversation).engine.getMessages(),\n },\n 200,\n NO_STORE,\n );\n },\n );\n app.post(\n SESSION_ROUTE_PATH,\n validate('application/json', (payload) => ({\n body: {\n select: payload.body,\n against: turnBodySchema,\n },\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { body, sessionId } = context.var.input;\n if (body.sessionId !== sessionId) {\n throw invalidSessionId('Route and body session IDs must match');\n }\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n const request = await validateTurnRequest(body);\n if (!(await runtime.sessionExists(conversation))) {\n if (request.message.role !== 'user') {\n throw invalidMessage('A new session must start with a user message');\n }\n if (request.trigger !== 'submit-message') {\n throw invalidMessage('A new session cannot regenerate a response');\n }\n await runtime.createSession(conversation);\n }\n const turn = await runtime.enqueue(conversation, request);\n\n return accepted(context, sessionId, turn.id);\n },\n );\n app.all(SESSION_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, POST'),\n );\n\n app.get(\n SESSION_TURN_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const status = await runtime.observe(conversation).status(turnId);\n if (!status) {\n throw new HTTPException(404, {\n message: 'Session turn not found',\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${turnId} does not exist in session ${sessionId}`,\n },\n });\n }\n return context.json({ sessionId, turnId, ...status }, 200, NO_STORE);\n },\n );\n app.all(SESSION_TURN_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n app.post(\n SESSION_TURN_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel(turnId);\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_TURN_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.post(\n SESSION_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel();\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n const eventSources: OwnerEventSource[] = [\n async (userId, signal) => {\n const events = await runtime.subscribeConversationStatus(signal);\n return {\n async *[Symbol.asyncIterator]() {\n for await (const event of events) {\n if (event.type === 'reset') {\n yield event;\n } else if (event.conversation.userId === userId) {\n yield {\n type: 'change',\n resource: 'conversation',\n id: event.conversation.chatId,\n status: event.status,\n ...(event.child ? { child: event.child } : {}),\n } satisfies OwnerEvent;\n }\n }\n },\n };\n },\n ...contributions.flatMap(({ events }) => (events ? [events] : [])),\n ];\n\n app.get(EVENTS_ROUTE_PATH, (context) => {\n const userId = context.get('userId');\n const abort = new AbortController();\n const requestSignal = context.req.raw.signal;\n const abortRequest = () => abort.abort();\n requestSignal.addEventListener('abort', abortRequest, { once: true });\n context.header('cache-control', 'no-store');\n return streamSSE(context, async (stream) => {\n stream.onAbort(abortRequest);\n let lastWrite: Promise<unknown> = Promise.resolve();\n const write = (event: OwnerEvent) => {\n const next = lastWrite.then(() =>\n stream.writeSSE({ data: JSON.stringify(event) }),\n );\n lastWrite = next.catch(() => {});\n return next;\n };\n const heartbeat = setInterval(() => {\n const next = lastWrite.then(async () => {\n await stream.write(': heartbeat\\n\\n');\n });\n lastWrite = next.catch(() => {});\n }, 15_000);\n try {\n const subscriptions = await Promise.all(\n eventSources.map((subscribe) => subscribe(userId, abort.signal)),\n );\n await write({ type: 'ready' });\n await Promise.all(\n subscriptions.map(async (events) => {\n for await (const event of events) {\n await write(event.type === 'reset' ? { type: 'ready' } : event);\n }\n }),\n );\n } catch (error) {\n if (!(error instanceof Error && error.name === 'AbortError')) {\n throw error;\n }\n } finally {\n clearInterval(heartbeat);\n abort.abort();\n requestSignal.removeEventListener('abort', abortRequest);\n }\n });\n });\n app.all(EVENTS_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_STREAM_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const stream = await runtime.observe(conversation).resume();\n if (!stream) {\n throw new HTTPException(404, {\n message: 'Session stream not found',\n cause: {\n code: 'zukhruf/session-stream-not-found',\n detail: `No durable stream exists for session ${sessionId}`,\n },\n });\n }\n\n return createUIMessageStreamResponse({\n headers: NO_STORE,\n stream,\n });\n },\n );\n app.all(SESSION_STREAM_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n for (const { authenticatedRoutes } of contributions) {\n if (authenticatedRoutes) app.route('/', authenticatedRoutes);\n }\n\n return app;\n}\n\nfunction accepted<Env extends HttpEnv>(\n context: Context<Env>,\n sessionId: string,\n turnId: string,\n) {\n return context.json({ ok: true, sessionId, turnId }, 202, {\n ...NO_STORE,\n [ZUKHRUF_SESSION_ID_HEADER]: sessionId,\n [ZUKHRUF_TURN_ID_HEADER]: turnId,\n });\n}\n\nasync function validateTurnMessage(\n value: unknown,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]['message']> {\n const result = await safeValidateUIMessages({ messages: [value] });\n if (!result.success) throw invalidMessage(result.error.message);\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw invalidMessage('System messages are not accepted');\n return message;\n}\n\nasync function validateTurnRequest(\n body: z.infer<typeof turnBodySchema>,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]> {\n const message = await validateTurnMessage(body.message);\n const tools = body.tools === undefined ? {} : { tools: body.tools };\n const elements =\n body.elements === undefined ? {} : { elements: body.elements };\n if (message.role === 'assistant') {\n if (body.trigger === 'regenerate-message') {\n throw invalidMessage(\n 'Regeneration requires the user message preceding the assistant response',\n );\n }\n return { message, trigger: 'submit-message', ...tools, ...elements };\n }\n return { message, trigger: body.trigger, ...tools, ...elements };\n}\n\nfunction isTurnMessage(\n message: UIMessage,\n): message is Parameters<HttpRuntime['enqueue']>[1]['message'] {\n return message.role === 'user' || message.role === 'assistant';\n}\n\nfunction invalidMessage(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nfunction invalidSessionId(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid session ID',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nasync function requireSession(\n runtime: HttpRuntime,\n conversation: ConversationId,\n): Promise<void> {\n if (await runtime.sessionExists(conversation)) return;\n throw new HTTPException(404, {\n message: 'Session not found',\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${conversation.chatId} does not exist`,\n },\n });\n}\n\nfunction methodNotAllowed(context: Context<HttpEnv>, allow: string): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { parse as parseContentType } from 'fast-content-type-parse';\nimport type { Context, MiddlewareHandler } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\nimport { parse } from './parse.ts';\n\ntype ContentType =\n | 'application/json'\n | 'application/x-www-form-urlencoded'\n | 'multipart/form-data'\n | 'text/plain';\n\ntype ValidatorConfig = Record<\n string,\n { select: unknown; against: z.ZodTypeAny }\n>;\n\n/** Each selected input's schema, under the input's name. */\ntype InputShape<T extends ValidatorConfig> = {\n [K in keyof T]: T[K]['against'];\n};\n\ntype ExtractInput<T extends ValidatorConfig> = z.output<\n ReturnType<typeof inputSchema<T>>\n>;\n\n/** The parsed request parts a selector picks its inputs from. */\ninterface RequestPayload {\n body: unknown;\n query: Record<string, string | null | undefined>;\n queries: Record<string, (string | null)[]>;\n params: Record<string, string>;\n headers: Record<string, string | undefined>;\n}\n\ntype SelectorFn<T> = (payload: RequestPayload) => T;\ntype ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<{\n Variables: {\n input: ExtractInput<T>;\n };\n}>;\n\nfunction inputSchema<T extends ValidatorConfig>(config: T) {\n const shape = Object.fromEntries(\n Object.entries(config).map(([key, { against }]) => [key, against]),\n );\n assertInputShape(shape, config);\n return z.object(shape);\n}\n\nfunction assertInputShape<T extends ValidatorConfig>(\n shape: Record<string, z.ZodTypeAny>,\n config: T,\n): asserts shape is InputShape<T> {\n const keys = Object.keys(config);\n if (\n Object.keys(shape).length !== keys.length ||\n keys.some((key) => shape[key] !== config[key]?.against)\n ) {\n throw new Error('The input schema does not match its selectors');\n }\n}\n\nexport function validate<T extends ValidatorConfig>(\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType,\n selector: SelectorFn<T>,\n): ValidateMiddleware<T>;\nexport function validate<T extends ValidatorConfig>(\n expectedContentTypeOrSelector: ContentType | SelectorFn<T>,\n selector?: SelectorFn<T>,\n): ValidateMiddleware<T> {\n const expectedContentType =\n typeof expectedContentTypeOrSelector === 'string'\n ? expectedContentTypeOrSelector\n : undefined;\n const _selector =\n typeof expectedContentTypeOrSelector === 'function'\n ? expectedContentTypeOrSelector\n : selector;\n void _selector;\n if (!_selector) {\n throw new Error('Selector function is required');\n }\n\n return createMiddleware(async (c, next) => {\n const ct = c.req.header('content-type');\n if (c.req.method === 'GET' && ct) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `GET requests cannot have a content type header`,\n },\n });\n }\n if (expectedContentType) {\n void verifyContentType(ct, expectedContentType);\n }\n\n const contentType = ct ? parseContentType(ct) : null;\n let body: unknown = null;\n\n switch (contentType?.type) {\n case 'application/json':\n body = await parseJson(c);\n break;\n case 'application/x-www-form-urlencoded':\n case 'multipart/form-data':\n body = await c.req.parseBody();\n break;\n default:\n body = {};\n }\n\n const payload: RequestPayload = {\n body,\n query: parseQueryParams(c.req.query()),\n queries: parseQueriesParams(c.req.queries()),\n params: c.req.param(),\n headers: c.req.header(),\n };\n\n const config = _selector(payload);\n const input = Object.fromEntries(\n Object.entries(config).map(([key, { select }]) => [key, select]),\n );\n c.set('input', await parse(inputSchema(config), input));\n await next();\n });\n}\n\nexport const openapi = validate;\n\nexport const consume = (contentType: ContentType) => {\n return createMiddleware(async (context, next) => {\n verifyContentType(context.req.header('content-type'), contentType);\n await next();\n });\n};\n\nexport function verifyContentType(\n actual: string | undefined,\n expected: ContentType,\n): asserts actual is ContentType {\n if (!actual) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: 'Missing content type header',\n },\n });\n }\n const { type: incomingContentType } = parseContentType(actual);\n if (incomingContentType !== expected) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n detail: `Expected content type: ${expected}, but got: ${incomingContentType}`,\n },\n });\n }\n}\n\nasync function parseJson(context: Context) {\n try {\n return await context.req.json();\n } catch (error) {\n throw new HTTPException(400, {\n message: 'The request body is not valid JSON',\n cause: {\n code: 'api/invalid-json',\n detail: error instanceof Error ? error.message : String(error),\n },\n });\n }\n}\n\nfunction parseQueryParams(\n queryParams: Record<string, string | undefined>,\n): Record<string, string | null | undefined> {\n return Object.fromEntries(\n Object.entries(queryParams).map(([key, value]) => [\n key,\n value === 'null' ? null : value,\n ]),\n );\n}\n\nfunction parseQueriesParams(\n queriesParams: Record<string, string[]>,\n): Record<string, (string | null)[]> {\n return Object.fromEntries(\n Object.entries(queriesParams).map(([key, values]) => [\n key,\n values.map((value) => (value === 'null' ? null : value)),\n ]),\n );\n}\n", "import { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\ninterface ValidationIssue {\n message: string;\n code: string;\n path: string;\n}\n\nexport async function parse<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n input: unknown,\n) {\n const result = await schema.safeParseAsync(input);\n if (!result.success) {\n const errors: z.inferFlattenedErrors<\n z.ZodObject<T>,\n ValidationIssue\n >['fieldErrors'] = result.error.flatten((issue) => ({\n message: issue.message,\n code: issue.code,\n path: issue.path.join('.'),\n })).fieldErrors;\n\n throw new HTTPException(400, {\n message: 'Validation failed',\n cause: {\n code: 'api/validation-failed',\n detail: 'The input data is invalid',\n errors,\n },\n });\n }\n return result.data;\n}\n"],
5
- "mappings": ";AAAA,SAAS,QAAAA,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,YAAYC,qBAAoB;AACzC,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,KAA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AkB,MAAM,KAAK;AAAA,IAClE,SAAS,MAAM;AAAA,IACf,OAAO;AAAA,MACL,MAAM,aAAa,MAAM,IAAI;AAAA,MAC7B,QAAQ,MAAM;AAAA,MACd,UAAU,MAAM;AAAA,IAClB;AAAA,EACF,CAAC;AACH;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": ["Hono", "HTTPException", "validateUuid", "z", "HTTPException", "z", "HTTPException", "z", "z", "HTTPException", "HTTPException", "z", "z", "validateUuid", "HTTPException", "Hono"]
3
+ "sources": ["../../../../src/zukhruf/plugins/schedules/http.ts", "../../../../src/zukhruf/plugins/http/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 { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport type { AgentPluginDefinition } from '../../runtime/agent-runtime.ts';\nimport {\n type HttpEnv,\n type HttpProjection,\n projectHttp,\n} from '../http/index.ts';\nimport type {\n ScheduleExecutionConfig,\n ScheduleTarget,\n Schedules,\n} from './index.ts';\nimport type {\n ScheduledRun,\n ScheduledRunReviewStatus,\n ScheduledRunStatus,\n ScheduledTask,\n ScheduledTaskStatus,\n ScheduledTasksError,\n ScheduledTasksErrorCode,\n ScheduledTasksResource,\n} from './scheduled-tasks.ts';\n\nconst SCHEDULES_PATH = '/schedules';\nconst TASKS_PATH = `${SCHEDULES_PATH}/tasks`;\nconst TASK_PATH = `${TASKS_PATH}/:taskId`;\nconst TASK_RUNS_PATH = `${TASK_PATH}/runs`;\nconst RUNS_PATH = `${SCHEDULES_PATH}/runs`;\nconst INBOX_PATH = `${RUNS_PATH}/inbox`;\nconst RUN_PATH = `${RUNS_PATH}/:runId`;\n\nconst MAX_BODY_BYTES = 10 * 1024;\nconst MAX_NAME_LENGTH = 200;\nconst MAX_PROMPT_LENGTH = 8_000;\nconst MAX_RECURRENCE_LENGTH = 1_000;\nconst MAX_TIMEZONE_LENGTH = 100;\nconst MAX_CHAT_ID_LENGTH = 200;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 200;\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\n\n/** Browser-safe Scheduled Task projection. Owner and scheduler bookkeeping stay server-side. */\nexport interface ScheduledTaskView {\n id: string;\n name: string;\n prompt: string;\n recurrence: string;\n timezone: string;\n target: ScheduleTarget;\n status: ScheduledTaskStatus;\n nextRunAt: number | null;\n createdAt: number;\n updatedAt: number;\n archivedAt: number | null;\n}\n\n/** Browser-safe Scheduled Run projection with its exact conversation reference. */\nexport interface ScheduledRunView {\n id: string;\n taskId: string;\n trigger: 'scheduled' | 'manual';\n occurrenceAt: number;\n prompt: string;\n target: ScheduleTarget;\n status: ScheduledRunStatus;\n reviewStatus: ScheduledRunReviewStatus | null;\n conversation: { chatId: string; turnId: string } | null;\n startedAt: number | null;\n finishedAt: number | null;\n error: string | null;\n createdAt: number;\n updatedAt: number;\n}\n\nconst scheduleIdSchema = z.string().refine(validateUuid);\nconst idempotencyKeySchema = z\n .string()\n .trim()\n .min(1)\n .max(MAX_IDEMPOTENCY_KEY_LENGTH);\nconst targetSchema = z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('new-conversation') }),\n z.strictObject({\n kind: z.literal('existing-conversation'),\n chatId: z.string().trim().min(1).max(MAX_CHAT_ID_LENGTH),\n }),\n]);\nconst definitionSchema = {\n name: z.string().trim().min(1).max(MAX_NAME_LENGTH),\n prompt: z.string().trim().min(1).max(MAX_PROMPT_LENGTH),\n recurrence: z.string().trim().min(1).max(MAX_RECURRENCE_LENGTH),\n timezone: z.string().trim().min(1).max(MAX_TIMEZONE_LENGTH),\n target: targetSchema,\n};\nconst createBodySchema = z.strictObject(definitionSchema);\nconst updateBodySchema = z\n .strictObject({\n name: definitionSchema.name.optional(),\n prompt: definitionSchema.prompt.optional(),\n recurrence: definitionSchema.recurrence.optional(),\n timezone: definitionSchema.timezone.optional(),\n target: targetSchema.optional(),\n })\n .refine((body) => Object.values(body).some((value) => value !== undefined), {\n message: 'At least one field must be provided',\n });\n\nconst limitBody = bodyLimit({\n maxSize: MAX_BODY_BYTES,\n onError: () => {\n throw new HTTPException(413, {\n message: 'Request body is too large',\n cause: {\n code: 'api/payload-too-large',\n detail: `Request body exceeds ${MAX_BODY_BYTES} bytes`,\n },\n });\n },\n});\n\n/**\n * Optional Scheduled Tasks capability bound to one `schedules()` definition.\n * Compose with `http(runtime, schedulesHttp(scheduled))`; omitting it removes\n * the capability from discovery so DevTool hides Scheduled navigation.\n */\nexport function schedulesHttp(\n definition: AgentPluginDefinition<Schedules>,\n): HttpProjection {\n return projectHttp(definition, (plugin) => ({\n capabilities: { schedules: { path: SCHEDULES_PATH } },\n authenticatedRoutes: scheduleRoutes(plugin),\n events: (userId, signal) => plugin.subscribeChanges(userId, signal),\n }));\n}\n\nfunction scheduleRoutes(schedules: Schedules) {\n const app = new Hono<HttpEnv>();\n\n app.get(TASKS_PATH, async (context) =>\n context.json(\n (await domain(schedules.list(context.get('userId')))).map(toTaskView),\n 200,\n NO_STORE,\n ),\n );\n app.post(\n TASKS_PATH,\n limitBody,\n validate('application/json', (payload) => ({\n body: { select: payload.body, against: createBodySchema },\n idempotencyKey: {\n select: payload.headers['idempotency-key'],\n against: idempotencyKeySchema,\n },\n })),\n async (context) => {\n const { body, idempotencyKey } = context.var.input;\n const task = await domain(\n schedules.create(context.get('userId'), {\n idempotencyKey,\n name: body.name,\n prompt: body.prompt,\n recurrence: body.recurrence,\n timezone: body.timezone,\n executionConfig: toExecutionConfig(body.target),\n }),\n );\n return context.json(toTaskView(task), 200, NO_STORE);\n },\n );\n app.all(TASKS_PATH, (context) => methodNotAllowed(context, 'GET, POST'));\n\n app.get(TASK_RUNS_PATH, taskIdInput, async (context) =>\n context.json(\n (\n await domain(\n schedules.listRuns(context.get('userId'), context.var.input.taskId),\n )\n ).map(toRunView),\n 200,\n NO_STORE,\n ),\n );\n app.all(TASK_RUNS_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n for (const [action, operation] of [\n ['pause', schedules.pause],\n ['resume', schedules.resume],\n ['archive', schedules.archive],\n ] as const) {\n const path = `${TASK_PATH}/${action}`;\n app.post(path, taskIdInput, async (context) =>\n context.json(\n toTaskView(\n await domain(\n operation.call(\n schedules,\n context.get('userId'),\n context.var.input.taskId,\n ),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(path, (context) => methodNotAllowed(context, 'POST'));\n }\n\n app.post(\n `${TASK_PATH}/run`,\n validate((payload) => ({\n taskId: { select: payload.params.taskId, against: scheduleIdSchema },\n idempotencyKey: {\n select: payload.headers['idempotency-key'],\n against: idempotencyKeySchema,\n },\n })),\n async (context) => {\n const { idempotencyKey, taskId } = context.var.input;\n const run = await domain(\n schedules.runNow(context.get('userId'), taskId, idempotencyKey),\n );\n return context.json(toRunView(run), 202, NO_STORE);\n },\n );\n app.all(`${TASK_PATH}/run`, (context) => methodNotAllowed(context, 'POST'));\n\n app.get(TASK_PATH, taskIdInput, async (context) =>\n context.json(\n toTaskView(\n await domain(\n schedules.get(context.get('userId'), context.var.input.taskId),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.patch(\n TASK_PATH,\n limitBody,\n validate('application/json', (payload) => ({\n body: { select: payload.body, against: updateBodySchema },\n taskId: { select: payload.params.taskId, against: scheduleIdSchema },\n })),\n async (context) => {\n const { body, taskId } = context.var.input;\n const task = await domain(\n schedules.update(context.get('userId'), taskId, {\n name: body.name,\n prompt: body.prompt,\n recurrence: body.recurrence,\n timezone: body.timezone,\n executionConfig: body.target && toExecutionConfig(body.target),\n }),\n );\n return context.json(toTaskView(task), 200, NO_STORE);\n },\n );\n app.delete(TASK_PATH, taskIdInput, async (context) => {\n await domain(\n schedules.purge(context.get('userId'), context.var.input.taskId),\n );\n return context.body(null, 204, NO_STORE);\n });\n app.all(TASK_PATH, (context) =>\n methodNotAllowed(context, 'GET, PATCH, DELETE'),\n );\n\n app.get(INBOX_PATH, async (context) =>\n context.json(\n (await domain(schedules.listPendingReview(context.get('userId')))).map(\n toRunView,\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(INBOX_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n for (const [action, operation] of [\n ['cancel', schedules.cancelRun],\n ['review', schedules.markReviewed],\n ] as const) {\n const path = `${RUN_PATH}/${action}`;\n app.post(path, runIdInput, async (context) =>\n context.json(\n toRunView(\n await domain(\n operation.call(\n schedules,\n context.get('userId'),\n context.var.input.runId,\n ),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(path, (context) => methodNotAllowed(context, 'POST'));\n }\n\n app.get(RUN_PATH, runIdInput, async (context) =>\n context.json(\n toRunView(\n await domain(\n schedules.getRun(context.get('userId'), context.var.input.runId),\n ),\n ),\n 200,\n NO_STORE,\n ),\n );\n app.all(RUN_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n return app;\n}\n\nconst taskIdInput = validate((payload) => ({\n taskId: { select: payload.params.taskId, against: scheduleIdSchema },\n}));\n\nconst runIdInput = validate((payload) => ({\n runId: { select: payload.params.runId, against: scheduleIdSchema },\n}));\n\nfunction toExecutionConfig(target: ScheduleTarget): ScheduleExecutionConfig {\n return target.kind === 'new-conversation' ? {} : { target };\n}\n\nfunction toTaskView(\n task: ScheduledTask<ScheduleExecutionConfig>,\n): ScheduledTaskView {\n return {\n id: task.id,\n name: task.name,\n prompt: task.prompt,\n recurrence: task.recurrence,\n timezone: task.timezone,\n target: viewTarget(task.executionConfig),\n status: task.status,\n nextRunAt: task.nextRunAt,\n createdAt: task.createdAt,\n updatedAt: task.updatedAt,\n archivedAt: task.archivedAt,\n };\n}\n\nfunction toRunView(\n run: ScheduledRun<ScheduleExecutionConfig>,\n): ScheduledRunView {\n const target = viewTarget(run.executionConfig);\n return {\n id: run.id,\n taskId: run.taskId,\n trigger: run.trigger,\n occurrenceAt: run.occurrenceAt,\n prompt: run.prompt,\n target,\n status: run.status,\n reviewStatus: run.reviewStatus,\n conversation: run.externalExecutionId\n ? {\n chatId:\n target.kind === 'existing-conversation' ? target.chatId : run.id,\n turnId: run.externalExecutionId,\n }\n : null,\n startedAt: run.startedAt,\n finishedAt: run.finishedAt,\n error: run.error,\n createdAt: run.createdAt,\n updatedAt: run.updatedAt,\n };\n}\n\nfunction viewTarget(config: ScheduleExecutionConfig): ScheduleTarget {\n return config.target ?? { kind: 'new-conversation' };\n}\n\n/** Hono resolves handler errors at the innermost dispatch frame, so every\n * domain call converts its own rejection instead of relying on middleware. */\nfunction domain<T>(result: Promise<T>): Promise<T> {\n return result.catch(rethrowAsHttp);\n}\n\nconst scheduledTasksErrorCodes: ReadonlySet<unknown> =\n new Set<ScheduledTasksErrorCode>(['invalid-input', 'not-found', 'conflict']);\nconst scheduledTasksResources: ReadonlySet<unknown> =\n new Set<ScheduledTasksResource>(['task', 'run']);\n\n/**\n * `name` rather than `instanceof`: this subpath is its own build entry point, so\n * a value import of the domain would bundle a second copy of the class and every\n * `instanceof` check against it would fail.\n */\nfunction isScheduledTasksError(\n error: unknown,\n): error is Pick<\n ScheduledTasksError,\n 'name' | 'message' | 'code' | 'resource'\n> {\n return (\n error instanceof Error &&\n error.name === 'ScheduledTasksError' &&\n 'code' in error &&\n scheduledTasksErrorCodes.has(error.code) &&\n 'resource' in error &&\n scheduledTasksResources.has(error.resource)\n );\n}\n\nfunction rethrowAsHttp(error: unknown): never {\n if (!isScheduledTasksError(error)) throw error;\n if (error.code === 'not-found') {\n throw new HTTPException(404, {\n message: 'Scheduled resource not found',\n cause: {\n code: 'schedules/not-found',\n detail: 'The requested scheduled resource does not exist',\n },\n });\n }\n throw new HTTPException(error.code === 'invalid-input' ? 400 : 409, {\n message: error.message,\n cause: {\n code: `schedules/${error.code}`,\n detail: error.message,\n resource: error.resource,\n },\n });\n}\n\nfunction methodNotAllowed(\n context: { header(name: string, value: string): void },\n allow: string,\n): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n", "import { validate } from '@sdk-it/hono/runtime';\nimport {\n type JSONSchema7,\n type UIMessage,\n createUIMessageStreamResponse,\n safeValidateUIMessages,\n} from 'ai';\nimport { type Context, Hono } from 'hono';\nimport { HTTPException } from 'hono/http-exception';\nimport { basePath } from 'hono/route';\nimport { streamSSE } from 'hono/streaming';\nimport { validate as validateUuid } from 'uuid';\nimport z from 'zod';\n\nimport { elementsSchema } from '@deepagents/elements';\n\nimport type { ConversationId } from '../../mailbox/types.ts';\nimport type {\n AgentHost,\n AgentObservation,\n AgentPluginDefinition,\n AgentPluginInstance,\n} from '../../runtime/agent-runtime.ts';\n\nexport type HttpEnv = { Variables: { userId: string } };\n\nexport type OwnerEvent =\n | { readonly type: 'ready' }\n | {\n readonly type: 'change';\n readonly resource: string;\n readonly id: string;\n readonly [key: string]: unknown;\n };\n\ntype OwnerEventNotification =\n Exclude<OwnerEvent, { type: 'ready' }> | { readonly type: 'reset' };\n\nexport type OwnerEventSource = (\n userId: string,\n signal: AbortSignal,\n) => Promise<AsyncIterable<OwnerEventNotification>>;\n\n/** A discoverable feature: its route under the mount plus any detail the client needs to use it. */\nexport interface HttpCapability {\n readonly path: string;\n readonly [detail: string]: unknown;\n}\n\nexport interface HttpContribution {\n readonly capabilities: Readonly<Record<string, HttpCapability>>;\n readonly publicRoutes?: Hono<HttpEnv>;\n readonly authenticatedRoutes?: Hono<HttpEnv>;\n readonly events?: OwnerEventSource;\n}\n\nexport interface HttpProjection {\n project(runtime: HttpRuntime): HttpContribution;\n}\n\nexport function projectHttp<Instance extends object>(\n definition: AgentPluginDefinition<Instance>,\n project: (\n plugin: AgentPluginInstance & Instance,\n runtime: HttpRuntime,\n ) => HttpContribution,\n): HttpProjection {\n return {\n project(runtime) {\n return project(runtime.plugin(definition), runtime);\n },\n };\n}\n\nconst SESSION_ROUTE_PATH = '/session/:sessionId';\nconst SESSION_CANCEL_ROUTE_PATH = '/session/:sessionId/cancel';\nconst SESSION_STREAM_ROUTE_PATH = '/session/:sessionId/stream';\nconst EVENTS_ROUTE_PATH = '/events';\nconst SESSION_TURN_ROUTE_PATH = '/session/:sessionId/turn/:turnId';\nconst SESSION_TURN_CANCEL_ROUTE_PATH =\n '/session/:sessionId/turn/:turnId/cancel';\nconst HISTORY_ROUTE_PATH = '/history';\nconst INFO_ROUTE_PATH = '/info';\nconst HEALTH_ROUTE_PATH = '/health';\nexport const ZUKHRUF_SESSION_ID_HEADER = 'x-zukhruf-session-id';\nexport const ZUKHRUF_TURN_ID_HEADER = 'x-zukhruf-turn-id';\n\n/** Where the host mounted this API, without a trailing slash; empty at `/`. */\nexport function mountPath(context: Context): string {\n return basePath(context).replace(/\\/$/, '');\n}\n\nconst NO_STORE = { 'cache-control': 'no-store' } as const;\nconst sessionIdSchema = z.string().refine(validateUuid);\nconst jsonSchema = z.custom<JSONSchema7>(\n (value) =>\n typeof value === 'object' && value !== null && !Array.isArray(value),\n);\nconst clientToolsSchema = z\n .record(\n z.string().min(1),\n z.strictObject({\n inputSchema: jsonSchema,\n description: z.string().min(1),\n }),\n )\n .optional();\nconst turnBodySchema = z.strictObject({\n sessionId: sessionIdSchema,\n message: z.unknown(),\n trigger: z.enum(['submit-message', 'regenerate-message']),\n tools: clientToolsSchema,\n elements: elementsSchema,\n});\n\nexport interface HttpRuntime extends Pick<\n AgentHost,\n | 'createSession'\n | 'enqueue'\n | 'info'\n | 'listHistory'\n | 'plugin'\n | 'sessionExists'\n | 'subscribeConversationStatus'\n> {\n observe(conversation: ConversationId): Pick<\n AgentObservation,\n 'cancel' | 'resume' | 'status'\n > & {\n engine: Pick<AgentObservation['engine'], 'getMessages'>;\n };\n}\n\n/** Mount at the host-selected path with `app.route(path, http(runtime))`. */\nexport function http(\n runtime: HttpRuntime,\n ...projections: readonly HttpProjection[]\n) {\n const contributions = projections.map((projection) =>\n projection.project(runtime),\n );\n const capabilities: Record<string, HttpCapability> = {\n history: { path: HISTORY_ROUTE_PATH },\n chat: { path: '/session' },\n events: { path: EVENTS_ROUTE_PATH },\n };\n for (const { capabilities: contributed } of contributions) {\n for (const [name, capability] of Object.entries(contributed)) {\n if (!name.trim() || name !== name.trim()) {\n throw new Error(\n `http: capability name \"${name}\" must be non-empty without surrounding whitespace`,\n );\n }\n if (!capability.path.startsWith('/')) {\n throw new Error(`http: capability \"${name}\" must use an absolute path`);\n }\n if (Object.hasOwn(capabilities, name)) {\n throw new Error(`http: duplicate capability \"${name}\"`);\n }\n capabilities[name] = capability;\n }\n }\n const app = new Hono<HttpEnv>();\n app.onError((error, context) => {\n if (error instanceof HTTPException) {\n return context.json(\n { cause: error.cause, error: error.message },\n error.status,\n NO_STORE,\n );\n }\n throw error;\n });\n\n app.on(['GET', 'HEAD'], HEALTH_ROUTE_PATH, (context) =>\n context.req.method === 'HEAD'\n ? context.body(null, 200, NO_STORE)\n : context.json({ ok: true }, 200, NO_STORE),\n );\n app.all(HEALTH_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, HEAD'),\n );\n\n for (const { publicRoutes } of contributions) {\n if (publicRoutes) app.route('/', publicRoutes);\n }\n\n app.use('*', async (context, next) => {\n if (!context.get('userId')?.trim()) {\n throw new HTTPException(401, {\n message: 'Authentication required',\n cause: {\n code: 'api/unauthenticated',\n detail: 'Authentication required to access Zukhruf',\n },\n });\n }\n await next();\n });\n\n app.get(INFO_ROUTE_PATH, (context) => {\n const mount = mountPath(context);\n return context.json(\n {\n ...runtime.info,\n capabilities: Object.fromEntries(\n Object.entries(capabilities).map(([name, { path, ...detail }]) => [\n name,\n { href: `${mount}${path}`, ...detail },\n ]),\n ),\n },\n 200,\n NO_STORE,\n );\n });\n app.all(INFO_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(HISTORY_ROUTE_PATH, async (context) =>\n context.json(\n await runtime.listHistory(context.get('userId')),\n 200,\n NO_STORE,\n ),\n );\n app.all(HISTORY_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n return context.json(\n {\n sessionId,\n messages: await runtime.observe(conversation).engine.getMessages(),\n },\n 200,\n NO_STORE,\n );\n },\n );\n app.post(\n SESSION_ROUTE_PATH,\n validate('application/json', (payload) => ({\n body: {\n select: payload.body,\n against: turnBodySchema,\n },\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { body, sessionId } = context.var.input;\n if (body.sessionId !== sessionId) {\n throw invalidSessionId('Route and body session IDs must match');\n }\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n const request = await validateTurnRequest(body);\n if (!(await runtime.sessionExists(conversation))) {\n if (request.message.role !== 'user') {\n throw invalidMessage('A new session must start with a user message');\n }\n if (request.trigger !== 'submit-message') {\n throw invalidMessage('A new session cannot regenerate a response');\n }\n await runtime.createSession(conversation);\n }\n const turn = await runtime.enqueue(conversation, request);\n\n return accepted(context, sessionId, turn.id);\n },\n );\n app.all(SESSION_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET, POST'),\n );\n\n app.get(\n SESSION_TURN_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const status = await runtime.observe(conversation).status(turnId);\n if (!status) {\n throw new HTTPException(404, {\n message: 'Session turn not found',\n cause: {\n code: 'zukhruf/session-turn-not-found',\n detail: `Turn ${turnId} does not exist in session ${sessionId}`,\n },\n });\n }\n return context.json({ sessionId, turnId, ...status }, 200, NO_STORE);\n },\n );\n app.all(SESSION_TURN_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n app.post(\n SESSION_TURN_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n turnId: {\n select: payload.params.turnId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId, turnId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel(turnId);\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_TURN_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n app.post(\n SESSION_CANCEL_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n await runtime.observe(conversation).cancel();\n return context.body(null, 204, NO_STORE);\n },\n );\n app.all(SESSION_CANCEL_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'POST'),\n );\n\n const eventSources: OwnerEventSource[] = [\n async (userId, signal) => {\n const events = await runtime.subscribeConversationStatus(signal);\n return {\n async *[Symbol.asyncIterator]() {\n for await (const event of events) {\n if (event.type === 'reset') {\n yield event;\n } else if (event.conversation.userId === userId) {\n yield {\n type: 'change',\n resource: 'conversation',\n id: event.conversation.chatId,\n status: event.status,\n ...(event.child ? { child: event.child } : {}),\n } satisfies OwnerEvent;\n }\n }\n },\n };\n },\n ...contributions.flatMap(({ events }) => (events ? [events] : [])),\n ];\n\n app.get(EVENTS_ROUTE_PATH, (context) => {\n const userId = context.get('userId');\n const abort = new AbortController();\n const requestSignal = context.req.raw.signal;\n const abortRequest = () => abort.abort();\n requestSignal.addEventListener('abort', abortRequest, { once: true });\n context.header('cache-control', 'no-store');\n return streamSSE(context, async (stream) => {\n stream.onAbort(abortRequest);\n let lastWrite: Promise<unknown> = Promise.resolve();\n const write = (event: OwnerEvent) => {\n const next = lastWrite.then(() =>\n stream.writeSSE({ data: JSON.stringify(event) }),\n );\n lastWrite = next.catch(() => {});\n return next;\n };\n const heartbeat = setInterval(() => {\n const next = lastWrite.then(async () => {\n await stream.write(': heartbeat\\n\\n');\n });\n lastWrite = next.catch(() => {});\n }, 15_000);\n try {\n const subscriptions = await Promise.all(\n eventSources.map((subscribe) => subscribe(userId, abort.signal)),\n );\n await write({ type: 'ready' });\n await Promise.all(\n subscriptions.map(async (events) => {\n for await (const event of events) {\n await write(event.type === 'reset' ? { type: 'ready' } : event);\n }\n }),\n );\n } catch (error) {\n if (!(error instanceof Error && error.name === 'AbortError')) {\n throw error;\n }\n } finally {\n clearInterval(heartbeat);\n abort.abort();\n requestSignal.removeEventListener('abort', abortRequest);\n }\n });\n });\n app.all(EVENTS_ROUTE_PATH, (context) => methodNotAllowed(context, 'GET'));\n\n app.get(\n SESSION_STREAM_ROUTE_PATH,\n validate((payload) => ({\n sessionId: {\n select: payload.params.sessionId,\n against: sessionIdSchema,\n },\n })),\n async (context) => {\n const { sessionId } = context.var.input;\n const conversation = {\n chatId: sessionId,\n userId: context.get('userId'),\n };\n await requireSession(runtime, conversation);\n const stream = await runtime.observe(conversation).resume();\n if (!stream) {\n throw new HTTPException(404, {\n message: 'Session stream not found',\n cause: {\n code: 'zukhruf/session-stream-not-found',\n detail: `No durable stream exists for session ${sessionId}`,\n },\n });\n }\n\n return createUIMessageStreamResponse({\n headers: NO_STORE,\n stream,\n });\n },\n );\n app.all(SESSION_STREAM_ROUTE_PATH, (context) =>\n methodNotAllowed(context, 'GET'),\n );\n\n for (const { authenticatedRoutes } of contributions) {\n if (authenticatedRoutes) app.route('/', authenticatedRoutes);\n }\n\n return app;\n}\n\nfunction accepted<Env extends HttpEnv>(\n context: Context<Env>,\n sessionId: string,\n turnId: string,\n) {\n return context.json({ ok: true, sessionId, turnId }, 202, {\n ...NO_STORE,\n [ZUKHRUF_SESSION_ID_HEADER]: sessionId,\n [ZUKHRUF_TURN_ID_HEADER]: turnId,\n });\n}\n\nasync function validateTurnMessage(\n value: unknown,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]['message']> {\n const result = await safeValidateUIMessages({ messages: [value] });\n if (!result.success) throw invalidMessage(result.error.message);\n const message = result.data[0];\n if (!isTurnMessage(message))\n throw invalidMessage('System messages are not accepted');\n return message;\n}\n\nasync function validateTurnRequest(\n body: z.infer<typeof turnBodySchema>,\n): Promise<Parameters<HttpRuntime['enqueue']>[1]> {\n const message = await validateTurnMessage(body.message);\n const tools = body.tools === undefined ? {} : { tools: body.tools };\n const elements =\n body.elements === undefined ? {} : { elements: body.elements };\n if (message.role === 'assistant') {\n if (body.trigger === 'regenerate-message') {\n throw invalidMessage(\n 'Regeneration requires the user message preceding the assistant response',\n );\n }\n return { message, trigger: 'submit-message', ...tools, ...elements };\n }\n return { message, trigger: body.trigger, ...tools, ...elements };\n}\n\nfunction isTurnMessage(\n message: UIMessage,\n): message is Parameters<HttpRuntime['enqueue']>[1]['message'] {\n return message.role === 'user' || message.role === 'assistant';\n}\n\nfunction invalidMessage(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid message',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nfunction invalidSessionId(detail: string): HTTPException {\n return new HTTPException(400, {\n message: 'Invalid session ID',\n cause: { code: 'api/validation-failed', detail },\n });\n}\n\nasync function requireSession(\n runtime: HttpRuntime,\n conversation: ConversationId,\n): Promise<void> {\n if (await runtime.sessionExists(conversation)) return;\n throw new HTTPException(404, {\n message: 'Session not found',\n cause: {\n code: 'zukhruf/session-not-found',\n detail: `Session ${conversation.chatId} does not exist`,\n },\n });\n}\n\nfunction methodNotAllowed(context: Context<HttpEnv>, allow: string): never {\n context.header('Allow', allow);\n throw new HTTPException(405, {\n message: 'Method not allowed',\n cause: {\n code: 'api/method-not-allowed',\n detail: `This endpoint only accepts ${allow} requests`,\n },\n });\n}\n"],
5
+ "mappings": ";AAAA,SAAS,YAAAA,iBAAgB;AACzB,SAAS,QAAAC,aAAY;AACrB,SAAS,iBAAiB;AAC1B,SAAS,iBAAAC,sBAAqB;AAC9B,SAAS,YAAYC,qBAAoB;AACzC,OAAOC,QAAO;;;ACLd,SAAS,gBAAgB;AACzB;AAAA,EAGE;AAAA,EACA;AAAA,OACK;AACP,SAAuB,YAAY;AACnC,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAC1B,SAAS,YAAY,oBAAoB;AACzC,OAAO,OAAO;AAEd,SAAS,sBAAsB;AA8CxB,SAAS,YACd,YACA,SAIgB;AAChB,SAAO;AAAA,IACL,QAAQ,SAAS;AACf,aAAO,QAAQ,QAAQ,OAAO,UAAU,GAAG,OAAO;AAAA,IACpD;AAAA,EACF;AACF;AAqBA,IAAM,kBAAkB,EAAE,OAAO,EAAE,OAAO,YAAY;AACtD,IAAM,aAAa,EAAE;AAAA,EACnB,CAAC,UACC,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AACvE;AACA,IAAM,oBAAoB,EACvB;AAAA,EACC,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChB,EAAE,aAAa;AAAA,IACb,aAAa;AAAA,IACb,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAC/B,CAAC;AACH,EACC,SAAS;AACZ,IAAM,iBAAiB,EAAE,aAAa;AAAA,EACpC,WAAW;AAAA,EACX,SAAS,EAAE,QAAQ;AAAA,EACnB,SAAS,EAAE,KA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S,MAAM;AAAA,IACf,OAAO;AAAA,MACL,MAAM,aAAa,MAAM,IAAI;AAAA,MAC7B,QAAQ,MAAM;AAAA,MACd,UAAU,MAAM;AAAA,IAClB;AAAA,EACF,CAAC;AACH;AAEA,SAAS,iBACP,SACA,OACO;AACP,UAAQ,OAAO,SAAS,KAAK;AAC7B,QAAM,IAAIA,eAAc,KAAK;AAAA,IAC3B,SAAS;AAAA,IACT,OAAO;AAAA,MACL,MAAM;AAAA,MACN,QAAQ,8BAA8B,KAAK;AAAA,IAC7C;AAAA,EACF,CAAC;AACH;",
6
+ "names": ["validate", "Hono", "HTTPException", "validateUuid", "z", "z", "validateUuid", "HTTPException", "Hono", "validate"]
7
7
  }
@@ -39,6 +39,9 @@ var listedAgentSchema = z.object({
39
39
  // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
40
40
  import { v5 as uuidv53 } from "uuid";
41
41
 
42
+ // packages/experimental/src/zukhruf/mailbox/coordinator.ts
43
+ import pMemoize from "p-memoize";
44
+
42
45
  // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
43
46
  import { experimental_codeModeTool } from "@ai-sdk/code-mode";
44
47
  import {
@@ -106,6 +109,7 @@ import {
106
109
  } from "@deepagents/context";
107
110
 
108
111
  // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
112
+ import { Latch } from "@zukhruf/async";
109
113
  import { MemoryStore, Mutex } from "@zukhruf/mutex";
110
114
  import {
111
115
  ContextEngine as ContextEngine4
@@ -130,6 +134,14 @@ var childActivityMetadataSchema = z3.looseObject({
130
134
  childActivities: childActivitiesSchema.default({})
131
135
  });
132
136
 
137
+ // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
138
+ var Detached = class {
139
+ // A private member keeps the type nominal: an empty class would also
140
+ // describe RemoteAttachment, and `instanceof` could not narrow the union.
141
+ #detached = true;
142
+ };
143
+ var DETACHED = new Detached();
144
+
133
145
  // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
134
146
  import { tool as tool2 } from "ai";
135
147
  import { z as z4 } from "zod";