@hhuangpanda/dsh-automation 0.0.0-stage → 0.3.34

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 (63) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +133 -2
  3. package/README.zh.md +134 -0
  4. package/cordis.patch.yml +3 -0
  5. package/docs/images/automation-overview-en.png +0 -0
  6. package/docs/images/automation-overview-zh.png +0 -0
  7. package/docs/reference.md +55 -0
  8. package/docs/reference.zh.md +55 -0
  9. package/lib/agent-configuration.d.ts +27 -0
  10. package/lib/agent-configuration.js +217 -0
  11. package/lib/api.d.ts +5 -0
  12. package/lib/api.js +253 -0
  13. package/lib/client/AutomationPanel.d.ts +9 -0
  14. package/lib/client/EmptyState.d.ts +10 -0
  15. package/lib/client/ModelSelection.d.ts +17 -0
  16. package/lib/client/ScheduleSection.d.ts +32 -0
  17. package/lib/client/SchedulerHealth.d.ts +10 -0
  18. package/lib/client/SkillPicker.d.ts +15 -0
  19. package/lib/client/TaskDetail.d.ts +34 -0
  20. package/lib/client/TaskEditor.d.ts +38 -0
  21. package/lib/client/TaskRow.d.ts +12 -0
  22. package/lib/client/editor-layout.d.ts +20 -0
  23. package/lib/client/i18n.d.ts +15 -0
  24. package/lib/client/icons.d.ts +30 -0
  25. package/lib/client/index.d.ts +6 -0
  26. package/lib/client/locales.d.ts +260 -0
  27. package/lib/client/rrule-editor.d.ts +15 -0
  28. package/lib/client/session-selection.d.ts +4 -0
  29. package/lib/client/shared.d.ts +77 -0
  30. package/lib/client/store.d.ts +40 -0
  31. package/lib/client.js +3014 -0
  32. package/lib/controller.d.ts +36 -0
  33. package/lib/controller.js +154 -0
  34. package/lib/domain.d.ts +44 -0
  35. package/lib/domain.js +473 -0
  36. package/lib/errors.d.ts +14 -0
  37. package/lib/errors.js +16 -0
  38. package/lib/im-delivery.d.ts +30 -0
  39. package/lib/im-delivery.js +69 -0
  40. package/lib/index.d.ts +25 -0
  41. package/lib/index.js +92 -0
  42. package/lib/recurrence.d.ts +14 -0
  43. package/lib/recurrence.js +203 -0
  44. package/lib/runner.d.ts +27 -0
  45. package/lib/runner.js +295 -0
  46. package/lib/runtime-marker.d.ts +3 -0
  47. package/lib/runtime-marker.js +2 -0
  48. package/lib/scheduler.d.ts +58 -0
  49. package/lib/scheduler.js +287 -0
  50. package/lib/store.d.ts +14 -0
  51. package/lib/store.js +108 -0
  52. package/lib/tool-configuration.d.ts +8 -0
  53. package/lib/tool-configuration.js +220 -0
  54. package/lib/tool-support.d.ts +67 -0
  55. package/lib/tool-support.js +47 -0
  56. package/lib/tools.d.ts +6 -0
  57. package/lib/tools.js +140 -0
  58. package/lib/types.d.ts +465 -0
  59. package/lib/types.js +99 -0
  60. package/lib/validation.d.ts +34 -0
  61. package/lib/validation.js +99 -0
  62. package/package.json +163 -4
  63. package/screenshots.json +1 -0
