@zhushanwen/pi-scheduler 0.4.3 → 0.5.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/README.md +4 -4
- package/package.json +2 -2
- package/skills/scheduler-ext-config/SKILL.md +4 -4
- package/src/__tests__/cron.test.ts +2 -3
- package/src/__tests__/parsing.test.ts +2 -7
- package/src/__tests__/service.test.ts +1 -1
- package/src/commands.ts +1 -1
- package/src/format.ts +1 -5
- package/src/parsing.ts +6 -9
- package/src/runtime.ts +0 -6
- package/src/service.ts +3 -2
- package/src/tool.ts +2 -2
- package/src/types.ts +0 -1
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ session_start
|
|
|
57
57
|
|
|
58
58
|
## /schedule 命令用法
|
|
59
59
|
|
|
60
|
-
注册为 `/schedule`
|
|
60
|
+
注册为 `/schedule` 命令。无参数时返回 TUI 未实现提示(用 `/schedule list` 查看任务);第一个参数匹配子命令关键词则走子命令分支,否则尝试创建任务。
|
|
61
61
|
|
|
62
62
|
### 子命令
|
|
63
63
|
|
|
@@ -90,7 +90,7 @@ session_start
|
|
|
90
90
|
|
|
91
91
|
### duration(间隔调度)
|
|
92
92
|
|
|
93
|
-
|
|
93
|
+
`<数字><单位>`,数字与单位间不留空格,**大小写不敏感**:
|
|
94
94
|
|
|
95
95
|
| 单位 | 含义 | 乘数 |
|
|
96
96
|
|------|------|------|
|
|
@@ -163,14 +163,14 @@ session_start
|
|
|
163
163
|
| 默认过期 | **7 天**(`DEFAULT_EXPIRY_MS`) | recurring 任务缺省 `expires` 时;`expires: 'never'` 关闭 |
|
|
164
164
|
| once 任务 | 触发后自动删除 | 不参与后续调度 |
|
|
165
165
|
| cron 失效 | 任务停用 + `lastStatus=failed` + `lastError='cron expression invalid'` | 不会用 `now()` 兜底导致每 tick 重触发死循环 |
|
|
166
|
-
| 忙时 dispatch | 非 force
|
|
166
|
+
| 忙时 dispatch | 非 force 任务经 session delivery 内核 park 模式:忙时消息入队等待(等 agent 空闲的 settled 边沿 / 下个 tick flush 投递),不丢弃 | force=true 绕过内核队列直投 |
|
|
167
167
|
| history | 保留最近 **20** 条执行记录 | 超出丢弃最旧;重放折叠时同样裁剪 |
|
|
168
168
|
| 持久化 | custom entry append 到 session JSONL(dispatch 成功后立即 append advance 记录执行) | 任务随 owner session 持久化,resume 后重放恢复,无需额外写盘 |
|
|
169
169
|
| 交付语义 | **at-least-once**(至少一次) | dispatch 成功后内存更新 nextRunAt 并 append advance;append 之前若进程崩溃可能重复注入一次(无精确一次保证,可接受) |
|
|
170
170
|
| 延迟写入窗口 | 新 session 首 turn 内建任务后进程崩溃可能丢失 | pi 延迟写入:首条 assistant 消息前不 flush。窗口窄、概率极低、无恢复手段 |
|
|
171
171
|
| 触发条件 | pi 进程需存活且 session 打开 | 电脑睡眠 / pi 进程未运行 = 不触发(非系统 cron,无后台守护) |
|
|
172
172
|
|
|
173
|
-
错误语义:创建时 schedule 解析失败 → `INVALID_SCHEDULE`;`run`/`toggle`/`delete` 引用不存在的 id → `TASK_NOT_FOUND`;`run` 时任务 disabled /
|
|
173
|
+
错误语义:创建时 schedule 解析失败 → `INVALID_SCHEDULE`;`run`/`toggle`/`delete` 引用不存在的 id → `TASK_NOT_FOUND`;`run` 时任务 disabled / rate-limited / 同任务已在投递队列(TTL 窗口内)→ `DISPATCH_SKIPPED`(message 含 `disabled, rate-limited, or already queued for delivery`)。
|
|
174
174
|
|
|
175
175
|
## 数据存储位置
|
|
176
176
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zhushanwen/pi-scheduler",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "index.ts",
|
|
6
6
|
"xyz-agent": {
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
48
|
"@xyz-agent/session-delivery": "0.3.0",
|
|
49
|
-
"@zhushanwen/pi-extension-logger": "0.
|
|
49
|
+
"@zhushanwen/pi-extension-logger": "0.4.0"
|
|
50
50
|
},
|
|
51
51
|
"scripts": {
|
|
52
52
|
"test": "vitest run",
|
|
@@ -33,7 +33,7 @@ description: "使用或排查 @zhushanwen/pi-scheduler(定时任务调度)
|
|
|
33
33
|
|
|
34
34
|
- **`schedule`**(创建):参数 `prompt`(必填,到期注入的消息)、`schedule`(必填,duration 或 cron)、`kind`(`once`/`recurring`,默认 `recurring`)、`name`(可选,缺省从 prompt 自动截取前 30 字)、`expires`(可选,默认 7 天;传 `"never"` 关闭过期)、`force`(可选,默认 `false`)。
|
|
35
35
|
- **`schedule_control`**(管理):`action` = `list`/`toggle`/`delete`/`run`,`id`(toggle/delete/run 必填),`enabled`(toggle 必填)。
|
|
36
|
-
- 两个工具的返回都是结构化 `{content: [{type:'text', text}], details
|
|
36
|
+
- 两个工具的返回都是结构化 `{content: [{type:'text', text}], details}`;业务失败以异常抛出(pi 只对 execute throw 置 `isError:true`,错误 message 作为 toolResult content 返回),不通过返回值表达失败。
|
|
37
37
|
|
|
38
38
|
> 创建/管理操作无需 agent idle——只有**到期 dispatch** 才受 idle/速率限制约束(见「运行限制与 dispatch 行为」)。
|
|
39
39
|
|
|
@@ -52,7 +52,7 @@ description: "使用或排查 @zhushanwen/pi-scheduler(定时任务调度)
|
|
|
52
52
|
| `h` | `hr`/`hour`/`hours` | 3_600_000 |
|
|
53
53
|
| `d` | `day`/`days` | 86_400_000 |
|
|
54
54
|
|
|
55
|
-
示例:`5m`、`2h`、`1d`、`30seconds`。正则 `/^(\d+)\s*(s|sec|...)$/i
|
|
55
|
+
示例:`5m`、`2h`、`1d`、`30seconds`。正则 `/^(\d+)\s*(s|sec|...)$/i`(注意:含空格的输入在 parseSchedule 分流时一律走 cron 分支,duration 实际不允许空格,`5 m` 解析失败)。
|
|
56
56
|
|
|
57
57
|
### cron(cron 表达式)
|
|
58
58
|
|
|
@@ -119,7 +119,7 @@ description: "使用或排查 @zhushanwen/pi-scheduler(定时任务调度)
|
|
|
119
119
|
|
|
120
120
|
dispatch 触发条件(`dispatchTask`):
|
|
121
121
|
|
|
122
|
-
- **非 force
|
|
122
|
+
- **非 force 任务**:走统一 session delivery 内核(park 模式)——到期即入队,agent 忙时消息 park 在内核队列,等 agent 空闲的 settled 边沿投递,scheduler 每 30s tick 触发一次 flush 兜底重试;不丢弃。
|
|
123
123
|
- **force=true 任务**:即使 agent busy 也立即触发(用于必须准点执行的场景)。
|
|
124
124
|
- dispatch 成功后:recurring 推进 `nextRunAt` 并 append `advance`;once 删除任务并 append `delete`;失败(`sendMessage` 抛错)记 `lastStatus='failed'` 不 rethrow,下个 tick 重试(transient 失败重试语义,不 append advance)。
|
|
125
125
|
- 注入的消息:`{content: task.prompt, customType: 'pi-scheduler:dispatched', display: true}`,`deliverAs: 'followUp'` + `triggerTurn: true`(排进 followUp 队列并唤醒 agent 开新 turn)。
|
|
@@ -137,7 +137,7 @@ dispatch 触发条件(`dispatchTask`):
|
|
|
137
137
|
- `force`:是否在 agent busy 时强制 dispatch。
|
|
138
138
|
- `createdAt` / `nextRunAt` / `expiresAt?`:时间戳(ms)。
|
|
139
139
|
- `runCount` / `lastRunAt?` / `lastStatus?`(`success`|`failed`)/ `lastError?`:执行统计。
|
|
140
|
-
- `history`:最近 20 条 `ExecutionRecord`(`{at, status
|
|
140
|
+
- `history`:最近 20 条 `ExecutionRecord`(`{at, status}`)。
|
|
141
141
|
- `ownerSessionFile?`:归属 session JSONL 路径(fork 过滤用,非持久化业务字段)。
|
|
142
142
|
- `pending?`:运行时标记「到期待 dispatch」,非持久化(与 `enabled` 正交)。
|
|
143
143
|
|
|
@@ -58,7 +58,7 @@ describe('computeNextCronRuns', () => {
|
|
|
58
58
|
})
|
|
59
59
|
|
|
60
60
|
describe('parseSchedule (cron 分支)', () => {
|
|
61
|
-
it('5 字段 cron
|
|
61
|
+
it('5 字段 cron 表达式补秒字段', async () => {
|
|
62
62
|
const result = await parseSchedule('*/10 * * * *')
|
|
63
63
|
expect(result).toEqual({
|
|
64
64
|
spec: { mode: 'cron', cronExpression: '0 */10 * * * *' },
|
|
@@ -85,8 +85,7 @@ describe('parseSchedule (cron 分支)', () => {
|
|
|
85
85
|
|
|
86
86
|
describe('normalizeCronExpression', () => {
|
|
87
87
|
it('6 字段 cron 原样返回', () => {
|
|
88
|
-
|
|
89
|
-
expect(result).toEqual({ expression: '0 9 * * 1-5 0' })
|
|
88
|
+
expect(normalizeCronExpression('0 9 * * 1-5 0')).toBe('0 9 * * 1-5 0')
|
|
90
89
|
})
|
|
91
90
|
|
|
92
91
|
it('2 字段返回 undefined', () => {
|
|
@@ -84,16 +84,11 @@ describe('formatDuration', () => {
|
|
|
84
84
|
|
|
85
85
|
describe('normalizeCronExpression', () => {
|
|
86
86
|
it('prepends seconds field for 5-field cron', () => {
|
|
87
|
-
|
|
88
|
-
expect(result).toEqual({
|
|
89
|
-
expression: '0 */10 * * * *',
|
|
90
|
-
note: 'Auto-prepended seconds field (0)',
|
|
91
|
-
})
|
|
87
|
+
expect(normalizeCronExpression('*/10 * * * *')).toBe('0 */10 * * * *')
|
|
92
88
|
})
|
|
93
89
|
|
|
94
90
|
it('keeps 6-field cron as-is', () => {
|
|
95
|
-
|
|
96
|
-
expect(result).toEqual({ expression: '0 */10 * * * *' })
|
|
91
|
+
expect(normalizeCronExpression('0 */10 * * * *')).toBe('0 */10 * * * *')
|
|
97
92
|
})
|
|
98
93
|
|
|
99
94
|
it('returns undefined for invalid field count', () => {
|
|
@@ -191,7 +191,7 @@ describe('SchedulerService', () => {
|
|
|
191
191
|
expect(result).toEqual({
|
|
192
192
|
success: false,
|
|
193
193
|
errorCode: 'DISPATCH_SKIPPED',
|
|
194
|
-
message: `Task ${id} not dispatched (
|
|
194
|
+
message: `Task ${id} not dispatched (disabled, rate-limited, or already queued for delivery).`,
|
|
195
195
|
})
|
|
196
196
|
})
|
|
197
197
|
|
package/src/commands.ts
CHANGED
|
@@ -48,7 +48,7 @@ export function registerScheduleCommand(
|
|
|
48
48
|
getService: () => SchedulerService | null,
|
|
49
49
|
) {
|
|
50
50
|
pi.registerCommand('schedule', {
|
|
51
|
-
description: 'Manage scheduled tasks.
|
|
51
|
+
description: 'Manage scheduled tasks. /schedule <schedule> <prompt> to create; /schedule list to see tasks.',
|
|
52
52
|
getArgumentCompletions(prefix: string) {
|
|
53
53
|
const service = getService()
|
|
54
54
|
const trimmed = prefix.trimStart()
|
package/src/format.ts
CHANGED
|
@@ -82,14 +82,10 @@ export function generateTaskId(): string {
|
|
|
82
82
|
|
|
83
83
|
/** autoName 任务名最大长度。 */
|
|
84
84
|
const AUTO_NAME_MAX_LENGTH = 30
|
|
85
|
-
/** 截断后保留的长度(预留省略号宽度)。 */
|
|
86
|
-
const AUTO_NAME_KEEP_LENGTH = AUTO_NAME_MAX_LENGTH - ELLIPSIS_LENGTH
|
|
87
85
|
|
|
88
86
|
/**
|
|
89
87
|
* 从 prompt 自动生成任务名称:取前 30 字。
|
|
90
88
|
*/
|
|
91
89
|
export function autoName(prompt: string): string {
|
|
92
|
-
|
|
93
|
-
if (trimmed.length <= AUTO_NAME_MAX_LENGTH) return trimmed
|
|
94
|
-
return trimmed.slice(0, AUTO_NAME_KEEP_LENGTH) + '...'
|
|
90
|
+
return truncate(prompt.trim(), AUTO_NAME_MAX_LENGTH)
|
|
95
91
|
}
|
package/src/parsing.ts
CHANGED
|
@@ -82,7 +82,7 @@ async function getCroner(): Promise<typeof import('croner') | null> {
|
|
|
82
82
|
* 规范化 cron 表达式:5 字段自动补秒字段。
|
|
83
83
|
* 返回 undefined 表示无效。
|
|
84
84
|
*/
|
|
85
|
-
export function normalizeCronExpression(input: string):
|
|
85
|
+
export function normalizeCronExpression(input: string): string | undefined {
|
|
86
86
|
const trimmed = input.trim()
|
|
87
87
|
if (!trimmed) return undefined
|
|
88
88
|
|
|
@@ -90,15 +90,12 @@ export function normalizeCronExpression(input: string): { expression: string; no
|
|
|
90
90
|
|
|
91
91
|
// 6 字段原样返回
|
|
92
92
|
if (parts.length === CRON_FIELD_COUNT_WITH_SECONDS) {
|
|
93
|
-
return
|
|
93
|
+
return trimmed
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
// 5 字段补秒字段
|
|
97
97
|
if (parts.length === CRON_FIELD_COUNT) {
|
|
98
|
-
return {
|
|
99
|
-
expression: `0 ${trimmed}`,
|
|
100
|
-
note: 'Auto-prepended seconds field (0)',
|
|
101
|
-
}
|
|
98
|
+
return `0 ${trimmed}`
|
|
102
99
|
}
|
|
103
100
|
|
|
104
101
|
return undefined
|
|
@@ -119,7 +116,7 @@ export async function computeNextCronRunAt(
|
|
|
119
116
|
const normalized = normalizeCronExpression(expression)
|
|
120
117
|
if (!normalized) return undefined
|
|
121
118
|
|
|
122
|
-
const job = new croner.Cron(normalized
|
|
119
|
+
const job = new croner.Cron(normalized, { startAt: from ? new Date(from) : undefined })
|
|
123
120
|
const next = job.nextRun()
|
|
124
121
|
return next ? next.getTime() : undefined
|
|
125
122
|
} catch {
|
|
@@ -143,7 +140,7 @@ export async function computeNextCronRuns(
|
|
|
143
140
|
const normalized = normalizeCronExpression(expression)
|
|
144
141
|
if (!normalized) return []
|
|
145
142
|
|
|
146
|
-
const job = new croner.Cron(normalized
|
|
143
|
+
const job = new croner.Cron(normalized, { startAt: from ? new Date(from) : undefined })
|
|
147
144
|
const runs: number[] = []
|
|
148
145
|
let current = from ? new Date(from) : new Date()
|
|
149
146
|
|
|
@@ -192,7 +189,7 @@ export async function parseSchedule(
|
|
|
192
189
|
const nextRun = await computeNextCronRunAt(trimmed)
|
|
193
190
|
if (nextRun !== undefined) {
|
|
194
191
|
return {
|
|
195
|
-
spec: { mode: 'cron', cronExpression: normalized
|
|
192
|
+
spec: { mode: 'cron', cronExpression: normalized },
|
|
196
193
|
}
|
|
197
194
|
}
|
|
198
195
|
}
|
package/src/runtime.ts
CHANGED
|
@@ -505,10 +505,4 @@ export class SchedulerRuntime {
|
|
|
505
505
|
const { ownerSessionFile: _o, pending: _p, history, ...rest } = task
|
|
506
506
|
return { ...rest, history: history.slice() }
|
|
507
507
|
}
|
|
508
|
-
|
|
509
|
-
// ── 工具方法 ──
|
|
510
|
-
|
|
511
|
-
getTaskCount(): number {
|
|
512
|
-
return this.tasks.size
|
|
513
|
-
}
|
|
514
508
|
}
|
package/src/service.ts
CHANGED
|
@@ -137,7 +137,8 @@ export class SchedulerService {
|
|
|
137
137
|
/**
|
|
138
138
|
* 立即执行任务。语义细分:
|
|
139
139
|
* 任务不存在 → TASK_NOT_FOUND;任务存在但 dispatch no-op
|
|
140
|
-
* (disabled /
|
|
140
|
+
* (disabled / rate-limited / 同任务入队已在 TTL 窗口内)→ DISPATCH_SKIPPED。
|
|
141
|
+
* busy 不再是 no-op:非 force 任务入队 delivery 内核即成功(park 等后续投递)。
|
|
141
142
|
* 修复了旧实现把 no-op 误报为 not found 的混同。
|
|
142
143
|
*/
|
|
143
144
|
async run(id: string | undefined): Promise<ServiceResult> {
|
|
@@ -152,7 +153,7 @@ export class SchedulerService {
|
|
|
152
153
|
return {
|
|
153
154
|
success: false,
|
|
154
155
|
errorCode: 'DISPATCH_SKIPPED',
|
|
155
|
-
message: `Task ${id} not dispatched (
|
|
156
|
+
message: `Task ${id} not dispatched (disabled, rate-limited, or already queued for delivery).`,
|
|
156
157
|
}
|
|
157
158
|
}
|
|
158
159
|
return { success: true, message: `Task ${id} executed.` }
|
package/src/tool.ts
CHANGED
|
@@ -11,7 +11,7 @@ export const ScheduleParams = Type.Object({
|
|
|
11
11
|
schedule: Type.String({ description: 'Schedule spec: duration (5m/2h/1d) for interval, or cron expression (*/10 * * * *).' }),
|
|
12
12
|
kind: Type.Optional(Type.Union([Type.Literal('once'), Type.Literal('recurring')], { description: 'Task kind. Default: recurring.' })),
|
|
13
13
|
name: Type.Optional(Type.String({ description: 'Human-readable task name. Auto-generated from prompt if omitted.' })),
|
|
14
|
-
expires: Type.Optional(Type.String({ description: 'Expiry duration (30m/2h/7d). Default: 7d. Pass "never" to disable.' })),
|
|
14
|
+
expires: Type.Optional(Type.String({ description: 'Expiry duration (30m/2h/7d). Default: 7d. Pass "never" to disable. Only applies to recurring tasks (once tasks fire and are removed, expires is ignored).' })),
|
|
15
15
|
force: Type.Optional(Type.Boolean({ description: 'Dispatch even when agent is busy. Default: false.' })),
|
|
16
16
|
})
|
|
17
17
|
|
|
@@ -53,7 +53,7 @@ export const controlGuidelines = [
|
|
|
53
53
|
'Use action="list" to see all scheduled tasks.',
|
|
54
54
|
'After listing, use the returned id for toggle/delete/run.',
|
|
55
55
|
'Prefer toggle(enabled=false) over delete for temporary pauses.',
|
|
56
|
-
'action="run"
|
|
56
|
+
'action="run" dispatches the task now: force tasks are sent directly; non-force tasks are enqueued via the delivery kernel and delivered once the agent is idle (busy messages wait in the queue and are flushed later).',
|
|
57
57
|
]
|
|
58
58
|
|
|
59
59
|
export function createScheduleControlHandler(service: SchedulerService) {
|