@goodandready/dsh-cron 0.3.42 → 0.3.45

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 (42) hide show
  1. package/lib/client.js +998 -3987
  2. package/lib/llm-ask.js +2 -1
  3. package/lib/routes/api-actions.js +36 -6
  4. package/lib/routes/api-item.js +1 -1
  5. package/lib/routes/api-webhook.js +2 -4
  6. package/lib/runtimes/runner-external.js +2 -3
  7. package/lib/runtimes/runner-session.js +385 -0
  8. package/lib/runtimes/runner-turn.js +255 -0
  9. package/lib/runtimes/runner.js +43 -616
  10. package/lib/scheduler/scheduler-execution.js +4 -1
  11. package/lib/scheduler/scheduler-lifecycle.js +65 -0
  12. package/lib/scheduler/scheduler-parser.js +261 -0
  13. package/lib/scheduler/scheduler.js +24 -319
  14. package/lib/store/store-archive.js +195 -0
  15. package/lib/store/store-io.js +331 -0
  16. package/lib/store/store-loader.js +165 -0
  17. package/lib/store/store-migration.js +38 -0
  18. package/lib/store/store-settings.js +126 -0
  19. package/lib/store/store-stats.js +55 -0
  20. package/lib/store/store.js +127 -810
  21. package/package.json +8 -6
  22. package/lib/client-src/00-open.js +0 -63
  23. package/lib/client-src/10-locales.js +0 -540
  24. package/lib/client-src/20-styles.js +0 -64
  25. package/lib/client-src/30-utils.js +0 -372
  26. package/lib/client-src/40-delivery-settings.js +0 -96
  27. package/lib/client-src/45-dag-graph-view.js +0 -287
  28. package/lib/client-src/46-live-logs-modal.js +0 -108
  29. package/lib/client-src/47-analytics-digest-modal.js +0 -166
  30. package/lib/client-src/48-timeline-heatmap-view.js +0 -176
  31. package/lib/client-src/50-cron-screen-state.js +0 -457
  32. package/lib/client-src/52-cron-screen-actions.js +0 -330
  33. package/lib/client-src/53-cron-screen-modal-actions.js +0 -677
  34. package/lib/client-src/54-cron-screen-analytics-actions.js +0 -68
  35. package/lib/client-src/55-cron-screen-view.js +0 -378
  36. package/lib/client-src/60-modal-task-form-head.js +0 -581
  37. package/lib/client-src/62-modal-task-form-tail.js +0 -563
  38. package/lib/client-src/65-modal-dialogs.js +0 -350
  39. package/lib/client-src/70-settings-card.js +0 -453
  40. package/lib/client-src/75-quick-action-bar.js +0 -146
  41. package/lib/client-src/80-sidebar-jobs.js +0 -200
  42. package/lib/client-src/90-close.js +0 -219
