minimal-agent 0.18.20 → 0.18.22

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 (188) hide show
  1. package/README.md +16 -3
  2. package/package.json +1 -1
  3. package/plugins/cron-runner/README.md +23 -0
  4. package/plugins/cron-runner/commands/cron.md +7 -1
  5. package/plugins/cron-runner/plugin.js +9 -2
  6. package/plugins/cron-runner/plugin.ts +10 -2
  7. package/plugins/cron-runner/src/commands.js +112 -25
  8. package/plugins/cron-runner/src/commands.ts +154 -33
  9. package/plugins/cron-runner/src/contract.js +70 -0
  10. package/plugins/cron-runner/src/contract.ts +70 -0
  11. package/plugins/cron-runner/src/requests.js +22 -13
  12. package/plugins/cron-runner/src/requests.ts +34 -14
  13. package/plugins/cron-runner/src/runs.js +63 -10
  14. package/plugins/cron-runner/src/runs.ts +107 -15
  15. package/plugins/cron-runner/src/scheduler.js +188 -76
  16. package/plugins/cron-runner/src/scheduler.ts +277 -94
  17. package/plugins/cron-runner/src/schema.js +52 -17
  18. package/plugins/cron-runner/src/schema.ts +73 -22
  19. package/plugins/cron-runner/src/service.js +29 -8
  20. package/plugins/cron-runner/src/service.ts +71 -18
  21. package/plugins/cron-runner/src/store.js +92 -30
  22. package/plugins/cron-runner/src/store.ts +156 -53
  23. package/plugins/cron-runner/src/transaction.js +24 -0
  24. package/plugins/cron-runner/src/transaction.ts +36 -0
  25. package/plugins/cron-runner/src/types.ts +30 -4
  26. package/plugins/cron-runner/test/lifecycle.test.ts +419 -0
  27. package/plugins/cron-runner/test/plugin-integration.test.ts +3 -2
  28. package/plugins/cron-runner/test/reliability.test.ts +2 -2
  29. package/plugins/cron-runner/test/store-and-scheduler.test.ts +9 -7
  30. package/plugins/workflow-runner/plugin.js +1 -0
  31. package/plugins/workflow-runner/plugin.ts +1 -0
  32. package/plugins/workflow-runner/src/index.js +1 -0
  33. package/plugins/workflow-runner/src/index.ts +2 -0
  34. package/plugins/workflow-runner/src/runner.js +6 -1
  35. package/plugins/workflow-runner/src/runner.ts +5 -1
  36. package/plugins/workflow-runner/src/types.ts +1 -0
  37. package/plugins/workflow-runner/test/api.test.ts +1 -0
  38. package/plugins/workflow-runner/test/apiCapabilities.test.ts +4 -0
  39. package/plugins/workflow-runner/test/apiConcurrencyGate.test.ts +1 -0
  40. package/plugins/workflow-runner/test/childWorkflow.test.ts +19 -0
  41. package/plugins/workflow-runner/test/embeddedExecution.test.ts +23 -3
  42. package/src/advisor/README.md +17 -6
  43. package/src/advisor/advisorNudge.js +23 -3
  44. package/src/advisor/advisorNudge.ts +20 -3
  45. package/src/advisor/deliveryReview.js +9 -2
  46. package/src/advisor/deliveryReview.ts +10 -2
  47. package/src/cli/args.js +1 -0
  48. package/src/cli/args.ts +1 -0
  49. package/src/cli/headlessTurn.js +143 -0
  50. package/src/cli/headlessTurn.ts +187 -0
  51. package/src/cli/lifecycle.js +52 -0
  52. package/src/cli/lifecycle.ts +59 -0
  53. package/src/cli/print.js +91 -240
  54. package/src/cli/print.ts +99 -301
  55. package/src/cli/quickModelSetup.js +3 -0
  56. package/src/cli/quickModelSetup.tsx +3 -0
  57. package/src/cli/streamJson.js +244 -334
  58. package/src/cli/streamJson.ts +248 -416
  59. package/src/cli/wizards/contextAdvisorWizard.js +0 -7
  60. package/src/cli/wizards/contextAdvisorWizard.tsx +0 -11
  61. package/src/cli/wizards/providerPresets.js +25 -14
  62. package/src/cli/wizards/providerPresets.ts +25 -14
  63. package/src/cli/wizards/providerWizard.js +29 -11
  64. package/src/cli/wizards/providerWizard.tsx +29 -11
  65. package/src/config/configDefaults.js +2 -2
  66. package/src/config/configDefaults.ts +2 -2
  67. package/src/config/configDiagnostics.js +7 -3
  68. package/src/config/configDiagnostics.ts +6 -3
  69. package/src/config/configFile.ts +1 -1
  70. package/src/context/compact.js +40 -10
  71. package/src/context/compact.ts +51 -12
  72. package/src/context/compactResources.js +39 -0
  73. package/src/context/compactResources.ts +35 -0
  74. package/src/context/manualCompact.js +20 -0
  75. package/src/context/manualCompact.ts +28 -0
  76. package/src/llm/client.js +4 -0
  77. package/src/llm/client.ts +4 -0
  78. package/src/llm/messageProvenance.js +1 -1
  79. package/src/llm/messageProvenance.ts +1 -1
  80. package/src/loop/README.md +4 -2
  81. package/src/loop/deliveryIntent.js +3 -2
  82. package/src/loop/deliveryIntent.ts +4 -2
  83. package/src/loop/messages.js +1 -0
  84. package/src/loop/messages.ts +1 -0
  85. package/src/loop/options.ts +2 -0
  86. package/src/loop.js +10 -2
  87. package/src/loop.ts +9 -2
  88. package/src/main.js +40 -45
  89. package/src/main.tsx +33 -52
  90. package/src/plugin-sdk.js +1 -1
  91. package/src/plugin-sdk.ts +1 -1
  92. package/src/plugins/artifactDelivery.js +76 -0
  93. package/src/plugins/artifactDelivery.ts +76 -0
  94. package/src/plugins/pluginApi.ts +4 -0
  95. package/src/plugins/pluginRunner.js +2 -0
  96. package/src/plugins/pluginRunner.ts +3 -0
  97. package/src/prompts/delegation.js +2 -2
  98. package/src/prompts/delegation.ts +2 -2
  99. package/src/prompts/policyRegistry.js +7 -5
  100. package/src/prompts/policyRegistry.ts +7 -5
  101. package/src/prompts/promptAssembly.js +2 -2
  102. package/src/prompts/promptAssembly.ts +2 -2
  103. package/src/runtime/requestIntent.js +86 -0
  104. package/src/runtime/requestIntent.ts +66 -0
  105. package/src/runtime/systemEvents.js +10 -1
  106. package/src/runtime/systemEvents.ts +9 -1
  107. package/src/session/commandTranscript.js +76 -0
  108. package/src/session/commandTranscript.ts +77 -0
  109. package/src/session/executionOutcome.js +25 -0
  110. package/src/session/executionOutcome.ts +34 -0
  111. package/src/session/runAgentTurn.js +8 -1
  112. package/src/session/runAgentTurn.ts +10 -1
  113. package/src/session/runTurn.js +40 -15
  114. package/src/session/runTurn.ts +38 -12
  115. package/src/session/sessionState.js +7 -2
  116. package/src/session/sessionState.ts +7 -2
  117. package/src/team/onlineToolContract.js +1 -0
  118. package/src/team/onlineToolContract.ts +1 -0
  119. package/src/tools/advisor/advisor.js +73 -30
  120. package/src/tools/advisor/advisor.ts +73 -33
  121. package/src/tools/advisor/advisorCoordination.js +44 -0
  122. package/src/tools/advisor/advisorCoordination.ts +45 -0
  123. package/src/tools/advisor/advisorDescription.js +1 -1
  124. package/src/tools/advisor/advisorDescription.ts +1 -1
  125. package/src/tools/agent/README.md +2 -0
  126. package/src/tools/agent/agent.js +7 -3
  127. package/src/tools/agent/agent.ts +7 -3
  128. package/src/tools/agent/agentHandoff.js +2 -1
  129. package/src/tools/agent/agentHandoff.ts +2 -1
  130. package/src/tools/agent/agentTaskService.js +26 -5
  131. package/src/tools/agent/agentTaskService.ts +25 -5
  132. package/src/tools/agent/agentTypes.js +2 -2
  133. package/src/tools/agent/agentTypes.ts +2 -2
  134. package/src/tools/agent/baselineAttach.js +14 -7
  135. package/src/tools/agent/baselineAttach.ts +14 -7
  136. package/src/tools/applypatch/applyPatch.js +39 -13
  137. package/src/tools/applypatch/applyPatch.ts +35 -15
  138. package/src/tools/bash/bash.js +3 -0
  139. package/src/tools/bash/bash.ts +3 -0
  140. package/src/tools/capabilities.js +1 -0
  141. package/src/tools/capabilities.ts +1 -0
  142. package/src/tools/download/download.js +147 -11
  143. package/src/tools/download/download.ts +193 -17
  144. package/src/tools/edit/edit.js +4 -4
  145. package/src/tools/edit/edit.ts +4 -4
  146. package/src/tools/edit/multi-edit.js +2 -2
  147. package/src/tools/edit/multi-edit.ts +2 -2
  148. package/src/tools/index.js +2 -0
  149. package/src/tools/index.ts +2 -0
  150. package/src/tools/powershell/powershell.js +2 -0
  151. package/src/tools/powershell/powershell.ts +2 -0
  152. package/src/tools/schedule/schedule.js +184 -0
  153. package/src/tools/schedule/schedule.ts +214 -0
  154. package/src/tools/shared/fileUtils.js +16 -6
  155. package/src/tools/shared/fileUtils.ts +15 -6
  156. package/src/tools/tasks/backgroundTaskService.js +108 -12
  157. package/src/tools/tasks/backgroundTaskService.ts +106 -14
  158. package/src/tools/tasks/taskOutput.js +15 -5
  159. package/src/tools/tasks/taskOutput.ts +13 -5
  160. package/src/tools/tasks/taskStop.js +2 -2
  161. package/src/tools/tasks/taskStop.ts +2 -2
  162. package/src/tools/toolPromptGuides.js +4 -3
  163. package/src/tools/toolPromptGuides.ts +4 -3
  164. package/src/tools/webfetch/webfetch.js +1 -1
  165. package/src/tools/webfetch/webfetch.ts +1 -1
  166. package/src/types.ts +6 -0
  167. package/src/ui/App.js +3 -1
  168. package/src/ui/App.tsx +2 -0
  169. package/src/ui/InputBox.js +2 -2
  170. package/src/ui/InputBox.tsx +2 -2
  171. package/src/ui/LiveArea.js +6 -1
  172. package/src/ui/LiveArea.tsx +6 -1
  173. package/src/ui/MessageList.js +2 -0
  174. package/src/ui/MessageList.tsx +2 -0
  175. package/src/ui/README.md +8 -2
  176. package/src/ui/activityPresentation.js +23 -3
  177. package/src/ui/activityPresentation.ts +22 -3
  178. package/src/ui/backgroundWake.js +20 -4
  179. package/src/ui/backgroundWake.ts +19 -4
  180. package/src/ui/commandTranscript.js +2 -69
  181. package/src/ui/commandTranscript.ts +2 -71
  182. package/src/ui/hooks/useBackgroundAgents.js +33 -0
  183. package/src/ui/hooks/useBackgroundAgents.ts +36 -0
  184. package/src/ui/hooks/useChat.js +46 -25
  185. package/src/ui/hooks/useChat.ts +36 -23
  186. package/src/web/protocol.ts +5 -2
  187. package/src/cli/wizards/advisorWizard.js +0 -152
  188. package/src/cli/wizards/advisorWizard.tsx +0 -203
