@amaster.ai/pi-task-scheduler 0.1.0-beta.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,60 @@
1
+ # @amaster.ai/pi-task-scheduler
2
+
3
+ Scheduled task domain types and execution scheduler for pi.
4
+
5
+ The package owns schedule parsing, task lifecycle state, process-local timers,
6
+ runner callbacks, and scheduler hooks. Persistence and locking are injected so
7
+ applications can use local JSON files, remote databases, or another backend
8
+ without coupling the scheduler to storage details.
9
+
10
+ ## Scope
11
+
12
+ This package does not persist data by itself and does not know how to execute a
13
+ pi chat turn. Applications provide both:
14
+
15
+ - a `ScheduledTaskStore` for persistence
16
+ - a `SchedulerLock` for single-owner execution
17
+ - a `ScheduledTaskRunner` callback for the actual work
18
+
19
+ Storage adapters live in `@amaster.ai/pi-storage/scheduler`.
20
+
21
+ ## Example
22
+
23
+ ```ts
24
+ import { PersistentTaskScheduler } from "@amaster.ai/pi-task-scheduler";
25
+ import {
26
+ FileSchedulerLock,
27
+ JsonScheduledTaskStore,
28
+ } from "@amaster.ai/pi-storage/scheduler";
29
+
30
+ const scheduler = new PersistentTaskScheduler({
31
+ store: new JsonScheduledTaskStore("/var/lib/pi/tasks.json"),
32
+ lock: new FileSchedulerLock("/var/lib/pi/tasks.lock"),
33
+ runner: async (task, run) => {
34
+ await runPrompt(task.prompt, { sessionId: run.sessionId });
35
+ },
36
+ hooks: {
37
+ onTaskFailed: ({ task, error }) => {
38
+ console.warn("scheduled task failed", task.id, error);
39
+ },
40
+ },
41
+ });
42
+
43
+ await scheduler.start();
44
+ ```
45
+
46
+ ## Scheduling
47
+
48
+ Tasks support three schedule types:
49
+
50
+ - `interval`: duration strings such as `30s`, `10m`, `1h`, or `1d`
51
+ - `once`: ISO timestamps or relative values such as `+5m`
52
+ - `cron`: 5/6-field cron expressions and a small RRULE subset
53
+
54
+ The scheduler does not catch up missed runs after process downtime. When it
55
+ starts, it registers future timers for enabled tasks.
56
+
57
+ ## Hooks
58
+
59
+ Hooks are best-effort observability callbacks. If a hook throws, the scheduler
60
+ swallows the error and keeps task state authoritative.
@@ -0,0 +1,166 @@
1
+ export type ScheduledTaskType = "cron" | "once" | "interval";
2
+ export type ScheduledTaskStatus = "success" | "error" | "running";
3
+ export type ScheduledTaskModelConfig = {
4
+ provider: string;
5
+ model: string;
6
+ thinkingLevel?: "off" | "minimal" | "low" | "medium" | "high" | "xhigh";
7
+ authProfileId?: string;
8
+ reasoning?: boolean;
9
+ };
10
+ export type ScheduledTaskRunHistoryEntry = {
11
+ id: string;
12
+ status: ScheduledTaskStatus | "paused" | "resumed";
13
+ createdAt: string;
14
+ sessionId?: string;
15
+ message?: string;
16
+ };
17
+ export type ScheduledTaskRunContext = {
18
+ historyEntryId: string;
19
+ sessionId: string;
20
+ startedAt: string;
21
+ };
22
+ export type ScheduledTask = {
23
+ id: string;
24
+ tenantId?: string;
25
+ userId?: string;
26
+ workspaceId?: string;
27
+ sessionId: string;
28
+ name?: string;
29
+ prompt: string;
30
+ type: ScheduledTaskType;
31
+ schedule: string;
32
+ intervalSeconds: number;
33
+ enabled: boolean;
34
+ model: ScheduledTaskModelConfig;
35
+ toolPolicyProfile: string;
36
+ workspaceDir?: string;
37
+ description?: string;
38
+ createdAt: string;
39
+ updatedAt: string;
40
+ lastRunAt?: string;
41
+ nextRunAt?: string;
42
+ runCount: number;
43
+ lastStatus?: ScheduledTaskStatus;
44
+ lastError?: string;
45
+ runHistory?: ScheduledTaskRunHistoryEntry[];
46
+ };
47
+ export type ScheduledTaskCreateInput = Omit<ScheduledTask, "id" | "createdAt" | "updatedAt" | "nextRunAt" | "runCount" | "lastStatus" | "lastRunAt" | "lastError" | "runHistory">;
48
+ export type ScheduledTaskUpdate = Partial<Omit<ScheduledTask, "id" | "tenantId" | "userId" | "workspaceId" | "createdAt" | "updatedAt" | "lastRunAt" | "lastError" | "nextRunAt" | "runCount" | "lastStatus" | "runHistory" | "name" | "description" | "workspaceDir">> & {
49
+ name?: string | undefined;
50
+ description?: string | undefined;
51
+ workspaceDir?: string | undefined;
52
+ };
53
+ export type TaskSchedulerStatus = {
54
+ active: boolean;
55
+ pid: number;
56
+ taskCount: number;
57
+ scheduledTimerCount: number;
58
+ scheduledCronCount: number;
59
+ runningTaskIds: string[];
60
+ lock: {
61
+ path: string;
62
+ acquired: boolean;
63
+ holderPid?: number;
64
+ };
65
+ };
66
+ export type TaskSchedulerScope = {
67
+ tenantId?: string;
68
+ userId?: string;
69
+ };
70
+ export interface TaskScheduler {
71
+ list(scope?: TaskSchedulerScope): Promise<ScheduledTask[]>;
72
+ get(taskId: string, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
73
+ status(): Promise<TaskSchedulerStatus>;
74
+ isActive(): boolean;
75
+ create(input: ScheduledTaskCreateInput): Promise<ScheduledTask>;
76
+ update(taskId: string, input: ScheduledTaskUpdate, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
77
+ delete(taskId: string, scope?: TaskSchedulerScope): Promise<boolean>;
78
+ runNow(taskId: string, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
79
+ start(): Promise<void>;
80
+ stop(): Promise<void>;
81
+ }
82
+ export interface ScheduledTaskStore {
83
+ list(scope?: TaskSchedulerScope): Promise<ScheduledTask[]>;
84
+ get(taskId: string, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
85
+ create(task: ScheduledTask): Promise<ScheduledTask>;
86
+ update(taskId: string, task: ScheduledTask, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
87
+ delete(taskId: string, scope?: TaskSchedulerScope): Promise<boolean>;
88
+ }
89
+ export interface SchedulerLock {
90
+ readonly path: string;
91
+ acquire(): boolean | Promise<boolean>;
92
+ release(): void | Promise<void>;
93
+ isAcquired(): boolean;
94
+ holderPid(): number | undefined | Promise<number | undefined>;
95
+ extend?(): boolean | Promise<boolean>;
96
+ }
97
+ export type ScheduledTaskRunner = (task: ScheduledTask, run: ScheduledTaskRunContext) => Promise<void>;
98
+ export type TaskSchedulerRunEvent = {
99
+ task: ScheduledTask;
100
+ run: ScheduledTaskRunContext;
101
+ timestamp: string;
102
+ };
103
+ export type TaskSchedulerFailureEvent = TaskSchedulerRunEvent & {
104
+ error: string;
105
+ };
106
+ export type TaskSchedulerLifecycleEvent = {
107
+ timestamp: string;
108
+ status: TaskSchedulerStatus;
109
+ };
110
+ export type TaskSchedulerHooks = {
111
+ onTaskStarted?: (event: TaskSchedulerRunEvent) => void | Promise<void>;
112
+ onTaskCompleted?: (event: TaskSchedulerRunEvent) => void | Promise<void>;
113
+ onTaskFailed?: (event: TaskSchedulerFailureEvent) => void | Promise<void>;
114
+ onSchedulerStarted?: (event: TaskSchedulerLifecycleEvent) => void | Promise<void>;
115
+ onSchedulerStopped?: (event: TaskSchedulerLifecycleEvent) => void | Promise<void>;
116
+ };
117
+ export type PersistentTaskSchedulerOptions = {
118
+ store: ScheduledTaskStore;
119
+ lock: SchedulerLock;
120
+ runner: ScheduledTaskRunner;
121
+ hooks?: TaskSchedulerHooks;
122
+ lockHeartbeatMs?: number;
123
+ };
124
+ export declare class PersistentTaskScheduler implements TaskScheduler {
125
+ private readonly options;
126
+ private readonly timers;
127
+ private readonly crons;
128
+ private readonly runningTaskIds;
129
+ private active;
130
+ private lockHeartbeat;
131
+ constructor(options: PersistentTaskSchedulerOptions);
132
+ list(scope?: TaskSchedulerScope): Promise<ScheduledTask[]>;
133
+ get(taskId: string, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
134
+ status(): Promise<TaskSchedulerStatus>;
135
+ isActive(): boolean;
136
+ create(input: ScheduledTaskCreateInput): Promise<ScheduledTask>;
137
+ update(taskId: string, input: ScheduledTaskUpdate, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
138
+ delete(taskId: string, scope?: TaskSchedulerScope): Promise<boolean>;
139
+ runNow(taskId: string, scope?: TaskSchedulerScope): Promise<ScheduledTask | undefined>;
140
+ start(): Promise<void>;
141
+ stop(): Promise<void>;
142
+ private schedule;
143
+ private execute;
144
+ private unschedule;
145
+ private refreshNextRun;
146
+ private markScheduleError;
147
+ private startLockHeartbeat;
148
+ private emitSchedulerStarted;
149
+ private emitSchedulerStopped;
150
+ private emitHook;
151
+ }
152
+ export declare function resolveScheduledTaskDefinition(input: {
153
+ type?: ScheduledTaskType;
154
+ schedule?: string;
155
+ }): Pick<ScheduledTask, "type" | "schedule" | "intervalSeconds">;
156
+ export declare function normalizeScheduledTask(rawTask: ScheduledTask): ScheduledTask;
157
+ export declare function computeNextRunAt(task: ScheduledTask): string | undefined;
158
+ export declare function createTaskHistoryEntry(status: ScheduledTaskRunHistoryEntry["status"], message?: string, options?: {
159
+ createdAt?: string;
160
+ sessionId?: string;
161
+ }): ScheduledTaskRunHistoryEntry;
162
+ export declare function appendTaskHistory(history: ScheduledTaskRunHistoryEntry[] | undefined, entry: ScheduledTaskRunHistoryEntry): ScheduledTaskRunHistoryEntry[];
163
+ export declare function updateTaskHistoryEntry(history: ScheduledTaskRunHistoryEntry[] | undefined, entryId: string, patch: Pick<ScheduledTaskRunHistoryEntry, "status"> & Pick<Partial<ScheduledTaskRunHistoryEntry>, "message">): ScheduledTaskRunHistoryEntry[];
164
+ export declare function createScheduledTaskRunSessionId(): string;
165
+ export declare function scheduleExpressionForCroner(value: string): string;
166
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,iBAAiB,GAAG,MAAM,GAAG,MAAM,GAAG,UAAU,CAAC;AAC7D,MAAM,MAAM,mBAAmB,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;AAClE,MAAM,MAAM,wBAAwB,GAAG;IACrC,QAAQ,E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AED,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,4BAA4B,EAAE,GAAG,SAAS,EACnD,OAAO,EAAE,MAAM,EACf,KAAK,EAAE,IAAI,CAAC,4BAA4B,EAAE,QAAQ,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,4BAA4B,CAAC,EAAE,SAAS,CAAC,GAC3G,4BAA4B,EAAE,CAEhC;AAED,wBAAgB,+BAA+B,IAAI,MAAM,CAExD;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAGjE"}
package/dist/index.js ADDED
@@ -0,0 +1,596 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Cron } from "croner";
3
+ export class PersistentTaskScheduler {
4
+ options;
5
+ timers = new Map();
6
+ crons = new Map();
7
+ runningTaskIds = new Set();
8
+ active = false;
9
+ lockHeartbeat;
10
+ constructor(options) {
11
+ this.options = options;
12
+ }
13
+ async list(scope = {}) {
14
+ return await this.options.store.list(scope);
15
+ }
16
+ async get(taskId, scope = {}) {
17
+ return await this.options.store.get(taskId, scope);
18
+ }
19
+ async status() {
20
+ const tasks = await this.options.store.list();
21
+ const holderPid = await this.options.lock.holderPid();
22
+ const lock = {
23
+ path: this.options.lock.path,
24
+ acquired: this.options.lock.isAcquired(),
25
+ };
26
+ if (holderPid !== undefined) {
27
+ lock.holderPid = holderPid;
28
+ }
29
+ return {
30
+ active: this.active,
31
+ pid: process.pid,
32
+ taskCount: tasks.length,
33
+ scheduledTimerCount: this.timers.size,
34
+ scheduledCronCount: this.crons.size,
35
+ runningTaskIds: [...this.runningTaskIds],
36
+ lock,
37
+ };
38
+ }
39
+ isActive() {
40
+ return this.active;
41
+ }
42
+ async create(input) {
43
+ const now = new Date().toISOString();
44
+ const task = withNextRun({
45
+ id: randomUUID(),
46
+ ...input,
47
+ createdAt: now,
48
+ updatedAt: now,
49
+ runCount: 0,
50
+ runHistory: input.enabled === false ? [createTaskHistoryEntry("paused", "Created paused")] : [],
51
+ });
52
+ const created = await this.options.store.create(task);
53
+ if (this.active) {
54
+ this.schedule(created);
55
+ }
56
+ return created;
57
+ }
58
+ async update(taskId, input, scope = {}) {
59
+ const existing = await this.options.store.get(taskId, scope);
60
+ if (!existing) {
61
+ return undefined;
62
+ }
63
+ const { name: inputName, description: inputDescription, workspaceDir: inputWorkspaceDir, ...inputRest } = input;
64
+ const nextTask = {
65
+ ...existing,
66
+ ...inputRest,
67
+ updatedAt: new Date().toISOString(),
68
+ };
69
+ if (Object.prototype.hasOwnProperty.call(input, "description") && input.description === undefined) {
70
+ delete nextTask.description;
71
+ }
72
+ else if (inputDescription !== undefined) {
73
+ nextTask.description = inputDescription;
74
+ }
75
+ if (Object.prototype.hasOwnProperty.call(input, "name") && input.name === undefined) {
76
+ delete nextTask.name;
77
+ }
78
+ else if (inputName !== undefined) {
79
+ nextTask.name = inputName;
80
+ }
81
+ if (Object.prototype.hasOwnProperty.call(input, "workspaceDir") && input.workspaceDir === undefined) {
82
+ delete nextTask.workspaceDir;
83
+ }
84
+ else if (inputWorkspaceDir !== undefined) {
85
+ nextTask.workspaceDir = inputWorkspaceDir;
86
+ }
87
+ if (input.enabled !== undefined && input.enabled !== existing.enabled) {
88
+ nextTask.runHistory = appendTaskHistory(existing.runHistory, input.enabled ? createTaskHistoryEntry("resumed", "Task resumed") : createTaskHistoryEntry("paused", "Task paused"));
89
+ }
90
+ const task = withNextRun(nextTask);
91
+ if (input.enabled !== false && existing.lastStatus === "error" && existing.lastError) {
92
+ delete task.lastError;
93
+ }
94
+ const updated = await this.options.store.update(taskId, task, scope);
95
+ if (this.active && updated) {
96
+ this.schedule(updated);
97
+ }
98
+ return updated;
99
+ }
100
+ async delete(taskId, scope = {}) {
101
+ this.unschedule(taskId);
102
+ return await this.options.store.delete(taskId, scope);
103
+ }
104
+ async runNow(taskId, scope = {}) {
105
+ const task = await this.options.store.get(taskId, scope);
106
+ if (!task) {
107
+ return undefined;
108
+ }
109
+ void this.execute(taskId);
110
+ return task;
111
+ }
112
+ async start() {
113
+ if (this.active) {
114
+ return;
115
+ }
116
+ if (!(await this.options.lock.acquire())) {
117
+ return;
118
+ }
119
+ this.active = true;
120
+ this.startLockHeartbeat();
121
+ const tasks = await this.options.store.list();
122
+ for (const task of tasks) {
123
+ this.schedule(task);
124
+ }
125
+ await this.emitSchedulerStarted();
126
+ }
127
+ async stop() {
128
+ for (const timer of this.timers.values()) {
129
+ clearTimeout(timer);
130
+ }
131
+ for (const cron of this.crons.values()) {
132
+ cron.stop();
133
+ }
134
+ this.timers.clear();
135
+ this.crons.clear();
136
+ this.active = false;
137
+ if (this.lockHeartbeat) {
138
+ clearInterval(this.lockHeartbeat);
139
+ this.lockHeartbeat = undefined;
140
+ }
141
+ await this.options.lock.release();
142
+ await this.emitSchedulerStopped();
143
+ }
144
+ schedule(task) {
145
+ this.unschedule(task.id);
146
+ if (!this.active || !task.enabled) {
147
+ return;
148
+ }
149
+ if (task.type === "cron") {
150
+ try {
151
+ const cron = new Cron(scheduleExpressionForCroner(task.schedule), { unref: true }, () => {
152
+ void this.execute(task.id);
153
+ });
154
+ this.crons.set(task.id, cron);
155
+ void this.refreshNextRun(task.id, cron.nextRun()?.toISOString());
156
+ }
157
+ catch (error) {
158
+ void this.markScheduleError(task.id, error instanceof Error ? error.message : String(error));
159
+ }
160
+ return;
161
+ }
162
+ if (task.type === "once") {
163
+ const target = new Date(task.schedule);
164
+ const delayMs = target.getTime() - Date.now();
165
+ if (!Number.isFinite(delayMs) || delayMs <= 0) {
166
+ void this.markScheduleError(task.id, `Scheduled time ${task.schedule} is in the past`);
167
+ return;
168
+ }
169
+ const timer = setTimeout(() => {
170
+ void this.execute(task.id);
171
+ }, delayMs);
172
+ timer.unref();
173
+ this.timers.set(task.id, timer);
174
+ void this.refreshNextRun(task.id, target.toISOString());
175
+ return;
176
+ }
177
+ const timer = setInterval(() => {
178
+ void this.execute(task.id);
179
+ }, task.intervalSeconds * 1000);
180
+ timer.unref();
181
+ this.timers.set(task.id, timer);
182
+ void this.refreshNextRun(task.id, new Date(Date.now() + task.intervalSeconds * 1000).toISOString());
183
+ }
184
+ async execute(taskId) {
185
+ if (!this.active || this.runningTaskIds.has(taskId)) {
186
+ return;
187
+ }
188
+ const task = await this.options.store.get(taskId);
189
+ if (!task?.enabled) {
190
+ return;
191
+ }
192
+ this.runningTaskIds.add(taskId);
193
+ const startedAt = new Date().toISOString();
194
+ const runningEntry = createTaskHistoryEntry("running", "Run started", {
195
+ createdAt: startedAt,
196
+ sessionId: createScheduledTaskRunSessionId(),
197
+ });
198
+ const runningTask = {
199
+ ...task,
200
+ lastStatus: "running",
201
+ runHistory: appendTaskHistory(task.runHistory, runningEntry),
202
+ updatedAt: startedAt,
203
+ };
204
+ await this.options.store.update(taskId, runningTask);
205
+ const run = {
206
+ historyEntryId: runningEntry.id,
207
+ sessionId: runningEntry.sessionId ?? task.sessionId,
208
+ startedAt,
209
+ };
210
+ await this.emitHook(() => this.options.hooks?.onTaskStarted?.({ task, run, timestamp: startedAt }));
211
+ try {
212
+ await this.options.runner(task, run);
213
+ const latest = await this.options.store.get(taskId) ?? runningTask;
214
+ const completedAt = new Date().toISOString();
215
+ const updated = withNextRun({
216
+ ...latest,
217
+ enabled: latest.type === "once" ? false : latest.enabled,
218
+ lastRunAt: completedAt,
219
+ lastStatus: "success",
220
+ runHistory: updateTaskHistoryEntry(latest.runHistory, runningEntry.id, {
221
+ status: "success",
222
+ message: "Run completed",
223
+ }),
224
+ runCount: latest.runCount + 1,
225
+ updatedAt: completedAt,
226
+ });
227
+ delete updated.lastError;
228
+ const stored = await this.options.store.update(taskId, updated) ?? updated;
229
+ if (updated.type === "once") {
230
+ this.unschedule(taskId);
231
+ }
232
+ await this.emitHook(() => this.options.hooks?.onTaskCompleted?.({ task: stored, run, timestamp: completedAt }));
233
+ }
234
+ catch (error) {
235
+ const latest = await this.options.store.get(taskId) ?? runningTask;
236
+ const failedAt = new Date().toISOString();
237
+ const message = error instanceof Error ? error.message : String(error);
238
+ const updated = withNextRun({
239
+ ...latest,
240
+ lastStatus: "error",
241
+ lastError: message,
242
+ runHistory: updateTaskHistoryEntry(latest.runHistory, runningEntry.id, {
243
+ status: "error",
244
+ message,
245
+ }),
246
+ updatedAt: failedAt,
247
+ });
248
+ const stored = await this.options.store.update(taskId, updated) ?? updated;
249
+ await this.emitHook(() => this.options.hooks?.onTaskFailed?.({ task: stored, run, timestamp: failedAt, error: message }));
250
+ }
251
+ finally {
252
+ this.runningTaskIds.delete(taskId);
253
+ }
254
+ }
255
+ unschedule(taskId) {
256
+ const timer = this.timers.get(taskId);
257
+ if (timer) {
258
+ clearTimeout(timer);
259
+ this.timers.delete(taskId);
260
+ }
261
+ const cron = this.crons.get(taskId);
262
+ if (cron) {
263
+ cron.stop();
264
+ this.crons.delete(taskId);
265
+ }
266
+ }
267
+ async refreshNextRun(taskId, nextRunAt) {
268
+ const task = await this.options.store.get(taskId);
269
+ if (!task || nextRunAt === task.nextRunAt) {
270
+ return;
271
+ }
272
+ const updated = { ...task, updatedAt: new Date().toISOString() };
273
+ if (nextRunAt) {
274
+ updated.nextRunAt = nextRunAt;
275
+ }
276
+ else {
277
+ delete updated.nextRunAt;
278
+ }
279
+ await this.options.store.update(taskId, updated);
280
+ }
281
+ async markScheduleError(taskId, error) {
282
+ const task = await this.options.store.get(taskId);
283
+ if (!task) {
284
+ return;
285
+ }
286
+ const updated = {
287
+ ...task,
288
+ enabled: false,
289
+ lastStatus: "error",
290
+ lastError: error,
291
+ runHistory: appendTaskHistory(task.runHistory, createTaskHistoryEntry("error", error)),
292
+ updatedAt: new Date().toISOString(),
293
+ };
294
+ delete updated.nextRunAt;
295
+ const stored = await this.options.store.update(taskId, updated) ?? updated;
296
+ await this.emitHook(() => this.options.hooks?.onTaskFailed?.({
297
+ task: stored,
298
+ run: {
299
+ historyEntryId: stored.runHistory?.at(-1)?.id ?? taskId,
300
+ sessionId: stored.sessionId,
301
+ startedAt: stored.updatedAt,
302
+ },
303
+ timestamp: stored.updatedAt,
304
+ error,
305
+ }));
306
+ }
307
+ startLockHeartbeat() {
308
+ if (!this.options.lock.extend) {
309
+ return;
310
+ }
311
+ const lockHeartbeatMs = this.options.lockHeartbeatMs ?? 10_000;
312
+ this.lockHeartbeat = setInterval(() => {
313
+ void (async () => {
314
+ if (!(await this.options.lock.extend?.())) {
315
+ await this.stop();
316
+ }
317
+ })();
318
+ }, lockHeartbeatMs);
319
+ this.lockHeartbeat.unref();
320
+ }
321
+ async emitSchedulerStarted() {
322
+ const status = await this.status();
323
+ await this.emitHook(() => this.options.hooks?.onSchedulerStarted?.({
324
+ timestamp: new Date().toISOString(),
325
+ status,
326
+ }));
327
+ }
328
+ async emitSchedulerStopped() {
329
+ const status = await this.status();
330
+ await this.emitHook(() => this.options.hooks?.onSchedulerStopped?.({
331
+ timestamp: new Date().toISOString(),
332
+ status,
333
+ }));
334
+ }
335
+ async emitHook(callback) {
336
+ try {
337
+ await callback();
338
+ }
339
+ catch {
340
+ // Hooks are observability side effects; scheduler state must not depend on them.
341
+ }
342
+ }
343
+ }
344
+ export function resolveScheduledTaskDefinition(input) {
345
+ const type = input.type;
346
+ if (!isScheduledTaskType(type)) {
347
+ throw new Error("Scheduled task type is required and must be one of: cron, once, interval");
348
+ }
349
+ if (!input.schedule?.trim()) {
350
+ throw new Error(`${type} scheduled tasks require schedule`);
351
+ }
352
+ if (type === "interval") {
353
+ const intervalSeconds = parseIntervalSeconds(input.schedule);
354
+ if (!intervalSeconds) {
355
+ throw new Error(`Invalid interval schedule: ${input.schedule}. Use formats like "30s", "5m", or "1h".`);
356
+ }
357
+ return {
358
+ type,
359
+ schedule: input.schedule.trim(),
360
+ intervalSeconds,
361
+ };
362
+ }
363
+ if (type === "once") {
364
+ const schedule = resolveOnceSchedule(input.schedule);
365
+ const delaySeconds = Math.max(1, Math.ceil((new Date(schedule).getTime() - Date.now()) / 1000));
366
+ return { type, schedule, intervalSeconds: delaySeconds };
367
+ }
368
+ validateCronSchedule(input.schedule);
369
+ return {
370
+ type,
371
+ schedule: input.schedule.trim(),
372
+ intervalSeconds: 0,
373
+ };
374
+ }
375
+ export function normalizeScheduledTask(rawTask) {
376
+ const raw = rawTask;
377
+ const type = isScheduledTaskType(raw.type) ? raw.type : "interval";
378
+ const intervalSeconds = typeof raw.intervalSeconds === "number" && Number.isFinite(raw.intervalSeconds)
379
+ ? Math.max(5, Math.floor(raw.intervalSeconds))
380
+ : 60;
381
+ const schedule = typeof raw.schedule === "string" && raw.schedule.trim()
382
+ ? raw.schedule.trim()
383
+ : type === "interval"
384
+ ? `${intervalSeconds}s`
385
+ : "";
386
+ const task = {
387
+ ...rawTask,
388
+ type,
389
+ schedule,
390
+ intervalSeconds,
391
+ enabled: typeof raw.enabled === "boolean" ? raw.enabled : true,
392
+ runCount: typeof raw.runCount === "number" && Number.isFinite(raw.runCount) ? Math.max(0, Math.floor(raw.runCount)) : 0,
393
+ runHistory: Array.isArray(raw.runHistory) ? raw.runHistory.filter(isTaskHistoryEntry).slice(-25) : [],
394
+ };
395
+ if (typeof raw.workspaceDir === "string" && raw.workspaceDir.trim()) {
396
+ task.workspaceDir = raw.workspaceDir.trim();
397
+ }
398
+ else {
399
+ delete task.workspaceDir;
400
+ }
401
+ const nextRunAt = computeNextRunAt(task);
402
+ if (nextRunAt) {
403
+ task.nextRunAt = nextRunAt;
404
+ }
405
+ else if (!task.enabled || task.type === "once") {
406
+ delete task.nextRunAt;
407
+ }
408
+ return task;
409
+ }
410
+ export function computeNextRunAt(task) {
411
+ if (!task.enabled) {
412
+ return undefined;
413
+ }
414
+ if (task.type === "interval") {
415
+ return new Date(Date.now() + task.intervalSeconds * 1000).toISOString();
416
+ }
417
+ if (task.type === "once") {
418
+ const target = new Date(task.schedule);
419
+ if (Number.isNaN(target.getTime()) || target.getTime() <= Date.now()) {
420
+ return undefined;
421
+ }
422
+ return target.toISOString();
423
+ }
424
+ try {
425
+ const cron = new Cron(scheduleExpressionForCroner(task.schedule), { paused: true });
426
+ const next = cron.nextRun()?.toISOString();
427
+ cron.stop();
428
+ return next;
429
+ }
430
+ catch {
431
+ return undefined;
432
+ }
433
+ }
434
+ export function createTaskHistoryEntry(status, message, options = {}) {
435
+ return {
436
+ id: randomUUID(),
437
+ status,
438
+ createdAt: options.createdAt ?? new Date().toISOString(),
439
+ ...(options.sessionId ? { sessionId: options.sessionId } : {}),
440
+ ...(message ? { message } : {}),
441
+ };
442
+ }
443
+ export function appendTaskHistory(history, entry) {
444
+ return [...(history ?? []), entry].slice(-25);
445
+ }
446
+ export function updateTaskHistoryEntry(history, entryId, patch) {
447
+ return (history ?? []).map((entry) => entry.id === entryId ? { ...entry, ...patch } : entry).slice(-25);
448
+ }
449
+ export function createScheduledTaskRunSessionId() {
450
+ return `scheduled-run-${randomUUID()}`;
451
+ }
452
+ export function scheduleExpressionForCroner(value) {
453
+ const schedule = value.trim();
454
+ return schedule.toUpperCase().startsWith("RRULE:") ? rruleToCronSchedule(schedule) : schedule;
455
+ }
456
+ function withNextRun(task) {
457
+ const nextRunAt = computeNextRunAt(task);
458
+ const result = { ...task };
459
+ if (nextRunAt) {
460
+ result.nextRunAt = nextRunAt;
461
+ }
462
+ else {
463
+ delete result.nextRunAt;
464
+ }
465
+ return result;
466
+ }
467
+ function isScheduledTaskType(value) {
468
+ return value === "cron" || value === "once" || value === "interval";
469
+ }
470
+ function isTaskHistoryEntry(value) {
471
+ if (!value || typeof value !== "object") {
472
+ return false;
473
+ }
474
+ const entry = value;
475
+ return typeof entry.id === "string" &&
476
+ typeof entry.createdAt === "string" &&
477
+ (entry.status === "success" || entry.status === "error" || entry.status === "running" || entry.status === "paused" || entry.status === "resumed") &&
478
+ (entry.sessionId === undefined || typeof entry.sessionId === "string") &&
479
+ (entry.message === undefined || typeof entry.message === "string");
480
+ }
481
+ function sanitizeIntervalSeconds(value) {
482
+ if (!Number.isFinite(value) || value <= 0) {
483
+ throw new Error("intervalSeconds must be a positive number");
484
+ }
485
+ return Math.max(5, Math.floor(value));
486
+ }
487
+ function parseIntervalSeconds(value) {
488
+ const match = value.trim().match(/^(\d+)(s|m|h|d)$/);
489
+ if (!match) {
490
+ return undefined;
491
+ }
492
+ const rawAmount = match[1];
493
+ const unit = match[2];
494
+ if (!rawAmount || !unit) {
495
+ return undefined;
496
+ }
497
+ const amount = Number(rawAmount);
498
+ const multipliers = {
499
+ s: 1,
500
+ m: 60,
501
+ h: 60 * 60,
502
+ d: 24 * 60 * 60,
503
+ };
504
+ const multiplier = multipliers[unit];
505
+ if (!Number.isFinite(amount) || !multiplier) {
506
+ return undefined;
507
+ }
508
+ return sanitizeIntervalSeconds(amount * multiplier);
509
+ }
510
+ function resolveOnceSchedule(value) {
511
+ const relative = parseRelativeSchedule(value);
512
+ if (relative) {
513
+ return relative;
514
+ }
515
+ const date = new Date(value);
516
+ if (Number.isNaN(date.getTime())) {
517
+ throw new Error(`Invalid once schedule: ${value}. Use an ISO timestamp or relative time like "+10m".`);
518
+ }
519
+ if (date.getTime() <= Date.now()) {
520
+ throw new Error(`Scheduled time is in the past: ${date.toISOString()}`);
521
+ }
522
+ return date.toISOString();
523
+ }
524
+ function parseRelativeSchedule(value) {
525
+ const match = value.trim().match(/^\+(\d+)(s|m|h|d)$/);
526
+ if (!match) {
527
+ return undefined;
528
+ }
529
+ const rawAmount = match[1];
530
+ const unit = match[2];
531
+ if (!rawAmount || !unit) {
532
+ return undefined;
533
+ }
534
+ const amount = Number(rawAmount);
535
+ const multipliers = {
536
+ s: 1000,
537
+ m: 60 * 1000,
538
+ h: 60 * 60 * 1000,
539
+ d: 24 * 60 * 60 * 1000,
540
+ };
541
+ const multiplier = multipliers[unit];
542
+ if (!Number.isFinite(amount) || !multiplier || amount <= 0) {
543
+ return undefined;
544
+ }
545
+ return new Date(Date.now() + amount * multiplier).toISOString();
546
+ }
547
+ function validateCronSchedule(value) {
548
+ const schedule = scheduleExpressionForCroner(value);
549
+ const fields = schedule.split(/\s+/);
550
+ if (fields.length !== 5 && fields.length !== 6) {
551
+ throw new Error(`Cron schedule must have 5 or 6 fields, got ${fields.length}`);
552
+ }
553
+ const cron = new Cron(schedule, { paused: true });
554
+ cron.stop();
555
+ }
556
+ function rruleToCronSchedule(value) {
557
+ const body = value.trim().replace(/^RRULE:/i, "");
558
+ const parts = Object.fromEntries(body.split(";").map((part) => {
559
+ const [rawKey, rawValue = ""] = part.split("=");
560
+ return [rawKey?.trim().toUpperCase() ?? "", rawValue.trim().toUpperCase()];
561
+ }));
562
+ const freq = parts.FREQ;
563
+ const hour = parseRruleNumber(parts.BYHOUR, 9, 0, 23);
564
+ const minute = parseRruleNumber(parts.BYMINUTE, 0, 0, 59);
565
+ if (freq === "HOURLY") {
566
+ return `${minute} * * * *`;
567
+ }
568
+ if (freq === "DAILY") {
569
+ return `${minute} ${hour} * * *`;
570
+ }
571
+ if (freq === "WEEKLY") {
572
+ const day = rruleDayToCron(parts.BYDAY);
573
+ return `${minute} ${hour} * * ${day}`;
574
+ }
575
+ throw new Error(`Unsupported RRULE frequency: ${freq || "missing"}`);
576
+ }
577
+ function parseRruleNumber(value, fallback, min, max) {
578
+ const parsed = Number(value ?? fallback);
579
+ return Number.isInteger(parsed) && parsed >= min && parsed <= max ? parsed : fallback;
580
+ }
581
+ function rruleDayToCron(value) {
582
+ const days = {
583
+ SU: "0",
584
+ MO: "1",
585
+ TU: "2",
586
+ WE: "3",
587
+ TH: "4",
588
+ FR: "5",
589
+ SA: "6",
590
+ };
591
+ if (!value) {
592
+ return "*";
593
+ }
594
+ return value.split(",").map((day) => days[day] ?? day).join(",");
595
+ }
596
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,IAAI,EAAE,MAAM,QAAQ,CAAC;AAkJ9B,MAAM,OAAO,uBAAuB;IAOL;IANZ,MAAM,GAAG,IAAI,GAAG,EAA0B,CAAC;IAC3C,K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GAAG,cAAc,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACxC,OAAO,GAAG,MAAM,IAAI,IAAI,QAAQ,GAAG,EAAE,CAAC;IACxC,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,gCAAgC,IAAI,IAAI,SAAS,EAAE,CAAC,CAAC;AACvE,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAyB,EAAE,QAAgB,EAAE,GAAW,EAAE,GAAW;IAC7F,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,IAAI,QAAQ,CAAC,CAAC;IACzC,OAAO,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,MAAM,IAAI,GAAG,IAAI,MAAM,IAAI,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxF,CAAC;AAED,SAAS,cAAc,CAAC,KAAyB;IAC/C,MAAM,IAAI,GAA2B;QACnC,EAAE,EAAE,GAAG;QACP,EAAE,EAAE,GAAG;QACP,EAAE,EAAE,GAAG;QACP,EAAE,EAAE,GAAG;QACP,EAAE,EAAE,GAAG;QACP,EAAE,EAAE,GAAG;QACP,EAAE,EAAE,GAAG;KACR,CAAC;IACF,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,GAAG,CAAC;IACb,CAAC;IACD,OAAO,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACnE,CAAC"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@amaster.ai/pi-task-scheduler",
3
+ "version": "0.1.0-beta.0",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./package.json": {
15
+ "default": "./package.json"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "https://github.com/TGYD-helige/pi.git",
28
+ "directory": "packages/task-scheduler"
29
+ },
30
+ "dependencies": {
31
+ "croner": "^10.0.1"
32
+ },
33
+ "devDependencies": {
34
+ "vitest": "^4.0.0"
35
+ },
36
+ "scripts": {
37
+ "build": "tsc -b",
38
+ "typecheck": "tsc -b --pretty false",
39
+ "test": "vitest run"
40
+ }
41
+ }