@deepagents/experimental 6.1.2 → 7.0.1

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 (131) 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 +3975 -2519
  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-status-projector.d.ts +6 -3
  32. package/dist/zukhruf/control-plane/agent-status-projector.d.ts.map +1 -1
  33. package/dist/zukhruf/control-plane/agent-thread.d.ts.map +1 -1
  34. package/dist/zukhruf/index.d.ts +7 -4
  35. package/dist/zukhruf/index.d.ts.map +1 -1
  36. package/dist/zukhruf/index.js +4184 -2728
  37. package/dist/zukhruf/index.js.map +4 -4
  38. package/dist/zukhruf/{multi-agent-v2-config.d.ts → multi-agent-config.d.ts} +14 -9
  39. package/dist/zukhruf/multi-agent-config.d.ts.map +1 -0
  40. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts +76 -0
  41. package/dist/zukhruf/plugins/conversation-scheduling/conversation-scheduler.d.ts.map +1 -0
  42. package/dist/zukhruf/plugins/conversation-scheduling/index.d.ts +13 -0
  43. package/dist/zukhruf/plugins/conversation-scheduling/index.d.ts.map +1 -0
  44. package/dist/zukhruf/plugins/conversation-scheduling/index.js +999 -0
  45. package/dist/zukhruf/plugins/conversation-scheduling/index.js.map +7 -0
  46. package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts +19 -0
  47. package/dist/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.d.ts.map +1 -0
  48. package/dist/zukhruf/plugins/conversation-scheduling/tools.d.ts +1305 -0
  49. package/dist/zukhruf/plugins/conversation-scheduling/tools.d.ts.map +1 -0
  50. package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts +12 -0
  51. package/dist/zukhruf/plugins/conversation-scheduling/wake-scheduler.d.ts.map +1 -0
  52. package/dist/zukhruf/plugins/http/index.d.ts +50 -0
  53. package/dist/zukhruf/plugins/http/index.d.ts.map +1 -0
  54. package/dist/zukhruf/plugins/http/index.js +618 -0
  55. package/dist/zukhruf/plugins/http/index.js.map +7 -0
  56. package/dist/zukhruf/plugins/http/parse.d.ts.map +1 -0
  57. package/dist/zukhruf/plugins/http/validator.d.ts.map +1 -0
  58. package/dist/zukhruf/plugins/mcp/index.d.ts +8 -0
  59. package/dist/zukhruf/plugins/mcp/index.d.ts.map +1 -0
  60. package/dist/zukhruf/plugins/mcp/index.js +25 -0
  61. package/dist/zukhruf/plugins/mcp/index.js.map +7 -0
  62. package/dist/zukhruf/plugins/schedules/http.d.ts +45 -0
  63. package/dist/zukhruf/plugins/schedules/http.d.ts.map +1 -0
  64. package/dist/zukhruf/plugins/schedules/http.js +528 -0
  65. package/dist/zukhruf/plugins/schedules/http.js.map +7 -0
  66. package/dist/zukhruf/plugins/schedules/index.d.ts +35 -0
  67. package/dist/zukhruf/plugins/schedules/index.d.ts.map +1 -0
  68. package/dist/zukhruf/plugins/schedules/index.js +1873 -0
  69. package/dist/zukhruf/plugins/schedules/index.js.map +7 -0
  70. package/dist/zukhruf/plugins/schedules/schedule-files.d.ts +6 -0
  71. package/dist/zukhruf/plugins/schedules/schedule-files.d.ts.map +1 -0
  72. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts +157 -0
  73. package/dist/zukhruf/plugins/schedules/scheduled-tasks.d.ts.map +1 -0
  74. package/dist/zukhruf/plugins/uploads/http.d.ts +27 -0
  75. package/dist/zukhruf/plugins/uploads/http.d.ts.map +1 -0
  76. package/dist/zukhruf/plugins/uploads/http.js +426 -0
  77. package/dist/zukhruf/plugins/uploads/http.js.map +7 -0
  78. package/dist/zukhruf/plugins/uploads/index.d.ts +73 -0
  79. package/dist/zukhruf/plugins/uploads/index.d.ts.map +1 -0
  80. package/dist/zukhruf/plugins/uploads/index.js +247 -0
  81. package/dist/zukhruf/plugins/uploads/index.js.map +7 -0
  82. package/dist/zukhruf/queue/pg-boss-notifications.d.ts +10 -0
  83. package/dist/zukhruf/queue/pg-boss-notifications.d.ts.map +1 -0
  84. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts +8 -11
  85. package/dist/zukhruf/queue/pg-boss.turn-queue.d.ts.map +1 -1
  86. package/dist/zukhruf/queue/turn-queue.d.ts +43 -38
  87. package/dist/zukhruf/queue/turn-queue.d.ts.map +1 -1
  88. package/dist/zukhruf/runtime/agent-runtime.d.ts +148 -43
  89. package/dist/zukhruf/runtime/agent-runtime.d.ts.map +1 -1
  90. package/dist/zukhruf/runtime/agent-turn-executor.d.ts +9 -2
  91. package/dist/zukhruf/runtime/agent-turn-executor.d.ts.map +1 -1
  92. package/dist/zukhruf/runtime/approval-controller.d.ts +10 -25
  93. package/dist/zukhruf/runtime/approval-controller.d.ts.map +1 -1
  94. package/dist/zukhruf/runtime/compaction.d.ts +47 -0
  95. package/dist/zukhruf/runtime/compaction.d.ts.map +1 -0
  96. package/dist/zukhruf/runtime/conversation-status/change-source.d.ts +19 -0
  97. package/dist/zukhruf/runtime/conversation-status/change-source.d.ts.map +1 -0
  98. package/dist/zukhruf/runtime/conversation-status/child-progress.d.ts +84 -0
  99. package/dist/zukhruf/runtime/conversation-status/child-progress.d.ts.map +1 -0
  100. package/dist/zukhruf/runtime/conversation-status/pg-boss-change-source.d.ts +22 -0
  101. package/dist/zukhruf/runtime/conversation-status/pg-boss-change-source.d.ts.map +1 -0
  102. package/dist/zukhruf/runtime/conversation-status/projector.d.ts +62 -0
  103. package/dist/zukhruf/runtime/conversation-status/projector.d.ts.map +1 -0
  104. package/dist/zukhruf/runtime/conversation-status/status-publishing-turn-queue.d.ts +20 -0
  105. package/dist/zukhruf/runtime/conversation-status/status-publishing-turn-queue.d.ts.map +1 -0
  106. package/dist/zukhruf/runtime/plugin/agent-skills.d.ts +22 -0
  107. package/dist/zukhruf/runtime/plugin/agent-skills.d.ts.map +1 -0
  108. package/dist/zukhruf/runtime/plugin/plugin-agents.d.ts +14 -0
  109. package/dist/zukhruf/runtime/plugin/plugin-agents.d.ts.map +1 -0
  110. package/dist/zukhruf/runtime/plugin/plugin-bindings.d.ts +8 -0
  111. package/dist/zukhruf/runtime/plugin/plugin-bindings.d.ts.map +1 -0
  112. package/dist/zukhruf/runtime/plugin/plugin-context-composition.d.ts +7 -0
  113. package/dist/zukhruf/runtime/plugin/plugin-context-composition.d.ts.map +1 -0
  114. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts +38 -0
  115. package/dist/zukhruf/runtime/plugin/plugin-manager.d.ts.map +1 -0
  116. package/dist/zukhruf/runtime/plugin/plugin-tool-composition.d.ts +10 -0
  117. package/dist/zukhruf/runtime/plugin/plugin-tool-composition.d.ts.map +1 -0
  118. package/dist/zukhruf/tool.d.ts +5 -1
  119. package/dist/zukhruf/tool.d.ts.map +1 -1
  120. package/package.json +72 -6
  121. package/dist/zukhruf/multi-agent-v2-config.d.ts.map +0 -1
  122. package/dist/zukhruf/protocol/parse.d.ts.map +0 -1
  123. package/dist/zukhruf/protocol/session.d.ts +0 -23
  124. package/dist/zukhruf/protocol/session.d.ts.map +0 -1
  125. package/dist/zukhruf/protocol/validator.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
  130. /package/dist/zukhruf/{protocol → plugins/http}/parse.d.ts +0 -0
  131. /package/dist/zukhruf/{protocol → plugins/http}/validator.d.ts +0 -0