@@ -23,18 +23,26 @@ export function normalizeTask(raw) {
23
23
  return null;
24
24
  if (typeof task.name !== 'string' || !task.name)
25
25
  return null;
26
- if (task.status !== 'active' && task.status !== 'paused' && task.status !== 'completed')
26
+ if (task.status !== 'active' &&
27
+ task.status !== 'paused' &&
28
+ task.status !== 'completed')
27
29
  return null;
28
30
  if (!task.schedule || typeof task.schedule !== 'object')
29
31
  return null;
30
32
  const schedule = task.schedule;
31
- const scheduleType = schedule.type === 'once' ? 'once' : schedule.type === 'interval' ? 'interval' : 'cron';
33
+ const scheduleType = schedule.type === 'once'
34
+ ? 'once'
35
+ : schedule.type === 'interval'
36
+ ? 'interval'
37
+ : 'cron';
32
38
  if (scheduleType === 'once') {
33
- if (typeof schedule.at !== 'string' || !Number.isFinite(Date.parse(schedule.at)))
39
+ if (typeof schedule.at !== 'string' ||
40
+ !Number.isFinite(Date.parse(schedule.at)))
34
41
  return null;
35
42
  }
36
43
  else if (scheduleType === 'cron') {
37
- if (typeof schedule.cron !== 'string' || !parseCronExpression(schedule.cron))
44
+ if (typeof schedule.cron !== 'string' ||
45
+ !parseCronExpression(schedule.cron))
38
46
  return null;
39
47
  }
40
48
  else if (typeof schedule.intervalMs !== 'number' ||
@@ -80,10 +88,13 @@ export function normalizeTask(raw) {
80
88
  typeof runtime.sessionId !== 'string' ||
81
89
  !runtime.sessionId ||
82
90
  runtime.sessionId.startsWith('cron-'));
83
- const bindingStatus = runtime.bindingStatus === 'needs_binding' || legacyNeedsBinding ? 'needs_binding' : 'bound';
91
+ const bindingStatus = runtime.bindingStatus === 'needs_binding' || legacyNeedsBinding
92
+ ? 'needs_binding'
93
+ : 'bound';
84
94
  return {
85
95
  ...(task.version === 2 ? { version: 2 } : {}),
86
96
  revision: typeof task.revision === 'number' ? task.revision : 0,
97
+ planId: typeof task.planId === 'string' ? task.planId : task.id,
87
98
  catchUp: task.catchUp === 'latest' ? 'latest' : 'skip',
88
99
  notifications: task.notifications === 'all' ? 'all' : 'failures',
89
100
  id: task.id,
@@ -91,11 +102,17 @@ export function normalizeTask(raw) {
91
102
  ...(typeof task.description === 'string' && task.description
92
103
  ? { description: task.description }
93
104
  : {}),
94
- status: bindingStatus === 'needs_binding' && task.status === 'active' ? 'paused' : task.status,
105
+ status: bindingStatus === 'needs_binding' && task.status === 'active'
106
+ ? 'paused'
107
+ : task.status,
95
108
  kind,
96
109
  ...(task.permanent ? { permanent: true } : {}),
97
- ...(typeof task.expiresAt === 'string' ? { expiresAt: task.expiresAt } : {}),
98
- ...(typeof task.maxRuns === 'number' && task.maxRuns > 0 ? { maxRuns: task.maxRuns } : {}),
110
+ ...(typeof task.expiresAt === 'string'
111
+ ? { expiresAt: task.expiresAt }
112
+ : {}),
113
+ ...(typeof task.maxRuns === 'number' && task.maxRuns > 0
114
+ ? { maxRuns: task.maxRuns }
115
+ : {}),
99
116
  schedule: scheduleType === 'once'
100
117
  ? {
101
118
  type: 'once',
@@ -104,7 +121,9 @@ export function normalizeTask(raw) {
104
121
  ...(typeof schedule.lastScheduledFor === 'string'
105
122
  ? { lastScheduledFor: schedule.lastScheduledFor }
106
123
  : {}),
107
- ...(typeof schedule.nextRunAt === 'string' ? { nextRunAt: schedule.nextRunAt } : {}),
124
+ ...(typeof schedule.nextRunAt === 'string'
125
+ ? { nextRunAt: schedule.nextRunAt }
126
+ : {}),
108
127
  }
109
128
  : scheduleType === 'interval'
110
129
  ? {
@@ -112,28 +131,36 @@ export function normalizeTask(raw) {
112
131
  intervalMs: schedule.intervalMs,
113
132
  anchorAt: schedule.anchorAt,
114
133
  human: intervalToHuman(schedule.intervalMs),
115
- ...(typeof schedule.nextRunAt === 'string' ? { nextRunAt: schedule.nextRunAt } : {}),
134
+ ...(typeof schedule.nextRunAt === 'string'
135
+ ? { nextRunAt: schedule.nextRunAt }
136
+ : {}),
116
137
  ...(typeof schedule.lastFiredAt === 'string'
117
138
  ? { lastFiredAt: schedule.lastFiredAt }
118
139
  : {}),
119
140
  ...(typeof schedule.lastScheduledFor === 'string'
120
141
  ? { lastScheduledFor: schedule.lastScheduledFor }
121
142
  : {}),
122
- ...(typeof schedule.jitterMs === 'number' ? { jitterMs: schedule.jitterMs } : {}),
143
+ ...(typeof schedule.jitterMs === 'number'
144
+ ? { jitterMs: schedule.jitterMs }
145
+ : {}),
123
146
  }
124
147
  : {
125
148
  type: 'cron',
126
149
  cron: schedule.cron,
127
150
  timezone,
128
151
  human: cronToHuman(schedule.cron),
129
- ...(typeof schedule.nextRunAt === 'string' ? { nextRunAt: schedule.nextRunAt } : {}),
152
+ ...(typeof schedule.nextRunAt === 'string'
153
+ ? { nextRunAt: schedule.nextRunAt }
154
+ : {}),
130
155
  ...(typeof schedule.lastFiredAt === 'string'
131
156
  ? { lastFiredAt: schedule.lastFiredAt }
132
157
  : {}),
133
158
  ...(typeof schedule.lastScheduledFor === 'string'
134
159
  ? { lastScheduledFor: schedule.lastScheduledFor }
135
160
  : {}),
136
- ...(typeof schedule.jitterMs === 'number' ? { jitterMs: schedule.jitterMs } : {}),
161
+ ...(typeof schedule.jitterMs === 'number'
162
+ ? { jitterMs: schedule.jitterMs }
163
+ : {}),
137
164
  },
138
165
  action,
139
166
  runtime: {
@@ -150,7 +177,9 @@ export function normalizeTask(raw) {
150
177
  ? 'fresh'
151
178
  : 'persistent',
152
179
  bindingStatus,
153
- ...(typeof runtime.model === 'string' && runtime.model ? { model: runtime.model } : {}),
180
+ ...(typeof runtime.model === 'string' && runtime.model
181
+ ? { model: runtime.model }
182
+ : {}),
154
183
  ...(typeof runtime.maxTurns === 'number' && runtime.maxTurns > 0
155
184
  ? { maxTurns: runtime.maxTurns }
156
185
  : {}),
@@ -160,9 +189,15 @@ export function normalizeTask(raw) {
160
189
  successCount: typeof stats.successCount === 'number' ? stats.successCount : 0,
161
190
  failureCount: typeof stats.failureCount === 'number' ? stats.failureCount : 0,
162
191
  skippedCount: typeof stats.skippedCount === 'number' ? stats.skippedCount : 0,
163
- ...(typeof stats.lastRunAt === 'string' ? { lastRunAt: stats.lastRunAt } : {}),
164
- ...(typeof stats.lastSuccessAt === 'string' ? { lastSuccessAt: stats.lastSuccessAt } : {}),
165
- ...(typeof stats.lastFailureAt === 'string' ? { lastFailureAt: stats.lastFailureAt } : {}),
192
+ ...(typeof stats.lastRunAt === 'string'
193
+ ? { lastRunAt: stats.lastRunAt }
194
+ : {}),
195
+ ...(typeof stats.lastSuccessAt === 'string'
196
+ ? { lastSuccessAt: stats.lastSuccessAt }
197
+ : {}),
198
+ ...(typeof stats.lastFailureAt === 'string'
199
+ ? { lastFailureAt: stats.lastFailureAt }
200
+ : {}),
166
201
  },
167
202
  createdAt: typeof task.createdAt === 'string' ? task.createdAt : now,
168
203
  updatedAt: typeof task.updatedAt === 'string' ? task.updatedAt : now,
@@ -13,9 +13,13 @@ export function validateCron(cron: string): ValidationResult {
13
13
  return { ok: true };
14
14
  }
15
15
 
16
- export function validateIsoDate(value: string, field: string): ValidationResult {
16
+ export function validateIsoDate(
17
+ value: string,
18
+ field: string,
19
+ ): ValidationResult {
17
20
  const time = Date.parse(value);
18
- if (!Number.isFinite(time)) return { ok: false, error: `${field} 必须是 ISO 时间。` };
21
+ if (!Number.isFinite(time))
22
+ return { ok: false, error: `${field} 必须是 ISO 时间。` };
19
23
  return { ok: true };
20
24
  }
21
25
 
@@ -24,16 +28,32 @@ export function normalizeTask(raw: unknown): CronTask | null {
24
28
  const task = raw as Partial<CronTask> & Record<string, unknown>;
25
29
  if (typeof task.id !== 'string' || !task.id) return null;
26
30
  if (typeof task.name !== 'string' || !task.name) return null;
27
- if (task.status !== 'active' && task.status !== 'paused' && task.status !== 'completed')
31
+ if (
32
+ task.status !== 'active' &&
33
+ task.status !== 'paused' &&
34
+ task.status !== 'completed'
35
+ )
28
36
  return null;
29
37
  if (!task.schedule || typeof task.schedule !== 'object') return null;
30
38
  const schedule = task.schedule as unknown as Record<string, unknown>;
31
39
  const scheduleType =
32
- schedule.type === 'once' ? 'once' : schedule.type === 'interval' ? 'interval' : 'cron';
40
+ schedule.type === 'once'
41
+ ? 'once'
42
+ : schedule.type === 'interval'
43
+ ? 'interval'
44
+ : 'cron';
33
45
  if (scheduleType === 'once') {
34
- if (typeof schedule.at !== 'string' || !Number.isFinite(Date.parse(schedule.at))) return null;
46
+ if (
47
+ typeof schedule.at !== 'string' ||
48
+ !Number.isFinite(Date.parse(schedule.at))
49
+ )
50
+ return null;
35
51
  } else if (scheduleType === 'cron') {
36
- if (typeof schedule.cron !== 'string' || !parseCronExpression(schedule.cron)) return null;
52
+ if (
53
+ typeof schedule.cron !== 'string' ||
54
+ !parseCronExpression(schedule.cron)
55
+ )
56
+ return null;
37
57
  } else if (
38
58
  typeof schedule.intervalMs !== 'number' ||
39
59
  schedule.intervalMs < MIN_INTERVAL_MS ||
@@ -76,11 +96,14 @@ export function normalizeTask(raw: unknown): CronTask | null {
76
96
  !runtime.sessionId ||
77
97
  runtime.sessionId.startsWith('cron-'));
78
98
  const bindingStatus =
79
- runtime.bindingStatus === 'needs_binding' || legacyNeedsBinding ? 'needs_binding' : 'bound';
99
+ runtime.bindingStatus === 'needs_binding' || legacyNeedsBinding
100
+ ? 'needs_binding'
101
+ : 'bound';
80
102
 
81
103
  return {
82
104
  ...(task.version === 2 ? { version: 2 as const } : {}),
83
105
  revision: typeof task.revision === 'number' ? task.revision : 0,
106
+ planId: typeof task.planId === 'string' ? task.planId : task.id,
84
107
  catchUp: task.catchUp === 'latest' ? 'latest' : 'skip',
85
108
  notifications: task.notifications === 'all' ? 'all' : 'failures',
86
109
  id: task.id,
@@ -88,11 +111,18 @@ export function normalizeTask(raw: unknown): CronTask | null {
88
111
  ...(typeof task.description === 'string' && task.description
89
112
  ? { description: task.description }
90
113
  : {}),
91
- status: bindingStatus === 'needs_binding' && task.status === 'active' ? 'paused' : task.status,
114
+ status:
115
+ bindingStatus === 'needs_binding' && task.status === 'active'
116
+ ? 'paused'
117
+ : task.status,
92
118
  kind,
93
119
  ...(task.permanent ? { permanent: true } : {}),
94
- ...(typeof task.expiresAt === 'string' ? { expiresAt: task.expiresAt } : {}),
95
- ...(typeof task.maxRuns === 'number' && task.maxRuns > 0 ? { maxRuns: task.maxRuns } : {}),
120
+ ...(typeof task.expiresAt === 'string'
121
+ ? { expiresAt: task.expiresAt }
122
+ : {}),
123
+ ...(typeof task.maxRuns === 'number' && task.maxRuns > 0
124
+ ? { maxRuns: task.maxRuns }
125
+ : {}),
96
126
  schedule:
97
127
  scheduleType === 'once'
98
128
  ? {
@@ -102,7 +132,9 @@ export function normalizeTask(raw: unknown): CronTask | null {
102
132
  ...(typeof schedule.lastScheduledFor === 'string'
103
133
  ? { lastScheduledFor: schedule.lastScheduledFor }
104
134
  : {}),
105
- ...(typeof schedule.nextRunAt === 'string' ? { nextRunAt: schedule.nextRunAt } : {}),
135
+ ...(typeof schedule.nextRunAt === 'string'
136
+ ? { nextRunAt: schedule.nextRunAt }
137
+ : {}),
106
138
  }
107
139
  : scheduleType === 'interval'
108
140
  ? {
@@ -110,28 +142,36 @@ export function normalizeTask(raw: unknown): CronTask | null {
110
142
  intervalMs: schedule.intervalMs as number,
111
143
  anchorAt: schedule.anchorAt as string,
112
144
  human: intervalToHuman(schedule.intervalMs as number),
113
- ...(typeof schedule.nextRunAt === 'string' ? { nextRunAt: schedule.nextRunAt } : {}),
145
+ ...(typeof schedule.nextRunAt === 'string'
146
+ ? { nextRunAt: schedule.nextRunAt }
147
+ : {}),
114
148
  ...(typeof schedule.lastFiredAt === 'string'
115
149
  ? { lastFiredAt: schedule.lastFiredAt }
116
150
  : {}),
117
151
  ...(typeof schedule.lastScheduledFor === 'string'
118
152
  ? { lastScheduledFor: schedule.lastScheduledFor }
119
153
  : {}),
120
- ...(typeof schedule.jitterMs === 'number' ? { jitterMs: schedule.jitterMs } : {}),
154
+ ...(typeof schedule.jitterMs === 'number'
155
+ ? { jitterMs: schedule.jitterMs }
156
+ : {}),
121
157
  }
122
158
  : {
123
159
  type: 'cron',
124
160
  cron: schedule.cron as string,
125
161
  timezone,
126
162
  human: cronToHuman(schedule.cron as string),
127
- ...(typeof schedule.nextRunAt === 'string' ? { nextRunAt: schedule.nextRunAt } : {}),
163
+ ...(typeof schedule.nextRunAt === 'string'
164
+ ? { nextRunAt: schedule.nextRunAt }
165
+ : {}),
128
166
  ...(typeof schedule.lastFiredAt === 'string'
129
167
  ? { lastFiredAt: schedule.lastFiredAt }
130
168
  : {}),
131
169
  ...(typeof schedule.lastScheduledFor === 'string'
132
170
  ? { lastScheduledFor: schedule.lastScheduledFor }
133
171
  : {}),
134
- ...(typeof schedule.jitterMs === 'number' ? { jitterMs: schedule.jitterMs } : {}),
172
+ ...(typeof schedule.jitterMs === 'number'
173
+ ? { jitterMs: schedule.jitterMs }
174
+ : {}),
135
175
  },
136
176
  action,
137
177
  runtime: {
@@ -149,19 +189,30 @@ export function normalizeTask(raw: unknown): CronTask | null {
149
189
  ? 'fresh'
150
190
  : 'persistent',
151
191
  bindingStatus,
152
- ...(typeof runtime.model === 'string' && runtime.model ? { model: runtime.model } : {}),
192
+ ...(typeof runtime.model === 'string' && runtime.model
193
+ ? { model: runtime.model }
194
+ : {}),
153
195
  ...(typeof runtime.maxTurns === 'number' && runtime.maxTurns > 0
154
196
  ? { maxTurns: runtime.maxTurns }
155
197
  : {}),
156
198
  },
157
199
  stats: {
158
200
  runCount: typeof stats.runCount === 'number' ? stats.runCount : 0,
159
- successCount: typeof stats.successCount === 'number' ? stats.successCount : 0,
160
- failureCount: typeof stats.failureCount === 'number' ? stats.failureCount : 0,
161
- skippedCount: typeof stats.skippedCount === 'number' ? stats.skippedCount : 0,
162
- ...(typeof stats.lastRunAt === 'string' ? { lastRunAt: stats.lastRunAt } : {}),
163
- ...(typeof stats.lastSuccessAt === 'string' ? { lastSuccessAt: stats.lastSuccessAt } : {}),
164
- ...(typeof stats.lastFailureAt === 'string' ? { lastFailureAt: stats.lastFailureAt } : {}),
201
+ successCount:
202
+ typeof stats.successCount === 'number' ? stats.successCount : 0,
203
+ failureCount:
204
+ typeof stats.failureCount === 'number' ? stats.failureCount : 0,
205
+ skippedCount:
206
+ typeof stats.skippedCount === 'number' ? stats.skippedCount : 0,
207
+ ...(typeof stats.lastRunAt === 'string'
208
+ ? { lastRunAt: stats.lastRunAt }
209
+ : {}),
210
+ ...(typeof stats.lastSuccessAt === 'string'
211
+ ? { lastSuccessAt: stats.lastSuccessAt }
212
+ : {}),
213
+ ...(typeof stats.lastFailureAt === 'string'
214
+ ? { lastFailureAt: stats.lastFailureAt }
215
+ : {}),
165
216
  },
166
217
  createdAt: typeof task.createdAt === 'string' ? task.createdAt : now,
167
218
  updatedAt: typeof task.updatedAt === 'string' ? task.updatedAt : now,
@@ -4,10 +4,13 @@ import { validateCron } from './schema.js';
4
4
  import { createTask, listMissed, listTasks, markMissedRead, markRunsRead, patchTask, recentRuns, upsertTask, } from './store.js';
5
5
  import { cronToHuman } from './cronTime.js';
6
6
  import { intervalToHuman, nextScheduleRunMs } from './scheduleEngine.js';
7
+ import { draftSchema, patchSchema } from './contract.js';
7
8
  export function draftCronFromText(text, context, requestId = randomUUID()) {
8
9
  const normalized = normalizeScheduleText(text);
9
10
  const once = normalized.match(/^(?:at|一次)\s+(\S+)\s+([\s\S]+)$/);
10
- if (once && context.cwd && (context.sessionId || context.sessionMode === 'fresh')) {
11
+ if (once &&
12
+ context.cwd &&
13
+ (context.sessionId || context.sessionMode === 'fresh')) {
11
14
  const at = new Date(once[1]);
12
15
  if (!Number.isFinite(at.getTime()) || at.getTime() <= Date.now())
13
16
  return {
@@ -51,9 +54,16 @@ export function draftCronFromText(text, context, requestId = randomUUID()) {
51
54
  if (parsed && 'error' in parsed) {
52
55
  if (parsed.error.includes('提示词') || parsed.error.includes('workflow'))
53
56
  missing.push('action');
54
- return { requestId, task: null, missing: unique(missing), error: parsed.error };
57
+ return {
58
+ requestId,
59
+ task: null,
60
+ missing: unique(missing),
61
+ error: parsed.error,
62
+ };
55
63
  }
56
- if (!parsed || !context.cwd || (!context.sessionId && context.sessionMode !== 'fresh')) {
64
+ if (!parsed ||
65
+ !context.cwd ||
66
+ (!context.sessionId && context.sessionMode !== 'fresh')) {
57
67
  return { requestId, task: null, missing: unique(missing) };
58
68
  }
59
69
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'local';
@@ -97,6 +107,7 @@ export function draftCronFromText(text, context, requestId = randomUUID()) {
97
107
  };
98
108
  }
99
109
  export async function createCronFromDraft(draft, requestId) {
110
+ draft = draftSchema.parse(draft);
100
111
  assertDraft(draft);
101
112
  if (draft.status === 'active' &&
102
113
  draft.schedule.type === 'once' &&
@@ -104,7 +115,9 @@ export async function createCronFromDraft(draft, requestId) {
104
115
  throw new Error('一次性任务的执行时间必须在未来。');
105
116
  const task = createTask({
106
117
  name: draft.name.trim(),
107
- ...(draft.description?.trim() ? { description: draft.description.trim() } : {}),
118
+ ...(draft.description?.trim()
119
+ ? { description: draft.description.trim() }
120
+ : {}),
108
121
  ...(draft.schedule.type === 'once'
109
122
  ? { at: draft.schedule.at, timezone: 'UTC' }
110
123
  : draft.schedule.type === 'cron'
@@ -134,6 +147,7 @@ export async function createCronFromDraft(draft, requestId) {
134
147
  return await upsertTask(task, Boolean(requestId));
135
148
  }
136
149
  export async function updateCronFromPatch(patch) {
150
+ patch = patchSchema.parse(patch);
137
151
  if (!patch.id)
138
152
  throw new Error('缺少定时任务 ID');
139
153
  if (patch.schedule?.type === 'cron') {
@@ -146,7 +160,9 @@ export async function updateCronFromPatch(patch) {
146
160
  if (patch.name !== undefined && !patch.name.trim())
147
161
  throw new Error('任务名称不能为空');
148
162
  if (patch.action &&
149
- !(patch.action.type === 'prompt' ? patch.action.prompt : patch.action.command).trim())
163
+ !(patch.action.type === 'prompt'
164
+ ? patch.action.prompt
165
+ : patch.action.command).trim())
150
166
  throw new Error('执行内容不能为空');
151
167
  for (const value of [patch.maxRuns, patch.runtime?.maxTurns])
152
168
  if (value !== undefined && (!Number.isInteger(value) || value < 1))
@@ -180,7 +196,9 @@ export async function listCronTasks(filter = {}) {
180
196
  if (filter.sessionId && task.runtime.sessionId !== filter.sessionId)
181
197
  return false;
182
198
  if (filter.status && filter.status !== 'all') {
183
- if (filter.status === 'attention' ? unreadCount === 0 : task.status !== filter.status)
199
+ if (filter.status === 'attention'
200
+ ? unreadCount === 0
201
+ : task.status !== filter.status)
184
202
  return false;
185
203
  }
186
204
  if (!query)
@@ -210,7 +228,9 @@ function assertDraft(draft) {
210
228
  for (const value of [draft.maxRuns, draft.runtime.maxTurns])
211
229
  if (value !== undefined && (!Number.isInteger(value) || value < 1))
212
230
  throw new Error('次数必须是正整数');
213
- if (draft.action.type === 'prompt' ? !draft.action.prompt.trim() : !draft.action.command.trim()) {
231
+ if (draft.action.type === 'prompt'
232
+ ? !draft.action.prompt.trim()
233
+ : !draft.action.command.trim()) {
214
234
  throw new Error('请输入执行内容');
215
235
  }
216
236
  }
@@ -226,7 +246,8 @@ function validateSchedule(schedule) {
226
246
  if (!checked.ok)
227
247
  throw new Error(checked.error);
228
248
  }
229
- else if (!Number.isFinite(schedule.intervalMs) || schedule.intervalMs < 60_000) {
249
+ else if (!Number.isFinite(schedule.intervalMs) ||
250
+ schedule.intervalMs < 60_000) {
230
251
  throw new Error('固定间隔最短为 1 分钟');
231
252
  }
232
253
  if (schedule.type === 'interval' &&
@@ -11,9 +11,15 @@ import {
11
11
  recentRuns,
12
12
  upsertTask,
13
13
  } from './store.js';
14
- import type { CronListFilter, CronTask, CronTaskDraft, CronTaskPatch } from './types.js';
14
+ import type {
15
+ CronListFilter,
16
+ CronTask,
17
+ CronTaskDraft,
18
+ CronTaskPatch,
19
+ } from './types.js';
15
20
  import { cronToHuman } from './cronTime.js';
16
21
  import { intervalToHuman, nextScheduleRunMs } from './scheduleEngine.js';
22
+ import { draftSchema, patchSchema } from './contract.js';
17
23
 
18
24
  export interface CronDraftContext {
19
25
  cwd: string;
@@ -38,7 +44,11 @@ export function draftCronFromText(
38
44
  ): CronDraftResult {
39
45
  const normalized = normalizeScheduleText(text);
40
46
  const once = normalized.match(/^(?:at|一次)\s+(\S+)\s+([\s\S]+)$/);
41
- if (once && context.cwd && (context.sessionId || context.sessionMode === 'fresh')) {
47
+ if (
48
+ once &&
49
+ context.cwd &&
50
+ (context.sessionId || context.sessionMode === 'fresh')
51
+ ) {
42
52
  const at = new Date(once[1]!);
43
53
  if (!Number.isFinite(at.getTime()) || at.getTime() <= Date.now())
44
54
  return {
@@ -74,14 +84,24 @@ export function draftCronFromText(
74
84
  const parsed = parseShortcutSchedule(head, rest);
75
85
  const missing: CronDraftResult['missing'] = [];
76
86
  if (!context.cwd) missing.push('workspace');
77
- if (!context.sessionId && context.sessionMode !== 'fresh') missing.push('session');
87
+ if (!context.sessionId && context.sessionMode !== 'fresh')
88
+ missing.push('session');
78
89
  if (!head || !parsed) missing.push('schedule');
79
90
  if (parsed && 'error' in parsed) {
80
91
  if (parsed.error.includes('提示词') || parsed.error.includes('workflow'))
81
92
  missing.push('action');
82
- return { requestId, task: null, missing: unique(missing), error: parsed.error };
93
+ return {
94
+ requestId,
95
+ task: null,
96
+ missing: unique(missing),
97
+ error: parsed.error,
98
+ };
83
99
  }
84
- if (!parsed || !context.cwd || (!context.sessionId && context.sessionMode !== 'fresh')) {
100
+ if (
101
+ !parsed ||
102
+ !context.cwd ||
103
+ (!context.sessionId && context.sessionMode !== 'fresh')
104
+ ) {
85
105
  return { requestId, task: null, missing: unique(missing) };
86
106
  }
87
107
  const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'local';
@@ -130,6 +150,7 @@ export async function createCronFromDraft(
130
150
  draft: CronTaskDraft,
131
151
  requestId?: string,
132
152
  ): Promise<CronTask> {
153
+ draft = draftSchema.parse(draft);
133
154
  assertDraft(draft);
134
155
  if (
135
156
  draft.status === 'active' &&
@@ -139,7 +160,9 @@ export async function createCronFromDraft(
139
160
  throw new Error('一次性任务的执行时间必须在未来。');
140
161
  const task = createTask({
141
162
  name: draft.name.trim(),
142
- ...(draft.description?.trim() ? { description: draft.description.trim() } : {}),
163
+ ...(draft.description?.trim()
164
+ ? { description: draft.description.trim() }
165
+ : {}),
143
166
  ...(draft.schedule.type === 'once'
144
167
  ? { at: draft.schedule.at, timezone: 'UTC' }
145
168
  : draft.schedule.type === 'cron'
@@ -147,7 +170,8 @@ export async function createCronFromDraft(
147
170
  : {
148
171
  intervalMs: draft.schedule.intervalMs,
149
172
  anchorAt: draft.schedule.anchorAt,
150
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'local',
173
+ timezone:
174
+ Intl.DateTimeFormat().resolvedOptions().timeZone || 'local',
151
175
  }),
152
176
  cwd: draft.runtime.cwd,
153
177
  sessionId: draft.runtime.sessionId,
@@ -169,17 +193,25 @@ export async function createCronFromDraft(
169
193
  return await upsertTask(task, Boolean(requestId));
170
194
  }
171
195
 
172
- export async function updateCronFromPatch(patch: CronTaskPatch): Promise<CronTask> {
196
+ export async function updateCronFromPatch(
197
+ patch: CronTaskPatch,
198
+ ): Promise<CronTask> {
199
+ patch = patchSchema.parse(patch);
173
200
  if (!patch.id) throw new Error('缺少定时任务 ID');
174
201
  if (patch.schedule?.type === 'cron') {
175
202
  const checked = validateCron(patch.schedule.cron);
176
203
  if (!checked.ok) throw new Error(checked.error);
177
204
  }
178
205
  if (patch.schedule) validateSchedule(patch.schedule);
179
- if (patch.name !== undefined && !patch.name.trim()) throw new Error('任务名称不能为空');
206
+ if (patch.name !== undefined && !patch.name.trim())
207
+ throw new Error('任务名称不能为空');
180
208
  if (
181
209
  patch.action &&
182
- !(patch.action.type === 'prompt' ? patch.action.prompt : patch.action.command).trim()
210
+ !(
211
+ patch.action.type === 'prompt'
212
+ ? patch.action.prompt
213
+ : patch.action.command
214
+ ).trim()
183
215
  )
184
216
  throw new Error('执行内容不能为空');
185
217
  for (const value of [patch.maxRuns, patch.runtime?.maxTurns])
@@ -196,7 +228,9 @@ export async function updateCronFromPatch(patch: CronTaskPatch): Promise<CronTas
196
228
  export async function listCronTasks(filter: CronListFilter = {}) {
197
229
  const query = filter.query?.trim().toLocaleLowerCase();
198
230
  const missed = await listMissed(500);
199
- const missedTaskIds = new Set(missed.filter((item) => !item.readAt).map((item) => item.taskId));
231
+ const missedTaskIds = new Set(
232
+ missed.filter((item) => !item.readAt).map((item) => item.taskId),
233
+ );
200
234
  const rows = await Promise.all(
201
235
  (await listTasks()).map(async (task) => {
202
236
  const runs = await recentRuns(task.id, 20);
@@ -216,9 +250,14 @@ export async function listCronTasks(filter: CronListFilter = {}) {
216
250
  );
217
251
  return rows.filter(({ task, unreadCount }) => {
218
252
  if (filter.cwd && task.runtime.cwd !== filter.cwd) return false;
219
- if (filter.sessionId && task.runtime.sessionId !== filter.sessionId) return false;
253
+ if (filter.sessionId && task.runtime.sessionId !== filter.sessionId)
254
+ return false;
220
255
  if (filter.status && filter.status !== 'all') {
221
- if (filter.status === 'attention' ? unreadCount === 0 : task.status !== filter.status)
256
+ if (
257
+ filter.status === 'attention'
258
+ ? unreadCount === 0
259
+ : task.status !== filter.status
260
+ )
222
261
  return false;
223
262
  }
224
263
  if (!query) return true;
@@ -247,20 +286,28 @@ function assertDraft(draft: CronTaskDraft): void {
247
286
  for (const value of [draft.maxRuns, draft.runtime.maxTurns])
248
287
  if (value !== undefined && (!Number.isInteger(value) || value < 1))
249
288
  throw new Error('次数必须是正整数');
250
- if (draft.action.type === 'prompt' ? !draft.action.prompt.trim() : !draft.action.command.trim()) {
289
+ if (
290
+ draft.action.type === 'prompt'
291
+ ? !draft.action.prompt.trim()
292
+ : !draft.action.command.trim()
293
+ ) {
251
294
  throw new Error('请输入执行内容');
252
295
  }
253
296
  }
254
297
 
255
298
  function validateSchedule(schedule: CronTaskDraft['schedule']): void {
256
299
  if (schedule.type === 'once') {
257
- if (!Number.isFinite(Date.parse(schedule.at))) throw new Error('无效的一次性日期');
300
+ if (!Number.isFinite(Date.parse(schedule.at)))
301
+ throw new Error('无效的一次性日期');
258
302
  } else if (schedule.type === 'cron') {
259
303
  if (schedule.timezone !== 'local')
260
304
  new Intl.DateTimeFormat('en', { timeZone: schedule.timezone }).format();
261
305
  const checked = validateCron(schedule.cron);
262
306
  if (!checked.ok) throw new Error(checked.error);
263
- } else if (!Number.isFinite(schedule.intervalMs) || schedule.intervalMs < 60_000) {
307
+ } else if (
308
+ !Number.isFinite(schedule.intervalMs) ||
309
+ schedule.intervalMs < 60_000
310
+ ) {
264
311
  throw new Error('固定间隔最短为 1 分钟');
265
312
  }
266
313
  if (
@@ -290,8 +337,14 @@ function normalizeScheduleText(value: string): string {
290
337
  /(?:下午|晚上)\s*(\d{1,2})[点时](\d{1,2})?分?/u,
291
338
  (_, h, m) => ` ${Number(h) < 12 ? Number(h) + 12 : h}:${m ?? '00'} `,
292
339
  )
293
- .replace(/(?:上午|早上)?\s*(\d{1,2})[点时](\d{1,2})?分?/u, (_, h, m) => ` ${h}:${m ?? '00'} `)
294
- .replace(/早上\s*(\d{1,2})[点时](\d{1,2})?分?/u, (_, h, m) => `${h}:${m ?? '00'}`)
340
+ .replace(
341
+ /(?:上午|早上)?\s*(\d{1,2})[点时](\d{1,2})?分?/u,
342
+ (_, h, m) => ` ${h}:${m ?? '00'} `,
343
+ )
344
+ .replace(
345
+ /早上\s*(\d{1,2})[点时](\d{1,2})?分?/u,
346
+ (_, h, m) => `${h}:${m ?? '00'}`,
347
+ )
295
348
  .replace(/(\d{1,2})[点时](\d{1,2})分/u, '$1:$2')
296
349
  .replace(/\s+/g, ' ')
297
350
  .trim();