@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,188 @@
1
+ /**
2
+ * BullMQ Backend — Production-grade task scheduling via Redis.
3
+ *
4
+ * - Cron tasks → BullMQ repeatable jobs with cron pattern
5
+ * - Interval tasks → BullMQ repeatable jobs with `every` option
6
+ * - One-shot tasks → BullMQ delayed jobs
7
+ * - Survives process restarts (Redis-persisted)
8
+ */
9
+ import { Queue, Worker } from "bullmq";
10
+ import { logger } from "../../utils/logger.js";
11
+ import { TaskError } from "../errors.js";
12
+ import { TASK_DEFAULTS, } from "../../types/taskTypes.js";
13
+ const QUEUE_NAME = "neurolink-tasks";
14
+ export class BullMQBackend {
15
+ name = "bullmq";
16
+ queue = null;
17
+ worker = null;
18
+ executors = new Map();
19
+ config;
20
+ constructor(config) {
21
+ this.config = config;
22
+ }
23
+ async initialize() {
24
+ const connection = this.getConnectionConfig();
25
+ this.queue = new Queue(QUEUE_NAME, { connection });
26
+ this.worker = new Worker(QUEUE_NAME, async (job) => {
27
+ const taskId = job.data.taskId;
28
+ const task = job.data.task;
29
+ const executor = this.executors.get(taskId);
30
+ if (!executor) {
31
+ logger.warn("[BullMQ] No executor found for task", { taskId });
32
+ return;
33
+ }
34
+ logger.info("[BullMQ] Executing task", { taskId, name: task.name });
35
+ const result = await executor(task);
36
+ return result;
37
+ }, {
38
+ connection,
39
+ concurrency: this.config.maxConcurrentRuns ?? TASK_DEFAULTS.maxConcurrentRuns,
40
+ });
41
+ this.worker.on("failed", (job, err) => {
42
+ logger.error("[BullMQ] Job failed", {
43
+ taskId: job?.data?.taskId,
44
+ error: String(err),
45
+ });
46
+ });
47
+ this.worker.on("error", (err) => {
48
+ logger.error("[BullMQ] Worker error", { error: String(err) });
49
+ });
50
+ logger.info("[BullMQ] Backend initialized");
51
+ }
52
+ async shutdown() {
53
+ if (this.worker) {
54
+ await this.worker.close();
55
+ this.worker = null;
56
+ }
57
+ if (this.queue) {
58
+ await this.queue.close();
59
+ this.queue = null;
60
+ }
61
+ this.executors.clear();
62
+ logger.info("[BullMQ] Backend shut down");
63
+ }
64
+ async schedule(task, executor) {
65
+ this.ensureInitialized();
66
+ this.executors.set(task.id, executor);
67
+ const jobData = { taskId: task.id, task };
68
+ const schedule = task.schedule;
69
+ if (schedule.type === "cron") {
70
+ await this.queue.upsertJobScheduler(task.id, {
71
+ pattern: schedule.expression,
72
+ ...(schedule.timezone ? { tz: schedule.timezone } : {}),
73
+ }, { name: task.name, data: jobData });
74
+ }
75
+ else if (schedule.type === "interval") {
76
+ await this.queue.upsertJobScheduler(task.id, { every: schedule.every }, { name: task.name, data: jobData });
77
+ }
78
+ else if (schedule.type === "once") {
79
+ const at = typeof schedule.at === "string" ? new Date(schedule.at) : schedule.at;
80
+ const delay = Math.max(0, at.getTime() - Date.now());
81
+ await this.queue.add(task.name, jobData, {
82
+ jobId: task.id,
83
+ delay,
84
+ });
85
+ }
86
+ logger.info("[BullMQ] Task scheduled", {
87
+ taskId: task.id,
88
+ type: schedule.type,
89
+ });
90
+ }
91
+ async cancel(taskId) {
92
+ this.ensureInitialized();
93
+ this.executors.delete(taskId);
94
+ // Remove repeatable job scheduler
95
+ try {
96
+ await this.queue.removeJobScheduler(taskId);
97
+ }
98
+ catch {
99
+ // May not be a repeatable job — try removing by job ID
100
+ }
101
+ // Remove delayed/waiting job
102
+ try {
103
+ const job = await this.queue.getJob(taskId);
104
+ if (job) {
105
+ await job.remove();
106
+ }
107
+ }
108
+ catch {
109
+ // Job may already be processed/removed
110
+ }
111
+ logger.info("[BullMQ] Task cancelled", { taskId });
112
+ }
113
+ async pause(taskId) {
114
+ // BullMQ doesn't have per-job pause, so we fully cancel the job scheduler
115
+ // and executor. This is intentionally destructive — cancel() removes both
116
+ // the executor from the map and the job/scheduler from Redis.
117
+ //
118
+ // Resume flow (orchestrated by TaskManager):
119
+ // 1. TaskManager.resume() updates task status to "active" in the store
120
+ // 2. TaskManager.resume() calls backend.schedule(task, newExecutor)
121
+ // 3. schedule() re-registers the executor and creates a new job/scheduler
122
+ //
123
+ // Because TaskManager always supplies a fresh executor on schedule(),
124
+ // there is no need to preserve the old executor here.
125
+ await this.cancel(taskId);
126
+ logger.info("[BullMQ] Task paused (cancelled pending jobs; TaskManager will re-schedule on resume)", { taskId });
127
+ }
128
+ async resume(taskId) {
129
+ // No-op: BullMQ resume is handled by TaskManager calling schedule() after
130
+ // this method returns. See TaskManager.resume() which calls:
131
+ // backend.schedule(updatedTask, executor)
132
+ // That call re-registers the executor and creates the job/scheduler in Redis.
133
+ logger.info("[BullMQ] Task resume requested (awaiting re-schedule from TaskManager)", { taskId });
134
+ }
135
+ async isHealthy() {
136
+ if (!this.queue) {
137
+ return false;
138
+ }
139
+ try {
140
+ // Check if the queue can reach Redis
141
+ await this.queue.getJobCounts();
142
+ return true;
143
+ }
144
+ catch {
145
+ return false;
146
+ }
147
+ }
148
+ // ── Internal ──────────────────────────────────────────
149
+ /**
150
+ * Returns a connection options object for BullMQ / ioredis.
151
+ * When a URL is provided we parse it fully, preserving TLS (`rediss://`),
152
+ * ACL username, password, db index, and any query-string parameters so
153
+ * nothing is silently dropped.
154
+ */
155
+ getConnectionConfig() {
156
+ const redis = this.config.redis ?? {};
157
+ if (redis.url) {
158
+ const parsed = new URL(redis.url);
159
+ const opts = {
160
+ host: parsed.hostname || "localhost",
161
+ port: Number(parsed.port) || 6379,
162
+ db: parsed.pathname ? Number(parsed.pathname.slice(1)) || 0 : 0,
163
+ };
164
+ if (parsed.password) {
165
+ opts.password = decodeURIComponent(parsed.password);
166
+ }
167
+ if (parsed.username) {
168
+ opts.username = decodeURIComponent(parsed.username);
169
+ }
170
+ // rediss:// scheme → enable TLS
171
+ if (parsed.protocol === "rediss:") {
172
+ opts.tls = {};
173
+ }
174
+ return opts;
175
+ }
176
+ return {
177
+ host: redis.host ?? TASK_DEFAULTS.redis.host,
178
+ port: redis.port ?? TASK_DEFAULTS.redis.port,
179
+ ...(redis.password ? { password: redis.password } : {}),
180
+ db: redis.db ?? 0,
181
+ };
182
+ }
183
+ ensureInitialized() {
184
+ if (!this.queue) {
185
+ throw TaskError.create("BACKEND_NOT_INITIALIZED", "[BullMQ] Backend not initialized. Call initialize() first.");
186
+ }
187
+ }
188
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * NodeTimeout Backend — Development/zero-dependency task scheduling.
3
+ *
4
+ * - Cron tasks → parsed with `croner`, scheduled via setTimeout chains
5
+ * - Interval tasks → setInterval
6
+ * - One-shot tasks → setTimeout
7
+ * - All timers are in-process — lost on restart
8
+ */
9
+ import { type Task, type TaskBackend, type TaskExecutorFn, type TaskManagerConfig } from "../../types/taskTypes.js";
10
+ export declare class NodeTimeoutBackend implements TaskBackend {
11
+ readonly name = "node-timeout";
12
+ private scheduled;
13
+ private paused;
14
+ private disposed;
15
+ private activeRuns;
16
+ private maxConcurrentRuns;
17
+ constructor(config: TaskManagerConfig);
18
+ initialize(): Promise<void>;
19
+ shutdown(): Promise<void>;
20
+ schedule(task: Task, executor: TaskExecutorFn): Promise<void>;
21
+ cancel(taskId: string): Promise<void>;
22
+ pause(taskId: string): Promise<void>;
23
+ resume(taskId: string): Promise<void>;
24
+ isHealthy(): Promise<boolean>;
25
+ private executeTask;
26
+ private clearEntry;
27
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * NodeTimeout Backend — Development/zero-dependency task scheduling.
3
+ *
4
+ * - Cron tasks → parsed with `croner`, scheduled via setTimeout chains
5
+ * - Interval tasks → setInterval
6
+ * - One-shot tasks → setTimeout
7
+ * - All timers are in-process — lost on restart
8
+ */
9
+ import { Cron } from "croner";
10
+ import { logger } from "../../utils/logger.js";
11
+ import { TASK_DEFAULTS, } from "../../types/taskTypes.js";
12
+ export class NodeTimeoutBackend {
13
+ name = "node-timeout";
14
+ scheduled = new Map();
15
+ paused = new Map();
16
+ disposed = false;
17
+ activeRuns = 0;
18
+ maxConcurrentRuns;
19
+ constructor(config) {
20
+ this.maxConcurrentRuns =
21
+ config.maxConcurrentRuns ?? TASK_DEFAULTS.maxConcurrentRuns;
22
+ }
23
+ async initialize() {
24
+ logger.info("[NodeTimeout] Backend initialized");
25
+ }
26
+ async shutdown() {
27
+ this.disposed = true;
28
+ for (const entry of this.scheduled.values()) {
29
+ this.clearEntry(entry);
30
+ }
31
+ this.scheduled.clear();
32
+ this.paused.clear();
33
+ logger.info("[NodeTimeout] Backend shut down");
34
+ }
35
+ async schedule(task, executor) {
36
+ // Cancel existing schedule for this task if any
37
+ await this.cancel(task.id);
38
+ const entry = { taskId: task.id, executor, task };
39
+ const schedule = task.schedule;
40
+ if (schedule.type === "cron") {
41
+ entry.cronJob = new Cron(schedule.expression, {
42
+ timezone: schedule.timezone,
43
+ catch: (err) => {
44
+ logger.error("[NodeTimeout] Cron execution error", {
45
+ taskId: task.id,
46
+ error: String(err),
47
+ });
48
+ },
49
+ }, () => {
50
+ this.executeTask(entry);
51
+ });
52
+ }
53
+ else if (schedule.type === "interval") {
54
+ // Wait for the first interval tick before executing
55
+ entry.intervalId = setInterval(() => {
56
+ this.executeTask(entry);
57
+ }, schedule.every);
58
+ }
59
+ else if (schedule.type === "once") {
60
+ const at = typeof schedule.at === "string" ? new Date(schedule.at) : schedule.at;
61
+ const delay = Math.max(0, at.getTime() - Date.now());
62
+ entry.timeoutId = setTimeout(() => {
63
+ this.executeTask(entry);
64
+ this.scheduled.delete(task.id);
65
+ }, delay);
66
+ }
67
+ this.scheduled.set(task.id, entry);
68
+ logger.info("[NodeTimeout] Task scheduled", {
69
+ taskId: task.id,
70
+ type: schedule.type,
71
+ });
72
+ }
73
+ async cancel(taskId) {
74
+ const entry = this.scheduled.get(taskId);
75
+ if (entry) {
76
+ this.clearEntry(entry);
77
+ this.scheduled.delete(taskId);
78
+ }
79
+ this.paused.delete(taskId);
80
+ logger.debug("[NodeTimeout] Task cancelled", { taskId });
81
+ }
82
+ async pause(taskId) {
83
+ const entry = this.scheduled.get(taskId);
84
+ if (!entry) {
85
+ return;
86
+ }
87
+ this.clearEntry(entry);
88
+ this.scheduled.delete(taskId);
89
+ // Save the entry so we can re-schedule on resume
90
+ this.paused.set(taskId, entry);
91
+ logger.info("[NodeTimeout] Task paused", { taskId });
92
+ }
93
+ async resume(taskId) {
94
+ const entry = this.paused.get(taskId);
95
+ if (!entry) {
96
+ return;
97
+ }
98
+ this.paused.delete(taskId);
99
+ // Re-schedule with the saved task and executor
100
+ await this.schedule(entry.task, entry.executor);
101
+ logger.info("[NodeTimeout] Task resumed", { taskId });
102
+ }
103
+ async isHealthy() {
104
+ return !this.disposed;
105
+ }
106
+ // ── Internal ──────────────────────────────────────────
107
+ executeTask(entry) {
108
+ if (this.activeRuns >= this.maxConcurrentRuns) {
109
+ logger.warn("[NodeTimeout] Max concurrent runs reached, skipping tick", {
110
+ taskId: entry.taskId,
111
+ activeRuns: this.activeRuns,
112
+ maxConcurrentRuns: this.maxConcurrentRuns,
113
+ });
114
+ return;
115
+ }
116
+ this.activeRuns++;
117
+ entry
118
+ .executor(entry.task)
119
+ .catch((err) => {
120
+ logger.error("[NodeTimeout] Task execution failed", {
121
+ taskId: entry.taskId,
122
+ error: String(err),
123
+ });
124
+ })
125
+ .finally(() => {
126
+ this.activeRuns--;
127
+ });
128
+ }
129
+ clearEntry(entry) {
130
+ if (entry.cronJob) {
131
+ entry.cronJob.stop();
132
+ }
133
+ if (entry.intervalId !== undefined) {
134
+ clearInterval(entry.intervalId);
135
+ }
136
+ if (entry.timeoutId !== undefined) {
137
+ clearTimeout(entry.timeoutId);
138
+ }
139
+ }
140
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * TaskBackendRegistry — registration point for all task backend implementations.
3
+ * Follows the same pattern as ProviderRegistry: dynamic imports, lazy registration.
4
+ */
5
+ import type { TaskBackendName, TaskBackendFactoryFn, TaskManagerConfig, TaskBackend } from "../../types/taskTypes.js";
6
+ export declare class TaskBackendRegistry {
7
+ private static factories;
8
+ private static registered;
9
+ /**
10
+ * Register a backend factory function.
11
+ * Can be called externally to add custom backends (e.g., "pg-boss").
12
+ */
13
+ static register(name: string, factory: TaskBackendFactoryFn): void;
14
+ /**
15
+ * Register the built-in backends (BullMQ, NodeTimeout).
16
+ * Idempotent — safe to call multiple times.
17
+ */
18
+ static registerDefaults(): void;
19
+ /**
20
+ * Create a backend instance by name.
21
+ */
22
+ static create(name: TaskBackendName | string, config: TaskManagerConfig): Promise<TaskBackend>;
23
+ /**
24
+ * Check if a backend is registered.
25
+ */
26
+ static has(name: string): boolean;
27
+ /**
28
+ * List all registered backend names.
29
+ */
30
+ static getAvailable(): string[];
31
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * TaskBackendRegistry — registration point for all task backend implementations.
3
+ * Follows the same pattern as ProviderRegistry: dynamic imports, lazy registration.
4
+ */
5
+ import { logger } from "../../utils/logger.js";
6
+ import { TaskError } from "../errors.js";
7
+ export class TaskBackendRegistry {
8
+ static factories = new Map();
9
+ static registered = false;
10
+ /**
11
+ * Register a backend factory function.
12
+ * Can be called externally to add custom backends (e.g., "pg-boss").
13
+ */
14
+ static register(name, factory) {
15
+ TaskBackendRegistry.factories.set(name, factory);
16
+ logger.debug(`[TaskBackendRegistry] Registered backend: ${name}`);
17
+ }
18
+ /**
19
+ * Register the built-in backends (BullMQ, NodeTimeout).
20
+ * Idempotent — safe to call multiple times.
21
+ */
22
+ static registerDefaults() {
23
+ if (TaskBackendRegistry.registered) {
24
+ return;
25
+ }
26
+ TaskBackendRegistry.registered = true;
27
+ // BullMQ backend (production, Redis-backed)
28
+ TaskBackendRegistry.register("bullmq", async (config) => {
29
+ const { BullMQBackend } = await import("./bullmqBackend.js");
30
+ return new BullMQBackend(config);
31
+ });
32
+ // NodeTimeout backend (development, in-process timers)
33
+ TaskBackendRegistry.register("node-timeout", async (config) => {
34
+ const { NodeTimeoutBackend } = await import("./nodeTimeoutBackend.js");
35
+ return new NodeTimeoutBackend(config);
36
+ });
37
+ logger.debug("[TaskBackendRegistry] Registered default backends");
38
+ }
39
+ /**
40
+ * Create a backend instance by name.
41
+ */
42
+ static async create(name, config) {
43
+ TaskBackendRegistry.registerDefaults();
44
+ const factory = TaskBackendRegistry.factories.get(name);
45
+ if (!factory) {
46
+ const available = Array.from(TaskBackendRegistry.factories.keys());
47
+ throw TaskError.create("BACKEND_UNKNOWN", `Unknown task backend: "${name}". Available: ${available.join(", ")}`);
48
+ }
49
+ return factory(config);
50
+ }
51
+ /**
52
+ * Check if a backend is registered.
53
+ */
54
+ static has(name) {
55
+ TaskBackendRegistry.registerDefaults();
56
+ return TaskBackendRegistry.factories.has(name);
57
+ }
58
+ /**
59
+ * List all registered backend names.
60
+ */
61
+ static getAvailable() {
62
+ TaskBackendRegistry.registerDefaults();
63
+ return Array.from(TaskBackendRegistry.factories.keys());
64
+ }
65
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * TaskError — Typed error factory for the TaskManager system.
3
+ *
4
+ * Uses the standard NeuroLink createErrorFactory pattern so every task-related
5
+ * error carries a structured code, feature tag, and optional retryable flag.
6
+ */
7
+ export declare const TaskErrorCodes: {
8
+ readonly TASK_NOT_FOUND: "TASK-001";
9
+ readonly BACKEND_NOT_INITIALIZED: "TASK-002";
10
+ readonly BACKEND_UNKNOWN: "TASK-003";
11
+ readonly INVALID_TASK_STATUS: "TASK-004";
12
+ readonly TASK_LIMIT_REACHED: "TASK-005";
13
+ readonly TASK_DISABLED: "TASK-006";
14
+ readonly SCHEDULE_FAILED: "TASK-007";
15
+ };
16
+ export declare const TaskError: {
17
+ codes: {
18
+ readonly TASK_NOT_FOUND: "TASK-001";
19
+ readonly BACKEND_NOT_INITIALIZED: "TASK-002";
20
+ readonly BACKEND_UNKNOWN: "TASK-003";
21
+ readonly INVALID_TASK_STATUS: "TASK-004";
22
+ readonly TASK_LIMIT_REACHED: "TASK-005";
23
+ readonly TASK_DISABLED: "TASK-006";
24
+ readonly SCHEDULE_FAILED: "TASK-007";
25
+ };
26
+ create: (code: "TASK_NOT_FOUND" | "BACKEND_NOT_INITIALIZED" | "BACKEND_UNKNOWN" | "INVALID_TASK_STATUS" | "TASK_LIMIT_REACHED" | "TASK_DISABLED" | "SCHEDULE_FAILED", message: string, options?: {
27
+ retryable?: boolean;
28
+ details?: Record<string, unknown>;
29
+ cause?: Error;
30
+ } | undefined) => import("../index.js").NeuroLinkFeatureError;
31
+ };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * TaskError — Typed error factory for the TaskManager system.
3
+ *
4
+ * Uses the standard NeuroLink createErrorFactory pattern so every task-related
5
+ * error carries a structured code, feature tag, and optional retryable flag.
6
+ */
7
+ import { createErrorFactory } from "../core/infrastructure/baseError.js";
8
+ export const TaskErrorCodes = {
9
+ TASK_NOT_FOUND: "TASK-001",
10
+ BACKEND_NOT_INITIALIZED: "TASK-002",
11
+ BACKEND_UNKNOWN: "TASK-003",
12
+ INVALID_TASK_STATUS: "TASK-004",
13
+ TASK_LIMIT_REACHED: "TASK-005",
14
+ TASK_DISABLED: "TASK-006",
15
+ SCHEDULE_FAILED: "TASK-007",
16
+ };
17
+ export const TaskError = createErrorFactory("Task", TaskErrorCodes);
@@ -0,0 +1,43 @@
1
+ /**
2
+ * FileTaskStore — File-based persistence for TaskManager.
3
+ * Used automatically when backend is "node-timeout".
4
+ *
5
+ * Storage layout:
6
+ * {storePath} — tasks.json (all task definitions)
7
+ * {logsPath}/{taskId}.jsonl — run log per task (append-only)
8
+ * Continuation history is in-memory only (lost on restart).
9
+ */
10
+ import { type Task, type TaskStatus, type TaskRunResult, type TaskStore, type TaskManagerConfig, type ConversationEntry } from "../../types/taskTypes.js";
11
+ export declare class FileTaskStore implements TaskStore {
12
+ readonly type: "file";
13
+ private storePath;
14
+ private logsPath;
15
+ private maxRunLogs;
16
+ private maxHistoryEntries;
17
+ private tasks;
18
+ /** In-memory only — lost on restart */
19
+ private history;
20
+ private flushQueue;
21
+ constructor(config: TaskManagerConfig);
22
+ initialize(): Promise<void>;
23
+ shutdown(): Promise<void>;
24
+ save(task: Task): Promise<void>;
25
+ get(taskId: string): Promise<Task | null>;
26
+ list(filter?: {
27
+ status?: TaskStatus;
28
+ }): Promise<Task[]>;
29
+ update(taskId: string, updates: Partial<Task>): Promise<Task>;
30
+ delete(taskId: string): Promise<void>;
31
+ appendRun(taskId: string, run: TaskRunResult): Promise<void>;
32
+ getRuns(taskId: string, options?: {
33
+ limit?: number;
34
+ status?: string;
35
+ }): Promise<TaskRunResult[]>;
36
+ appendHistory(taskId: string, messages: ConversationEntry[]): Promise<void>;
37
+ getHistory(taskId: string): Promise<ConversationEntry[]>;
38
+ clearHistory(taskId: string): Promise<void>;
39
+ /** Write all tasks to disk atomically, serialized via promise queue */
40
+ private flush;
41
+ /** Prune run log if it exceeds maxRunLogs entries */
42
+ private pruneRunLog;
43
+ }