package/lib/domain.js ADDED
@@ -0,0 +1,473 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { instant, latestDueOccurrence, nextOccurrence, validateSchedule } from './recurrence.js';
3
+ import { AutomationStore } from './store.js';
4
+ import { AutomationDeliverySchema } from './types.js';
5
+ import { AutomationError } from './errors.js';
6
+ import { assertOverrideId, assertProviderModelPair, applyExecutionPatch, normalizeSkills, validateExecutionPatch, validateReasoningExecution, validateTarget } from './validation.js';
7
+ export class AutomationDomainError extends AutomationError {
8
+ code;
9
+ constructor(code, message) {
10
+ super(code, message);
11
+ this.code = code;
12
+ this.name = 'AutomationDomainError';
13
+ }
14
+ }
15
+ function nonTerminal(run) {
16
+ return run.status === 'queued' || run.status === 'running';
17
+ }
18
+ function failedOutcome(status) {
19
+ return status === 'failed' || status === 'timed_out';
20
+ }
21
+ function shouldNotify(task, status) {
22
+ if (task.notificationPolicy === 'never')
23
+ return false;
24
+ if (task.notificationPolicy === 'always')
25
+ return true;
26
+ return failedOutcome(status) || status === 'interrupted' || status === 'outcome_unknown';
27
+ }
28
+ function makeRun(trigger, now, scheduledAt) {
29
+ return {
30
+ id: `run-${randomUUID()}`,
31
+ trigger,
32
+ ...(scheduledAt === undefined ? {} : { scheduledAt: instant(scheduledAt) }),
33
+ enqueuedAt: instant(now),
34
+ status: 'queued',
35
+ };
36
+ }
37
+ function snapshotTarget(execution) {
38
+ const target = execution.target ?? { mode: 'fresh' };
39
+ return target.mode === 'pinned-session'
40
+ ? { mode: 'pinned-session', sessionId: target.sessionId }
41
+ : { mode: 'fresh' };
42
+ }
43
+ function pruneRuns(task, maxHistory) {
44
+ if (task.runs.length <= maxHistory)
45
+ return;
46
+ const retained = (run) => nonTerminal(run) || run.delivery?.status === 'sending';
47
+ const active = task.runs.filter(retained);
48
+ const slots = Math.max(0, maxHistory - active.length);
49
+ const terminal = slots === 0 ? [] : task.runs.filter((run) => !retained(run)).slice(-slots);
50
+ task.runs = [...terminal, ...active];
51
+ }
52
+ export class AutomationDomain {
53
+ store;
54
+ maxRunHistory;
55
+ constructor(store, maxRunHistory = Infinity) {
56
+ this.store = store;
57
+ this.maxRunHistory = maxRunHistory;
58
+ }
59
+ async init(now) {
60
+ await this.store.init();
61
+ const needsRecovery = Object.values(this.store.snapshot().tasks).some((task) => task.runs.some((run) => run.status === 'running' || run.delivery?.status === 'sending'));
62
+ if (!needsRecovery)
63
+ return;
64
+ await this.store.mutate((state) => {
65
+ for (const task of Object.values(state.tasks)) {
66
+ for (const run of task.runs) {
67
+ if (run.delivery?.status === 'sending') {
68
+ run.delivery.status = 'unknown';
69
+ run.delivery.finishedAt = instant(now);
70
+ run.delivery.error = 'DSH restarted before delivery was recorded; the message may have been sent. It will not be resent automatically.';
71
+ if (run.status !== 'running' && task.notificationPolicy !== 'never' && !shouldNotify(task, run.status))
72
+ task.unreadNotifications += 1;
73
+ }
74
+ if (run.status !== 'running')
75
+ continue;
76
+ run.status = 'outcome_unknown';
77
+ run.finishedAt = instant(now);
78
+ run.error = 'DSH restarted before this automation run reported its outcome; it may have completed.';
79
+ if (shouldNotify(task, run.status))
80
+ task.unreadNotifications += 1;
81
+ }
82
+ pruneRuns(task, this.maxRunHistory);
83
+ }
84
+ });
85
+ }
86
+ list() {
87
+ return Object.values(this.store.snapshot().tasks)
88
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
89
+ .map((task) => ({
90
+ ...task,
91
+ running: task.runs.some((run) => nonTerminal(run)),
92
+ }));
93
+ }
94
+ get(id) {
95
+ const task = this.store.snapshot().tasks[id];
96
+ if (task === undefined)
97
+ throw new AutomationDomainError('task_not_found', `Automation ${id} was not found.`);
98
+ return task;
99
+ }
100
+ async create(request, now) {
101
+ const name = request.name.trim();
102
+ const prompt = request.prompt.trim();
103
+ if (!name)
104
+ throw new Error('Automation name must not be empty.');
105
+ if (!prompt)
106
+ throw new Error('Automation prompt must not be empty.');
107
+ assertProviderModelPair(request.execution.provider, request.execution.model);
108
+ validateReasoningExecution(request.execution);
109
+ validateTarget({ ...request.execution, target: request.execution.target ?? { mode: 'fresh' } }, request.sessionTargetConfirmed === true);
110
+ for (const value of [request.execution.agentPreset, request.execution.provider, request.execution.model]) {
111
+ assertOverrideId(value, 'Execution override ids');
112
+ }
113
+ const schedule = validateSchedule(request.schedule, now);
114
+ const first = nextOccurrence(schedule, now);
115
+ if (first === undefined) {
116
+ throw new AutomationDomainError('schedule_exhausted', 'The recurring schedule has no future occurrence.');
117
+ }
118
+ const task = {
119
+ id: `automation-${randomUUID()}`,
120
+ name,
121
+ prompt,
122
+ createdAt: instant(now),
123
+ createdBySessionId: request.createdBySessionId,
124
+ status: 'active',
125
+ schedule,
126
+ nextRunAt: instant(first),
127
+ notificationPolicy: request.notificationPolicy ?? 'failures',
128
+ pauseAfterConsecutiveFailures: request.pauseAfterConsecutiveFailures ?? false,
129
+ consecutiveFailures: 0,
130
+ unreadNotifications: 0,
131
+ execution: {
132
+ ...request.execution,
133
+ ...(request.execution.agentPreset === undefined ? {} : { agentPreset: request.execution.agentPreset.trim() }),
134
+ ...(request.execution.provider === undefined ? {} : { provider: request.execution.provider.trim() }),
135
+ ...(request.execution.model === undefined ? {} : { model: request.execution.model.trim() }),
136
+ skills: normalizeSkills(request.execution.skills),
137
+ ...(request.execution.target === undefined ? { target: { mode: 'fresh' } } : { target: request.execution.target }),
138
+ },
139
+ security: {
140
+ permissionPreset: request.permissionPreset,
141
+ source: 'user-confirmed',
142
+ grantedAt: instant(now),
143
+ },
144
+ runs: [],
145
+ };
146
+ await this.store.mutate((state) => {
147
+ state.tasks[task.id] = task;
148
+ });
149
+ return structuredClone(task);
150
+ }
151
+ async update(id, request, now, beforeCommit) {
152
+ if (this.store.snapshot().tasks[id] === undefined) {
153
+ throw new AutomationDomainError('task_not_found', `Automation ${id} was not found.`);
154
+ }
155
+ if (request.name === undefined && request.prompt === undefined && request.schedule === undefined && request.notificationPolicy === undefined && request.pauseAfterConsecutiveFailures === undefined && request.permissionPreset === undefined && request.delivery === undefined && (request.execution === undefined || Object.keys(request.execution).length === 0)) {
156
+ throw new Error('Supply at least one field to update.');
157
+ }
158
+ if (request.execution !== undefined) {
159
+ validateExecutionPatch(request.execution);
160
+ }
161
+ const delivery = request.delivery == null ? request.delivery : AutomationDeliverySchema.parse(request.delivery);
162
+ const name = request.name?.trim();
163
+ const prompt = request.prompt?.trim();
164
+ if (name === '')
165
+ throw new Error('Automation name must not be empty.');
166
+ if (prompt === '')
167
+ throw new Error('Automation prompt must not be empty.');
168
+ const schedule = request.schedule === undefined ? undefined : validateSchedule(request.schedule, now);
169
+ const next = schedule === undefined ? undefined : nextOccurrence(schedule, now);
170
+ if (schedule !== undefined && next === undefined) {
171
+ throw new AutomationDomainError('schedule_exhausted', 'The recurring schedule has no future occurrence.');
172
+ }
173
+ return this.store.mutate(async (state) => {
174
+ const task = state.tasks[id];
175
+ if (task === undefined)
176
+ throw new AutomationDomainError('task_not_found', `Automation ${id} was not found.`);
177
+ const target = request.execution?.target;
178
+ if (target !== undefined) {
179
+ const current = task.execution.target ?? { mode: 'fresh' };
180
+ const changed = target.mode !== current.mode || (target.mode === 'pinned-session' && current.mode === 'pinned-session' && target.sessionId !== current.sessionId);
181
+ if (changed) {
182
+ if (request.execution?.sessionTargetConfirmed !== true)
183
+ throw new Error('Explicit user confirmation is required to change the session target.');
184
+ if (task.runs.some(nonTerminal))
185
+ throw new AutomationDomainError('invalid_state', 'Session target cannot change while an automation has a queued or running run.');
186
+ }
187
+ validateTarget({ ...task.execution, target }, true);
188
+ }
189
+ if (delivery !== undefined) {
190
+ const changed = delivery === null ? task.delivery !== undefined
191
+ : task.delivery?.botId !== delivery.botId || task.delivery?.targetId !== delivery.targetId;
192
+ if (changed) {
193
+ if (delivery !== null && request.deliveryChangeConfirmed !== true)
194
+ throw new Error('Explicit user confirmation is required to enable or change message delivery.');
195
+ if (task.runs.some(nonTerminal))
196
+ throw new AutomationDomainError('invalid_state', 'Message delivery cannot change while an automation has a queued or running run.');
197
+ }
198
+ }
199
+ validateReasoningExecution(applyExecutionPatch(task.execution, request.execution));
200
+ await beforeCommit?.(structuredClone(task));
201
+ if (delivery === null)
202
+ delete task.delivery;
203
+ else if (delivery !== undefined)
204
+ task.delivery = delivery;
205
+ if (name !== undefined)
206
+ task.name = name;
207
+ if (prompt !== undefined)
208
+ task.prompt = prompt;
209
+ if (request.notificationPolicy !== undefined)
210
+ task.notificationPolicy = request.notificationPolicy;
211
+ if (request.pauseAfterConsecutiveFailures !== undefined) {
212
+ task.pauseAfterConsecutiveFailures = request.pauseAfterConsecutiveFailures;
213
+ }
214
+ if (request.permissionPreset !== undefined && request.permissionPreset !== task.security.permissionPreset) {
215
+ task.security.permissionPreset = request.permissionPreset;
216
+ task.security.source = 'user-confirmed';
217
+ task.security.grantedAt = instant(now);
218
+ }
219
+ if (request.execution !== undefined) {
220
+ task.execution = applyExecutionPatch(task.execution, request.execution);
221
+ }
222
+ if (schedule !== undefined && next !== undefined) {
223
+ task.schedule = schedule;
224
+ if (task.status === 'paused') {
225
+ task.pausedNextRunAt = instant(next);
226
+ task.nextRunAt = null;
227
+ }
228
+ else {
229
+ task.status = 'active';
230
+ task.nextRunAt = instant(next);
231
+ delete task.pausedAt;
232
+ delete task.pausedNextRunAt;
233
+ }
234
+ }
235
+ const result = structuredClone(task);
236
+ if (result.execution.target?.mode === 'fresh') {
237
+ const { target: _target, ...execution } = result.execution;
238
+ return { ...result, execution };
239
+ }
240
+ return result;
241
+ });
242
+ }
243
+ async delete(id) {
244
+ if (this.store.snapshot().tasks[id] === undefined)
245
+ return false;
246
+ await this.store.mutate((state) => {
247
+ delete state.tasks[id];
248
+ });
249
+ return true;
250
+ }
251
+ async deleteRun(taskId, runId) {
252
+ return this.store.mutate((state) => {
253
+ const task = Object.hasOwn(state.tasks, taskId) ? state.tasks[taskId] : undefined;
254
+ if (task === undefined)
255
+ throw new AutomationDomainError('task_not_found', `Automation ${taskId} was not found.`);
256
+ const index = task.runs.findIndex((run) => run.id === runId);
257
+ const run = task.runs[index];
258
+ if (run === undefined)
259
+ return false;
260
+ if (nonTerminal(run) || run.delivery?.status === 'sending') {
261
+ throw new AutomationDomainError('run_in_progress', 'A queued, running, or sending run cannot be deleted.');
262
+ }
263
+ task.runs.splice(index, 1);
264
+ return true;
265
+ });
266
+ }
267
+ async markNotificationsRead() {
268
+ if (!Object.values(this.store.snapshot().tasks).some((task) => task.unreadNotifications > 0))
269
+ return;
270
+ await this.store.mutate((state) => {
271
+ for (const task of Object.values(state.tasks))
272
+ task.unreadNotifications = 0;
273
+ });
274
+ }
275
+ async pause(id, now) {
276
+ return this.store.mutate((state) => {
277
+ const task = state.tasks[id];
278
+ if (task === undefined)
279
+ throw new AutomationDomainError('task_not_found', `Automation ${id} was not found.`);
280
+ if (task.status !== 'active') {
281
+ throw new AutomationDomainError('invalid_state', `Automation ${id} is not active.`);
282
+ }
283
+ task.status = 'paused';
284
+ task.pausedAt = instant(now);
285
+ if (task.nextRunAt !== null)
286
+ task.pausedNextRunAt = task.nextRunAt;
287
+ task.nextRunAt = null;
288
+ return structuredClone(task);
289
+ });
290
+ }
291
+ async resume(id, options, now) {
292
+ return this.store.mutate((state) => {
293
+ const task = state.tasks[id];
294
+ if (task === undefined)
295
+ throw new AutomationDomainError('task_not_found', `Automation ${id} was not found.`);
296
+ if (task.status !== 'paused') {
297
+ throw new AutomationDomainError('invalid_state', `Automation ${id} is not paused.`);
298
+ }
299
+ if (options.runNow && task.runs.some(nonTerminal)) {
300
+ throw new AutomationDomainError('run_in_progress', `Automation ${id} already has a queued or running run.`);
301
+ }
302
+ delete task.pausedAt;
303
+ delete task.pausedNextRunAt;
304
+ if (task.schedule.kind === 'once') {
305
+ const fireAt = Date.parse(task.schedule.fireAt);
306
+ if (fireAt <= now) {
307
+ if (!options.runNow) {
308
+ throw new AutomationDomainError('invalid_state', 'This one-time automation is overdue; resume it with runNow or delete it.');
309
+ }
310
+ task.status = 'completed';
311
+ task.nextRunAt = null;
312
+ }
313
+ else {
314
+ task.status = 'active';
315
+ task.nextRunAt = instant(fireAt);
316
+ }
317
+ }
318
+ else {
319
+ const next = nextOccurrence(task.schedule, now);
320
+ task.status = next === undefined ? 'completed' : 'active';
321
+ task.nextRunAt = next === undefined ? null : instant(next);
322
+ }
323
+ if (options.runNow)
324
+ task.runs.push({ ...makeRun('manual', now), executionTarget: snapshotTarget(task.execution) });
325
+ pruneRuns(task, this.maxRunHistory);
326
+ return structuredClone(task);
327
+ });
328
+ }
329
+ async runNow(id, now) {
330
+ return this.store.mutate((state) => {
331
+ const task = state.tasks[id];
332
+ if (task === undefined)
333
+ throw new AutomationDomainError('task_not_found', `Automation ${id} was not found.`);
334
+ if (task.runs.some(nonTerminal)) {
335
+ throw new AutomationDomainError('run_in_progress', `Automation ${id} already has a queued or running run.`);
336
+ }
337
+ const run = { ...makeRun('manual', now), executionTarget: snapshotTarget(task.execution) };
338
+ task.runs.push(run);
339
+ pruneRuns(task, this.maxRunHistory);
340
+ return structuredClone(run);
341
+ });
342
+ }
343
+ async cancelQueuedRun(id, runId, now) {
344
+ return this.store.mutate((state) => {
345
+ const task = state.tasks[id];
346
+ if (task === undefined)
347
+ throw new AutomationDomainError('task_not_found', `Automation ${id} was not found.`);
348
+ const run = task.runs.find((entry) => entry.id === runId);
349
+ if (run === undefined || run.status !== 'queued') {
350
+ throw new AutomationDomainError('invalid_state', `Automation ${id} does not have that queued run.`);
351
+ }
352
+ run.status = 'canceled';
353
+ run.finishedAt = instant(now);
354
+ run.error = 'Canceled before execution.';
355
+ pruneRuns(task, this.maxRunHistory);
356
+ return structuredClone(run);
357
+ });
358
+ }
359
+ async claimDue(now) {
360
+ const due = Object.values(this.store.snapshot().tasks).some((task) => task.status === 'active' && task.nextRunAt !== null && Date.parse(task.nextRunAt) <= now);
361
+ if (!due)
362
+ return [];
363
+ return this.store.mutate((state) => {
364
+ const claimed = [];
365
+ for (const task of Object.values(state.tasks)) {
366
+ if (task.status !== 'active' || task.nextRunAt === null)
367
+ continue;
368
+ const floor = Date.parse(task.nextRunAt);
369
+ const occurrence = latestDueOccurrence(task.schedule, floor, now);
370
+ if (occurrence === undefined)
371
+ continue;
372
+ if (!task.runs.some(nonTerminal)) {
373
+ const run = { ...makeRun('scheduled', now, occurrence), executionTarget: snapshotTarget(task.execution) };
374
+ task.runs.push(run);
375
+ claimed.push(structuredClone(run));
376
+ }
377
+ const next = nextOccurrence(task.schedule, now);
378
+ task.nextRunAt = next === undefined ? null : instant(next);
379
+ if (next === undefined)
380
+ task.status = 'completed';
381
+ pruneRuns(task, this.maxRunHistory);
382
+ }
383
+ return claimed;
384
+ });
385
+ }
386
+ nextWakeAt(now) {
387
+ const state = this.store.snapshot();
388
+ if (Object.values(state.tasks).some((task) => task.runs.some((run) => run.status === 'queued'))) {
389
+ return now;
390
+ }
391
+ let next;
392
+ for (const task of Object.values(state.tasks)) {
393
+ if (task.status !== 'active' || task.nextRunAt === null)
394
+ continue;
395
+ const candidate = Date.parse(task.nextRunAt);
396
+ if (next === undefined || candidate < next)
397
+ next = candidate;
398
+ }
399
+ return next;
400
+ }
401
+ async takeNextQueued(now) {
402
+ const candidate = Object.values(this.store.snapshot().tasks)
403
+ .flatMap((task) => task.runs.filter((run) => run.status === 'queued').map((run) => ({ task, run })))
404
+ .sort((a, b) => a.run.enqueuedAt.localeCompare(b.run.enqueuedAt))[0];
405
+ if (candidate === undefined)
406
+ return undefined;
407
+ return this.store.mutate((state) => {
408
+ const task = state.tasks[candidate.task.id];
409
+ const run = task?.runs.find((entry) => entry.id === candidate.run.id);
410
+ if (task === undefined || run === undefined || run.status !== 'queued')
411
+ return undefined;
412
+ run.status = 'running';
413
+ run.startedAt = instant(now);
414
+ run.sessionId ??= run.executionTarget?.mode === 'pinned-session' ? run.executionTarget.sessionId : `automation-${randomUUID()}`;
415
+ return { task: structuredClone(task), run: structuredClone(run) };
416
+ });
417
+ }
418
+ async finishRun(taskId, runId, outcome, now, delivery) {
419
+ const task = this.store.snapshot().tasks[taskId];
420
+ if (task === undefined || !task.runs.some((run) => run.id === runId && run.status === 'running'))
421
+ return;
422
+ await this.store.mutate((state) => {
423
+ const current = state.tasks[taskId];
424
+ const run = current?.runs.find((entry) => entry.id === runId);
425
+ if (current === undefined || run === undefined || run.status !== 'running')
426
+ return;
427
+ run.status = outcome.status;
428
+ run.finishedAt = instant(now);
429
+ if (outcome.sessionId !== undefined)
430
+ run.sessionId = outcome.sessionId;
431
+ if (outcome.summary !== undefined)
432
+ run.summary = outcome.summary;
433
+ if (outcome.error !== undefined)
434
+ run.error = outcome.error;
435
+ if (delivery !== undefined && (outcome.status === 'succeeded' || failedOutcome(outcome.status))) {
436
+ run.delivery = { ...AutomationDeliverySchema.parse(delivery), status: 'sending', attemptedAt: instant(now) };
437
+ }
438
+ if (outcome.status === 'succeeded')
439
+ current.consecutiveFailures = 0;
440
+ else if (failedOutcome(outcome.status))
441
+ current.consecutiveFailures += 1;
442
+ if (shouldNotify(current, outcome.status))
443
+ current.unreadNotifications += 1;
444
+ if (current.pauseAfterConsecutiveFailures && current.consecutiveFailures >= 3 && current.status === 'active') {
445
+ current.status = 'paused';
446
+ current.pausedAt = instant(now);
447
+ if (current.nextRunAt !== null)
448
+ current.pausedNextRunAt = current.nextRunAt;
449
+ current.nextRunAt = null;
450
+ }
451
+ pruneRuns(current, this.maxRunHistory);
452
+ });
453
+ }
454
+ /** Delivery settlement never changes execution status or failure counters. */
455
+ async finishDelivery(taskId, runId, delivery) {
456
+ const matches = (run) => run?.delivery?.status === 'sending'
457
+ && run.delivery.botId === delivery.botId && run.delivery.targetId === delivery.targetId
458
+ && run.delivery.attemptedAt === delivery.attemptedAt;
459
+ if (!matches(this.store.snapshot().tasks[taskId]?.runs.find((run) => run.id === runId)))
460
+ return;
461
+ await this.store.mutate((state) => {
462
+ const task = state.tasks[taskId];
463
+ const run = task?.runs.find((entry) => entry.id === runId);
464
+ if (task === undefined || run === undefined || !matches(run))
465
+ return;
466
+ run.delivery = { ...delivery };
467
+ if ((delivery.status === 'failed' || delivery.status === 'unknown') && task.notificationPolicy !== 'never' && !shouldNotify(task, run.status))
468
+ task.unreadNotifications += 1;
469
+ pruneRuns(task, this.maxRunHistory);
470
+ });
471
+ }
472
+ }
473
+ //# sourceMappingURL=domain.js.map
@@ -0,0 +1,14 @@
1
+ /** Machine-readable codes shared by every Automation error. */
2
+ export type AutomationErrorCode = 'task_not_found' | 'invalid_state' | 'run_in_progress' | 'schedule_exhausted' | 'target_resume_failed' | 'target_workspace_mismatch' | 'target_session_unavailable' | 'target_session_not_found' | 'target_session_busy';
3
+ /**
4
+ * Base class for every error Automation raises on purpose.
5
+ *
6
+ * `code` is the stable machine-readable identifier; `message` is the
7
+ * human-readable detail. Consumers (API, tools, scheduler) can branch on
8
+ * `code` instead of string-matching message prefixes.
9
+ */
10
+ export declare class AutomationError extends Error {
11
+ readonly code: AutomationErrorCode;
12
+ constructor(code: AutomationErrorCode, message: string);
13
+ }
14
+ //# sourceMappingURL=errors.d.ts.map
package/lib/errors.js ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Base class for every error Automation raises on purpose.
3
+ *
4
+ * `code` is the stable machine-readable identifier; `message` is the
5
+ * human-readable detail. Consumers (API, tools, scheduler) can branch on
6
+ * `code` instead of string-matching message prefixes.
7
+ */
8
+ export class AutomationError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ this.name = 'AutomationError';
14
+ }
15
+ }
16
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1,30 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { AutomationDelivery, AutomationDeliveryOptions, AutomationRun, AutomationTask } from './types.js';
3
+ import type { RunOutcome } from './domain.js';
4
+ interface DshImService {
5
+ listBots(): Promise<readonly {
6
+ botId: string;
7
+ channel: string;
8
+ }[]>;
9
+ listTargets(botId: string): Promise<readonly {
10
+ targetId: string;
11
+ name?: string;
12
+ kind: string;
13
+ }[]>;
14
+ send(botId: string, targetId: string, text: string, options?: {
15
+ signal?: AbortSignal;
16
+ format?: 'plain' | 'markdown';
17
+ }): Promise<{
18
+ sent: boolean;
19
+ }>;
20
+ }
21
+ declare module '@deepseek-ai/cordis' {
22
+ interface Context {
23
+ dshIm: DshImService;
24
+ }
25
+ }
26
+ export declare function deliveryOptions(ctx: Context, botId?: string): Promise<AutomationDeliveryOptions>;
27
+ export declare function validateDelivery(ctx: Context, delivery: AutomationDelivery): Promise<void>;
28
+ export declare function sendAutomationResult(ctx: Context, task: AutomationTask, _run: AutomationRun, outcome: RunOutcome, signal: AbortSignal): Promise<void>;
29
+ export {};
30
+ //# sourceMappingURL=im-delivery.d.ts.map
@@ -0,0 +1,69 @@
1
+ function service(ctx) {
2
+ const value = ctx.get('dshIm');
3
+ return value !== undefined &&
4
+ typeof value.listBots === 'function' &&
5
+ typeof value.listTargets === 'function' &&
6
+ typeof value.send === 'function'
7
+ ? value
8
+ : undefined;
9
+ }
10
+ export async function deliveryOptions(ctx, botId) {
11
+ const im = service(ctx);
12
+ if (im === undefined)
13
+ return { available: false, bots: [], targets: [] };
14
+ let timer;
15
+ try {
16
+ return await Promise.race([
17
+ (async () => {
18
+ const bots = (await im.listBots()).map(({ botId, channel }) => ({ botId, channel }));
19
+ // Keep other bots selectable when a previously saved bot was removed.
20
+ const targets = botId === undefined || !bots.some((bot) => bot.botId === botId)
21
+ ? []
22
+ : (await im.listTargets(botId)).map(({ targetId, name, kind }) => ({
23
+ targetId,
24
+ kind,
25
+ ...(name === undefined ? {} : { name }),
26
+ }));
27
+ return { available: true, bots, targets };
28
+ })(),
29
+ new Promise((_resolve, reject) => {
30
+ timer = setTimeout(() => reject(new Error('dsh-im target discovery timed out. Try again.')), 5_000);
31
+ }),
32
+ ]);
33
+ }
34
+ finally {
35
+ clearTimeout(timer);
36
+ }
37
+ }
38
+ export async function validateDelivery(ctx, delivery) {
39
+ const options = await deliveryOptions(ctx, delivery.botId);
40
+ if (!options.available)
41
+ throw new Error('dsh-im direct delivery is unavailable on this Host.');
42
+ if (!options.bots.some((bot) => bot.botId === delivery.botId))
43
+ throw new Error('The selected dsh-im bot is no longer available.');
44
+ if (!options.targets.some((target) => target.targetId === delivery.targetId))
45
+ throw new Error('Select a saved target belonging to the selected dsh-im bot.');
46
+ }
47
+ export async function sendAutomationResult(ctx, task, _run, outcome, signal) {
48
+ const im = service(ctx);
49
+ if (im === undefined)
50
+ throw new Error('dsh-im direct delivery is unavailable on this Host.');
51
+ if (task.delivery === undefined)
52
+ throw new Error('No message delivery destination was configured.');
53
+ signal.throwIfAborted();
54
+ const text = [
55
+ `[Automation] ${task.name}`,
56
+ `Status: ${outcome.status}`,
57
+ '',
58
+ outcome.output?.trim() ||
59
+ outcome.summary?.trim() ||
60
+ (outcome.status === 'succeeded' ? 'Task completed without a text reply.' : ''),
61
+ ...(outcome.error === undefined ? [] : [`Error: ${outcome.error}`]),
62
+ ]
63
+ .filter((line, index) => line !== '' || index === 2)
64
+ .join('\n');
65
+ const result = await im.send(task.delivery.botId, task.delivery.targetId, text, { signal, format: 'markdown' });
66
+ if (result.sent !== true)
67
+ throw new Error('dsh-im did not confirm platform acceptance. Delivery will not be retried automatically.');
68
+ }
69
+ //# sourceMappingURL=im-delivery.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import '@deepseek-ai/dsh-agent-preset-registry';
3
+ import '@deepseek-ai/dsh-host-webserver';
4
+ import '@deepseek-ai/dsh-llm';
5
+ import '@deepseek-ai/dsh-permission-presets';
6
+ import '@deepseek-ai/dsh-session-title';
7
+ import '@deepseek-ai/dsh-workspace';
8
+ import '@deepseek-ai/dsh-skill';
9
+ export * from './types.js';
10
+ export * from './errors.js';
11
+ export * from './recurrence.js';
12
+ export * from './store.js';
13
+ export * from './domain.js';
14
+ export * from './scheduler.js';
15
+ export * from './controller.js';
16
+ export declare const name = "automation";
17
+ export declare const inject: string[];
18
+ export interface Config {
19
+ readonly root?: string;
20
+ /** Run history is unlimited unless an explicit limit is configured. */
21
+ readonly maxRunHistory?: number;
22
+ readonly maxRunDurationMs?: number;
23
+ }
24
+ export declare function apply(ctx: Context, config?: Config): Promise<void>;
25
+ //# sourceMappingURL=index.d.ts.map