@juspay/neurolink 9.40.0 → 9.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/browser/neurolink.min.js +440 -433
  3. package/dist/cli/commands/task.d.ts +56 -0
  4. package/dist/cli/commands/task.js +835 -0
  5. package/dist/cli/parser.js +4 -1
  6. package/dist/lib/neurolink.d.ts +16 -0
  7. package/dist/lib/neurolink.js +119 -2
  8. package/dist/lib/tasks/backends/bullmqBackend.d.ts +32 -0
  9. package/dist/lib/tasks/backends/bullmqBackend.js +189 -0
  10. package/dist/lib/tasks/backends/nodeTimeoutBackend.d.ts +27 -0
  11. package/dist/lib/tasks/backends/nodeTimeoutBackend.js +141 -0
  12. package/dist/lib/tasks/backends/taskBackendRegistry.d.ts +31 -0
  13. package/dist/lib/tasks/backends/taskBackendRegistry.js +66 -0
  14. package/dist/lib/tasks/errors.d.ts +31 -0
  15. package/dist/lib/tasks/errors.js +18 -0
  16. package/dist/lib/tasks/store/fileTaskStore.d.ts +43 -0
  17. package/dist/lib/tasks/store/fileTaskStore.js +179 -0
  18. package/dist/lib/tasks/store/redisTaskStore.d.ts +42 -0
  19. package/dist/lib/tasks/store/redisTaskStore.js +189 -0
  20. package/dist/lib/tasks/taskExecutor.d.ts +21 -0
  21. package/dist/lib/tasks/taskExecutor.js +166 -0
  22. package/dist/lib/tasks/taskManager.d.ts +60 -0
  23. package/dist/lib/tasks/taskManager.js +393 -0
  24. package/dist/lib/tasks/tools/taskTools.d.ts +135 -0
  25. package/dist/lib/tasks/tools/taskTools.js +274 -0
  26. package/dist/lib/types/configTypes.d.ts +3 -0
  27. package/dist/lib/types/generateTypes.d.ts +13 -0
  28. package/dist/lib/types/index.d.ts +1 -0
  29. package/dist/lib/types/taskTypes.d.ts +275 -0
  30. package/dist/lib/types/taskTypes.js +37 -0
  31. package/dist/neurolink.d.ts +16 -0
  32. package/dist/neurolink.js +119 -2
  33. package/dist/tasks/backends/bullmqBackend.d.ts +32 -0
  34. package/dist/tasks/backends/bullmqBackend.js +188 -0
  35. package/dist/tasks/backends/nodeTimeoutBackend.d.ts +27 -0
  36. package/dist/tasks/backends/nodeTimeoutBackend.js +140 -0
  37. package/dist/tasks/backends/taskBackendRegistry.d.ts +31 -0
  38. package/dist/tasks/backends/taskBackendRegistry.js +65 -0
  39. package/dist/tasks/errors.d.ts +31 -0
  40. package/dist/tasks/errors.js +17 -0
  41. package/dist/tasks/store/fileTaskStore.d.ts +43 -0
  42. package/dist/tasks/store/fileTaskStore.js +178 -0
  43. package/dist/tasks/store/redisTaskStore.d.ts +42 -0
  44. package/dist/tasks/store/redisTaskStore.js +188 -0
  45. package/dist/tasks/taskExecutor.d.ts +21 -0
  46. package/dist/tasks/taskExecutor.js +165 -0
  47. package/dist/tasks/taskManager.d.ts +60 -0
  48. package/dist/tasks/taskManager.js +392 -0
  49. package/dist/tasks/tools/taskTools.d.ts +135 -0
  50. package/dist/tasks/tools/taskTools.js +273 -0
  51. package/dist/types/configTypes.d.ts +3 -0
  52. package/dist/types/generateTypes.d.ts +13 -0
  53. package/dist/types/index.d.ts +1 -0
  54. package/dist/types/taskTypes.d.ts +275 -0
  55. package/dist/types/taskTypes.js +36 -0
  56. package/package.json +3 -1
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Built-in agent tools for TaskManager.
3
+ *
4
+ * These tools allow the AI to self-schedule, manage, and inspect tasks
5
+ * during conversations. Created per-instance via `createTaskTools()` factory,
6
+ * following the same pattern as `createFileTools()` in files/fileTools.ts.
7
+ *
8
+ * @module tasks/tools/taskTools
9
+ */
10
+ import type { TaskManager } from "../taskManager.js";
11
+ import type { TaskSchedule } from "../../types/taskTypes.js";
12
+ /**
13
+ * Create task management tools bound to a TaskManager instance.
14
+ *
15
+ * These tools follow the same factory pattern as `createFileTools()` in
16
+ * `src/lib/files/fileTools.ts`. The `manager` is captured via closure,
17
+ * eliminating the need for module-level singleton state.
18
+ *
19
+ * @param manager - The TaskManager instance to bind to
20
+ * @returns Record of tool name to tool definition
21
+ *
22
+ * @example
23
+ * ```typescript
24
+ * const manager = new TaskManager(neurolink, config);
25
+ * const tools = createTaskTools(manager);
26
+ * // tools.createTask, tools.listTasks, tools.getTaskRuns, etc.
27
+ * ```
28
+ */
29
+ export declare function createTaskTools(manager: TaskManager): {
30
+ createTask: import("ai").Tool<{
31
+ name: string;
32
+ prompt: string;
33
+ schedule: {
34
+ type: "cron" | "interval" | "once";
35
+ expression?: string | undefined;
36
+ timezone?: string | undefined;
37
+ every?: number | undefined;
38
+ at?: string | undefined;
39
+ };
40
+ mode?: "isolated" | "continuation" | undefined;
41
+ }, {
42
+ success: boolean;
43
+ taskId: string;
44
+ name: string;
45
+ status: import("../../types/taskTypes.js").TaskStatus;
46
+ mode: import("../../types/taskTypes.js").TaskExecutionMode;
47
+ nextRunAt: string | undefined;
48
+ schedule: TaskSchedule;
49
+ error?: undefined;
50
+ } | {
51
+ success: boolean;
52
+ error: string;
53
+ taskId?: undefined;
54
+ name?: undefined;
55
+ status?: undefined;
56
+ mode?: undefined;
57
+ nextRunAt?: undefined;
58
+ schedule?: undefined;
59
+ }>;
60
+ listTasks: import("ai").Tool<{
61
+ status?: "failed" | "pending" | "active" | "paused" | "completed" | "cancelled" | undefined;
62
+ }, {
63
+ success: boolean;
64
+ count: number;
65
+ tasks: {
66
+ taskId: string;
67
+ name: string;
68
+ status: import("../../types/taskTypes.js").TaskStatus;
69
+ mode: import("../../types/taskTypes.js").TaskExecutionMode;
70
+ schedule: TaskSchedule;
71
+ runCount: number;
72
+ lastRunAt: string | undefined;
73
+ nextRunAt: string | undefined;
74
+ }[];
75
+ error?: undefined;
76
+ } | {
77
+ success: boolean;
78
+ error: string;
79
+ count?: undefined;
80
+ tasks?: undefined;
81
+ }>;
82
+ getTaskRuns: import("ai").Tool<{
83
+ taskId: string;
84
+ limit?: number | undefined;
85
+ }, {
86
+ success: boolean;
87
+ taskId: string;
88
+ count: number;
89
+ runs: {
90
+ runId: string;
91
+ status: "error" | "success";
92
+ output: string | undefined;
93
+ durationMs: number;
94
+ timestamp: string;
95
+ error: string | undefined;
96
+ }[];
97
+ error?: undefined;
98
+ } | {
99
+ success: boolean;
100
+ error: string;
101
+ taskId?: undefined;
102
+ count?: undefined;
103
+ runs?: undefined;
104
+ }>;
105
+ deleteTask: import("ai").Tool<{
106
+ taskId: string;
107
+ }, {
108
+ success: boolean;
109
+ error: string;
110
+ deletedTask?: undefined;
111
+ taskId?: undefined;
112
+ } | {
113
+ success: boolean;
114
+ deletedTask: string;
115
+ taskId: string;
116
+ error?: undefined;
117
+ }>;
118
+ runTaskNow: import("ai").Tool<{
119
+ taskId: string;
120
+ }, {
121
+ success: boolean;
122
+ runId: string;
123
+ status: "error" | "success";
124
+ output: string | undefined;
125
+ durationMs: number;
126
+ error: string | undefined;
127
+ } | {
128
+ success: boolean;
129
+ error: string;
130
+ runId?: undefined;
131
+ status?: undefined;
132
+ output?: undefined;
133
+ durationMs?: undefined;
134
+ }>;
135
+ };
@@ -0,0 +1,274 @@
1
+ /**
2
+ * Built-in agent tools for TaskManager.
3
+ *
4
+ * These tools allow the AI to self-schedule, manage, and inspect tasks
5
+ * during conversations. Created per-instance via `createTaskTools()` factory,
6
+ * following the same pattern as `createFileTools()` in files/fileTools.ts.
7
+ *
8
+ * @module tasks/tools/taskTools
9
+ */
10
+ import { tool } from "ai";
11
+ import { z } from "zod";
12
+ import { logger } from "../../utils/logger.js";
13
+ import { TaskError } from "../errors.js";
14
+ /**
15
+ * Parse a schedule object from tool input.
16
+ * Accepts: { type: "cron", expression } | { type: "interval", every } | { type: "once", at }
17
+ */
18
+ function parseSchedule(input) {
19
+ const type = input.type;
20
+ if (type === "cron") {
21
+ if (!input.expression || typeof input.expression !== "string") {
22
+ throw TaskError.create("SCHEDULE_FAILED", "Cron schedule requires an 'expression' field");
23
+ }
24
+ return {
25
+ type: "cron",
26
+ expression: input.expression,
27
+ ...(input.timezone ? { timezone: input.timezone } : {}),
28
+ };
29
+ }
30
+ if (type === "interval") {
31
+ if (typeof input.every !== "number" ||
32
+ !isFinite(input.every) ||
33
+ input.every <= 0) {
34
+ throw TaskError.create("SCHEDULE_FAILED", "Interval schedule requires a positive 'every' field (milliseconds)");
35
+ }
36
+ return { type: "interval", every: input.every };
37
+ }
38
+ if (type === "once") {
39
+ if (!input.at) {
40
+ throw TaskError.create("SCHEDULE_FAILED", "Once schedule requires an 'at' field (ISO 8601 date string)");
41
+ }
42
+ return { type: "once", at: input.at };
43
+ }
44
+ throw TaskError.create("SCHEDULE_FAILED", `Invalid schedule type: "${type}". Must be "cron", "interval", or "once".`);
45
+ }
46
+ /**
47
+ * Create task management tools bound to a TaskManager instance.
48
+ *
49
+ * These tools follow the same factory pattern as `createFileTools()` in
50
+ * `src/lib/files/fileTools.ts`. The `manager` is captured via closure,
51
+ * eliminating the need for module-level singleton state.
52
+ *
53
+ * @param manager - The TaskManager instance to bind to
54
+ * @returns Record of tool name to tool definition
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * const manager = new TaskManager(neurolink, config);
59
+ * const tools = createTaskTools(manager);
60
+ * // tools.createTask, tools.listTasks, tools.getTaskRuns, etc.
61
+ * ```
62
+ */
63
+ export function createTaskTools(manager) {
64
+ return {
65
+ createTask: tool({
66
+ description: 'Schedule a recurring or one-shot task that runs a prompt on a schedule. Use schedule type "cron" for calendar-based (e.g. "0 9 * * *"), "interval" for fixed frequency (every N milliseconds), or "once" for a single future execution.',
67
+ inputSchema: z.object({
68
+ name: z.string().describe("Human-readable task name"),
69
+ prompt: z.string().describe("The prompt to execute on each run"),
70
+ schedule: z
71
+ .object({
72
+ type: z.enum(["cron", "interval", "once"]),
73
+ expression: z
74
+ .string()
75
+ .optional()
76
+ .describe('Cron expression (for type "cron"), e.g. "0 9 * * *"'),
77
+ timezone: z
78
+ .string()
79
+ .optional()
80
+ .describe('IANA timezone for cron, e.g. "America/New_York"'),
81
+ every: z
82
+ .number()
83
+ .optional()
84
+ .describe('Interval in milliseconds (for type "interval")'),
85
+ at: z
86
+ .string()
87
+ .optional()
88
+ .describe('ISO 8601 timestamp (for type "once")'),
89
+ })
90
+ .describe("When to run the task"),
91
+ mode: z
92
+ .enum(["isolated", "continuation"])
93
+ .optional()
94
+ .describe('Execution mode. "isolated" = fresh context per run (default). "continuation" = preserves conversation history across runs.'),
95
+ }),
96
+ execute: async ({ name, prompt, schedule, mode }) => {
97
+ try {
98
+ const parsedSchedule = parseSchedule(schedule);
99
+ const task = await manager.create({
100
+ name,
101
+ prompt,
102
+ schedule: parsedSchedule,
103
+ mode: mode,
104
+ });
105
+ return {
106
+ success: true,
107
+ taskId: task.id,
108
+ name: task.name,
109
+ status: task.status,
110
+ mode: task.mode,
111
+ nextRunAt: task.nextRunAt,
112
+ schedule: task.schedule,
113
+ };
114
+ }
115
+ catch (error) {
116
+ logger.error("[taskTools] createTask failed", {
117
+ error: String(error),
118
+ });
119
+ return {
120
+ success: false,
121
+ error: error instanceof Error ? error.message : String(error),
122
+ };
123
+ }
124
+ },
125
+ }),
126
+ listTasks: tool({
127
+ description: "List all scheduled tasks and their current status.",
128
+ inputSchema: z.object({
129
+ status: z
130
+ .enum([
131
+ "active",
132
+ "paused",
133
+ "completed",
134
+ "failed",
135
+ "cancelled",
136
+ "pending",
137
+ ])
138
+ .optional()
139
+ .describe("Filter by task status"),
140
+ }),
141
+ execute: async ({ status }) => {
142
+ try {
143
+ const tasks = await manager.list(status
144
+ ? {
145
+ status: status,
146
+ }
147
+ : undefined);
148
+ return {
149
+ success: true,
150
+ count: tasks.length,
151
+ tasks: tasks.map((t) => ({
152
+ taskId: t.id,
153
+ name: t.name,
154
+ status: t.status,
155
+ mode: t.mode,
156
+ schedule: t.schedule,
157
+ runCount: t.runCount,
158
+ lastRunAt: t.lastRunAt,
159
+ nextRunAt: t.nextRunAt,
160
+ })),
161
+ };
162
+ }
163
+ catch (error) {
164
+ logger.error("[taskTools] listTasks failed", {
165
+ error: String(error),
166
+ });
167
+ return {
168
+ success: false,
169
+ error: error instanceof Error ? error.message : String(error),
170
+ };
171
+ }
172
+ },
173
+ }),
174
+ getTaskRuns: tool({
175
+ description: "Get the run history of a scheduled task, showing recent executions and their results.",
176
+ inputSchema: z.object({
177
+ taskId: z.string().describe("The task ID"),
178
+ limit: z
179
+ .number()
180
+ .optional()
181
+ .describe("Max results to return (default: 10)"),
182
+ }),
183
+ execute: async ({ taskId, limit }) => {
184
+ try {
185
+ const runs = await manager.runs(taskId, { limit: limit ?? 10 });
186
+ return {
187
+ success: true,
188
+ taskId,
189
+ count: runs.length,
190
+ runs: runs.map((r) => ({
191
+ runId: r.runId,
192
+ status: r.status,
193
+ output: r.output
194
+ ? r.output.length > 500
195
+ ? r.output.slice(0, 500) + "..."
196
+ : r.output
197
+ : undefined,
198
+ durationMs: r.durationMs,
199
+ timestamp: r.timestamp,
200
+ error: r.error,
201
+ })),
202
+ };
203
+ }
204
+ catch (error) {
205
+ logger.error("[taskTools] getTaskRuns failed", {
206
+ error: String(error),
207
+ });
208
+ return {
209
+ success: false,
210
+ error: error instanceof Error ? error.message : String(error),
211
+ };
212
+ }
213
+ },
214
+ }),
215
+ deleteTask: tool({
216
+ description: "Cancel and permanently remove a scheduled task.",
217
+ inputSchema: z.object({
218
+ taskId: z.string().describe("The task ID to delete"),
219
+ }),
220
+ execute: async ({ taskId }) => {
221
+ try {
222
+ const task = await manager.get(taskId);
223
+ if (!task) {
224
+ return { success: false, error: `Task not found: ${taskId}` };
225
+ }
226
+ await manager.delete(taskId);
227
+ return { success: true, deletedTask: task.name, taskId };
228
+ }
229
+ catch (error) {
230
+ logger.error("[taskTools] deleteTask failed", {
231
+ error: String(error),
232
+ });
233
+ return {
234
+ success: false,
235
+ error: error instanceof Error ? error.message : String(error),
236
+ };
237
+ }
238
+ },
239
+ }),
240
+ runTaskNow: tool({
241
+ description: "Immediately execute a scheduled task outside of its normal schedule. Returns the run result.",
242
+ inputSchema: z.object({
243
+ taskId: z.string().describe("The task ID to run"),
244
+ }),
245
+ execute: async ({ taskId }) => {
246
+ try {
247
+ const result = await manager.run(taskId);
248
+ return {
249
+ success: true,
250
+ runId: result.runId,
251
+ status: result.status,
252
+ output: result.output
253
+ ? result.output.length > 1000
254
+ ? result.output.slice(0, 1000) + "..."
255
+ : result.output
256
+ : undefined,
257
+ durationMs: result.durationMs,
258
+ error: result.error,
259
+ };
260
+ }
261
+ catch (error) {
262
+ logger.error("[taskTools] runTaskNow failed", {
263
+ error: String(error),
264
+ });
265
+ return {
266
+ success: false,
267
+ error: error instanceof Error ? error.message : String(error),
268
+ };
269
+ }
270
+ },
271
+ }),
272
+ };
273
+ }
274
+ //# sourceMappingURL=taskTools.js.map
@@ -3,6 +3,7 @@
3
3
  * Centralized configuration type definitions following the established architecture pattern
