@fish-under-sea/dsh-client-ui-task-board-fish 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/LICENSE +202 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +202 -2
  4. package/README.zh.md +203 -0
  5. package/cordis.patch.yml +12 -0
  6. package/icon.svg +3 -0
  7. package/lib/client.js +12941 -0
  8. package/lib/client.js.map +1 -0
  9. package/lib/index.js +10471 -0
  10. package/lib/types/client/PluginSettingsCard.d.ts +144 -0
  11. package/lib/types/client/TaskBoardSettingsCard.d.ts +92 -0
  12. package/lib/types/client/apply-guard.d.ts +25 -0
  13. package/lib/types/client/board/ClampedMarkdown.d.ts +3 -0
  14. package/lib/types/client/board/ConfirmDialog.d.ts +15 -0
  15. package/lib/types/client/board/EditTaskModal.d.ts +17 -0
  16. package/lib/types/client/board/LinkSubtaskModal.d.ts +14 -0
  17. package/lib/types/client/board/NewTaskModal.d.ts +26 -0
  18. package/lib/types/client/board/TagManagerModal.d.ts +26 -0
  19. package/lib/types/client/board/TaskBoard.d.ts +26 -0
  20. package/lib/types/client/board/TaskCard.d.ts +36 -0
  21. package/lib/types/client/board/TaskDetail.d.ts +9 -0
  22. package/lib/types/client/board/TaskForm.d.ts +72 -0
  23. package/lib/types/client/board/VerificationReport.d.ts +23 -0
  24. package/lib/types/client/board/card-view.d.ts +113 -0
  25. package/lib/types/client/board/icons.d.ts +32 -0
  26. package/lib/types/client/board/overlay.d.ts +69 -0
  27. package/lib/types/client/board/parse-model-pref.d.ts +4 -0
  28. package/lib/types/client/board/preset-label.d.ts +22 -0
  29. package/lib/types/client/board/status-key.d.ts +19 -0
  30. package/lib/types/client/board/task-markdown.d.ts +19 -0
  31. package/lib/types/client/host-api.d.ts +63 -0
  32. package/lib/types/client/index.d.ts +128 -0
  33. package/lib/types/client/locales.d.ts +443 -0
  34. package/lib/types/client/main-session.d.ts +32 -0
  35. package/lib/types/client/native-panel.d.ts +48 -0
  36. package/lib/types/client/plugin-card-seat.d.ts +108 -0
  37. package/lib/types/client/schedule-presets.d.ts +10 -0
  38. package/lib/types/client/schedule-zone.d.ts +97 -0
  39. package/lib/types/client/seats.d.ts +18 -0
  40. package/lib/types/client/service.d.ts +32 -0
  41. package/lib/types/client/settings-entry-form.d.ts +49 -0
  42. package/lib/types/client/settings-form.d.ts +213 -0
  43. package/lib/types/core/controller.d.ts +373 -0
  44. package/lib/types/core/degraded-reason.d.ts +46 -0
  45. package/lib/types/core/extension.d.ts +283 -0
  46. package/lib/types/core/freeze-snapshot.d.ts +71 -0
  47. package/lib/types/core/handover.d.ts +70 -0
  48. package/lib/types/core/issue-form.d.ts +16 -0
  49. package/lib/types/core/package-name.d.ts +9 -0
  50. package/lib/types/core/poll-cadence.d.ts +31 -0
  51. package/lib/types/core/schedule.d.ts +124 -0
  52. package/lib/types/core/session-reuse.d.ts +24 -0
  53. package/lib/types/core/store.d.ts +64 -0
  54. package/lib/types/core/subtask.d.ts +141 -0
  55. package/lib/types/core/tasks.d.ts +601 -0
  56. package/lib/types/core/use-cases/task-archive.d.ts +20 -0
  57. package/lib/types/core/use-cases/task-create.d.ts +27 -0
  58. package/lib/types/core/use-cases/task-delete.d.ts +27 -0
  59. package/lib/types/core/use-cases/task-parent.d.ts +21 -0
  60. package/lib/types/core/use-cases/task-schedule.d.ts +96 -0
  61. package/lib/types/core/use-cases/task-tag.d.ts +48 -0
  62. package/lib/types/core/use-cases/task-update.d.ts +56 -0
  63. package/lib/types/core/verification-budget.d.ts +52 -0
  64. package/lib/types/core/verification.d.ts +753 -0
  65. package/lib/types/core/workspace-target.d.ts +41 -0
  66. package/lib/types/dsh-home.d.ts +16 -0
  67. package/lib/types/host/agent-tools.d.ts +27 -0
  68. package/lib/types/host/extension-registry.d.ts +111 -0
  69. package/lib/types/host/llm-dispatch.d.ts +63 -0
  70. package/lib/types/host/verification-gate.d.ts +95 -0
  71. package/lib/types/host/verification-runner.d.ts +139 -0
  72. package/lib/types/host/workspace-evidence.d.ts +53 -0
  73. package/lib/types/host-ai.d.ts +51 -0
  74. package/lib/types/host-ledger.d.ts +385 -0
  75. package/lib/types/host-routes.d.ts +36 -0
  76. package/lib/types/host-runner.d.ts +252 -0
  77. package/lib/types/host-service.d.ts +379 -0
  78. package/lib/types/http.d.ts +59 -0
  79. package/lib/types/index.d.ts +322 -0
  80. package/lib/types/loopback.d.ts +24 -0
  81. package/lib/types/mount-once.d.ts +55 -0
  82. package/lib/types/power-inhibitor.d.ts +73 -0
  83. package/lib/types/protocol.d.ts +212 -0
  84. package/lib/types/tool-surface.d.ts +71 -0
  85. package/package.json +107 -4
  86. package/src/client/PluginSettingsCard.tsx +564 -0
  87. package/src/client/TaskBoardSettingsCard.tsx +539 -0
  88. package/src/client/apply-guard.ts +35 -0
  89. package/src/client/board/ClampedMarkdown.tsx +69 -0
  90. package/src/client/board/ConfirmDialog.tsx +44 -0
  91. package/src/client/board/EditTaskModal.tsx +110 -0
  92. package/src/client/board/LinkSubtaskModal.tsx +97 -0
  93. package/src/client/board/NewTaskModal.tsx +718 -0
  94. package/src/client/board/TagManagerModal.tsx +235 -0
  95. package/src/client/board/TaskBoard.tsx +558 -0
  96. package/src/client/board/TaskCard.tsx +315 -0
  97. package/src/client/board/TaskDetail.tsx +985 -0
  98. package/src/client/board/TaskForm.tsx +264 -0
  99. package/src/client/board/VerificationReport.tsx +322 -0
  100. package/src/client/board/card-view.ts +220 -0
  101. package/src/client/board/icons.tsx +89 -0
  102. package/src/client/board/overlay.tsx +189 -0
  103. package/src/client/board/parse-model-pref.ts +35 -0
  104. package/src/client/board/preset-label.ts +44 -0
  105. package/src/client/board/status-key.ts +41 -0
  106. package/src/client/board/task-markdown.module.css +137 -0
  107. package/src/client/board/task-markdown.tsx +106 -0
  108. package/src/client/board-settings.module.css +66 -0
  109. package/src/client/board.module.css +1837 -0
  110. package/src/client/css-modules.d.ts +5 -0
  111. package/src/client/host-api.ts +336 -0
  112. package/src/client/index.ts +501 -0
  113. package/src/client/locales.ts +905 -0
  114. package/src/client/main-session.ts +43 -0
  115. package/src/client/native-panel.tsx +140 -0
  116. package/src/client/plugin-card-seat.ts +199 -0
  117. package/src/client/schedule-presets.ts +13 -0
  118. package/src/client/schedule-zone.ts +233 -0
  119. package/src/client/seats.tsx +58 -0
  120. package/src/client/service.ts +94 -0
  121. package/src/client/settings-card.module.css +444 -0
  122. package/src/client/settings-entry-form.ts +142 -0
  123. package/src/client/settings-form.ts +468 -0
  124. package/src/core/controller.ts +871 -0
  125. package/src/core/degraded-reason.ts +81 -0
  126. package/src/core/extension.ts +376 -0
  127. package/src/core/freeze-snapshot.ts +213 -0
  128. package/src/core/handover.ts +132 -0
  129. package/src/core/issue-form.ts +19 -0
  130. package/src/core/package-name.ts +9 -0
  131. package/src/core/poll-cadence.ts +41 -0
  132. package/src/core/schedule.ts +363 -0
  133. package/src/core/session-reuse.ts +40 -0
  134. package/src/core/store.ts +371 -0
  135. package/src/core/subtask.ts +341 -0
  136. package/src/core/tasks.ts +843 -0
  137. package/src/core/use-cases/task-archive.ts +91 -0
  138. package/src/core/use-cases/task-create.ts +110 -0
  139. package/src/core/use-cases/task-delete.ts +43 -0
  140. package/src/core/use-cases/task-parent.ts +65 -0
  141. package/src/core/use-cases/task-schedule.ts +251 -0
  142. package/src/core/use-cases/task-tag.ts +110 -0
  143. package/src/core/use-cases/task-update.ts +126 -0
  144. package/src/core/verification-budget.ts +115 -0
  145. package/src/core/verification.ts +1594 -0
  146. package/src/core/workspace-target.ts +59 -0
  147. package/src/dsh-home.ts +42 -0
  148. package/src/host/agent-tools.ts +762 -0
  149. package/src/host/extension-registry.ts +509 -0
  150. package/src/host/llm-dispatch.ts +87 -0
  151. package/src/host/verification-gate.ts +487 -0
  152. package/src/host/verification-runner.ts +702 -0
  153. package/src/host/workspace-evidence.ts +176 -0
  154. package/src/host-ai.ts +158 -0
  155. package/src/host-ledger.ts +1826 -0
  156. package/src/host-routes.ts +306 -0
  157. package/src/host-runner.ts +755 -0
  158. package/src/host-service.ts +1112 -0
  159. package/src/http.ts +127 -0
  160. package/src/index.ts +722 -0
  161. package/src/loopback.ts +63 -0
  162. package/src/mount-once.ts +142 -0
  163. package/src/power-inhibitor.ts +321 -0
  164. package/src/protocol.ts +591 -0
  165. package/src/tool-surface.ts +95 -0
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Handover bundle (issue #5, ADR 0001): the resource reference set a
3
+ * continuation card carries — the pinned execution triplet (workspace /
4
+ * agent preset / permission) plus doc/script references — so a picking-up
5
+ * session can start with zero context.
6
+ *
7
+ * Security gate (adversarial scenario b): a bundle whose effective
8
+ * permission is HIGHER than the session default is an unconfirmed binding.
9
+ * It enters the pending-confirmation state (the card stores the binding
10
+ * without a permissionConfirmedAt stamp); manual execution refuses, cron
11
+ * refuses to schedule, and the human confirm-permission action resolves the
12
+ * transaction by stamping the confirmation. Any later permission or
13
+ * handover change re-arms the gate (the confirmation binds the exact
14
+ * permission value, blocking confirm-then-swap escalation).
15
+ */
16
+ import { isTaskPermission, type TaskPermission, type TaskRecord } from './tasks.ts'
17
+
18
+ export type { TaskPermission }
19
+
20
+ /** Wire shape of a handover bundle (before bundledAt is stamped). */
21
+ export interface TaskHandoverInput {
22
+ workspaceId?: string
23
+ mode?: string
24
+ permission?: TaskPermission
25
+ references: string[]
26
+ }
27
+
28
+ /** Persisted handover bundle on a task record. */
29
+ export interface TaskHandover extends TaskHandoverInput {
30
+ /** When the bundle was attached/replaced (ms epoch, stamped by the use case). */
31
+ bundledAt: number
32
+ }
33
+
34
+ /** Most references a bundle may carry. */
35
+ export const HANDOVER_MAX_REFERENCES = 32
36
+ /** Per-reference UTF-8 byte cap. */
37
+ export const HANDOVER_MAX_REFERENCE_BYTES = 512
38
+ /** Total references UTF-8 byte cap. */
39
+ export const HANDOVER_MAX_TOTAL_BYTES = 8 * 1024
40
+ /** Per target-id (workspace/preset) byte cap. */
41
+ export const HANDOVER_MAX_TARGET_BYTES = 256
42
+
43
+ /**
44
+ * Fail-safe baseline for the confirmation gate: what it falls back to when the
45
+ * deployment pins no baseline of its own and the Host's default permission
46
+ * preset cannot be read. Every elevation above it stays gated.
47
+ */
48
+ export const DEFAULT_SESSION_PERMISSION: TaskPermission = 'read-only'
49
+
50
+ /** Permission elevation rank (higher = more authority). */
51
+ export const PERMISSION_RANK: ReadonlyMap<TaskPermission, number> = new Map([
52
+ ['read-only', 0],
53
+ ['workspace-write', 1],
54
+ ['danger-full-access', 2],
55
+ ])
56
+
57
+ function byteLength(value: string): number {
58
+ return new TextEncoder().encode(value).length
59
+ }
60
+
61
+ /**
62
+ * Gate a handover bundle from the wire or disk: exact keys, string targets
63
+ * under the byte cap, a known permission, and a bounded string reference
64
+ * list. Returns the sanitized bundle, or undefined when rejected.
65
+ */
66
+ export function sanitizeHandover(value: unknown): TaskHandoverInput | undefined {
67
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined
68
+ const bundle = value as Record<string, unknown>
69
+ const keys = Object.keys(bundle)
70
+ if (!keys.every(key => ['workspaceId', 'mode', 'permission', 'references'].includes(key))) return undefined
71
+ if (!Array.isArray(bundle.references)) return undefined
72
+ if (bundle.references.length > HANDOVER_MAX_REFERENCES) return undefined
73
+ let total = 0
74
+ for (const reference of bundle.references) {
75
+ if (typeof reference !== 'string' || reference === '') return undefined
76
+ const size = byteLength(reference)
77
+ if (size > HANDOVER_MAX_REFERENCE_BYTES) return undefined
78
+ total += size
79
+ if (total > HANDOVER_MAX_TOTAL_BYTES) return undefined
80
+ }
81
+ for (const key of ['workspaceId', 'mode'] as const) {
82
+ const target: unknown = bundle[key]
83
+ if (target !== undefined && (typeof target !== 'string' || byteLength(target) > HANDOVER_MAX_TARGET_BYTES)) return undefined
84
+ }
85
+ if (bundle.permission !== undefined && !isTaskPermission(bundle.permission)) return undefined
86
+ const workspaceId = bundle.workspaceId
87
+ const mode = bundle.mode
88
+ return {
89
+ ...(typeof workspaceId === 'string' ? { workspaceId } : {}),
90
+ ...(typeof mode === 'string' ? { mode } : {}),
91
+ ...(bundle.permission === undefined ? {} : { permission: bundle.permission as TaskPermission }),
92
+ references: [...bundle.references as string[]],
93
+ }
94
+ }
95
+
96
+ /** Build the persisted bundle from a sanitized input, stamping bundledAt. */
97
+ export function handoverOf(input: TaskHandoverInput, now: number): TaskHandover {
98
+ return { ...input, bundledAt: now }
99
+ }
100
+
101
+ /** The permission an execution session would actually run under. */
102
+ export function effectivePermission(task: Pick<TaskRecord, 'permission' | 'handover'>): TaskPermission | undefined {
103
+ return task.handover?.permission ?? task.permission
104
+ }
105
+
106
+ /** Whether a binding's permission is elevated above the session default. */
107
+ export function exceedsSessionDefault(permission: TaskPermission | undefined, sessionDefault: TaskPermission): boolean {
108
+ if (permission === undefined) return false
109
+ return (PERMISSION_RANK.get(permission) ?? -1) > (PERMISSION_RANK.get(sessionDefault) ?? -1)
110
+ }
111
+
112
+ /**
113
+ * Whether a session running at `holder` already carries `permission`: the
114
+ * permission is absent, or its rank does not exceed the holder's. A teammate
115
+ * inherits the Lead session's permission and cannot be narrowed below it, so a
116
+ * subtask's own pin is carried by a team run exactly when this holds, and a pin
117
+ * it does not carry would be silently dropped instead.
118
+ */
119
+ export function permissionCarriedBy(holder: TaskPermission, permission: TaskPermission | undefined): boolean {
120
+ return !exceedsSessionDefault(permission, holder)
121
+ }
122
+
123
+ /**
124
+ * The confirmation-gate predicate: an elevated permission without a human
125
+ * confirmation stamp. Manual run/rerun and cron must refuse such a card.
126
+ */
127
+ export function requiresPermissionConfirmation(
128
+ task: Pick<TaskRecord, 'permission' | 'handover' | 'permissionConfirmedAt'>,
129
+ sessionDefault: TaskPermission = DEFAULT_SESSION_PERMISSION,
130
+ ): boolean {
131
+ return exceedsSessionDefault(effectivePermission(task), sessionDefault) && task.permissionConfirmedAt === undefined
132
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Issue-form vocabulary the card excerpt recognizes.
3
+ *
4
+ * Issue forms from an issue tracker (and the zh templates this family's repositories use)
5
+ * write the same section headings and empty-field placeholders on every issue.
6
+ * The patterns are data about those forms, not UI copy, so they live in the
7
+ * shared core rather than in a locale dictionary; the browser half imports them.
8
+ *
9
+ * @module @fish-under-sea/dsh-client-ui-task-board-fish/core/issue-form
10
+ */
11
+
12
+ /** Section headings whose body is the issue's own summary (zh and en forms). */
13
+ export const SUMMARY_HEADING = /^(?:摘要|概要|概述|简介|描述|问题描述|问题|现象|summary|description|overview|problem|what happened)$/i
14
+
15
+ /** Values an issue form writes for an empty field. */
16
+ export const EMPTY_FIELD = /^(?:_?no response_?|n\/a|none|无|暂无)$/i
17
+
18
+ /** A trailing colon (ASCII or full-width) after a heading. */
19
+ export const HEADING_COLON = /[:\uFF1A]\s*$/
@@ -0,0 +1,9 @@
1
+ /**
2
+ * npm identity of this plugin. The dsh-web-all degraded ledger is keyed by the
3
+ * real plugin package name of a family row, and this plugin's browser half
4
+ * must name its OWN row there to learn why its Host API is missing (issue
5
+ * #1730): the served bundle cannot derive the name, because a family row
6
+ * mounts the package from a versioned profile path. The host half spells the
7
+ * same name in its single-mount guard (src/index.ts); the two move together.
8
+ */
9
+ export const TASK_BOARD_PACKAGE = '@fish-under-sea/dsh-client-ui-task-board-fish'
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Roster-poll cadence: the one recurring Host timer the board holds.
3
+ *
4
+ * The cadence is a user setting (seconds), so the bounds and the seconds to
5
+ * milliseconds conversion live here rather than in either half: the settings
6
+ * card validates a draft against the same range the Host clamps a hand-edited
7
+ * configuration to, and a programmatic mount that passes no cadence gets the
8
+ * default.
9
+ *
10
+ * @module dsh-task-board/core/poll-cadence
11
+ */
12
+
13
+ /** Cadence used when neither the settings document nor the mount names one. */
14
+ export const DEFAULT_SESSION_POLL_SECONDS = 5
15
+
16
+ /** Shortest accepted cadence: a faster poll only burns CPU on the Host. */
17
+ export const SESSION_POLL_MIN_SECONDS = 1
18
+
19
+ /** Longest accepted cadence, five minutes. */
20
+ export const SESSION_POLL_MAX_SECONDS = 300
21
+
22
+ /**
23
+ * Clamp a configured cadence into the supported range. A value the schema
24
+ * would refuse (non-finite, below the floor, above the ceiling) still leaves
25
+ * the board polling: an out-of-range setting never disables the timer.
26
+ * @param seconds - configured cadence in seconds, or undefined for the default.
27
+ * @returns the effective cadence in seconds.
28
+ */
29
+ export function normalizeSessionPollSeconds(seconds: number | undefined): number {
30
+ if (seconds === undefined || !Number.isFinite(seconds)) return DEFAULT_SESSION_POLL_SECONDS
31
+ return Math.min(Math.max(Math.trunc(seconds), SESSION_POLL_MIN_SECONDS), SESSION_POLL_MAX_SECONDS)
32
+ }
33
+
34
+ /**
35
+ * The cadence in the milliseconds the Host timer face takes.
36
+ * @param seconds - configured cadence in seconds, or undefined for the default.
37
+ * @returns the effective cadence in milliseconds.
38
+ */
39
+ export function sessionPollMs(seconds: number | undefined): number {
40
+ return normalizeSessionPollSeconds(seconds) * 1_000
41
+ }
@@ -0,0 +1,363 @@
1
+ /**
2
+ * Zone-aware 5-field cron parsing and next-run computation for scheduled task
3
+ * runs. Framework-free and dependency-free (Intl only) so the Host scheduler
4
+ * and the browser next-run preview share one tiny pure module.
5
+ *
6
+ * Grammar: five whitespace-separated fields, 分 时 日 月 周. Every field
7
+ * supports the wildcard, step (wildcard or range + "/n"), single value,
8
+ * inclusive range a-b, and comma lists mixing any of those. Ranges: minutes
9
+ * 0-59, hours 0-23, days 1-31, months 1-12, weekdays 0-7 (0 and 7 both mean
10
+ * Sunday). Invalid expressions parse to null and are rejected by the UI and
11
+ * the Host.
12
+ *
13
+ * Day semantics follow Vixie cron: a field is *starred* when its field text
14
+ * starts with `*`. When day-of-month and day-of-week are both restricted the
15
+ * fields combine with OR; otherwise they combine with AND. The distinction
16
+ * matters for a stepped star such as `*&#47;2`, which still restricts the dates it
17
+ * matches, so `0 0 *&#47;2 * 1` means "the Mondays that fall on an even day of
18
+ * month" rather than "every even day, or every Monday".
19
+ *
20
+ * Time zone: every candidate wall clock is interpreted in an explicit IANA
21
+ * zone (the schedule's stored zone, or the Host zone when none is given).
22
+ * A wall clock that does not exist (spring-forward gap) is skipped, and an
23
+ * ambiguous wall clock (fall-back overlap) resolves to the earlier instant, so
24
+ * a repeated local minute fires exactly once. The Host-scheduler semantics are
25
+ * byte-identical to `@deepseek-ai/dsh-schedule`'s resolver, which was verified
26
+ * against it across twelve IANA zones (including 30-minute and 45-minute DST
27
+ * offsets and a date-line jump) and 300k decision instants.
28
+ *
29
+ * That upstream is on the experimental track and is NOT a dependency here (no
30
+ * import, no inject, no peer range), so a change to it fails no test. Re-run the
31
+ * differential check on any `dsh-schedule` release or cohort bump that moves it,
32
+ * and keep this comment honest; the re-verification trigger is recorded in
33
+ * [the owning Agent Note](../../../../.agents/notes/implemented/feature/2026-09-29-task-board-schedule-time-zone.md).
34
+ */
35
+
36
+ /** The parsed match sets of one cron expression. */
37
+ export interface CronSchedule {
38
+ minutes: ReadonlySet<number>
39
+ hours: ReadonlySet<number>
40
+ days: ReadonlySet<number>
41
+ months: ReadonlySet<number>
42
+ /** Weekdays 0-6, 0 = Sunday (input 7 normalized to 0). */
43
+ weekdays: ReadonlySet<number>
44
+ /** Whether the day-of-month field text starts with `*` (Vixie starred). */
45
+ dayStarred: boolean
46
+ /** Whether the weekday field text starts with `*` (Vixie starred). */
47
+ weekdayStarred: boolean
48
+ }
49
+
50
+ /** Inclusive ranges per field, in cron order. */
51
+ const FIELD_RANGES: ReadonlyArray<readonly [number, number]> = [
52
+ [0, 59], // minutes
53
+ [0, 23], // hours
54
+ [1, 31], // days
55
+ [1, 12], // months
56
+ [0, 7], // weekdays (7 = Sunday, normalized below)
57
+ ]
58
+
59
+ /** Fallback zone when the process reports no usable IANA zone. */
60
+ export const HOST_TIME_ZONE_FALLBACK = 'UTC'
61
+
62
+ /** IANA `Area/Location`, plus the bare `UTC` the platform reports. */
63
+ const IANA_ZONE = /^[A-Za-z][A-Za-z0-9_+.-]*(?:\/[A-Za-z0-9_+.-]+)+$/
64
+
65
+ /** One resolved wall-clock reading in some zone. */
66
+ export interface ZonedParts {
67
+ year: number
68
+ month: number
69
+ day: number
70
+ hour: number
71
+ minute: number
72
+ }
73
+
74
+ /** Cached formatters: constructing an Intl formatter dominates the cost of a resolve. */
75
+ const FORMATTERS = new Map<string, Intl.DateTimeFormat>()
76
+
77
+ function zoneFormatter(timeZone: string): Intl.DateTimeFormat {
78
+ let formatter = FORMATTERS.get(timeZone)
79
+ if (formatter === undefined) {
80
+ formatter = new Intl.DateTimeFormat('en-US', {
81
+ timeZone,
82
+ hourCycle: 'h23',
83
+ year: 'numeric',
84
+ month: '2-digit',
85
+ day: '2-digit',
86
+ hour: '2-digit',
87
+ minute: '2-digit',
88
+ })
89
+ FORMATTERS.set(timeZone, formatter)
90
+ }
91
+ return formatter
92
+ }
93
+
94
+ /**
95
+ * The wall-clock reading of one instant in an explicit zone. Reading through
96
+ * Intl (rather than the process `Date` accessors) is what makes the result
97
+ * independent of the Host's own TZ.
98
+ * @param timeZone - explicit IANA zone.
99
+ * @param epochMs - instant to read.
100
+ * @returns the zone-local calendar and clock fields.
101
+ */
102
+ export function partsInZone(timeZone: string, epochMs: number): ZonedParts {
103
+ const fields: Record<string, string> = {}
104
+ for (const part of zoneFormatter(timeZone).formatToParts(new Date(epochMs))) {
105
+ if (part.type !== 'literal') fields[part.type] = part.value
106
+ }
107
+ return {
108
+ year: Number(fields.year),
109
+ month: Number(fields.month),
110
+ day: Number(fields.day),
111
+ hour: Number(fields.hour),
112
+ minute: Number(fields.minute),
113
+ }
114
+ }
115
+
116
+ /** The zone's UTC offset in effect at one instant, in milliseconds. */
117
+ function offsetAt(timeZone: string, epochMs: number): number {
118
+ const parts = partsInZone(timeZone, epochMs)
119
+ return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute) - epochMs
120
+ }
121
+
122
+ /**
123
+ * Resolve a wall clock in an explicit zone to its instant.
124
+ *
125
+ * The offset is probed a day either side of the naive guess so both DST
126
+ * transitions are covered, then every candidate offset whose inverse maps back
127
+ * to the requested wall clock is kept. No survivor means the wall clock does
128
+ * not exist (a spring-forward gap); several means it is ambiguous (a fall-back
129
+ * overlap), and the earliest instant wins so the repeated clock is taken once.
130
+ * @param timeZone - explicit IANA zone.
131
+ * @param year - full calendar year.
132
+ * @param month - 1-12.
133
+ * @param day - day of month.
134
+ * @param hour - 0-23.
135
+ * @param minute - 0-59.
136
+ * @returns the instant in ms epoch, or undefined when the wall clock is skipped.
137
+ */
138
+ export function zonedEpoch(
139
+ timeZone: string,
140
+ year: number,
141
+ month: number,
142
+ day: number,
143
+ hour: number,
144
+ minute: number,
145
+ ): number | undefined {
146
+ const naive = Date.UTC(year, month - 1, day, hour, minute)
147
+ const offsets = new Set([
148
+ offsetAt(timeZone, naive - 86_400_000),
149
+ offsetAt(timeZone, naive),
150
+ offsetAt(timeZone, naive + 86_400_000),
151
+ ])
152
+ let earliest: number | undefined
153
+ for (const offset of offsets) {
154
+ const candidate = naive - offset
155
+ const parts = partsInZone(timeZone, candidate)
156
+ if (parts.year !== year || parts.month !== month || parts.day !== day) continue
157
+ if (parts.hour !== hour || parts.minute !== minute) continue
158
+ if (earliest === undefined || candidate < earliest) earliest = candidate
159
+ }
160
+ return earliest
161
+ }
162
+
163
+ /**
164
+ * The Host process's IANA zone, used for schedules that store no zone of their
165
+ * own (a ledger written before zones were persisted).
166
+ * @returns a zone name Intl accepts, never empty.
167
+ */
168
+ export function resolveHostTimeZone(): string {
169
+ try {
170
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone
171
+ return typeof zone === 'string' && zone !== '' ? zone : HOST_TIME_ZONE_FALLBACK
172
+ } catch {
173
+ return HOST_TIME_ZONE_FALLBACK
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Whether a value names a zone this runtime can actually resolve. A stored
179
+ * zone is trusted only after it round-trips through Intl, so a typo or a zone
180
+ * that this ICU build does not know can never arm a schedule.
181
+ * @param value - candidate zone name.
182
+ * @returns true when the name is usable.
183
+ */
184
+ export function isValidTimeZone(value: string): boolean {
185
+ if (value.trim() !== value || value === '') return false
186
+ if (value !== 'UTC' && !IANA_ZONE.test(value)) return false
187
+ try {
188
+ return new Intl.DateTimeFormat('en-US', { timeZone: value }).resolvedOptions().timeZone !== undefined
189
+ } catch {
190
+ return false
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Parse a 5-field cron expression.
196
+ * @returns the match sets, or null when the expression is invalid.
197
+ */
198
+ export function parseCron(expr: string): CronSchedule | null {
199
+ const fields = expr.trim().split(/\s+/)
200
+ if (fields.length !== 5) return null
201
+ const sets: Set<number>[] = []
202
+ for (let index = 0; index < 5; index++) {
203
+ const [min, max] = FIELD_RANGES[index]
204
+ const set = new Set<number>()
205
+ if (!parseField(fields[index], min, max, set)) return null
206
+ sets.push(set)
207
+ }
208
+ const weekdays = new Set<number>()
209
+ for (const day of sets[4]) weekdays.add(day === 7 ? 0 : day)
210
+ return {
211
+ minutes: sets[0],
212
+ hours: sets[1],
213
+ days: sets[2],
214
+ months: sets[3],
215
+ weekdays,
216
+ // Vixie selects the day branch from the field TEXT: only a field starting
217
+ // with '*' is starred. A written-out range such as '1-31' is restricted and
218
+ // still participates in the OR/AND choice.
219
+ dayStarred: fields[2].startsWith('*'),
220
+ weekdayStarred: fields[4].startsWith('*'),
221
+ }
222
+ }
223
+
224
+ /** Whether the expression parses. */
225
+ export function isValidCron(expr: string): boolean {
226
+ return parseCron(expr) !== null
227
+ }
228
+
229
+ /**
230
+ * Compute the next matching instant after `fromMs` strictly greater than it,
231
+ * interpreting the expression's wall clock in `timeZone` (the Host zone when
232
+ * omitted). Returns the ms epoch of the matching minute's start, or undefined
233
+ * when the calendar constraint can never match (for example `0 0 30 2 *`).
234
+ * The five-year horizon includes a full leap cycle, so a valid February 29
235
+ * schedule remains reachable from every non-leap year.
236
+ *
237
+ * Walks candidate year/month/day/hour/minute values straight from the parsed
238
+ * field sets instead of scanning every minute: a sparse expression such as
239
+ * `0 0 29 2 *` used to iterate ~1.5M wall-clock minutes before reaching the
240
+ * next leap day. A candidate wall clock that the zone skips (spring-forward
241
+ * gap) is passed over, which is what makes the gap semantics fall out of the
242
+ * candidate walk rather than needing a separate rule.
243
+ * @param expr - 5-field cron expression.
244
+ * @param fromMs - exclusive lower bound, ms epoch.
245
+ * @param timeZone - explicit IANA zone; defaults to the Host zone.
246
+ * @returns the next trigger instant, or undefined when unreachable.
247
+ */
248
+ export function nextRunAtMs(expr: string, fromMs: number, timeZone?: string): number | undefined {
249
+ const schedule = parseCron(expr)
250
+ if (schedule === null) return undefined
251
+ if (!hasPossibleCalendarDay(schedule)) return undefined
252
+ const zone = timeZone ?? resolveHostTimeZone()
253
+ const start = partsInZone(zone, fromMs)
254
+ const limitMs = fromMs + 5 * 366 * 24 * 60 * 60 * 1000
255
+
256
+ const sortedMinutes = [...schedule.minutes].sort((a, b) => a - b)
257
+ const sortedHours = [...schedule.hours].sort((a, b) => a - b)
258
+ const sortedMonths = [...schedule.months].sort((a, b) => a - b)
259
+
260
+ let year = start.year
261
+ let month = start.month
262
+ let day = start.day
263
+ let hour = start.hour
264
+ // Strictly after fromMs: the walk starts from the next minute.
265
+ let minute = start.minute + 1
266
+
267
+ while (Date.UTC(year, month - 1, 1) <= limitMs + 86_400_000) {
268
+ for (const candidateMonth of sortedMonths) {
269
+ if (candidateMonth < month) continue
270
+ const daysInMonth = new Date(Date.UTC(year, candidateMonth, 0)).getUTCDate()
271
+ const dayStart = candidateMonth === month ? day : 1
272
+ for (let candidateDay = dayStart; candidateDay <= daysInMonth; candidateDay += 1) {
273
+ if (!dayCandidate(schedule, year, candidateMonth, candidateDay)) continue
274
+ const hourStart = candidateMonth === month && candidateDay === day ? hour : 0
275
+ for (const candidateHour of sortedHours) {
276
+ if (candidateHour < hourStart) continue
277
+ const minuteStart = candidateMonth === month && candidateDay === day && candidateHour === hour ? minute : 0
278
+ for (const candidateMinute of sortedMinutes) {
279
+ if (candidateMinute < minuteStart) continue
280
+ const time = zonedEpoch(zone, year, candidateMonth, candidateDay, candidateHour, candidateMinute)
281
+ if (time === undefined) continue
282
+ if (time <= fromMs) continue
283
+ if (time > limitMs) return undefined
284
+ return time
285
+ }
286
+ }
287
+ }
288
+ }
289
+ year += 1
290
+ month = 1
291
+ day = 1
292
+ hour = 0
293
+ minute = 0
294
+ }
295
+ return undefined
296
+ }
297
+
298
+ /**
299
+ * The Vixie day gate shared by the candidate walk. Both fields restricted is
300
+ * OR; any other combination is AND, because a starred field matches every
301
+ * value and so cannot widen the result.
302
+ */
303
+ function dayCandidate(schedule: CronSchedule, year: number, month: number, day: number): boolean {
304
+ const dayMatches = schedule.days.has(day)
305
+ // Day of week is a property of the calendar date, so it is zone-independent.
306
+ const weekdayMatches = schedule.weekdays.has(new Date(Date.UTC(year, month - 1, day)).getUTCDay())
307
+ if (!schedule.dayStarred && !schedule.weekdayStarred) return dayMatches || weekdayMatches
308
+ return dayMatches && weekdayMatches
309
+ }
310
+
311
+ /** Reject impossible month/day pairs without spending the multi-year scan. */
312
+ function hasPossibleCalendarDay(schedule: CronSchedule): boolean {
313
+ if (schedule.dayStarred || !schedule.weekdayStarred) return true
314
+ const maximumDay = new Map<number, number>([
315
+ [1, 31], [2, 29], [3, 31], [4, 30], [5, 31], [6, 30],
316
+ [7, 31], [8, 31], [9, 30], [10, 31], [11, 30], [12, 31],
317
+ ])
318
+ for (const month of schedule.months) {
319
+ const maximum = maximumDay.get(month) ?? 0
320
+ if ([...schedule.days].some(day => day <= maximum)) return true
321
+ }
322
+ return false
323
+ }
324
+
325
+ /** Parse one comma-list field into the match set. */
326
+ function parseField(field: string, min: number, max: number, out: Set<number>): boolean {
327
+ if (field === '*') {
328
+ for (let value = min; value <= max; value++) out.add(value)
329
+ return true
330
+ }
331
+ for (const part of field.split(',')) {
332
+ if (part === '') return false
333
+ const [range, stepRaw] = part.split('/')
334
+ let low: number
335
+ let high: number
336
+ if (range === '*') {
337
+ low = min
338
+ high = max
339
+ } else if (range.includes('-')) {
340
+ const [a, b] = range.split('-')
341
+ if (a === '' || b === '' || !isDigits(a) || !isDigits(b)) return false
342
+ low = Number(a)
343
+ high = Number(b)
344
+ } else if (isDigits(range)) {
345
+ low = Number(range)
346
+ // Standard cron: a bare value carrying a step runs from that value to the
347
+ // field maximum (minutes 5/15 are 5,20,35,50), while a bare value alone is
348
+ // exactly itself (#1493).
349
+ high = stepRaw === undefined ? low : max
350
+ } else {
351
+ return false
352
+ }
353
+ if (low < min || high > max || low > high) return false
354
+ const step = stepRaw === undefined ? 1 : isDigits(stepRaw) ? Number(stepRaw) : NaN
355
+ if (!Number.isInteger(step) || step < 1) return false
356
+ for (let value = low; value <= high; value += step) out.add(value)
357
+ }
358
+ return true
359
+ }
360
+
361
+ function isDigits(value: string): boolean {
362
+ return /^\d+$/.test(value)
363
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Session-reuse rule (issue #1419): decides which task runs continue in the
3
+ * previous execution's conversation. Pure, so the fail-closed conditions stay
4
+ * unit-testable without a gateway.
5
+ */
6
+ import type { ExecutionRecord, TaskRecord } from './tasks.ts'
7
+
8
+ /**
9
+ * Pick the session a new execution of this task may continue in, or undefined
10
+ * to mint a fresh conversation. Reuse requires ALL of:
11
+ * - the task opted in (`reuseSession === true`);
12
+ * - the task's newest SETTLED execution carries a session id (issue #1587: the
13
+ * launch path calls this after `startExecution` appended this run's own open
14
+ * record, so reading the array tail always found an unsettled row and reuse
15
+ * never happened);
16
+ * - the roster is known and that session is present and idle.
17
+ *
18
+ * An unknown roster (session/list unavailable) never reuses: minting a fresh
19
+ * conversation is always safe, prompting into a session we cannot see is not.
20
+ * @param task - the task about to run.
21
+ * @param idleSessionIds - ids the last roster saw as present and not running;
22
+ * undefined when that roster is unknown.
23
+ * @returns the session id to continue in, or undefined for a fresh session.
24
+ */
25
+ export function reusableSessionId(
26
+ task: TaskRecord,
27
+ idleSessionIds: ReadonlySet<string> | undefined,
28
+ ): string | undefined {
29
+ if (task.reuseSession !== true || idleSessionIds === undefined) return undefined
30
+ let last: ExecutionRecord | undefined
31
+ for (let index = task.executions.length - 1; index >= 0; index -= 1) {
32
+ const candidate = task.executions[index]
33
+ if (candidate.sessionId !== undefined && candidate.endedAt !== undefined) {
34
+ last = candidate
35
+ break
36
+ }
37
+ }
38
+ if (last === undefined || last.sessionId === undefined) return undefined
39
+ return idleSessionIds.has(last.sessionId) ? last.sessionId : undefined
40
+ }