@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
@@ -1,3 +1,4 @@
1
+ import { executeAgentTurn } from "./runner-turn.js";
1
2
  import { logStreamer } from '../log-streamer.js';
2
3
  import { logger } from '../logger.js';
3
4
  import { bestEffort } from '../best-effort.js';
@@ -21,7 +22,29 @@ import {
21
22
  removeTaskWorktree,
22
23
  } from './runner-worktree.js';
23
24
 
25
+ import {
26
+ formatDateYmd,
27
+ resolveTargetSessionId,
28
+ getAgentsService,
29
+ getSessionService,
30
+ getWorkspaceRegistry,
31
+ resolveWorkspace,
32
+ applyPermissionPreset,
33
+ pinApprovalPolicy,
34
+ nameSession,
35
+ extractUsage,
36
+ disposeAgentRun,
37
+ makeAbortRacer,
38
+ resolveRunContext,
39
+ shapeAgentPrompt,
40
+ runOriginalDispatch,
41
+ runLegacySession,
42
+ runBare,
43
+ } from './runner-session.js';
44
+
24
45
  export {
46
+ formatDateYmd,
47
+ resolveTargetSessionId,
25
48
  isContextOverflowError,
26
49
  terminateProcessTree,
27
50
  isTransientError,
@@ -38,41 +61,6 @@ export {
38
61
  * Resolves the effective target session ID taking into account rotation policies (#143).
39
62
  * Supports {{date}} interpolation, 'daily' rotation (adds -YYYY-MM-DD), and 'weekly' rotation (-YYYY-Www).
40
63
  */
41
- export function formatDateYmd(date = new Date()) {
42
- const yyyy = date.getFullYear();
43
- const mm = String(date.getMonth() + 1).padStart(2, '0');
44
- const dd = String(date.getDate()).padStart(2, '0');
45
- return `${yyyy}-${mm}-${dd}`;
46
- }
47
-
48
- export function resolveTargetSessionId(targetSessionId, resetPolicy = 'never', date = new Date()) {
49
- if (!targetSessionId || typeof targetSessionId !== 'string') return null;
50
- let baseId = targetSessionId.trim();
51
- if (!baseId) return null;
52
-
53
- const yyyymmdd = formatDateYmd(date);
54
-
55
- if (baseId.includes('{{date}}')) {
56
- return baseId.replaceAll('{{date}}', yyyymmdd);
57
- }
58
-
59
- if (resetPolicy === 'daily') {
60
- return `${baseId}-${yyyymmdd}`;
61
- }
62
-
63
- if (resetPolicy === 'weekly') {
64
- const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
65
- const dayNum = d.getUTCDay() || 7;
66
- d.setUTCDate(d.getUTCDate() + 4 - dayNum);
67
- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));
68
- const weekNo = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);
69
- const ww = String(weekNo).padStart(2, '0');
70
- return `${baseId}-${d.getUTCFullYear()}-W${ww}`;
71
- }
72
-
73
- return baseId;
74
- }
75
-
76
64
  export class SessionRunner {
77
65
  constructor(ctx, store = null) {
78
66
  this.ctx = ctx;
@@ -80,80 +68,19 @@ export class SessionRunner {
80
68
  }
81
69
 
82
70
  _getAgentsService() {
83
- if (!this.ctx) return null;
84
- try {
85
- if (typeof this.ctx.get === 'function') {
86
- const svc = this.ctx.get('agents');
87
- if (svc) return svc;
88
- }
89
- } catch (_err) {
90
- // service unavailable via ctx.get
91
- }
92
- try {
93
- return this.ctx.agents || null;
94
- } catch (_err) {
95
- return null;
96
- }
71
+ return getAgentsService(this.ctx);
97
72
  }
98
73
 
99
74
  _getSessionService() {
100
- if (!this.ctx) return null;
101
- try {
102
- if (typeof this.ctx.get === 'function') {
103
- const svc = this.ctx.get('session');
104
- if (svc) return svc;
105
- }
106
- } catch (_err) {
107
- // service unavailable via ctx.get
108
- }
109
- try {
110
- return this.ctx.session || null;
111
- } catch (_err) {
112
- return null;
113
- }
75
+ return getSessionService(this.ctx);
114
76
  }
115
77
 
116
78
  _getWorkspaceRegistry() {
117
- if (!this.ctx) return null;
118
- try {
119
- if (typeof this.ctx.get === 'function') {
120
- const svc = this.ctx.get('workspaceRegistry');
121
- if (svc) return svc;
122
- }
123
- } catch (_err) {
124
- // service unavailable via ctx.get
125
- }
126
- try {
127
- return this.ctx.workspaceRegistry || null;
128
- } catch (_err) {
129
- return null;
130
- }
79
+ return getWorkspaceRegistry(this.ctx);
131
80
  }
132
81
 
133
- /**
134
- * Resolve the registered Workspace object for a task's workspaceId (workspace attach & archive).
135
- * Mirrors the id/title/path lookup used by resolveCwd; returns null when the
136
- * id is absent, the registry is unavailable, or no workspace matches.
137
- */
138
82
  _resolveWorkspace(task) {
139
- const rawId = task?.workspaceId ? String(task.workspaceId).trim() : '';
140
- if (!rawId) return null;
141
- return bestEffort('resolve-workspace', () => {
142
- const registry = this._getWorkspaceRegistry();
143
- if (!registry) return null;
144
- if (typeof registry.get === 'function') {
145
- const ws = registry.get(rawId);
146
- if (ws && typeof ws.attachSession === 'function') return ws;
147
- }
148
- if (typeof registry.list === 'function') {
149
- const list = registry.list();
150
- if (Array.isArray(list)) {
151
- const matched = list.find((w) => w && (w.id === rawId || w.path === rawId || w.title === rawId));
152
- if (matched && typeof matched.attachSession === 'function') return matched;
153
- }
154
- }
155
- return null;
156
- }) || null;
83
+ return resolveWorkspace(this, task);
157
84
  }
158
85
 
159
86
  async execute(task, options = {}) {
@@ -342,57 +269,19 @@ export class SessionRunner {
342
269
  }
343
270
 
344
271
  // Legacy dispatch replaced above; original runner helpers remain unchanged below:
345
- async _runOriginalDispatch(task, signal, options = {}) {
346
- const runtime = normalizeTaskType(task.type);
347
- if (EXTERNAL_RUNTIMES.includes(runtime) || task.mode === 'no-llm') {
348
- return this._runExternal(task, runtime === 'llm' ? 'script' : runtime, signal, options);
349
- }
272
+ _normalizeTaskType(t) { return normalizeTaskType(t); }
273
+ get _externalRuntimes() { return EXTERNAL_RUNTIMES; }
350
274
 
351
- // 2. Agent session, when the harness exposes one
352
- const agentsSvc2 = this._getAgentsService();
353
- if (agentsSvc2 && typeof agentsSvc2.create === 'function') {
354
- return this._runAgentSession(task, runtime, signal, options);
355
- }
356
-
357
- // 3. Legacy session service
358
- const sessionSvc2 = this._getSessionService();
359
- if (sessionSvc2 && typeof sessionSvc2.create === 'function') {
360
- return this._runLegacySession(task, options);
361
- }
362
-
363
- // 4. Nothing to run through: report the prompt as triggered
364
- return this._runBare(task, options);
275
+ async _runOriginalDispatch(task, signal, options = {}) {
276
+ return runOriginalDispatch(this, task, signal, options);
365
277
  }
366
278
 
367
- /** Legacy session service path; falls back to the bare report. */
368
- async _runLegacySession(task) {
369
- try {
370
- const ymd = formatDateYmd();
371
- const explicit = task.sessionTitle ? String(task.sessionTitle).trim().replaceAll('{{date}}', ymd) : '';
372
- const legacyTitle = explicit || `[Cron] ${ymd} ${task.title}`;
373
- const session = await this.ctx.session.create({
374
- title: legacyTitle,
375
- ephemeral: task.delivery === 'isolated',
376
- });
377
- if (session && typeof session.send === 'function') {
378
- const result = await session.send(task.prompt);
379
- const out = typeof result === 'string' ? result : JSON.stringify(result);
380
- const usage = session.usage || { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
381
- return { output: out, usage, costUsd: estimateTokenCost(task.model, usage) };
382
- }
383
- } catch (err) {
384
- logger.error(`[dsh-cron] session execution failed:`, err.message);
385
- throw err;
386
- }
387
- return this._runBare(task);
279
+ async _runLegacySession(task, options = {}) {
280
+ return runLegacySession(this, task, options);
388
281
  }
389
282
 
390
283
  _runBare(task, execOptions = {}) {
391
- return {
392
- output: `[dsh-cron] Prompt triggered: "${task.prompt.slice(0, 100)}..."`,
393
- usage: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 },
394
- costUsd: 0,
395
- };
284
+ return runBare(task, execOptions);
396
285
  }
397
286
 
398
287
  async _runAgentSession(task, runtime, signal, execOptions = {}) {
@@ -493,500 +382,38 @@ export class SessionRunner {
493
382
  * awaits and forces an immediate dispose (#88).
494
383
  */
495
384
  _makeAbortRacer(signal) {
496
- const abortError = () => (signal && signal.reason) || new Error('Task aborted');
497
- return (promise) => {
498
- if (!signal) return promise;
499
- return Promise.race([
500
- promise,
501
- new Promise((_, reject) => {
502
- if (signal.aborted) {
503
- reject(abortError());
504
- return;
505
- }
506
- signal.addEventListener('abort', () => reject(abortError()), { once: true });
507
- }),
508
- ]);
509
- };
385
+ return makeAbortRacer(signal);
510
386
  }
511
387
 
512
- /** Working directory for the run, in an isolated worktree when requested (#29, #231). */
513
388
  async _resolveRunContext(task) {
514
- const baseCwd = this.resolveCwd(task);
515
- let cwd = baseCwd;
516
- let taskWorktree = null;
517
- if (task.worktree) {
518
- // Issue #231: Fail-closed — if worktree creation fails, abort run and preserve base workspace
519
- taskWorktree = await this.createTaskWorktree(baseCwd, task);
520
- cwd = taskWorktree;
521
- }
522
- return { baseCwd, cwd, taskWorktree };
389
+ return resolveRunContext(this, task);
523
390
  }
524
391
 
525
- /** #6/#10: skill- and workflow-driven tasks name the skill/workflow. */
526
392
  _shapeAgentPrompt(task, runtime) {
527
- const prompt = String(task.prompt || '');
528
- if (runtime === 'skill' && task.skillName) {
529
- return `Use the DSH skill "${task.skillName}" for this task:\n${prompt}`;
530
- }
531
- if (runtime === 'workflow' && task.workflowName) {
532
- return `Execute this through the DSH workflow "${task.workflowName}" step by step:\n${prompt}`;
533
- }
534
- return prompt;
393
+ return shapeAgentPrompt(task, runtime);
535
394
  }
536
395
 
537
- /** Create the session, drive one turn, and always clean up. */
538
396
  async _executeAgentTurn(task, prep) {
539
- let handle = prep?.handle || null;
540
- let isResumed = false;
541
- try {
542
- // Resolve agent preset (#GH-1, #GH-2): scheduled llm sessions must join an agent preset
543
- // (default or task-configured), otherwise tools resolve against the empty global layer.
544
- let presets = null;
545
- try {
546
- if (typeof this.ctx.get === 'function') {
547
- presets = this.ctx.get('agentPresets');
548
- } else {
549
- presets = this.ctx.agentPresets;
550
- }
551
- } catch {
552
- presets = null;
553
- }
554
- let preset = null;
555
- if (presets && typeof presets.resolve === 'function') {
556
- try {
557
- preset = await presets.resolve(task.agentPreset || undefined);
558
- if (preset && typeof presets.standingKeyFor === 'function') {
559
- await presets.standingKeyFor(preset.id);
560
- }
561
- } catch (presetErr) {
562
- logger.warn('[dsh-cron] agent preset unavailable, running without one:', presetErr && presetErr.message);
563
- preset = null;
564
- }
565
- }
566
-
567
- const presetSetup = preset ? {
568
- setup: async (agentCtx) => {
569
- if (typeof presets.mount === 'function') {
570
- await presets.mount(agentCtx, preset.id);
571
- }
572
- }
573
- } : {};
574
-
575
- // If targetSessionId is set, attempt to borrow or resume the existing session (#143, #346, GH #9, GH #23)
576
- let resumeFailure = null;
577
- const agents = this._getAgentsService();
578
- if (prep.targetSessionId && agents) {
579
- let liveAgent = null;
580
- try {
581
- if (typeof agents.get === 'function') {
582
- liveAgent = agents.get(prep.targetSessionId);
583
- }
584
- } catch (_getErr) {
585
- liveAgent = null;
586
- }
587
-
588
- if (liveAgent) {
589
- handle = { agent: liveAgent, __borrowedLive: true };
590
- isResumed = true;
591
- logger.info(`[dsh-cron] borrowed active live session: ${prep.targetSessionId}`);
592
- } else if (typeof agents.resume === 'function') {
593
- try {
594
- handle = await agents.resume({
595
- sessionId: prep.targetSessionId,
596
- resumeSessionId: prep.targetSessionId,
597
- meta: {
598
- cwd: prep.cwd,
599
- ...(preset ? { agentPreset: preset.id } : {})
600
- },
601
- agentOptions: prep.provider && prep.model ? { provider: prep.provider, model: prep.model } : undefined,
602
- ...presetSetup,
603
- });
604
- isResumed = true;
605
- logger.info(`[dsh-cron] resumed existing persistent session: ${prep.targetSessionId}`);
606
- } catch (resumeErr) {
607
- resumeFailure = resumeErr;
608
- logger.warn(`[dsh-cron] could not resume session ${prep.targetSessionId} (${resumeErr.message}), fallback creating new session`);
609
- handle = null;
610
- }
611
- }
612
- }
613
-
614
- // Create new session if not resumed
615
- if (!handle) {
616
- const isLockedOrColliding = resumeFailure && /already (?:active|owned|exists)|write handle|locked|collision/i.test(resumeFailure.message || '');
617
- const targetId = prep.mintSessionId({ fresh: isLockedOrColliding });
618
- try {
619
- handle = await agents.create({
620
- sessionId: targetId,
621
- meta: {
622
- cwd: prep.cwd,
623
- ephemeral: !prep.targetSessionId,
624
- internal: !prep.targetSessionId,
625
- ...(preset ? { agentPreset: preset.id } : {})
626
- },
627
- agentOptions: prep.provider && prep.model ? { provider: prep.provider, model: prep.model } : undefined,
628
- ...presetSetup,
629
- });
630
- } catch (createErr) {
631
- if (prep.targetSessionId && targetId === prep.targetSessionId) {
632
- logger.warn(`[dsh-cron] failed to create session with targetSessionId ${prep.targetSessionId} (${createErr.message}), retrying with fresh session ID`);
633
- try {
634
- handle = await agents.create({
635
- sessionId: prep.mintSessionId({ fresh: true }),
636
- meta: {
637
- cwd: prep.cwd,
638
- ephemeral: !prep.targetSessionId,
639
- internal: !prep.targetSessionId,
640
- ...(preset ? { agentPreset: preset.id } : {})
641
- },
642
- agentOptions: prep.provider && prep.model ? { provider: prep.provider, model: prep.model } : undefined,
643
- ...presetSetup,
644
- });
645
- } catch (retryErr) {
646
- if (resumeFailure) {
647
- throw new Error(`could not resume session "${prep.targetSessionId}" (${resumeFailure.message}): ${retryErr.message}`);
648
- }
649
- throw retryErr;
650
- }
651
- } else {
652
- if (resumeFailure) {
653
- throw new Error(`could not resume session "${prep.targetSessionId}" (${resumeFailure.message}): ${createErr.message}`);
654
- }
655
- throw createErr;
656
- }
657
- }
658
- }
659
-
660
- // workspace attach & archive: register the new session with its workspace ledger so it shows
661
- // up under the project instead of "ungrouped". attachSession validates
662
- // that the session cwd resolves to the workspace path, so skip when the
663
- // run uses an isolated worktree (different cwd) or the workspaceId does
664
- // not resolve to a registered workspace.
665
- if (!isResumed && !prep.taskWorktree && task.workspaceId && handle?.agent?.session?.id) {
666
- await bestEffort('attach-session-to-workspace', () =>
667
- this._resolveWorkspace(task)?.attachSession(handle.agent.session.id)
668
- );
669
- }
670
-
671
- this._applyPermissionPreset(task, handle);
672
- this._nameSession(task, handle, isResumed);
673
- await prep.raceAbort(handle.agent.whenIdle());
674
-
675
- // 1. Capture starting sequence before sending user message (#227, #228)
676
- const session = handle.agent.session;
677
- const startSeq = (session && typeof session.seq === 'number')
678
- ? session.seq
679
- : (Array.isArray(session?.log) ? session.log.length : 0);
680
-
681
- handle.agent.followup(prep.createUserMessage({
682
- content: [{ type: 'text', text: prep.agentPrompt }],
683
- source: { kind: 'plugin:dsh-cron', form: 'cron-execute' },
684
- }));
685
- // Await agent turn completion (#67), abortable on timeout/overlap (#88)
686
- if (typeof handle.agent.whenIdle === 'function') {
687
- await prep.raceAbort(handle.agent.whenIdle());
688
- }
689
-
690
- // 2. Snapshot events from this turn only (#227, #228)
691
- let turnEvents = [];
692
- if (typeof session?.snapshotEvents === 'function') {
693
- turnEvents = session.snapshotEvents(startSeq) || [];
694
- } else if (Array.isArray(session?.log)) {
695
- turnEvents = session.log.slice(startSeq);
696
- } else if (Array.isArray(handle.agent?.log)) {
697
- turnEvents = handle.agent.log.slice(startSeq);
698
- }
699
-
700
- // Extract usage FIRST so failed turns and budget checks have accurate token and cost accounting (#228)
701
- const usage = this._extractUsage(handle, turnEvents);
702
- const costUsd = estimateTokenCost(prep.model, usage);
703
-
704
- // 3. Terminal turn failure and settlement check (#227)
705
- let hasTerminalEvent = false;
706
- for (const ev of turnEvents) {
707
- if (!ev) continue;
708
- if (ev.type === 'turn/end' || ev.type === 'turn/error' || ev.type === 'turn/failure') {
709
- hasTerminalEvent = true;
710
- const reason = ev.data?.reason || ev.reason;
711
- const reasonKind = (reason && typeof reason === 'object') ? reason.kind : reason;
712
- if (['error', 'interrupted', 'failed', 'aborted', 'blocked'].includes(reasonKind) || ev.data?.error || ev.error) {
713
- const errMsg = ev.data?.error?.message || ev.error?.message || reason?.message || (typeof reason === 'string' ? reason : `Agent turn ended with status: ${reasonKind || 'error'}`);
714
- const err = new Error(errMsg);
715
- err.reason = reason;
716
- err.reasonKind = reasonKind;
717
- err.turnFailed = true;
718
- err.usage = usage;
719
- err.costUsd = costUsd;
720
- err.sessionId = handle.agent.session?.id || null;
721
- throw err;
722
- }
723
- }
724
- }
725
-
726
- const hasEventLog = typeof session?.snapshotEvents === 'function' || Array.isArray(session?.log) || Array.isArray(handle.agent?.log);
727
- if (hasEventLog && !hasTerminalEvent) {
728
- const err = new Error(
729
- turnEvents.length === 0
730
- ? 'Agent turn produced no events before quiescence'
731
- : 'Agent turn ended without terminal completion event'
732
- );
733
- err.turnFailed = true;
734
- err.usage = usage;
735
- err.costUsd = costUsd;
736
- err.sessionId = handle.agent.session?.id || null;
737
- throw err;
738
- }
739
-
740
- // 4. Extract assistant message text from turn events (#227)
741
- const messageTexts = [];
742
- const chunkTexts = [];
743
- for (const ev of turnEvents) {
744
- if (!ev) continue;
745
- if (ev.type === 'assistant/message') {
746
- const msg = ev.data?.message || ev.data;
747
- if (msg) {
748
- if (typeof msg.content === 'string' && msg.content.trim()) {
749
- messageTexts.push(msg.content.trim());
750
- } else if (Array.isArray(msg.content)) {
751
- const parts = msg.content
752
- .filter((p) => p && p.type === 'text' && typeof p.text === 'string')
753
- .map((p) => p.text)
754
- .join('');
755
- if (parts.trim()) messageTexts.push(parts.trim());
756
- }
757
- }
758
- } else if (ev.type === 'assistant/chunk' && ev.data?.chunk) {
759
- const chunk = ev.data.chunk;
760
- if (chunk.type === 'text' && typeof chunk.text === 'string') {
761
- chunkTexts.push(chunk.text);
762
- } else if (chunk.type === 'text-delta' && typeof chunk.delta === 'string') {
763
- chunkTexts.push(chunk.delta);
764
- }
765
- }
766
- }
767
- let outputText = messageTexts.length > 0 ? messageTexts.join('\n') : chunkTexts.join('');
768
-
769
- // Fallback if no assistant message text was extracted from turn events
770
- if (!outputText.trim()) {
771
- const sessionNote = isResumed
772
- ? `resumed: ${prep.targetSessionId}`
773
- : `session: ${handle.agent.session?.id || 'cron'}`;
774
- outputText = `[dsh-cron] Agent finished turn for task "${task.title}" (${sessionNote})`;
775
- }
776
-
777
- return {
778
- output: outputText,
779
- usage,
780
- costUsd,
781
- sessionId: handle.agent.session?.id || null,
782
- };
783
- } finally {
784
- await this._disposeAgentRun(task, prep, handle);
785
- }
397
+ return executeAgentTurn(this, task, prep);
786
398
  }
787
399
 
788
- /** Per-job permission preset (#32, #380, GH #18): read-only | workspace-write | danger-full-access (or full alias). */
789
400
  _applyPermissionPreset(task, handle) {
790
- if (!task.permissionPreset || task.permissionPreset === 'default') {
791
- this._pinApprovalPolicy(handle);
792
- return;
793
- }
794
- const targetPreset = task.permissionPreset === 'full' ? 'danger-full-access' : task.permissionPreset;
795
- try {
796
- const presets = this.ctx.get ? this.ctx.get('permissionPresets') : this.ctx.permissionPresets;
797
- if (presets && typeof presets.set === 'function') {
798
- presets.set(handle.agent.session, targetPreset);
799
- }
800
- } catch (ppErr) {
801
- logger.warn(`[dsh-cron] permission preset "${task.permissionPreset}" (target: "${targetPreset}") not applied to task ${task.id || ''}:`, ppErr.message);
802
- }
803
- this._pinApprovalPolicy(handle);
401
+ return applyPermissionPreset(this, task, handle);
804
402
  }
805
403
 
806
404
  _pinApprovalPolicy(handle) {
807
- try {
808
- const approval = this.ctx.get ? this.ctx.get('approval') : this.ctx.approval;
809
- if (approval && typeof approval.setPolicy === 'function') {
810
- if (handle?.agent) {
811
- bestEffort('approval-set-policy-agent', () => approval.setPolicy(handle.agent, 'never'), logger);
812
- }
813
- }
814
- } catch (appErr) {
815
- logger.warn('[dsh-cron] approval setPolicy not applied:', appErr.message);
816
- }
405
+ return pinApprovalPolicy(this, handle);
817
406
  }
818
407
 
819
408
  _nameSession(task, handle, isResumed) {
820
- if (!handle?.agent?.session) return;
821
- const session = handle.agent.session;
822
- try {
823
- const sessionTitle = this.ctx.get ? this.ctx.get('sessionTitle') : this.ctx.sessionTitle;
824
- if (!sessionTitle || typeof sessionTitle.rename !== 'function') return;
825
-
826
- const explicitTitle = task.sessionTitle ? String(task.sessionTitle).trim() : '';
827
- const taskTitle = task.title ? String(task.title).trim() : '';
828
- const ymd = formatDateYmd();
829
-
830
- let label = '';
831
- if (explicitTitle) {
832
- label = explicitTitle.replaceAll('{{date}}', ymd);
833
- } else if (taskTitle.startsWith('[')) {
834
- label = taskTitle.replaceAll('{{date}}', ymd);
835
- } else if (taskTitle) {
836
- label = `${ymd} ${taskTitle}`;
837
- }
838
-
839
- if (!label.trim()) return;
840
- if (isResumed && !explicitTitle) return;
841
-
842
- sessionTitle.rename(session, label.trim());
843
- logger.info(`[dsh-cron] assigned session title "${label.trim()}" for session ${session.id}`);
844
- } catch (titleErr) {
845
- logger.debug?.(`[dsh-cron] could not rename session ${session?.id}: ${titleErr.message}`);
846
- }
409
+ return nameSession(this, task, handle, isResumed);
847
410
  }
848
411
 
849
- /** Token usage reported by session events or the handle (#228). */
850
412
  _extractUsage(handle, turnEvents = []) {
851
- const usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
852
- let hasEventUsage = false;
853
-
854
- bestEffort('extract-session-events-usage', () => {
855
- const stepUsage = new Map();
856
- const failedAttempts = [];
857
-
858
- for (const ev of turnEvents) {
859
- if (!ev || !ev.type) continue;
860
-
861
- // assistant/chunk with usage type
862
- if (ev.type === 'assistant/chunk' && ev.data?.chunk?.type === 'usage' && ev.data.chunk.usage) {
863
- const u = ev.data.chunk.usage;
864
- const key = `${ev.data.turn || 0}:${ev.data.step || 0}`;
865
- if (!stepUsage.has(key)) {
866
- stepUsage.set(key, {
867
- inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
868
- outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
869
- cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
870
- });
871
- hasEventUsage = true;
872
- }
873
- }
874
-
875
- // assistant/message finalized usage overwrites intermediate chunk usage for this step
876
- if (ev.type === 'assistant/message') {
877
- const u = ev.data?.usage || ev.data?.message?.usage;
878
- if (u) {
879
- const key = `${ev.data.turn || 0}:${ev.data.step || 0}`;
880
- stepUsage.set(key, {
881
- inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
882
- outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
883
- cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
884
- });
885
- hasEventUsage = true;
886
- }
887
- }
888
-
889
- // assistant/attempt usage (e.g. paid failed attempts, retries, streaming attempts) (#228)
890
- if (ev.type === 'assistant/attempt') {
891
- let attemptUsage = null;
892
- if (ev.data?.usage) {
893
- const u = ev.data.usage;
894
- attemptUsage = {
895
- inputTokens: Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0,
896
- outputTokens: Number(u.outputTokens || u.completionTokens) || 0,
897
- cacheReadTokens: Number(u.cacheReadTokens || u.cachedTokens) || 0,
898
- };
899
- }
900
- // DSH 0.2.0-rc.2 AssistantStreamRecord: stream contains usage chunks
901
- if (Array.isArray(ev.data?.stream)) {
902
- for (const item of ev.data.stream) {
903
- const u = item?.chunk?.usage || item?.usage;
904
- if (u) {
905
- if (!attemptUsage) {
906
- attemptUsage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 };
907
- }
908
- attemptUsage.inputTokens += Number(u.inputTokens || u.promptTokens || u.uncachedInputTokens) || 0;
909
- attemptUsage.outputTokens += Number(u.outputTokens || u.completionTokens) || 0;
910
- attemptUsage.cacheReadTokens += Number(u.cacheReadTokens || u.cachedTokens) || 0;
911
- }
912
- }
913
- }
914
- if (attemptUsage) {
915
- failedAttempts.push(attemptUsage);
916
- hasEventUsage = true;
917
- }
918
- }
919
- }
920
-
921
- if (hasEventUsage) {
922
- for (const item of stepUsage.values()) {
923
- usage.inputTokens += item.inputTokens;
924
- usage.outputTokens += item.outputTokens;
925
- usage.cacheReadTokens += item.cacheReadTokens;
926
- }
927
- for (const item of failedAttempts) {
928
- usage.inputTokens += item.inputTokens;
929
- usage.outputTokens += item.outputTokens;
930
- usage.cacheReadTokens += item.cacheReadTokens;
931
- }
932
- }
933
- });
934
-
935
- if (!hasEventUsage) {
936
- bestEffort('extract-session-usage-fallback', () => {
937
- const sessionUsage = handle?.agent?.session?.usage || handle?.agent?.usage;
938
- if (sessionUsage) {
939
- usage.inputTokens = Number(sessionUsage.inputTokens || sessionUsage.promptTokens) || 0;
940
- usage.outputTokens = Number(sessionUsage.outputTokens || sessionUsage.completionTokens) || 0;
941
- usage.cacheReadTokens = Number(sessionUsage.cacheReadTokens || sessionUsage.cachedTokens) || 0;
942
- }
943
- });
944
- }
945
-
946
- return usage;
413
+ return extractUsage(this, handle, turnEvents);
947
414
  }
948
415
 
949
- /** Dispose the session, archive it best-effort, drop the worktree (#30, #29). */
950
416
  async _disposeAgentRun(task, prep, handle) {
951
- if (handle?.__borrowedLive) {
952
- logger.info(`[dsh-cron] skipping disposal of borrowed live session: ${prep.targetSessionId}`);
953
- return;
954
- }
955
- let archivedSessionId = null;
956
- archivedSessionId = bestEffort('get-archived-session-id', () => {
957
- return (handle && handle.agent && handle.agent.session && handle.agent.session.id) || null;
958
- }) || null;
959
- try {
960
- if (handle && typeof handle.dispose === 'function') {
961
- await handle.dispose();
962
- } else if (handle && handle.agent && typeof handle.agent.destroy === 'function') {
963
- await handle.agent.destroy();
964
- }
965
- } catch (disposeErr) {
966
- logger.warn('[dsh-cron] session dispose notice:', disposeErr.message);
967
- }
968
- // Best-effort: keep ephemeral cron sessions out of the main chat list (#30).
969
- // Persistent sessions (targetSessionId configured) stay unarchived so users can interact with them (#143).
970
- if (archivedSessionId && this.ctx && !prep.targetSessionId) {
971
- // workspace attach & archive: the host SessionStore has no archive() method (it was a silent
972
- // no-op on every run). The durable archive set is written by
973
- // workspaceRegistry.archiveSession, which needs no workspace membership.
974
- await bestEffort('archive-session-cleanup', async () => {
975
- const registry = this._getWorkspaceRegistry();
976
- if (registry && typeof registry.archiveSession === 'function') {
977
- await registry.archiveSession(archivedSessionId);
978
- return;
979
- }
980
- const sessions = typeof this.ctx.get === 'function' ? this.ctx.get('sessions') : null;
981
- if (sessions && typeof sessions.archive === 'function') {
982
- sessions.archive(archivedSessionId);
983
- }
984
- });
985
- }
986
- // #29: dispose the isolated worktree (kept when keepWorktree is set).
987
- if (prep.taskWorktree && !task.keepWorktree) {
988
- await this.removeTaskWorktree(prep.baseCwd, prep.taskWorktree);
989
- }
417
+ return disposeAgentRun(this, task, prep, handle);
990
418
  }
991
419
  }
992
-