package/lib/llm-ask.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { bestEffort } from './best-effort.js';
2
+ import { logger } from './logger.js';
2
3
  /**
3
4
  * Small helper for asking the configured model a short question (#44, #43).
4
5
  *
@@ -107,7 +108,7 @@ export async function askModel(ctx, options = {}) {
107
108
  return { text: String(text || '').trim(), finishKind };
108
109
  })();
109
110
  // The abandoned stream must not surface as an unhandled rejection.
110
- work.catch(() => {});
111
+ void bestEffort('llm-ask-abandoned-stream', () => work, logger);
111
112
 
112
113
  const { text, finishKind } = await Promise.race([work, deadline]);
113
114
  if (!isCleanFinish(finishKind)) {
@@ -1,4 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { logger } from '../logger.js';
2
3
  import { captureGitDiff, discardGitChanges, applyGitDiff } from '../git-diff.js';
3
4
  import { applyDoctorFix, revertDoctorFix, diagnoseFailure } from '../doctor.js';
4
5
  import { rollbackPromptVersion } from '../prompt-evolver.js';
@@ -8,7 +9,13 @@ import { sendJson, readBody, redactTaskSecrets } from '../http-utils.js';
8
9
  import { buildDuplicateTask } from '../task-transfer.js';
9
10
  import { refuseConfigOwned, NOT_FOUND } from './api-collection.js';
10
11
 
11
- export async function handleItemPost({ store, scheduler, req, res, url, id, action, subAction }) {
12
+ async function readOptionalBody(req, res) {
13
+ const { body, error } = await readBody(req, res);
14
+ if (error) return null;
15
+ return body && typeof body === 'object' ? body : {};
16
+ }
17
+
18
+ export async function handleItemPost({ store, scheduler, req, res, url, id, action, subAction, ctx }) {
12
19
  if (action === 'git-diff' && (subAction === 'discard' || subAction === 'revert')) {
13
20
  const task = store.get(id);
14
21
  if (!task) {
@@ -149,7 +156,8 @@ export async function handleItemPost({ store, scheduler, req, res, url, id, acti
149
156
  sendJson(res, 404, NOT_FOUND);
150
157
  return true;
151
158
  }
152
- const body = await readBodyJson(req).catch(() => ({}));
159
+ const body = await readOptionalBody(req, res);
160
+ if (!body) return true;
153
161
  const targetVersion = Number(body.version || url.searchParams.get('version'));
154
162
  if (!targetVersion || targetVersion < 1) {
155
163
  sendJson(res, 400, { ok: false, error: 'A valid target prompt version is required' });
@@ -175,7 +183,8 @@ export async function handleItemPost({ store, scheduler, req, res, url, id, acti
175
183
  sendJson(res, 404, NOT_FOUND);
176
184
  return true;
177
185
  }
178
- const body = await readBodyJson(req).catch(() => ({}));
186
+ const body = await readOptionalBody(req, res);
187
+ if (!body) return true;
179
188
  const runId = body.runId || url.searchParams.get('runId');
180
189
  const runs = store.history.get(id) || [];
181
190
  const run = runId ? runs.find(r => r.id === runId) : runs[0];
@@ -203,7 +212,8 @@ export async function handleItemPost({ store, scheduler, req, res, url, id, acti
203
212
  sendJson(res, 404, NOT_FOUND);
204
213
  return true;
205
214
  }
206
- const body = await readBodyJson(req).catch(() => ({}));
215
+ const body = await readOptionalBody(req, res);
216
+ if (!body) return true;
207
217
  const proposalId = body.proposalId || url.searchParams.get('proposalId');
208
218
  const proposal = proposalId
209
219
  ? approvalManager.getProposal(proposalId)
@@ -225,8 +235,27 @@ export async function handleItemPost({ store, scheduler, req, res, url, id, acti
225
235
  return true;
226
236
  }
227
237
 
238
+ const warnLog = (ctx?.logger && typeof ctx.logger.warn === 'function')
239
+ ? ctx.logger
240
+ : (scheduler?.logger && typeof scheduler.logger.warn === 'function' ? scheduler.logger : logger);
241
+
228
242
  if (decision === 'approve') {
229
- scheduler.runTask(id, { approvedBy: body.decidedBy || 'web-user' }).catch(() => {});
243
+ try {
244
+ const runOutcome = await scheduler.runTask(id, { approvedBy: body.decidedBy || 'web-user' });
245
+ if (runOutcome && (runOutcome.ok === false || runOutcome.status === 'error' || runOutcome.status === 'timeout')) {
246
+ const errMsg = runOutcome.error || runOutcome.stoppedReason || `Task run failed (${runOutcome.status || 'error'})`;
247
+ warnLog.warn(`[dsh-cron] Approved task "${id}" failed to run: ${errMsg}`);
248
+ sendJson(res, 500, { ok: false, error: errMsg, proposal: result.proposal, run: runOutcome });
249
+ return true;
250
+ }
251
+ sendJson(res, 200, { ok: true, proposal: result.proposal, ...(runOutcome ? { run: runOutcome } : {}) });
252
+ return true;
253
+ } catch (err) {
254
+ const errMsg = (err && err.message) || String(err);
255
+ warnLog.warn(`[dsh-cron] Approved task "${id}" threw during execution: ${errMsg}`);
256
+ sendJson(res, 500, { ok: false, error: errMsg, proposal: result.proposal });
257
+ return true;
258
+ }
230
259
  }
231
260
 
232
261
  sendJson(res, 200, { ok: true, proposal: result.proposal });
@@ -238,7 +267,8 @@ export async function handleItemPost({ store, scheduler, req, res, url, id, acti
238
267
  sendJson(res, 404, NOT_FOUND);
239
268
  return true;
240
269
  }
241
- const body = await readBody(req).then(b => JSON.parse(b || '{}')).catch(() => ({}));
270
+ const body = await readOptionalBody(req, res);
271
+ if (!body) return true;
242
272
  const runId = body.runId || url.searchParams.get('runId');
243
273
  if (!runId) {
244
274
  sendJson(res, 400, { ok: false, error: 'runId is required' });
@@ -116,7 +116,7 @@ export async function handleTaskItem({ store, scheduler, req, res, url, id, acti
116
116
  }
117
117
  }
118
118
  if (req.method === 'POST') {
119
- const handled = await handleItemPost({ store, scheduler, req, res, url, id, action, subAction });
119
+ const handled = await handleItemPost({ store, scheduler, req, res, url, id, action, subAction, ctx });
120
120
  if (handled) return;
121
121
  }
122
122
  if (req.method === 'PATCH') {
@@ -165,14 +165,12 @@ export async function handleTelegramWebhook({ store, scheduler, req, res }) {
165
165
  if (botToken) {
166
166
  await answerTelegramCallbackQuery({ botToken, callbackQueryId: queryId, text: summary.slice(0, 190) });
167
167
  if (summary.length > 190 && chatId) {
168
- await sendTelegramMessage({
168
+ await bestEffort('telegram-full-output', () => sendTelegramMessage({
169
169
  botToken,
170
170
  chatId,
171
171
  text: `*Full Output for ${task.title}:*\n\`\`\`\n${summary.slice(0, 3000)}\n\`\`\``,
172
172
  parseMode: 'Markdown',
173
- }).catch(() => {
174
- bestEffort('telegram-full-output', () => {}, scheduler?.logger);
175
- });
173
+ }), scheduler?.logger || logger);
176
174
  }
177
175
  }
178
176
  }
@@ -31,11 +31,10 @@ export function terminateProcessTree(child, sig = 'SIGTERM', { isPosix = process
31
31
  bestEffort('kill-posix-pid', () => process.kill(-child.pid, sig));
32
32
  } else if (child.pid) {
33
33
  const runner = execFn || ((cmd) => {
34
- bestEffort('exec-taskkill-fn', () => {
34
+ void bestEffort('exec-taskkill-fn', () =>
35
35
  import('node:child_process').then(({ exec }) => {
36
36
  exec(cmd, { windowsHide: true }, () => {});
37
- }).catch(() => {});
38
- });
37
+ }), logger);
39
38
  });
40
39
  bestEffort('exec-taskkill', () => runner(`taskkill /pid ${child.pid} /T /F`));
41
40
  bestEffort('child-kill', () => child.kill(sig));
@@ -0,0 +1,385 @@
1
+ import { logger } from '../logger.js';
2
+ import { bestEffort } from '../best-effort.js';
3
+
4
+ export function formatDateYmd(date = new Date()) {
5
+ const yyyy = date.getFullYear();
6
+ const mm = String(date.getMonth() + 1).padStart(2, '0');
7
+ const dd = String(date.getDate()).padStart(2, '0');
8
+ return `${yyyy}-${mm}-${dd}`;
9
+ }
10
+
11
+ export function resolveTargetSessionId(targetSessionId, resetPolicy = 'never', date = new Date()) {
12
+ if (!targetSessionId || typeof targetSessionId !== 'string') return null;
13
+ let baseId = targetSessionId.trim();
14
+ if (!baseId) return null;
15
+
16
+ const yyyymmdd = formatDateYmd(date);
17
+
18
+ if (baseId.includes('{{date}}')) {
19
+ return baseId.replaceAll('{{date}}', yyyymmdd);
20
+ }
21
+
22
+ if (resetPolicy === 'daily') {
23
+ return `${baseId}-${yyyymmdd}`;
24
+ }
25
+
26
+ if (resetPolicy === 'weekly') {
27
+ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
28
+ const dayNum = d.getUTCDay() || 7;
29
+ d.setUTCDate(d.getUTCDate() + 4 - dayNum);
30
+ const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
31
+ const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
32
+ const ww = String(weekNo).padStart(2, '0');
33
+ return `${baseId}-${d.getUTCFullYear()}-W${ww}`;
34
+ }
35
+
36
+ return baseId;
37
+ }
38
+
39
+ export function getAgentsService(ctx) {
40
+ if (!ctx) return null;
41
+ try {
42
+ if (typeof ctx.get === 'function') {
43
+ const svc = ctx.get('agents');
44
+ if (svc) return svc;
45
+ }
46
+ } catch (_err) {
47
+ // service unavailable via ctx.get
48
+ }
49
+ try {
50
+ return ctx.agents || null;
51
+ } catch (_err) {
52
+ return null;
53
+ }
54
+ }
55
+
56
+ export function getSessionService(ctx) {
57
+ if (!ctx) return null;
58
+ try {
59
+ if (typeof ctx.get === 'function') {
60
+ const svc = ctx.get('session') || ctx.get('sessions');
61
+ if (svc) return svc;
62
+ }
63
+ } catch (_err) {
64
+ // service unavailable via ctx.get
65
+ }
66
+ try {
67
+ return ctx.session || ctx.sessions || null;
68
+ } catch (_err) {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ export function getWorkspaceRegistry(ctx) {
74
+ if (!ctx) return null;
75
+ try {
76
+ if (typeof ctx.get === 'function') {
77
+ const svc = ctx.get('workspaceRegistry') || ctx.get('workspaces');
78
+ if (svc) return svc;
79
+ }
80
+ } catch (_err) {
81
+ // service unavailable via ctx.get
82
+ }
83
+ try {
84
+ return ctx.workspaceRegistry || ctx.workspaces || null;
85
+ } catch (_err) {
86
+ return null;
87
+ }
88
+ }
89
+
90
+ export function resolveWorkspace(runner, task) {
91
+ const rawId = task?.workspaceId ? String(task.workspaceId).trim() : '';
92
+ if (!rawId) return null;
93
+ return bestEffort('resolve-workspace', () => {
94
+ const registry = runner._getWorkspaceRegistry();
95
+ if (!registry) return null;
96
+ if (typeof registry.get === 'function') {
97
+ const ws = registry.get(rawId);
98
+ if (ws && typeof ws.attachSession === 'function') return ws;
99
+ }
100
+ if (typeof registry.list === 'function') {
101
+ const list = registry.list();
102
+ if (Array.isArray(list)) {
103
+ const matched = list.find((w) => w && (w.id === rawId || w.path === rawId || w.title === rawId));
104
+ if (matched && typeof matched.attachSession === 'function') return matched;
105
+ }
106
+ }
107
+ return null;
108
+ }) || null;
109
+ }
110
+
111
+ export function applyPermissionPreset(runner, task, handle) {
112
+ if (!task.permissionPreset || task.permissionPreset === 'default') {
113
+ runner._pinApprovalPolicy(handle);
114
+ return;
115
+ }
116
+ const targetPreset = task.permissionPreset === 'full' ? 'danger-full-access' : task.permissionPreset;
117
+ try {
118
+ const presets = runner.ctx.get ? runner.ctx.get('permissionPresets') : runner.ctx.permissionPresets;
119
+ if (presets && typeof presets.set === 'function') {
120
+ presets.set(handle.agent.session, targetPreset);
121
+ }
122
+ } catch (ppErr) {
123
+ logger.warn(`[dsh-cron] permission preset "${task.permissionPreset}" (target: "${targetPreset}") not applied to task ${task.id || ''}:`, ppErr.message);
124
+ }
125
+ runner._pinApprovalPolicy(handle);
126
+ }
127
+
128
+ export function pinApprovalPolicy(runner, handle) {
129
+ try {
130
+ const approval = runner.ctx.get ? runner.ctx.get('approval') : runner.ctx.approval;
131
+ if (approval && typeof approval.setPolicy === 'function') {
132
+ if (handle?.agent) {
133
+ bestEffort('approval-set-policy-agent', () => approval.setPolicy(handle.agent, 'never'), logger);
134
+ }
135
+ }
136
+ } catch (appErr) {
137
+ logger.warn('[dsh-cron] approval setPolicy not applied:', appErr.message);
138
+ }
139
+ }
140
+
141
+ export function nameSession(runner, task, handle, isResumed) {
142
+ if (!handle?.agent?.session) return;
143
+ const session = handle.agent.session;
144
+ try {
145
+ const sessionTitle = runner.ctx.get ? runner.ctx.get('sessionTitle') : runner.ctx.sessionTitle;
146
+ if (!sessionTitle || typeof sessionTitle.rename !== 'function') return;
147
+
148
+ const explicitTitle = task.sessionTitle ? String(task.sessionTitle).trim() : '';
149
+ const taskTitle = task.title ? String(task.title).trim() : '';
150
+ const ymd = formatDateYmd();
151
+
152
+ let label = '';
153
+ if (explicitTitle) {
154
+ label = explicitTitle.replaceAll('{{date}}', ymd);
155
+ } else if (taskTitle.startsWith('[')) {
156
+ label = taskTitle.replaceAll('{{date}}', ymd);
157
+ } else if (taskTitle) {
158
+ label = `${ymd} ${taskTitle}`;
159
+ }
160
+
161
+ if (!label.trim()) return;
162
+ if (isResumed && !explicitTitle) return;
163
+
164
+ sessionTitle.rename(session, label.trim());
165
+ logger.info(`[dsh-cron] assigned session title "${label.trim()}" for session ${session.id}`);
166
+ } catch (titleErr) {
167
+ logger.debug?.(`[dsh-cron] could not rename session ${session?.id}: ${titleErr.message}`);
168
+ }
169
+ }
170
+
171
+ export function extractUsage(runner, handle, turnEvents = []) {
172
+ const usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
173
+ let hasEventUsage = false;
174
+
175
+ bestEffort('extract-session-events-usage', () => {
176
+ const stepUsage = new Map();
177
+ const failedAttempts = [];
178
+
179
+ for (const ev of turnEvents) {
180
+ if (!ev || !ev.type) continue;
181
+
182
+ if (ev.type === 'assistant/chunk' && ev.data?.chunk?.type === 'usage' && ev.data.chunk.usage) {
183
+ const u = ev.data.chunk.usage;
184
+ const key = `${ev.data.turn || 0}:${ev.data.step || 0}`;
185
+ if (!stepUsage.has(key)) {
186
+ stepUsage.set(key, {
187
+ inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
188
+ outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
189
+ cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
190
+ });
191
+ hasEventUsage = true;
192
+ }
193
+ }
194
+
195
+ if (ev.type === 'assistant/message') {
196
+ const u = ev.data?.usage || ev.data?.message?.usage;
197
+ if (u) {
198
+ const key = `${ev.data.turn || 0}:${ev.data.step || 0}`;
199
+ stepUsage.set(key, {
200
+ inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
201
+ outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
202
+ cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
203
+ });
204
+ hasEventUsage = true;
205
+ }
206
+ }
207
+
208
+ if (ev.type === 'assistant/attempt') {
209
+ let attemptUsage = null;
210
+ if (ev.data?.usage) {
211
+ const u = ev.data.usage;
212
+ attemptUsage = {
213
+ inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
214
+ outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
215
+ cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
216
+ };
217
+ }
218
+ if (Array.isArray(ev.data?.stream)) {
219
+ for (const item of ev.data.stream) {
220
+ const u = item?.chunk?.usage || item?.usage;
221
+ if (u) {
222
+ if (!attemptUsage) {
223
+ attemptUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
224
+ }
225
+ attemptUsage.inputTokens += Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0;
226
+ attemptUsage.outputTokens += Number(u.outputTokens || u.completionTokens) || 0;
227
+ attemptUsage.cacheReadTokens += Number(u.cacheReadTokens || u.cachedTokens) || 0;
228
+ }
229
+ }
230
+ }
231
+ if (attemptUsage) {
232
+ failedAttempts.push(attemptUsage);
233
+ hasEventUsage = true;
234
+ }
235
+ }
236
+ }
237
+
238
+ if (hasEventUsage) {
239
+ for (const item of stepUsage.values()) {
240
+ usage.inputTokens += item.inputTokens;
241
+ usage.outputTokens += item.outputTokens;
242
+ usage.cacheReadTokens += item.cacheReadTokens;
243
+ }
244
+ for (const item of failedAttempts) {
245
+ usage.inputTokens += item.inputTokens;
246
+ usage.outputTokens += item.outputTokens;
247
+ usage.cacheReadTokens += item.cacheReadTokens;
248
+ }
249
+ }
250
+ });
251
+
252
+ if (!hasEventUsage) {
253
+ bestEffort('extract-session-usage-fallback', () => {
254
+ const sessionUsage = handle?.agent?.session?.usage || handle?.agent?.usage;
255
+ if (sessionUsage) {
256
+ usage.inputTokens = Number(sessionUsage.inputTokens || sessionUsage.promptTokens) || 0;
257
+ usage.outputTokens = Number(sessionUsage.outputTokens || sessionUsage.completionTokens) || 0;
258
+ usage.cacheReadTokens = Number(sessionUsage.cacheReadTokens || sessionUsage.cachedTokens) || 0;
259
+ }
260
+ });
261
+ }
262
+
263
+ return usage;
264
+ }
265
+
266
+ export async function disposeAgentRun(runner, task, prep, handle) {
267
+ if (handle?.__borrowedLive) {
268
+ logger.info(`[dsh-cron] skipping disposal of borrowed live session: ${prep.targetSessionId}`);
269
+ return;
270
+ }
271
+ let archivedSessionId = null;
272
+ archivedSessionId = bestEffort('get-archived-session-id', () => {
273
+ return (handle && handle.agent && handle.agent.session && handle.agent.session.id) || null;
274
+ }) || null;
275
+ try {
276
+ if (handle && typeof handle.dispose === 'function') {
277
+ await handle.dispose();
278
+ } else if (handle && handle.agent && typeof handle.agent.destroy === 'function') {
279
+ await handle.agent.destroy();
280
+ }
281
+ } catch (disposeErr) {
282
+ logger.warn('[dsh-cron] session dispose notice:', disposeErr.message);
283
+ }
284
+ if (archivedSessionId && runner.ctx && !prep.targetSessionId) {
285
+ await bestEffort('archive-session-cleanup', async () => {
286
+ const registry = runner._getWorkspaceRegistry();
287
+ if (registry && typeof registry.archiveSession === 'function') {
288
+ await registry.archiveSession(archivedSessionId);
289
+ return;
290
+ }
291
+ const sessions = typeof runner.ctx.get === 'function' ? runner.ctx.get('sessions') : null;
292
+ if (sessions && typeof sessions.archive === 'function') {
293
+ sessions.archive(archivedSessionId);
294
+ }
295
+ });
296
+ }
297
+ if (prep.taskWorktree && !task.keepWorktree) {
298
+ await runner.removeTaskWorktree(prep.baseCwd, prep.taskWorktree);
299
+ }
300
+ }
301
+
302
+ export function makeAbortRacer(signal) {
303
+ const abortError = () => (signal && signal.reason) || new Error('Task aborted');
304
+ return (promise) => {
305
+ if (!signal) return promise;
306
+ return Promise.race([
307
+ promise,
308
+ new Promise((_, reject) => {
309
+ if (signal.aborted) {
310
+ reject(abortError());
311
+ return;
312
+ }
313
+ signal.addEventListener('abort', () => reject(abortError()), { once: true });
314
+ }),
315
+ ]);
316
+ };
317
+ }
318
+
319
+ export async function resolveRunContext(runner, task) {
320
+ const baseCwd = runner.resolveCwd(task);
321
+ let cwd = baseCwd;
322
+ let taskWorktree = null;
323
+ if (task.worktree) {
324
+ taskWorktree = await runner.createTaskWorktree(baseCwd, task);
325
+ cwd = taskWorktree;
326
+ }
327
+ return { baseCwd, cwd, taskWorktree };
328
+ }
329
+
330
+ export function shapeAgentPrompt(task, runtime) {
331
+ const prompt = String(task.prompt || '');
332
+ if (runtime === 'skill' && task.skillName) {
333
+ return `Use the DSH skill "${task.skillName}" for this task:\n${prompt}`;
334
+ }
335
+ if (runtime === 'workflow' && task.workflowName) {
336
+ return `Execute this through the DSH workflow "${task.workflowName}" step by step:\n${prompt}`;
337
+ }
338
+ return prompt;
339
+ }
340
+
341
+ export async function runOriginalDispatch(runner, task, signal, options = {}) {
342
+ const runtime = runner._normalizeTaskType ? runner._normalizeTaskType(task.type) : (task.type || 'llm');
343
+ if ((runner._externalRuntimes && runner._externalRuntimes.includes(runtime)) || task.mode === 'no-llm') {
344
+ return runner._runExternal(task, runtime === 'llm' ? 'script' : runtime, signal, options);
345
+ }
346
+ const agentsSvc2 = runner._getAgentsService();
347
+ if (agentsSvc2 && typeof agentsSvc2.create === 'function') {
348
+ return runner._runAgentSession(task, runtime, signal, options);
349
+ }
350
+ const sessionSvc2 = runner._getSessionService();
351
+ if (sessionSvc2 && typeof sessionSvc2.create === 'function') {
352
+ return runner._runLegacySession(task, options);
353
+ }
354
+ return runner._runBare(task, options);
355
+ }
356
+
357
+ export async function runLegacySession(runner, task) {
358
+ try {
359
+ const ymd = formatDateYmd();
360
+ const explicit = task.sessionTitle ? String(task.sessionTitle).trim().replaceAll('{{date}}', ymd) : '';
361
+ const legacyTitle = explicit || `[Cron] ${ymd} ${task.title}`;
362
+ const session = await runner.ctx.session.create({
363
+ title: legacyTitle,
364
+ ephemeral: task.delivery === 'isolated',
365
+ });
366
+ if (session && typeof session.send === 'function') {
367
+ const result = await session.send(task.prompt);
368
+ const out = typeof result === 'string' ? result : JSON.stringify(result);
369
+ const usage = session.usage || { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
370
+ return { output: out, usage, costUsd: 0 };
371
+ }
372
+ } catch (err) {
373
+ logger.error(`[dsh-cron] session execution failed:`, err.message);
374
+ throw err;
375
+ }
376
+ return runner._runBare(task);
377
+ }
378
+
379
+ export function runBare(task, execOptions = {}) {
380
+ return {
381
+ output: `[dsh-cron] Prompt triggered: "${task.prompt.slice(0, 100)}..."`,
382
+ usage: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 },
383
+ costUsd: 0,
384
+ };
385
+ }