4
4
  */
5
5
  import { MCPToolRegistry } from "../mcp/toolRegistry.js";
6
+ import type { TaskManagerConfig } from "./taskTypes.js";
6
7
  import type { HITLConfig } from "../types/hitlTypes.js";
7
8
  import type { ConversationMemoryConfig } from "./conversation.js";
8
9
  import type { ObservabilityConfig } from "./observability.js";
@@ -36,6 +37,8 @@ export type NeurolinkConstructorConfig = {
36
37
  mcp?: MCPEnhancementsConfig;
37
38
  /** Authentication provider configuration */
38
39
  auth?: NeuroLinkAuthConfig;
40
+ /** TaskManager configuration (scheduled and self-running tasks) */
41
+ tasks?: TaskManagerConfig;
39
42
  };
40
43
  /**
41
44
  * Configuration for MCP enhancement modules wired into generate()/stream() paths.
@@ -315,10 +315,23 @@ export type GenerateOptions = {
315
315
  context?: StandardRecord;
316
316
  evaluationDomain?: string;
317
317
  toolUsageContext?: string;
318
+ /**
319
+ * @deprecated Use `conversationMessages` instead. This field uses a simple `{role, content}` shape
320
+ * that is not consumed by `buildMessagesArray()` — messages passed here will NOT reach the AI model
321
+ * as proper conversation turns. `conversationMessages` uses the full `ChatMessage` type and is
322
+ * correctly wired through the entire generate pipeline.
323
+ */
318
324
  conversationHistory?: Array<{
319
325
  role: string;
320
326
  content: string;
321
327
  }>;