@@ -0,0 +1,999 @@
1
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
2
+ import {
3
+ ContextEngine as ContextEngine5
4
+ } from "@deepagents/context";
5
+
6
+ // packages/experimental/src/zukhruf/control-plane/agent-control-plane.ts
7
+ import { v5 as uuidv54 } from "uuid";
8
+
9
+ // packages/experimental/src/zukhruf/control-plane/agent-directory.ts
10
+ import { v5 as uuidv5 } from "uuid";
11
+
12
+ // packages/experimental/src/zukhruf/control-plane/agent-history-forker.ts
13
+ import { validateUIMessages } from "ai";
14
+ import { v5 as uuidv52 } from "uuid";
15
+ import {
16
+ isSyntheticReminderMessage
17
+ } from "@deepagents/context";
18
+
19
+ // packages/experimental/src/zukhruf/control-plane/agent-status-projector.ts
20
+ import { isTextUIPart } from "ai";
21
+ import { z } from "zod";
22
+ import {
23
+ ContextEngine
24
+ } from "@deepagents/context";
25
+ var listedAgentStatusSchema = z.union([
26
+ z.enum(["pending_init", "running", "interrupted", "shutdown", "not_found"]),
27
+ z.object({ completed: z.string().nullable() }).strict(),
28
+ z.object({ errored: z.string() }).strict()
29
+ ]);
30
+ var listedAgentSchema = z.object({
31
+ agent_name: z.string(),
32
+ agent_status: listedAgentStatusSchema
33
+ }).strict();
34
+
35
+ // packages/experimental/src/zukhruf/control-plane/agent-turn-id.ts
36
+ import { v5 as uuidv53 } from "uuid";
37
+ function conversationNamespace(conversation) {
38
+ if (!conversation.chatId.trim() || !conversation.userId.trim()) {
39
+ throw new Error("conversation requires non-empty chatId and userId");
40
+ }
41
+ return uuidv53(
42
+ JSON.stringify([conversation.userId, conversation.chatId]),
43
+ uuidv53.URL
44
+ );
45
+ }
46
+
47
+ // packages/experimental/src/zukhruf/runtime/agent-turn-executor.ts
48
+ import { experimental_codeModeTool } from "@ai-sdk/code-mode";
49
+ import {
50
+ jsonSchema,
51
+ tool
52
+ } from "ai";
53
+ import {
54
+ ContextEngine as ContextEngine2,
55
+ agent,
56
+ assistant,
57
+ chat,
58
+ role,
59
+ user
60
+ } from "@deepagents/context";
61
+ import { elementsSchema } from "@deepagents/elements";
62
+ import {
63
+ elementsFragment,
64
+ elementsStreamTransform
65
+ } from "@deepagents/elements/context";
66
+
67
+ // packages/experimental/src/zukhruf/runtime/compaction.ts
68
+ import {
69
+ asSchema,
70
+ modelMessageSchema as modelMessageSchema2
71
+ } from "ai";
72
+ import { z as z2 } from "zod";
73
+
74
+ // packages/compaction/dist/index.js
75
+ import {
76
+ generateText,
77
+ modelMessageSchema
78
+ } from "ai";
79
+
80
+ // packages/experimental/src/zukhruf/runtime/compaction.ts
81
+ var checkpointSchema = z2.object({
82
+ sourceCount: z2.number().int().positive(),
83
+ sourceHash: z2.string(),
84
+ replacement: z2.array(z2.unknown()).transform(
85
+ (messages) => messages.map((message) => modelMessageSchema2.parse(message))
86
+ )
87
+ });
88
+ var cacheObservationSchema = z2.object({
89
+ scope: z2.string(),
90
+ prefixLength: z2.number().int().nonnegative(),
91
+ prefixHash: z2.string(),
92
+ startedAt: z2.number().int().nonnegative(),
93
+ retentionMs: z2.number().int().positive().optional()
94
+ });
95
+ var inputUsageSchema = cacheObservationSchema.pick({ scope: true, prefixLength: true, prefixHash: true }).extend({ inputTokens: z2.number().int().nonnegative() });
96
+
97
+ // packages/experimental/src/zukhruf/runtime/plugin/agent-skills.ts
98
+ import {
99
+ parseFrontmatter,
100
+ skills
101
+ } from "@deepagents/context";
102
+
103
+ // packages/experimental/src/zukhruf/runtime/approval-controller.ts
104
+ import {
105
+ getToolName,
106
+ isToolUIPart
107
+ } from "ai";
108
+ import {
109
+ ContextEngine as ContextEngine3,
110
+ assistant as assistant2
111
+ } from "@deepagents/context";
112
+
113
+ // packages/experimental/src/zukhruf/runtime/conversation-status/projector.ts
114
+ import {
115
+ ContextEngine as ContextEngine4
116
+ } from "@deepagents/context";
117
+
118
+ // packages/experimental/src/zukhruf/runtime/conversation-status/child-progress.ts
119
+ import { z as z3 } from "zod";
120
+ var childActivitySchema = z3.object({
121
+ id: z3.string(),
122
+ type: z3.enum(["spawn", "message", "followup", "interrupt", "completion"]),
123
+ at: z3.number(),
124
+ actorPath: z3.string(),
125
+ targetPath: z3.string(),
126
+ streamId: z3.string(),
127
+ outcome: z3.enum(["completed", "failed", "cancelled"]).optional()
128
+ });
129
+ var childActivitiesSchema = z3.partialRecord(
130
+ childActivitySchema.shape.type,
131
+ childActivitySchema
132
+ );
133
+ var childActivityMetadataSchema = z3.looseObject({
134
+ childActivities: childActivitiesSchema.default({})
135
+ });
136
+
137
+ // packages/experimental/src/zukhruf/collaboration/interrupt-agent.ts
138
+ import { tool as tool2 } from "ai";
139
+ import { z as z4 } from "zod";
140
+ var interruptAgentInputSchema = z4.object({
141
+ target: z4.string().trim().min(1).describe(
142
+ "The canonical /root/... path, or a descendant-relative target name."
143
+ )
144
+ });
145
+ var interruptAgentOutputSchema = z4.object({ previous_status: listedAgentStatusSchema }).strict();
146
+ var interruptAgentTool = tool2({
147
+ description: "Interrupt an agent's current turn, if any, and return its previous status. The agent remains available for messages and follow-up tasks.",
148
+ inputSchema: interruptAgentInputSchema,
149
+ outputSchema: interruptAgentOutputSchema,
150
+ execute: async (input, { context }) => context.controlPlane.interruptAgent(context.actor, input)
151
+ });
152
+
153
+ // packages/experimental/src/zukhruf/collaboration/list-agents.ts
154
+ import { tool as tool3 } from "ai";
155
+ import { z as z5 } from "zod";
156
+ var listAgentsInputSchema = z5.object({
157
+ path_prefix: z5.string().trim().min(1).describe(
158
+ "Task-path prefix without a trailing slash. Omit to list the whole tree."
159
+ ).optional()
160
+ });
161
+ var listAgentsOutputSchema = z5.object({ agents: z5.array(listedAgentSchema) }).strict();
162
+ var listAgentsTool = tool3({
163
+ description: "List live agents in the current root thread tree. Optionally filter by task-path prefix.",
164
+ inputSchema: listAgentsInputSchema,
165
+ outputSchema: listAgentsOutputSchema,
166
+ execute: async ({ path_prefix }, { context }) => context.controlPlane.listAgents(context.actor, path_prefix)
167
+ });
168
+
169
+ // packages/experimental/src/zukhruf/collaboration/message-tools.ts
170
+ import { tool as tool4 } from "ai";
171
+ import { z as z6 } from "zod";
172
+ var agentMessageInputSchema = z6.object({
173
+ target: z6.string().trim().min(1).describe(
174
+ "The canonical /root/... path, or a descendant-relative target name."
175
+ ),
176
+ message: z6.string().trim().min(1).describe("The message or follow-up task.")
177
+ });
178
+ var sendMessageTool = tool4({
179
+ description: "Queue a message for another agent. Address siblings with their canonical /root/... path.",
180
+ inputSchema: agentMessageInputSchema,
181
+ execute: async (input, { context }) => {
182
+ await context.controlPlane.sendMessage(context.actor, input);
183
+ return "";
184
+ }
185
+ });
186
+ var followupTaskTool = tool4({
187
+ description: "Send a follow-up task to an existing non-root agent and wake its thread.",
188
+ inputSchema: agentMessageInputSchema,
189
+ execute: async (input, { context }) => {
190
+ await context.controlPlane.followupTask(context.actor, input);
191
+ return "";
192
+ }
193
+ });
194
+
195
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
196
+ import { tool as tool5 } from "ai";
197
+ import { z as z7 } from "zod";
198
+
199
+ // packages/experimental/src/zukhruf/control-plane/fork-turns.ts
200
+ var forkTurnsError = "fork_turns must be `none`, `all`, or a positive integer string";
201
+ function parseForkTurns(value) {
202
+ const normalized = value.trim().toLowerCase();
203
+ if (normalized === "none" || normalized === "all") return normalized;
204
+ if (!/^\d+$/.test(normalized)) return void 0;
205
+ const turns = Number(normalized);
206
+ return Number.isSafeInteger(turns) && turns > 0 ? turns : void 0;
207
+ }
208
+
209
+ // packages/experimental/src/zukhruf/collaboration/spawn-agent.ts
210
+ var spawnAgentInputSchema = z7.object({
211
+ agent_type: z7.string().trim().min(1).describe("The name of one available subagent declaration."),
212
+ task_name: z7.string().trim().min(1).refine(
213
+ (value) => value !== "." && value !== ".." && !value.includes("/"),
214
+ "task_name must be one non-empty path segment"
215
+ ).describe("One path segment naming this independent agent task."),
216
+ message: z7.string().refine((value) => value.trim().length > 0, "message cannot be empty").describe("The initial task for the spawned agent."),
217
+ fork_turns: z7.string().trim().refine((value) => parseForkTurns(value) !== void 0, forkTurnsError).describe(
218
+ "Required number of parent turns to fork. Use `none`, `all`, or a positive integer string such as `3`."
219
+ )
220
+ });
221
+ var spawnAgentOutputSchema = z7.object({ task_name: z7.string() }).strict();
222
+
223
+ // packages/experimental/src/zukhruf/collaboration/wait-agent.ts
224
+ import { tool as tool6 } from "ai";
225
+ import { z as z8 } from "zod";
226
+ var waitAgentOutputSchema = z8.object({ message: z8.string(), timed_out: z8.boolean() }).strict();
227
+
228
+ // packages/experimental/src/zukhruf/runtime/plugin/plugin-agents.ts
229
+ import { parseFrontmatter as parseFrontmatter2, role as role2 } from "@deepagents/context";
230
+
231
+ // packages/experimental/src/zukhruf/runtime/agent-runtime.ts
232
+ var AgentPluginCapability = class {
233
+ name;
234
+ constructor(name) {
235
+ this.name = name;
236
+ }
237
+ bind(value) {
238
+ return { capability: this, value };
239
+ }
240
+ };
241
+
242
+ // packages/experimental/src/zukhruf/plugins/conversation-scheduling/conversation-scheduler.ts
243
+ import { CronExpressionParser } from "cron-parser";
244
+ import { v5 as uuidv55 } from "uuid";
245
+ import { z as z9 } from "zod";
246
+ var DAY_MS = 24 * 60 * 60 * 1e3;
247
+ var CRON_LIFETIME_MS = 7 * DAY_MS;
248
+ var MAX_CRON_JOBS = 50;
249
+ var cronDefinitionSchema = z9.object({
250
+ id: z9.uuid(),
251
+ expression: z9.string().min(1),
252
+ prompt: z9.string(),
253
+ recurring: z9.boolean(),
254
+ timezone: z9.string().min(1),
255
+ createdAt: z9.number().int().nonnegative(),
256
+ expiresAt: z9.number().int().nonnegative(),
257
+ nextRunAt: z9.number().int().nonnegative(),
258
+ generation: z9.number().int().positive()
259
+ }).strict();
260
+ var dispatchingOccurrenceSchema = z9.object({
261
+ kind: z9.enum(["cron", "dynamic"]),
262
+ definitionId: z9.uuid().optional(),
263
+ generation: z9.number().int().positive(),
264
+ scheduledFor: z9.number().int().nonnegative(),
265
+ prompt: z9.string()
266
+ }).strict().superRefine((occurrence, context) => {
267
+ if (occurrence.kind === "cron" !== (occurrence.definitionId !== void 0)) {
268
+ context.addIssue({
269
+ code: "custom",
270
+ message: "cron occurrences require definitionId and dynamic occurrences omit it"
271
+ });
272
+ }
273
+ });
274
+ var schedulingStateSchema = z9.object({
275
+ cron: z9.record(z9.string(), cronDefinitionSchema),
276
+ dynamic: z9.object({
277
+ prompt: z9.string(),
278
+ reason: z9.string(),
279
+ createdAt: z9.number().int().nonnegative(),
280
+ nextRunAt: z9.number().int().nonnegative(),
281
+ generation: z9.number().int().positive()
282
+ }).strict().optional(),
283
+ dispatching: dispatchingOccurrenceSchema.optional()
284
+ }).strict().superRefine(({ cron }, context) => {
285
+ for (const [id, definition] of Object.entries(cron)) {
286
+ if (id !== definition.id) {
287
+ context.addIssue({
288
+ code: "custom",
289
+ message: `cron key "${id}" does not match definition id "${definition.id}"`,
290
+ path: ["cron", id, "id"]
291
+ });
292
+ }
293
+ }
294
+ });
295
+ var schedulingWakeSchema = z9.object({
296
+ conversation: z9.object({ chatId: z9.string().min(1), userId: z9.string().min(1) }).strict(),
297
+ kind: z9.enum(["cron", "dynamic"]),
298
+ definitionId: z9.uuid().optional(),
299
+ generation: z9.number().int().positive(),
300
+ scheduledFor: z9.number().int().nonnegative()
301
+ }).strict().superRefine((wake, context) => {
302
+ if (wake.kind === "cron" !== (wake.definitionId !== void 0)) {
303
+ context.addIssue({
304
+ code: "custom",
305
+ message: "cron wakes require definitionId and dynamic wakes omit it"
306
+ });
307
+ }
308
+ });
309
+ var ConversationScheduler = class _ConversationScheduler {
310
+ #scheduler;
311
+ #host;
312
+ timezone;
313
+ constructor(options) {
314
+ this.#scheduler = options.scheduler;
315
+ this.#host = options.host;
316
+ this.timezone = _ConversationScheduler.#resolveTimezone(options.timezone);
317
+ }
318
+ async createCron(conversation, input, operationId) {
319
+ const expression = input.cron.trim();
320
+ const recurring = input.recurring ?? true;
321
+ const createdAt = Date.now();
322
+ const nextRunAt = this.#nextOccurrence(
323
+ expression,
324
+ this.timezone,
325
+ createdAt
326
+ );
327
+ const matches = (definition2) => definition2.expression === expression && definition2.prompt === input.prompt && definition2.recurring === recurring && definition2.timezone === this.timezone;
328
+ const id = uuidv55(operationId, conversationNamespace(conversation));
329
+ const state = await this.#read(conversation);
330
+ const existing = state.cron[id];
331
+ if (existing) {
332
+ if (matches(existing)) return existing;
333
+ throw new Error(`CronCreate operation "${operationId}" was reused`);
334
+ }
335
+ if (Object.keys(state.cron).length >= MAX_CRON_JOBS) {
336
+ throw new Error(
337
+ `CronCreate supports at most ${MAX_CRON_JOBS} active jobs per conversation`
338
+ );
339
+ }
340
+ const definition = {
341
+ id,
342
+ expression,
343
+ prompt: input.prompt,
344
+ recurring,
345
+ timezone: this.timezone,
346
+ createdAt,
347
+ expiresAt: recurring ? createdAt + CRON_LIFETIME_MS : nextRunAt,
348
+ nextRunAt,
349
+ generation: 1
350
+ };
351
+ await this.#armCron(conversation, definition);
352
+ let committed = definition;
353
+ await this.#update(conversation, (current) => {
354
+ const currentDefinition = current.cron[id];
355
+ if (currentDefinition) {
356
+ if (!matches(currentDefinition)) {
357
+ throw new Error(`CronCreate operation "${operationId}" was reused`);
358
+ }
359
+ committed = currentDefinition;
360
+ return current;
361
+ }
362
+ if (Object.keys(current.cron).length >= MAX_CRON_JOBS) {
363
+ throw new Error(
364
+ `CronCreate supports at most ${MAX_CRON_JOBS} active jobs per conversation`
365
+ );
366
+ }
367
+ return { ...current, cron: { ...current.cron, [id]: definition } };
368
+ });
369
+ return committed;
370
+ }
371
+ async cronJobs(conversation) {
372
+ const state = await this.#read(conversation);
373
+ return Object.values(state.cron).toSorted(
374
+ (left, right) => left.id.localeCompare(right.id)
375
+ );
376
+ }
377
+ async deleteCron(conversation, id) {
378
+ let removed;
379
+ await this.#update(conversation, (state) => {
380
+ removed = state.cron[id];
381
+ if (!removed) throw new Error(`CronDelete could not find job "${id}"`);
382
+ const cron = { ...state.cron };
383
+ delete cron[id];
384
+ return { ...state, cron };
385
+ });
386
+ if (!removed) throw new Error(`CronDelete could not find job "${id}"`);
387
+ try {
388
+ await this.#scheduler.cancel(this.#cronWake(conversation, removed).id);
389
+ } catch {
390
+ }
391
+ }
392
+ async scheduleDynamic(conversation, input) {
393
+ const rounded = Math.round(input.delaySeconds);
394
+ const clampedDelaySeconds = Math.min(3600, Math.max(60, rounded));
395
+ const createdAt = Date.now();
396
+ const nextRunAt = createdAt + clampedDelaySeconds * 1e3;
397
+ const generation = _ConversationScheduler.#randomGeneration();
398
+ let previous;
399
+ const dynamic = {
400
+ prompt: input.prompt,
401
+ reason: input.reason,
402
+ createdAt,
403
+ nextRunAt,
404
+ generation
405
+ };
406
+ await this.#scheduler.schedule(this.#dynamicWake(conversation, dynamic));
407
+ await this.#update(conversation, (state) => {
408
+ previous = state.dynamic;
409
+ return { ...state, dynamic };
410
+ });
411
+ if (previous) {
412
+ try {
413
+ await this.#scheduler.cancel(
414
+ this.#dynamicWake(conversation, previous).id
415
+ );
416
+ } catch {
417
+ }
418
+ }
419
+ return {
420
+ scheduledFor: nextRunAt,
421
+ clampedDelaySeconds,
422
+ wasClamped: rounded !== clampedDelaySeconds
423
+ };
424
+ }
425
+ async stopDynamic(conversation) {
426
+ let removed;
427
+ await this.#update(conversation, (state) => {
428
+ removed = state.dynamic;
429
+ if (!removed) return state;
430
+ const withoutDynamic = { ...state };
431
+ delete withoutDynamic.dynamic;
432
+ return withoutDynamic;
433
+ });
434
+ if (!removed) return 0;
435
+ try {
436
+ await this.#scheduler.cancel(this.#dynamicWake(conversation, removed).id);
437
+ } catch {
438
+ }
439
+ return 1;
440
+ }
441
+ async work(waitForActive) {
442
+ return this.#scheduler.consume((wake) => this.#handle(wake), waitForActive);
443
+ }
444
+ async materializeDueIfEligible(conversation) {
445
+ if (!await this.#host().isConversationAvailable(conversation)) return;
446
+ const state = await this.#read(conversation);
447
+ const now = Date.now();
448
+ const wake = state.dispatching ? this.#dispatchingWake(conversation, state.dispatching) : [
449
+ ...Object.values(state.cron).map((definition) => ({
450
+ runAt: definition.nextRunAt,
451
+ wake: this.#cronWake(conversation, definition)
452
+ })),
453
+ ...state.dynamic ? [
454
+ {
455
+ runAt: state.dynamic.nextRunAt,
456
+ wake: this.#dynamicWake(conversation, state.dynamic)
457
+ }
458
+ ] : []
459
+ ].filter(({ runAt }) => runAt <= now).toSorted(
460
+ (left, right) => left.runAt - right.runAt || left.wake.id.localeCompare(right.wake.id)
461
+ )[0]?.wake;
462
+ if (wake) await this.#handle(wake);
463
+ }
464
+ async #handle(rawWake) {
465
+ const wake = schedulingWakeSchema.parse(rawWake.data);
466
+ if (rawWake.runAt.getTime() !== wake.scheduledFor) {
467
+ throw new Error("Scheduling wake due time does not match its payload");
468
+ }
469
+ if (rawWake.id !== this.#wakeId(wake)) {
470
+ throw new Error(
471
+ `Scheduling wake id "${rawWake.id}" does not match its payload`
472
+ );
473
+ }
474
+ if (!await this.#host().isConversationAvailable(wake.conversation))
475
+ return;
476
+ const state = await this.#read(wake.conversation);
477
+ const dispatching = this.#matchingDispatching(state, wake);
478
+ if (dispatching) {
479
+ await this.#dispatch(wake, dispatching);
480
+ return;
481
+ }
482
+ if (state.dispatching) return;
483
+ const definition = this.#matchingCron(state, wake);
484
+ const dynamic = this.#matchingDynamic(state, wake);
485
+ const prompt = definition?.prompt ?? dynamic?.prompt;
486
+ if (prompt === void 0) return;
487
+ if (definition && definition.nextRunAt > definition.expiresAt) {
488
+ await this.#update(wake.conversation, (current) => {
489
+ const expired = this.#matchingCron(current, wake);
490
+ if (!expired) return current;
491
+ const cron = { ...current.cron };
492
+ delete cron[expired.id];
493
+ return { ...current, cron };
494
+ });
495
+ return;
496
+ }
497
+ const successor = definition?.recurring === true ? {
498
+ ...definition,
499
+ nextRunAt: this.#nextOccurrence(
500
+ definition.expression,
501
+ definition.timezone,
502
+ Math.max(Date.now(), definition.nextRunAt)
503
+ ),
504
+ generation: definition.generation + 1
505
+ } : void 0;
506
+ const activeSuccessor = successor && successor.nextRunAt <= successor.expiresAt ? successor : void 0;
507
+ if (activeSuccessor) {
508
+ await this.#armCron(wake.conversation, activeSuccessor);
509
+ }
510
+ const claimed = await this.#claimOccurrence(wake, activeSuccessor);
511
+ if (!claimed) return;
512
+ await this.#dispatch(wake, claimed);
513
+ }
514
+ async #claimOccurrence(wake, successor) {
515
+ let claimed;
516
+ await this.#update(wake.conversation, (current) => {
517
+ const concurrentClaim = this.#matchingDispatching(current, wake);
518
+ if (concurrentClaim) {
519
+ claimed = concurrentClaim;
520
+ return current;
521
+ }
522
+ if (current.dispatching) return current;
523
+ const currentDefinition = this.#matchingCron(current, wake);
524
+ const currentDynamic = this.#matchingDynamic(current, wake);
525
+ const currentPrompt = currentDefinition?.prompt ?? currentDynamic?.prompt;
526
+ if (currentPrompt === void 0) return current;
527
+ claimed = {
528
+ kind: wake.kind,
529
+ ...wake.definitionId === void 0 ? {} : { definitionId: wake.definitionId },
530
+ generation: wake.generation,
531
+ scheduledFor: wake.scheduledFor,
532
+ prompt: currentPrompt
533
+ };
534
+ if (currentDynamic) {
535
+ const withoutDynamic = { ...current };
536
+ delete withoutDynamic.dynamic;
537
+ return { ...withoutDynamic, dispatching: claimed };
538
+ }
539
+ if (!currentDefinition) return current;
540
+ const cron = { ...current.cron };
541
+ if (!successor) delete cron[currentDefinition.id];
542
+ else cron[currentDefinition.id] = successor;
543
+ return { ...current, cron, dispatching: claimed };
544
+ });
545
+ return claimed;
546
+ }
547
+ async #dispatch(wake, occurrence) {
548
+ const occurrenceId = this.#occurrenceId(wake);
549
+ const schedule = {
550
+ kind: wake.kind,
551
+ ...wake.definitionId === void 0 ? {} : { definitionId: wake.definitionId },
552
+ generation: wake.generation,
553
+ scheduledFor: wake.scheduledFor,
554
+ occurrenceId
555
+ };
556
+ await this.#host().enqueue(wake.conversation, {
557
+ message: {
558
+ id: occurrenceId,
559
+ role: "user",
560
+ parts: [{ type: "text", text: occurrence.prompt }],
561
+ metadata: { zukhruf: { origin: "scheduled", schedule } }
562
+ },
563
+ trigger: "submit-message"
564
+ });
565
+ await this.#update(wake.conversation, (current) => {
566
+ if (!this.#matchingDispatching(current, wake)) return current;
567
+ const withoutDispatching = { ...current };
568
+ delete withoutDispatching.dispatching;
569
+ return withoutDispatching;
570
+ });
571
+ }
572
+ #matchingDispatching(state, wake) {
573
+ const occurrence = state.dispatching;
574
+ return occurrence?.kind === wake.kind && occurrence.definitionId === wake.definitionId && occurrence.generation === wake.generation && occurrence.scheduledFor === wake.scheduledFor ? occurrence : void 0;
575
+ }
576
+ #matchingCron(state, wake) {
577
+ if (wake.kind !== "cron" || wake.definitionId === void 0) return;
578
+ const definition = state.cron[wake.definitionId];
579
+ return definition?.generation === wake.generation && definition.nextRunAt === wake.scheduledFor ? definition : void 0;
580
+ }
581
+ #matchingDynamic(state, wake) {
582
+ if (wake.kind !== "dynamic") return;
583
+ return state.dynamic?.generation === wake.generation && state.dynamic.nextRunAt === wake.scheduledFor ? state.dynamic : void 0;
584
+ }
585
+ #armCron(conversation, definition) {
586
+ return this.#scheduler.schedule(this.#cronWake(conversation, definition));
587
+ }
588
+ #cronWake(conversation, definition) {
589
+ return this.#toWake({
590
+ conversation,
591
+ kind: "cron",
592
+ definitionId: definition.id,
593
+ generation: definition.generation,
594
+ scheduledFor: definition.nextRunAt
595
+ });
596
+ }
597
+ #dynamicWake(conversation, dynamic) {
598
+ return this.#toWake({
599
+ conversation,
600
+ kind: "dynamic",
601
+ generation: dynamic.generation,
602
+ scheduledFor: dynamic.nextRunAt
603
+ });
604
+ }
605
+ #dispatchingWake(conversation, occurrence) {
606
+ return this.#toWake({
607
+ conversation,
608
+ kind: occurrence.kind,
609
+ ...occurrence.definitionId === void 0 ? {} : { definitionId: occurrence.definitionId },
610
+ generation: occurrence.generation,
611
+ scheduledFor: occurrence.scheduledFor
612
+ });
613
+ }
614
+ #toWake(data) {
615
+ return {
616
+ id: this.#wakeId(data),
617
+ runAt: new Date(data.scheduledFor),
618
+ data
619
+ };
620
+ }
621
+ #wakeId(wake) {
622
+ return uuidv55(
623
+ JSON.stringify([
624
+ "wake",
625
+ wake.kind,
626
+ wake.definitionId ?? null,
627
+ wake.generation,
628
+ wake.scheduledFor
629
+ ]),
630
+ conversationNamespace(wake.conversation)
631
+ );
632
+ }
633
+ #occurrenceId(wake) {
634
+ return uuidv55(
635
+ JSON.stringify([
636
+ "occurrence",
637
+ wake.kind,
638
+ wake.definitionId ?? null,
639
+ wake.generation,
640
+ wake.scheduledFor
641
+ ]),
642
+ conversationNamespace(wake.conversation)
643
+ );
644
+ }
645
+ #nextOccurrence(expression, timezone, after) {
646
+ if (expression.split(/\s+/).length !== 5) {
647
+ throw new Error("CronCreate requires exactly five cron fields");
648
+ }
649
+ const oneYearLater = new Date(after);
650
+ oneYearLater.setUTCFullYear(oneYearLater.getUTCFullYear() + 1);
651
+ try {
652
+ return CronExpressionParser.parse(expression, {
653
+ currentDate: new Date(after),
654
+ endDate: oneYearLater,
655
+ tz: timezone
656
+ }).next().getTime();
657
+ } catch (cause) {
658
+ throw new Error(
659
+ "CronCreate requires a valid five-field expression with a match in the next year",
660
+ { cause }
661
+ );
662
+ }
663
+ }
664
+ async #read(conversation) {
665
+ return this.#parse(
666
+ await this.#host().readConversationMetadata(conversation)
667
+ );
668
+ }
669
+ async #update(conversation, update) {
670
+ await this.#host().updateConversationMetadata(conversation, (stored) => {
671
+ const state = update(this.#parse(stored));
672
+ const metadata = stored ?? {};
673
+ const zukhruf = _ConversationScheduler.#record(metadata.zukhruf);
674
+ return {
675
+ ...metadata,
676
+ zukhruf: { ...zukhruf, scheduling: state }
677
+ };
678
+ });
679
+ }
680
+ #parse(metadata) {
681
+ if (metadata?.zukhruf === void 0) return { cron: {} };
682
+ const zukhruf = _ConversationScheduler.#record(metadata.zukhruf);
683
+ if (zukhruf.scheduling === void 0) return { cron: {} };
684
+ const parsed = schedulingStateSchema.safeParse(zukhruf.scheduling);
685
+ if (!parsed.success) {
686
+ throw new Error("Invalid metadata.zukhruf.scheduling state", {
687
+ cause: parsed.error
688
+ });
689
+ }
690
+ return parsed.data;
691
+ }
692
+ static #record(value) {
693
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
694
+ throw new Error("Invalid metadata.zukhruf state");
695
+ }
696
+ return value;
697
+ }
698
+ static #resolveTimezone(timezone) {
699
+ try {
700
+ return new Intl.DateTimeFormat("en", {
701
+ timeZone: timezone
702
+ }).resolvedOptions().timeZone;
703
+ } catch (cause) {
704
+ throw new Error(`Invalid scheduling timezone "${timezone}"`, { cause });
705
+ }
706
+ }
707
+ static #randomGeneration() {
708
+ const [high, low] = crypto.getRandomValues(new Uint32Array(2));
709
+ return Number(BigInt(high) << 21n | BigInt(low >>> 11)) || 1;
710
+ }
711
+ };
712
+
713
+ // packages/experimental/src/zukhruf/plugins/conversation-scheduling/tools.ts
714
+ import { tool as tool7 } from "ai";
715
+ import cronstrue from "cronstrue";
716
+ import { z as z10 } from "zod";
717
+ var nonBlank = z10.string().refine((value) => value.trim().length > 0, {
718
+ message: "must not be blank"
719
+ });
720
+ var cronCreateInput = z10.object({
721
+ cron: z10.string().trim().min(1),
722
+ prompt: nonBlank,
723
+ recurring: z10.boolean().optional()
724
+ }).strict();
725
+ var cronOutput = z10.object({
726
+ id: z10.uuid(),
727
+ humanSchedule: z10.string(),
728
+ nextRunAt: z10.number(),
729
+ timezone: z10.string(),
730
+ recurring: z10.boolean(),
731
+ warning: z10.string().optional()
732
+ }).strict();
733
+ var cronListOutput = z10.object({
734
+ jobs: z10.array(
735
+ z10.object({
736
+ id: z10.uuid(),
737
+ cron: z10.string(),
738
+ humanSchedule: z10.string(),
739
+ nextRunAt: z10.number(),
740
+ timezone: z10.string(),
741
+ prompt: z10.string(),
742
+ recurring: z10.boolean().optional()
743
+ }).strict()
744
+ )
745
+ }).strict();
746
+ var cronDeleteInput = z10.object({ id: z10.uuid() }).strict();
747
+ var cronDeleteOutput = z10.object({ id: z10.uuid() }).strict();
748
+ var scheduleWakeupInput = z10.union([
749
+ z10.object({ stop: z10.literal(true) }).strict(),
750
+ z10.object({
751
+ delaySeconds: z10.number().finite().min(60).max(3600),
752
+ reason: nonBlank,
753
+ prompt: nonBlank
754
+ }).strict()
755
+ ]);
756
+ var scheduleWakeupOutput = z10.object({
757
+ scheduledFor: z10.number(),
758
+ clampedDelaySeconds: z10.number(),
759
+ wasClamped: z10.boolean(),
760
+ stopped: z10.boolean().optional(),
761
+ cancelledWakeups: z10.number().int().nonnegative().optional()
762
+ }).strict();
763
+ var schedulingToolMetadata = {
764
+ zukhruf: {
765
+ kind: "scheduling",
766
+ codeModeExposure: "direct-model-only"
767
+ }
768
+ };
769
+ function calendarYearWarning(definition) {
770
+ if (definition.recurring) return {};
771
+ const year = new Intl.DateTimeFormat("en", {
772
+ calendar: "iso8601",
773
+ timeZone: definition.timezone,
774
+ year: "numeric"
775
+ });
776
+ const createdYear = year.format(definition.createdAt);
777
+ const nextYear = year.format(definition.nextRunAt);
778
+ if (createdYear === nextYear) return {};
779
+ return {
780
+ warning: `This one-shot cron resolves in calendar year ${nextYear}, not ${createdYear}. Confirm that year is intended.`
781
+ };
782
+ }
783
+ function createSchedulingTools(conversationScheduler) {
784
+ return {
785
+ CronCreate: tool7({
786
+ description: "Create a durable fixed cron schedule in this conversation.",
787
+ inputSchema: cronCreateInput,
788
+ outputSchema: cronOutput,
789
+ metadata: schedulingToolMetadata,
790
+ execute: async (input, { context, toolCallId }) => {
791
+ const definition = await conversationScheduler.createCron(
792
+ context.conversation,
793
+ input,
794
+ toolCallId
795
+ );
796
+ return {
797
+ id: definition.id,
798
+ humanSchedule: cronstrue.toString(definition.expression, {
799
+ throwExceptionOnParseError: true
800
+ }),
801
+ nextRunAt: definition.nextRunAt,
802
+ timezone: definition.timezone,
803
+ recurring: definition.recurring,
804
+ ...calendarYearWarning(definition)
805
+ };
806
+ }
807
+ }),
808
+ CronList: tool7({
809
+ description: "List durable cron schedules in this conversation.",
810
+ inputSchema: z10.object({}).strict(),
811
+ outputSchema: cronListOutput,
812
+ metadata: schedulingToolMetadata,
813
+ execute: async (_input, { context }) => {
814
+ return {
815
+ jobs: (await conversationScheduler.cronJobs(context.conversation)).map((definition) => ({
816
+ id: definition.id,
817
+ cron: definition.expression,
818
+ humanSchedule: cronstrue.toString(definition.expression, {
819
+ throwExceptionOnParseError: true
820
+ }),
821
+ nextRunAt: definition.nextRunAt,
822
+ timezone: definition.timezone,
823
+ prompt: definition.prompt,
824
+ ...!definition.recurring ? { recurring: false } : {}
825
+ }))
826
+ };
827
+ }
828
+ }),
829
+ CronDelete: tool7({
830
+ description: "Delete a durable cron schedule in this conversation.",
831
+ inputSchema: cronDeleteInput,
832
+ outputSchema: cronDeleteOutput,
833
+ metadata: schedulingToolMetadata,
834
+ execute: async ({ id }, { context }) => {
835
+ await conversationScheduler.deleteCron(context.conversation, id);
836
+ return { id };
837
+ }
838
+ }),
839
+ ScheduleWakeup: tool7({
840
+ description: "Replace or stop the dynamic one-shot wakeup for this conversation.",
841
+ inputSchema: scheduleWakeupInput,
842
+ outputSchema: scheduleWakeupOutput,
843
+ metadata: schedulingToolMetadata,
844
+ execute: async (input, { context }) => {
845
+ const conversation = context.conversation;
846
+ if ("stop" in input) {
847
+ return {
848
+ scheduledFor: 0,
849
+ clampedDelaySeconds: 0,
850
+ wasClamped: false,
851
+ stopped: true,
852
+ cancelledWakeups: await conversationScheduler.stopDynamic(conversation)
853
+ };
854
+ }
855
+ return conversationScheduler.scheduleDynamic(conversation, input);
856
+ }
857
+ })
858
+ };
859
+ }
860
+
861
+ // packages/experimental/src/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.ts
862
+ import { isDeepStrictEqual } from "node:util";
863
+
864
+ // packages/experimental/src/zukhruf/plugins/conversation-scheduling/wake-scheduler.ts
865
+ var WakeScheduler = class {
866
+ };
867
+
868
+ // packages/experimental/src/zukhruf/plugins/conversation-scheduling/pg-boss.wake-scheduler.ts
869
+ var PgBossWakeScheduler = class extends WakeScheduler {
870
+ #boss;
871
+ #queue;
872
+ #pollingIntervalSeconds;
873
+ #expireInSeconds;
874
+ #heartbeatSeconds;
875
+ constructor(boss, options) {
876
+ super();
877
+ this.#boss = boss;
878
+ this.#queue = options.queue;
879
+ this.#pollingIntervalSeconds = options.pollingIntervalSeconds ?? 1;
880
+ this.#expireInSeconds = options.expireInSeconds ?? 3600;
881
+ this.#heartbeatSeconds = options.heartbeatSeconds ?? 30;
882
+ }
883
+ async initialize() {
884
+ await this.#boss.createQueue(this.#queue, {
885
+ retryLimit: 20,
886
+ retryDelay: 1,
887
+ retryBackoff: true,
888
+ retryDelayMax: 60,
889
+ expireInSeconds: this.#expireInSeconds,
890
+ heartbeatSeconds: this.#heartbeatSeconds
891
+ });
892
+ }
893
+ async schedule(wake) {
894
+ if (!wake.id.trim())
895
+ throw new Error("WakeScheduler wake id cannot be empty");
896
+ if (Number.isNaN(wake.runAt.getTime())) {
897
+ throw new Error("WakeScheduler runAt must be a valid Date");
898
+ }
899
+ const inserted = await this.#boss.sendAfter(
900
+ this.#queue,
901
+ wake.data,
902
+ { id: wake.id },
903
+ wake.runAt
904
+ );
905
+ if (inserted !== null) return;
906
+ const existing = (await this.#boss.findJobs(this.#queue, { id: wake.id }))[0];
907
+ if (!existing) {
908
+ const retried = await this.#boss.sendAfter(
909
+ this.#queue,
910
+ wake.data,
911
+ { id: wake.id },
912
+ wake.runAt
913
+ );
914
+ if (retried !== null) return;
915
+ throw new Error(`WakeScheduler could not persist wake "${wake.id}"`);
916
+ }
917
+ if (existing.startAfter.getTime() !== wake.runAt.getTime() || !isDeepStrictEqual(existing.data, wake.data)) {
918
+ throw new Error(`WakeScheduler wake id "${wake.id}" is already in use`);
919
+ }
920
+ if (existing.state === "failed") {
921
+ await this.#boss.retry(this.#queue, wake.id);
922
+ } else if (existing.state === "cancelled") {
923
+ await this.#boss.resume(this.#queue, wake.id);
924
+ }
925
+ }
926
+ async cancel(id) {
927
+ if (!id.trim()) throw new Error("WakeScheduler wake id cannot be empty");
928
+ await this.#boss.cancel(this.#queue, id);
929
+ }
930
+ async consume(handler, waitForActive) {
931
+ const workerId = await this.#boss.work(
932
+ this.#queue,
933
+ {
934
+ includeMetadata: true,
935
+ pollingIntervalSeconds: this.#pollingIntervalSeconds
936
+ },
937
+ async ([job]) => {
938
+ await handler({
939
+ id: job.id,
940
+ runAt: job.startAfter,
941
+ data: job.data
942
+ });
943
+ await this.#boss.deleteJob(this.#queue, job.id);
944
+ }
945
+ );
946
+ return {
947
+ [Symbol.asyncDispose]: () => this.#boss.offWork(this.#queue, { id: workerId, wait: waitForActive })
948
+ };
949
+ }
950
+ };
951
+
952
+ // packages/experimental/src/zukhruf/plugins/conversation-scheduling/index.ts
953
+ var conversationSchedulingCapabilities = {
954
+ scheduler: new AgentPluginCapability(
955
+ "conversation-scheduling.scheduler"
956
+ ),
957
+ timezone: new AgentPluginCapability(
958
+ "conversation-scheduling.timezone"
959
+ )
960
+ };
961
+ function conversationScheduling() {
962
+ return {
963
+ name: "conversation-scheduling",
964
+ capabilities: [
965
+ conversationSchedulingCapabilities.scheduler,
966
+ conversationSchedulingCapabilities.timezone
967
+ ],
968
+ create(bindings) {
969
+ let host;
970
+ const scheduler = new ConversationScheduler({
971
+ scheduler: bindings.get(conversationSchedulingCapabilities.scheduler),
972
+ host: () => {
973
+ if (!host) {
974
+ throw new Error(
975
+ "conversation-scheduling plugin must be initialized before use"
976
+ );
977
+ }
978
+ return host;
979
+ },
980
+ timezone: bindings.get(conversationSchedulingCapabilities.timezone)
981
+ });
982
+ return {
983
+ tools: createSchedulingTools(scheduler),
984
+ async initialize(runtimeHost) {
985
+ host = runtimeHost;
986
+ },
987
+ work: (_host, waitForActive) => scheduler.work(waitForActive),
988
+ conversationAvailable: (_host, conversation) => scheduler.materializeDueIfEligible(conversation)
989
+ };
990
+ }
991
+ };
992
+ }
993
+ export {
994
+ PgBossWakeScheduler,
995
+ WakeScheduler,
996
+ conversationScheduling,
997
+ conversationSchedulingCapabilities
998
+ };
999
+ //# sourceMappingURL=index.js.map