328
+ /**
329
+ * Previous conversation as a ChatMessage array.
330
+ * Messages are injected as proper multi-turn conversation history before the current prompt,
331
+ * so the AI model sees them as real prior exchanges (not text dumped into the prompt).
332
+ * Used by task continuation mode and available to external callers.
333
+ */
334
+ conversationMessages?: ChatMessage[];
322
335
  factoryConfig?: {
323
336
  domainType?: string;
324
337
  domainConfig?: StandardRecord;
@@ -46,3 +46,4 @@ export type { ClientConfig, RequestOptions as ClientRequestOptions, RetryConfig
46
46
  export type { TokenRefresher } from "./subscriptionTypes.js";
47
47
  export * from "./proxyTypes.js";
48
48
  export type { AuthProviderType, AuthProviderConfig, MastraAuthProvider, BetterAuthConfig, Auth0Config, ClerkConfig, FirebaseConfig, SupabaseConfig, WorkOSConfig, JWTConfig, OAuth2Config, CognitoConfig, KeycloakConfig, CustomAuthConfig, BaseAuthProviderConfig, AuthUser, AuthSession, TokenType, TokenValidationResult as AuthTokenValidationResult, TokenClaims, JWK, JWKS, TokenRefreshResult, TokenValidationConfig, TokenExtractionConfig, SessionValidationResult, SessionStorage, AuthorizationResult, AuthRequestContext, AuthenticatedContext, TokenExtractionStrategy, SessionConfig, SessionStorageType, RBACConfig, PermissionDefinition, AuthCacheConfig, AuthMiddlewareOptions, AuthMiddlewareConfig, RBACMiddlewareConfig, AuthErrorCode, AuthErrorInfo, AuthErrorInfo as AuthErrorType, AuthEventType, AuthEventData, AuthEventHandler, AuthProviderFactoryFn, AuthProviderRegistration, AuthHealthCheck, AuthProviderHealthCheck, AuthEvents, AuthProviderMetadata, AuthProviderHealthStatus, AuthTokenValidator, AuthUserAuthorizer, AuthSessionManager, AuthRequestHandler, AuthUserManager, AuthLifecycle, } from "./authTypes.js";
49
+ export type { Task, TaskDefinition, TaskSchedule, TaskScheduleType, CronSchedule, IntervalSchedule, OnceSchedule, TaskExecutionMode, TaskStatus, TaskRunResult, TaskRunError, TaskStore, TaskBackend, TaskBackendName, TaskManagerConfig, TaskRetentionConfig, ConversationEntry as TaskConversationEntry, } from "./taskTypes.js";