@causyne/agent 1.20.124 → 1.20.128

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 (254) hide show
  1. package/bin/causyne.js +1 -1
  2. package/docs/THIRD_PARTY_NOTICES.md +36 -2
  3. package/package.json +6 -4
  4. package/src/acp/protocol.ts +19 -1
  5. package/src/acp/server.js +282 -8
  6. package/src/acp/server.ts +284 -8
  7. package/src/agent/abortableDelay.js +2 -2
  8. package/src/agent/abortableDelay.ts +2 -2
  9. package/src/agent/errorClassifier.js +9 -1
  10. package/src/agent/errorClassifier.ts +8 -1
  11. package/src/agentLoop.js +142 -53
  12. package/src/agentLoop.ts +151 -50
  13. package/src/approvalPolicy.js +34 -10
  14. package/src/approvalPolicy.ts +42 -11
  15. package/src/browser/causyneBrowser.js +61 -3
  16. package/src/browser/causyneBrowser.ts +65 -3
  17. package/src/browser/urlPolicy.js +14 -1
  18. package/src/browser/urlPolicy.ts +12 -1
  19. package/src/cliMode.js +21 -9
  20. package/src/cliMode.ts +20 -8
  21. package/src/commands.js +365 -45
  22. package/src/commands.ts +403 -45
  23. package/src/config.js +19 -4
  24. package/src/config.ts +18 -4
  25. package/src/core/contextCompactor.js +54 -7
  26. package/src/core/contextCompactor.ts +63 -7
  27. package/src/core/goalLoop.js +257 -0
  28. package/src/core/goalLoop.ts +310 -0
  29. package/src/entrypoint.js +135 -3
  30. package/src/entrypoint.ts +136 -3
  31. package/src/game/causyneCoreBridge.js +686 -0
  32. package/src/game/causyneCoreBridge.ts +702 -0
  33. package/src/game/gameLauncher.js +287 -0
  34. package/src/game/gameLauncher.ts +352 -0
  35. package/src/game/gameProvisioner.js +425 -0
  36. package/src/game/gameProvisioner.ts +488 -0
  37. package/src/headlessCli.js +19 -12
  38. package/src/headlessCli.ts +22 -8
  39. package/src/infra/atomicWriter.js +40 -4
  40. package/src/infra/atomicWriter.ts +36 -4
  41. package/src/launchIntent.js +73 -3
  42. package/src/launchIntent.ts +76 -3
  43. package/src/lsp/lspClient.js +83 -12
  44. package/src/lsp/lspClient.ts +75 -12
  45. package/src/mcp/mcpRegistry.js +75 -8
  46. package/src/mcp/mcpRegistry.ts +70 -7
  47. package/src/memory/contextBudget.js +2 -0
  48. package/src/memory/contextBudget.ts +1 -0
  49. package/src/memory/episodicStore.js +40 -0
  50. package/src/memory/episodicStore.ts +46 -0
  51. package/src/memory.js +67 -0
  52. package/src/memory.ts +65 -0
  53. package/src/modelVariants.js +45 -0
  54. package/src/modelVariants.ts +54 -0
  55. package/src/outputRecovery.js +3 -2
  56. package/src/outputRecovery.ts +4 -2
  57. package/src/permissionPresets.js +327 -0
  58. package/src/permissionPresets.ts +361 -0
  59. package/src/personalization.js +365 -0
  60. package/src/personalization.ts +471 -0
  61. package/src/projectInstructions.js +30 -10
  62. package/src/projectInstructions.ts +31 -12
  63. package/src/providers/acp.js +3 -2
  64. package/src/providers/acp.ts +3 -2
  65. package/src/providers/antigravity.js +64 -9
  66. package/src/providers/antigravity.ts +75 -9
  67. package/src/providers/byokHttp.js +7 -1
  68. package/src/providers/byokHttp.ts +6 -1
  69. package/src/providers/byokStream.js +21 -8
  70. package/src/providers/byokStream.ts +17 -7
  71. package/src/providers/dashscope-byok.js +21 -5
  72. package/src/providers/dashscope-byok.ts +29 -11
  73. package/src/providers/moonshot.js +26 -7
  74. package/src/providers/moonshot.ts +34 -13
  75. package/src/providers/muse.js +6 -0
  76. package/src/providers/muse.ts +8 -0
  77. package/src/providers/ollama.js +39 -7
  78. package/src/providers/ollama.ts +36 -7
  79. package/src/providers/openai-compatible.js +16 -3
  80. package/src/providers/openai-compatible.ts +13 -3
  81. package/src/providers/openai.js +62 -4
  82. package/src/providers/openai.ts +50 -4
  83. package/src/providers/openrouter.js +19 -4
  84. package/src/providers/openrouter.ts +21 -4
  85. package/src/providers/qwen-byok.js +21 -5
  86. package/src/providers/qwen-byok.ts +29 -11
  87. package/src/providers/xai.js +26 -10
  88. package/src/providers/xai.ts +34 -16
  89. package/src/reporting.js +4 -2
  90. package/src/reporting.ts +4 -2
  91. package/src/sandbox.js +34 -0
  92. package/src/sandbox.ts +43 -0
  93. package/src/scheduler/scheduler.js +372 -0
  94. package/src/scheduler/scheduler.ts +433 -0
  95. package/src/sessionSearchIndex.js +267 -0
  96. package/src/sessionSearchIndex.ts +311 -0
  97. package/src/skillsManager.js +2 -3
  98. package/src/skillsManager.ts +2 -3
  99. package/src/toolPacks.js +6 -0
  100. package/src/toolPacks.ts +6 -0
  101. package/src/tools/applyPatch.js +1 -1
  102. package/src/tools/applyPatch.ts +1 -1
  103. package/src/tools/generateMediaViaApi.js +4 -3
  104. package/src/tools/generateMediaViaApi.ts +4 -3
  105. package/src/tools/memoryWrite.js +15 -1
  106. package/src/tools/memoryWrite.ts +16 -1
  107. package/src/tools/nativeEngine.js +2 -2
  108. package/src/tools/nativeEngine.ts +2 -2
  109. package/src/tools/openSourceToolProvisioner.js +2 -2
  110. package/src/tools/openSourceToolProvisioner.ts +2 -2
  111. package/src/tools/osSandbox.js +1 -1
  112. package/src/tools/osSandbox.ts +1 -1
  113. package/src/tools/payloadSanitizer.js +0 -1
  114. package/src/tools/payloadSanitizer.ts +0 -1
  115. package/src/tools/pdfReader.js +122 -20
  116. package/src/tools/pdfReader.ts +111 -20
  117. package/src/tools/presentDeliverable.js +103 -0
  118. package/src/tools/presentDeliverable.ts +127 -0
  119. package/src/tools/ptcRuntime.js +444 -0
  120. package/src/tools/ptcRuntime.ts +490 -0
  121. package/src/tools/ptyTerminal.js +1108 -0
  122. package/src/tools/ptyTerminal.ts +1245 -0
  123. package/src/tools/registry.js +21 -12
  124. package/src/tools/registry.ts +21 -12
  125. package/src/tools/toolOutputStore.js +26 -4
  126. package/src/tools/toolOutputStore.ts +22 -4
  127. package/src/tools/webFetch.js +158 -11
  128. package/src/tools/webFetch.ts +145 -11
  129. package/src/tools/webSearch.js +123 -36
  130. package/src/tools/webSearch.ts +124 -33
  131. package/src/tui/banner.js +5 -1
  132. package/src/tui/banner.ts +6 -1
  133. package/src/tui/chatRenderer.js +1 -2
  134. package/src/tui/chatRenderer.ts +1 -2
  135. package/src/tui/completion.js +1 -0
  136. package/src/tui/completion.ts +1 -0
  137. package/src/tui/composerControls.js +111 -27
  138. package/src/tui/composerControls.ts +124 -28
  139. package/src/tui/dialogs.js +3 -16
  140. package/src/tui/dialogs.ts +3 -16
  141. package/src/tui/home.js +1 -0
  142. package/src/tui/home.ts +1 -0
  143. package/src/tui/invocation.js +1 -2
  144. package/src/tui/invocation.ts +1 -2
  145. package/src/tui/modelPicker.js +22 -12
  146. package/src/tui/modelPicker.ts +22 -12
  147. package/src/tui/overlay.js +2 -5
  148. package/src/tui/overlay.ts +2 -5
  149. package/src/tui/prompt.js +6 -4
  150. package/src/tui/prompt.ts +6 -4
  151. package/src/tui/selectList.js +4 -12
  152. package/src/tui/selectList.ts +4 -12
  153. package/src/tui/setup.js +22 -9
  154. package/src/tui/setup.ts +26 -9
  155. package/src/tui/statusLine.ts +2 -0
  156. package/src/web/client/browserPanel.js +905 -0
  157. package/src/web/client/browserPanel.ts +872 -0
  158. package/src/web/client/chatStream.js +321 -0
  159. package/src/web/client/chatStream.ts +297 -0
  160. package/src/web/client/cliPanel.js +165 -0
  161. package/src/web/client/cliPanel.ts +171 -0
  162. package/src/web/client/composer.js +204 -0
  163. package/src/web/client/composer.ts +209 -0
  164. package/src/web/client/diffPanel.js +176 -0
  165. package/src/web/client/diffPanel.ts +203 -0
  166. package/src/web/client/dom.js +271 -0
  167. package/src/web/client/dom.ts +272 -0
  168. package/src/web/client/filesAndCanvas.js +233 -0
  169. package/src/web/client/filesAndCanvas.ts +240 -0
  170. package/src/web/client/gameLauncherUi.js +78 -0
  171. package/src/web/client/gameLauncherUi.ts +78 -0
  172. package/src/web/client/main.js +316 -0
  173. package/src/web/client/main.ts +391 -0
  174. package/src/web/client/markdown.js +364 -0
  175. package/src/web/client/markdown.ts +373 -0
  176. package/src/web/client/modelPicker.js +455 -0
  177. package/src/web/client/modelPicker.ts +451 -0
  178. package/src/web/client/permissionPresetsUi.js +307 -0
  179. package/src/web/client/permissionPresetsUi.ts +333 -0
  180. package/src/web/client/sessions.js +353 -0
  181. package/src/web/client/sessions.ts +372 -0
  182. package/src/web/client/settingsModal.js +824 -0
  183. package/src/web/client/settingsModal.ts +959 -0
  184. package/src/web/client/state.js +280 -0
  185. package/src/web/client/state.ts +259 -0
  186. package/src/web/client/streamSmoother.js +127 -0
  187. package/src/web/client/streamSmoother.ts +119 -0
  188. package/src/web/client/studioLayout.js +89 -0
  189. package/src/web/client/studioLayout.ts +103 -0
  190. package/src/web/client/studioShell.js +660 -0
  191. package/src/web/client/studioShell.ts +672 -0
  192. package/src/web/client/studioStart.js +77 -0
  193. package/src/web/client/studioStart.ts +89 -0
  194. package/src/web/client/terminalPanel.js +606 -0
  195. package/src/web/client/terminalPanel.ts +632 -0
  196. package/src/web/client/terminalTheme.js +249 -0
  197. package/src/web/client/terminalTheme.ts +258 -0
  198. package/src/web/client/turnView.js +934 -0
  199. package/src/web/client/turnView.ts +981 -0
  200. package/src/web/client/types.js +1 -0
  201. package/src/web/client/types.ts +322 -0
  202. package/src/web/client/validators.js +147 -0
  203. package/src/web/client/validators.ts +140 -0
  204. package/src/web/server/activeRuns.js +152 -0
  205. package/src/web/server/activeRuns.ts +171 -0
  206. package/src/web/server/routesBrowser.js +409 -0
  207. package/src/web/server/routesBrowser.ts +435 -0
  208. package/src/web/server/routesChat.js +304 -0
  209. package/src/web/server/routesChat.ts +347 -0
  210. package/src/web/server/routesCore.js +472 -0
  211. package/src/web/server/routesCore.ts +522 -0
  212. package/src/web/server/routesSettings.js +344 -0
  213. package/src/web/server/routesSettings.ts +397 -0
  214. package/src/web/server/routesTerminal.js +162 -0
  215. package/src/web/server/routesTerminal.ts +182 -0
  216. package/src/web/server/routesWorkspace.js +510 -0
  217. package/src/web/server/routesWorkspace.ts +546 -0
  218. package/src/web/server/security.js +98 -0
  219. package/src/web/server/security.ts +108 -0
  220. package/src/web/server/sessionTranscript.js +586 -0
  221. package/src/web/server/sessionTranscript.ts +566 -0
  222. package/src/web/server/staticAssets.js +104 -0
  223. package/src/web/server/staticAssets.ts +116 -0
  224. package/src/web/server/types.js +1 -0
  225. package/src/web/server/types.ts +135 -0
  226. package/src/web/server/workspaceFiles.js +368 -0
  227. package/src/web/server/workspaceFiles.ts +363 -0
  228. package/src/web/skybridgeServer.js +78 -2448
  229. package/src/web/skybridgeServer.ts +120 -2600
  230. package/src/web/skybridgeUi.js +20 -450
  231. package/src/web/skybridgeUi.ts +24 -455
  232. package/src/web/styles/agent.css +380 -0
  233. package/src/web/styles/composer.css +193 -0
  234. package/src/web/styles/overlays.css +935 -0
  235. package/src/web/styles/shell.css +387 -0
  236. package/src/web/styles/studio.css +951 -0
  237. package/src/web/styles/thread.css +221 -0
  238. package/src/web/styles/tokens.css +94 -0
  239. package/src/web/ui/brandMark.js +73 -0
  240. package/src/web/ui/brandMark.ts +82 -0
  241. package/src/web/ui/modalsTemplate.js +388 -0
  242. package/src/web/ui/modalsTemplate.ts +388 -0
  243. package/src/web/ui/sidebarTemplate.js +63 -0
  244. package/src/web/ui/sidebarTemplate.ts +64 -0
  245. package/src/web/ui/studioTemplate.js +256 -0
  246. package/src/web/ui/studioTemplate.ts +256 -0
  247. package/src/web/ui/workspaceTemplate.js +72 -0
  248. package/src/web/ui/workspaceTemplate.ts +73 -0
  249. package/src/worktreeManager.js +16 -1
  250. package/src/worktreeManager.ts +22 -1
  251. package/src/web/skybridgeClientScript.js +0 -3951
  252. package/src/web/skybridgeClientScript.ts +0 -3952
  253. package/src/web/skybridgeStyles.js +0 -827
  254. package/src/web/skybridgeStyles.ts +0 -828
@@ -0,0 +1,433 @@
1
+ /**
2
+ * Causyne Agent — Durable Zero-Dependency Task Scheduler & Tool
3
+ *
4
+ * Pure Strict TypeScript scheduler supporting `after`, `at`, `every` (>=60s),
5
+ * `daily`, `weekly`, and 5-field Vixie `cron` schedules evaluated with built-in
6
+ * `Intl.DateTimeFormat` IANA timezone math (zero external polyfills/packages).
7
+ *
8
+ * Operational invariants:
9
+ * - Atomic JSON persistence under `~/.causyne/schedules.json`.
10
+ * - Optimistic concurrency (`expectedUpdatedAt` -> `schedule_conflict`).
11
+ * - Missed-occurrence coalescing (never storms after laptop sleep/downtime).
12
+ * - Subagent refusal (only top-level user sessions can mutate schedules).
13
+ */
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import crypto from 'node:crypto';
18
+ import { atomicWriteFileSync } from '../infra/atomicWriter.js';
19
+ import { causyneHome } from '../utils/paths.js';
20
+ import { boundedInteger, sanitizeToolError, type ToolWorkspaceContext } from '../tools/toolPathSafety.js';
21
+
22
+ export type ScheduleKind = 'after' | 'at' | 'every' | 'daily' | 'weekly' | 'cron';
23
+ export type ScheduleStatus = 'active' | 'paused' | 'completed';
24
+
25
+ export interface ScheduleTaskRecord {
26
+ id: string;
27
+ name: string;
28
+ prompt: string;
29
+ workspaceRoot: string;
30
+ kind: ScheduleKind;
31
+ spec: string;
32
+ timezone: string;
33
+ status: ScheduleStatus;
34
+ nextRunAt: number | null;
35
+ lastRunAt: number | null;
36
+ runCount: number;
37
+ createdAt: number;
38
+ updatedAt: number;
39
+ }
40
+
41
+ interface ScheduleStoreFile {
42
+ version: number;
43
+ tasks: ScheduleTaskRecord[];
44
+ }
45
+
46
+ const STORE_VERSION = 1;
47
+ const MIN_INTERVAL_SEC = 60;
48
+ const MAX_TASKS = 100;
49
+
50
+ function storeFilePath(): string {
51
+ return path.join(causyneHome(), 'schedules.json');
52
+ }
53
+
54
+ function readStore(): ScheduleStoreFile {
55
+ const fp = storeFilePath();
56
+ if (!fs.existsSync(fp)) return { version: STORE_VERSION, tasks: [] };
57
+ try {
58
+ const stat = fs.lstatSync(fp);
59
+ if (stat.isSymbolicLink() || !stat.isFile()) return { version: STORE_VERSION, tasks: [] };
60
+ const parsed = JSON.parse(fs.readFileSync(fp, 'utf8')) as Partial<ScheduleStoreFile>;
61
+ const tasks = Array.isArray(parsed.tasks) ? parsed.tasks : [];
62
+ return { version: STORE_VERSION, tasks };
63
+ } catch {
64
+ return { version: STORE_VERSION, tasks: [] };
65
+ }
66
+ }
67
+
68
+ function writeStore(store: ScheduleStoreFile): void {
69
+ const fp = storeFilePath();
70
+ fs.mkdirSync(path.dirname(fp), { recursive: true, mode: 0o700 });
71
+ atomicWriteFileSync(fp, `${JSON.stringify(store, null, 2)}\n`);
72
+ }
73
+
74
+ function validateTimezone(tz?: string): string {
75
+ const candidate = typeof tz === 'string' && tz.trim() ? tz.trim() : Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
76
+ try {
77
+ new Intl.DateTimeFormat('en-US', { timeZone: candidate });
78
+ return candidate;
79
+ } catch {
80
+ throw new Error(`Invalid IANA timezone: "${candidate}".`);
81
+ }
82
+ }
83
+
84
+ function parseCronField(expr: string, min: number, max: number): Set<number> {
85
+ const values = new Set<number>();
86
+ const parts = expr.split(',');
87
+ for (const part of parts) {
88
+ const trimmed = part.trim();
89
+ if (!trimmed) throw new Error(`Empty cron segment in "${expr}".`);
90
+ const [rangePart, stepPart] = trimmed.split('/');
91
+ const step = stepPart !== undefined ? Number.parseInt(stepPart, 10) : 1;
92
+ if (!Number.isInteger(step) || step <= 0) throw new Error(`Invalid cron step in "${trimmed}".`);
93
+
94
+ let start = min;
95
+ let end = max;
96
+ if (rangePart !== '*') {
97
+ if (rangePart!.includes('-')) {
98
+ const [a, b] = rangePart!.split('-');
99
+ start = Number.parseInt(a || '', 10);
100
+ end = Number.parseInt(b || '', 10);
101
+ } else {
102
+ start = Number.parseInt(rangePart!, 10);
103
+ end = stepPart !== undefined ? max : start;
104
+ }
105
+ }
106
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < min || end > max || start > end) {
107
+ throw new Error(`Out-of-range cron field "${trimmed}" (expected ${min}-${max}).`);
108
+ }
109
+ for (let v = start; v <= end; v += step) values.add(v);
110
+ }
111
+ return values;
112
+ }
113
+
114
+ function getZonedParts(epochMs: number, timeZone: string): {
115
+ minute: number;
116
+ hour: number;
117
+ day: number;
118
+ month: number;
119
+ weekday: number;
120
+ } {
121
+ const fmt = new Intl.DateTimeFormat('en-US', {
122
+ timeZone,
123
+ year: 'numeric',
124
+ month: 'numeric',
125
+ day: 'numeric',
126
+ hour: 'numeric',
127
+ minute: 'numeric',
128
+ weekday: 'short',
129
+ hourCycle: 'h23'
130
+ });
131
+ const parts = fmt.formatToParts(new Date(epochMs));
132
+ const map: Record<string, string> = {};
133
+ for (const p of parts) map[p.type] = p.value;
134
+ const weekdayNames: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
135
+ return {
136
+ minute: Number.parseInt(map.minute || '0', 10),
137
+ hour: Number.parseInt(map.hour || '0', 10) % 24,
138
+ day: Number.parseInt(map.day || '1', 10),
139
+ month: Number.parseInt(map.month || '1', 10),
140
+ weekday: weekdayNames[map.weekday || 'Sun'] ?? 0
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Computes the next scheduled UTC epoch timestamp (ms) strictly after `fromMs`.
146
+ * Coalesces missed past occurrences automatically by scanning forward from `fromMs`.
147
+ */
148
+ export function computeNextRunAt(
149
+ kind: ScheduleKind,
150
+ spec: string,
151
+ timezone: string,
152
+ fromMs = Date.now()
153
+ ): number {
154
+ const tz = validateTimezone(timezone);
155
+ const raw = String(spec || '').trim();
156
+
157
+ if (kind === 'after') {
158
+ const secs = Number.parseInt(raw, 10);
159
+ if (!Number.isInteger(secs) || secs < 10 || secs > 365 * 86_400) {
160
+ throw new Error('`after` spec must be a delay in seconds (10 to 31536000).');
161
+ }
162
+ return fromMs + secs * 1000;
163
+ }
164
+
165
+ if (kind === 'at') {
166
+ const parsed = Date.parse(raw);
167
+ if (!Number.isFinite(parsed)) throw new Error('`at` spec must be a valid ISO-8601 timestamp.');
168
+ if (parsed <= fromMs) throw new Error('`at` timestamp must be in the future.');
169
+ return parsed;
170
+ }
171
+
172
+ if (kind === 'every') {
173
+ const secs = Number.parseInt(raw, 10);
174
+ if (!Number.isInteger(secs) || secs < MIN_INTERVAL_SEC || secs > 30 * 86_400) {
175
+ throw new Error(`\`every\` spec must be an interval in seconds (${MIN_INTERVAL_SEC} to 2592000).`);
176
+ }
177
+ return fromMs + secs * 1000;
178
+ }
179
+
180
+ let cronExpr = raw;
181
+ if (kind === 'daily') {
182
+ const m = /^(\d{1,2}):(\d{2})$/.exec(raw);
183
+ if (!m) throw new Error('`daily` spec must be HH:MM (24-hour).');
184
+ const hh = Number.parseInt(m[1]!, 10);
185
+ const mm = Number.parseInt(m[2]!, 10);
186
+ if (hh < 0 || hh > 23 || mm < 0 || mm > 59) throw new Error('`daily` time out of range.');
187
+ cronExpr = `${mm} ${hh} * * *`;
188
+ } else if (kind === 'weekly') {
189
+ const m = /^(sun|mon|tue|wed|thu|fri|sat)\s+(\d{1,2}):(\d{2})$/i.exec(raw);
190
+ if (!m) throw new Error('`weekly` spec must be "<day> HH:MM", e.g. "mon 09:00".');
191
+ const dayMap: Record<string, number> = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 };
192
+ const dow = dayMap[m[1]!.toLowerCase()]!;
193
+ const hh = Number.parseInt(m[2]!, 10);
194
+ const mm = Number.parseInt(m[3]!, 10);
195
+ if (hh < 0 || hh > 23 || mm < 0 || mm > 59) throw new Error('`weekly` time out of range.');
196
+ cronExpr = `${mm} ${hh} * * ${dow}`;
197
+ }
198
+
199
+ const fields = cronExpr.split(/\s+/);
200
+ if (fields.length !== 5) {
201
+ throw new Error('`cron` spec must have exactly 5 fields: minute hour day-of-month month day-of-week.');
202
+ }
203
+ const minutes = parseCronField(fields[0]!, 0, 59);
204
+ const hours = parseCronField(fields[1]!, 0, 23);
205
+ const days = parseCronField(fields[2]!, 1, 31);
206
+ const months = parseCronField(fields[3]!, 1, 12);
207
+ const rawDows = parseCronField(fields[4]!, 0, 7);
208
+ if (rawDows.has(7)) {
209
+ rawDows.delete(7);
210
+ rawDows.add(0);
211
+ }
212
+
213
+ // Advance minute-by-minute up to 366 days (fast short-circuit by hour/day)
214
+ let probe = Math.floor(fromMs / 60_000) * 60_000 + 60_000;
215
+ const maxProbe = fromMs + 366 * 86_400_000;
216
+ while (probe <= maxProbe) {
217
+ const zp = getZonedParts(probe, tz);
218
+ if (!months.has(zp.month)) {
219
+ probe += 24 * 60 * 60_000;
220
+ continue;
221
+ }
222
+ if (!days.has(zp.day) || !rawDows.has(zp.weekday)) {
223
+ probe += 60 * 60_000;
224
+ continue;
225
+ }
226
+ if (!hours.has(zp.hour)) {
227
+ probe += 60_000;
228
+ continue;
229
+ }
230
+ if (minutes.has(zp.minute)) {
231
+ return probe;
232
+ }
233
+ probe += 60_000;
234
+ }
235
+ throw new Error('Could not find next occurrence within 366 days for cron expression.');
236
+ }
237
+
238
+ export class DurableScheduler {
239
+ public list(workspaceRoot?: string): ScheduleTaskRecord[] {
240
+ const store = readStore();
241
+ return workspaceRoot
242
+ ? store.tasks.filter((t) => t.workspaceRoot === workspaceRoot)
243
+ : store.tasks;
244
+ }
245
+
246
+ public get(id: string): ScheduleTaskRecord | null {
247
+ return readStore().tasks.find((t) => t.id === id) ?? null;
248
+ }
249
+
250
+ public create(options: {
251
+ name: string;
252
+ prompt: string;
253
+ workspaceRoot: string;
254
+ kind: ScheduleKind;
255
+ spec: string;
256
+ timezone?: string | undefined;
257
+ }): ScheduleTaskRecord {
258
+ const store = readStore();
259
+ if (store.tasks.length >= MAX_TASKS) {
260
+ throw new Error(`Maximum scheduled tasks (${MAX_TASKS}) reached.`);
261
+ }
262
+ const name = String(options.name || '').trim().slice(0, 80);
263
+ const prompt = String(options.prompt || '').trim().slice(0, 4000);
264
+ if (!name || !prompt) throw new Error('Both name and prompt are required.');
265
+ const timezone = validateTimezone(options.timezone);
266
+ const now = Date.now();
267
+ const nextRunAt = computeNextRunAt(options.kind, options.spec, timezone, now);
268
+ const record: ScheduleTaskRecord = {
269
+ id: `sched_${crypto.randomBytes(6).toString('hex')}`,
270
+ name,
271
+ prompt,
272
+ workspaceRoot: options.workspaceRoot,
273
+ kind: options.kind,
274
+ spec: options.spec.trim(),
275
+ timezone,
276
+ status: 'active',
277
+ nextRunAt,
278
+ lastRunAt: null,
279
+ runCount: 0,
280
+ createdAt: now,
281
+ updatedAt: now
282
+ };
283
+ store.tasks.push(record);
284
+ writeStore(store);
285
+ return record;
286
+ }
287
+
288
+ public edit(options: {
289
+ id: string;
290
+ action: 'pause' | 'resume' | 'delete' | 'update';
291
+ expectedUpdatedAt?: number | undefined;
292
+ prompt?: string | undefined;
293
+ spec?: string | undefined;
294
+ timezone?: string | undefined;
295
+ }): ScheduleTaskRecord | null {
296
+ const store = readStore();
297
+ const idx = store.tasks.findIndex((t) => t.id === options.id);
298
+ if (idx === -1) throw new Error(`Schedule "${options.id}" not found.`);
299
+ const existing = store.tasks[idx]!;
300
+ if (options.expectedUpdatedAt !== undefined && existing.updatedAt !== options.expectedUpdatedAt) {
301
+ throw new Error(`schedule_conflict: Schedule "${options.id}" was modified concurrently.`);
302
+ }
303
+ if (options.action === 'delete') {
304
+ store.tasks.splice(idx, 1);
305
+ writeStore(store);
306
+ return null;
307
+ }
308
+ const now = Date.now();
309
+ const updated: ScheduleTaskRecord = { ...existing, updatedAt: now };
310
+ if (options.action === 'pause') {
311
+ updated.status = 'paused';
312
+ } else if (options.action === 'resume') {
313
+ updated.status = 'active';
314
+ updated.nextRunAt = computeNextRunAt(updated.kind, updated.spec, updated.timezone, now);
315
+ } else if (options.action === 'update') {
316
+ if (typeof options.prompt === 'string' && options.prompt.trim()) {
317
+ updated.prompt = options.prompt.trim().slice(0, 4000);
318
+ }
319
+ if (typeof options.timezone === 'string' && options.timezone.trim()) {
320
+ updated.timezone = validateTimezone(options.timezone);
321
+ }
322
+ if (typeof options.spec === 'string' && options.spec.trim()) {
323
+ updated.spec = options.spec.trim();
324
+ }
325
+ if (updated.status === 'active') {
326
+ updated.nextRunAt = computeNextRunAt(updated.kind, updated.spec, updated.timezone, now);
327
+ }
328
+ }
329
+ store.tasks[idx] = updated;
330
+ writeStore(store);
331
+ return updated;
332
+ }
333
+ }
334
+
335
+ export const durableScheduler = new DurableScheduler();
336
+
337
+ export const scheduleTool = {
338
+ schema: {
339
+ name: 'schedule',
340
+ description:
341
+ 'Create, list, view, pause, resume, update, or delete durable scheduled tasks (`after`, `at`, `every`, `daily`, `weekly`, or 5-field `cron` with IANA timezone). Enforces optimistic concurrency and subagent safety.',
342
+ parameters: {
343
+ type: 'object',
344
+ properties: {
345
+ action: { type: 'string', enum: ['create', 'list', 'view', 'pause', 'resume', 'update', 'delete'] },
346
+ id: { type: 'string', description: 'Schedule ID for view/pause/resume/update/delete.' },
347
+ name: { type: 'string', description: 'Short task title (for create).' },
348
+ prompt: { type: 'string', description: 'Prompt instruction to execute on schedule.' },
349
+ kind: { type: 'string', enum: ['after', 'at', 'every', 'daily', 'weekly', 'cron'] },
350
+ spec: {
351
+ type: 'string',
352
+ description: 'Schedule specification (seconds for after/every, ISO timestamp for at, HH:MM for daily, "mon 09:00" for weekly, or 5-field cron).'
353
+ },
354
+ timezone: { type: 'string', description: 'Optional IANA timezone (e.g. "UTC", "Asia/Jakarta", "America/New_York").' },
355
+ expectedUpdatedAt: { type: 'integer', description: 'Optional optimistic concurrency timestamp guard.' }
356
+ },
357
+ required: ['action'],
358
+ additionalProperties: false
359
+ }
360
+ },
361
+
362
+ async execute(
363
+ args: {
364
+ action: 'create' | 'list' | 'view' | 'pause' | 'resume' | 'update' | 'delete';
365
+ id?: string;
366
+ name?: string;
367
+ prompt?: string;
368
+ kind?: ScheduleKind;
369
+ spec?: string;
370
+ timezone?: string;
371
+ expectedUpdatedAt?: number;
372
+ },
373
+ context: ToolWorkspaceContext & { isSubagent?: boolean | undefined } = {}
374
+ ) {
375
+ try {
376
+ if (context.isSubagent && args.action !== 'list' && args.action !== 'view') {
377
+ return { success: false, error: 'Subagents are not permitted to create or modify durable schedules.' };
378
+ }
379
+ const workspaceRoot = context.workspaceRoot || context.workspacePaths?.[0] || process.cwd();
380
+ if (args.action === 'list') {
381
+ const tasks = durableScheduler.list(workspaceRoot);
382
+ return {
383
+ success: true,
384
+ tasks,
385
+ output: tasks.length === 0
386
+ ? 'No scheduled tasks in this workspace.'
387
+ : tasks.map((t) => `${t.id} [${t.status}] ${t.name} (${t.kind}: ${t.spec}, tz=${t.timezone}, next=${t.nextRunAt ? new Date(t.nextRunAt).toISOString() : 'none'})`).join('\n')
388
+ };
389
+ }
390
+ if (args.action === 'view') {
391
+ const task = args.id ? durableScheduler.get(args.id) : null;
392
+ if (!task) return { success: false, error: `Schedule "${args.id || ''}" not found.` };
393
+ return { success: true, task, output: JSON.stringify(task, null, 2) };
394
+ }
395
+ if (args.action === 'create') {
396
+ if (!args.kind || !args.spec) return { success: false, error: 'kind and spec are required to create a schedule.' };
397
+ const created = durableScheduler.create({
398
+ name: args.name || 'Scheduled task',
399
+ prompt: args.prompt || '',
400
+ workspaceRoot,
401
+ kind: args.kind,
402
+ spec: args.spec,
403
+ timezone: args.timezone
404
+ });
405
+ return {
406
+ success: true,
407
+ task: created,
408
+ output: `Created schedule ${created.id} (${created.kind}: ${created.spec}, next run ${created.nextRunAt ? new Date(created.nextRunAt).toISOString() : 'none'}).`
409
+ };
410
+ }
411
+ if (!args.id) return { success: false, error: 'id is required for this schedule action.' };
412
+ const updated = durableScheduler.edit({
413
+ id: args.id,
414
+ action: args.action,
415
+ expectedUpdatedAt: args.expectedUpdatedAt,
416
+ prompt: args.prompt,
417
+ spec: args.spec,
418
+ timezone: args.timezone
419
+ });
420
+ if (!updated) return { success: true, deleted: true, output: `Deleted schedule ${args.id}.` };
421
+ return {
422
+ success: true,
423
+ task: updated,
424
+ output: `Updated schedule ${updated.id} -> status=${updated.status}, next=${updated.nextRunAt ? new Date(updated.nextRunAt).toISOString() : 'none'}.`
425
+ };
426
+ } catch (error) {
427
+ return { success: false, error: sanitizeToolError(error) };
428
+ }
429
+ }
430
+ };
431
+
432
+ // Keep boundedInteger export-clean if referenced externally
433
+ void boundedInteger;
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Causyne Agent — Disposable SQLite FTS5 Session Search Index & Tool
3
+ *
4
+ * Indexes workspace-scoped JSONL session transcripts under `~/.causyne/sessions/`
5
+ * using Node's built-in `node:sqlite` FTS5 (zero external npm dependencies) with
6
+ * automatic fallback to linear streaming scan if SQLite FTS5 is unavailable.
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { listSessions, getSession } from './sessionJournal.js';
11
+ import { physicalPath } from './agent/workspaceBoundary.js';
12
+ import { causyneHome } from './utils/paths.js';
13
+ import { boundedInteger, resolveToolWorkspaceRoots, sanitizeToolError } from './tools/toolPathSafety.js';
14
+ const INDEX_SCHEMA_VERSION = 1;
15
+ const MAX_SNIPPET_CHARS = 240;
16
+ function extractMessagePlainText(msg) {
17
+ if (!msg || typeof msg !== 'object')
18
+ return '';
19
+ const rec = msg;
20
+ if (typeof rec.content === 'string')
21
+ return rec.content;
22
+ if (Array.isArray(rec.content)) {
23
+ const parts = [];
24
+ for (const block of rec.content) {
25
+ if (typeof block === 'string')
26
+ parts.push(block);
27
+ else if (block && typeof block === 'object' && typeof block.text === 'string') {
28
+ parts.push(block.text);
29
+ }
30
+ }
31
+ return parts.join('\n');
32
+ }
33
+ return '';
34
+ }
35
+ function buildMatchSnippet(text, query) {
36
+ const cleaned = text.replace(/\s+/g, ' ').trim();
37
+ if (cleaned.length <= MAX_SNIPPET_CHARS)
38
+ return cleaned;
39
+ const lower = cleaned.toLowerCase();
40
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
41
+ let pos = -1;
42
+ for (const term of terms) {
43
+ const found = lower.indexOf(term);
44
+ if (found !== -1 && (pos === -1 || found < pos))
45
+ pos = found;
46
+ }
47
+ if (pos === -1)
48
+ return `${cleaned.slice(0, MAX_SNIPPET_CHARS)}...`;
49
+ const start = Math.max(0, pos - 70);
50
+ const end = Math.min(cleaned.length, start + MAX_SNIPPET_CHARS);
51
+ return `${start > 0 ? '...' : ''}${cleaned.slice(start, end)}${end < cleaned.length ? '...' : ''}`;
52
+ }
53
+ function quoteFtsQuery(rawQuery) {
54
+ const tokens = rawQuery
55
+ .trim()
56
+ .split(/\s+/)
57
+ .map((t) => t.replace(/"/g, '').trim())
58
+ .filter((t) => t.length > 0)
59
+ .slice(0, 12);
60
+ if (tokens.length === 0)
61
+ return '';
62
+ return tokens.map((t) => `"${t}"`).join(' AND ');
63
+ }
64
+ function sameWorkspace(sessionWorkspace, workspaceRoot) {
65
+ if (!sessionWorkspace)
66
+ return false;
67
+ const a = physicalPath(sessionWorkspace) || path.resolve(sessionWorkspace);
68
+ const b = physicalPath(workspaceRoot) || path.resolve(workspaceRoot);
69
+ return a === b;
70
+ }
71
+ async function searchWithSqliteFts5(workspaceRoot, query, options) {
72
+ let DatabaseSyncCtor;
73
+ try {
74
+ const mod = await import('node:sqlite');
75
+ DatabaseSyncCtor = mod.DatabaseSync;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ if (typeof DatabaseSyncCtor !== 'function')
81
+ return null;
82
+ const ftsQuery = quoteFtsQuery(query);
83
+ if (!ftsQuery)
84
+ return [];
85
+ const indexDir = path.join(causyneHome(), 'cache');
86
+ const dbPath = path.join(indexDir, 'session-search-fts5.sqlite');
87
+ fs.mkdirSync(indexDir, { recursive: true, mode: 0o700 });
88
+ const db = new DatabaseSyncCtor(dbPath);
89
+ try {
90
+ const verRow = db.prepare('PRAGMA user_version').get();
91
+ if (!verRow || verRow.user_version !== INDEX_SCHEMA_VERSION) {
92
+ db.exec('DROP TABLE IF EXISTS session_meta; DROP TABLE IF EXISTS session_docs;');
93
+ db.exec(`
94
+ CREATE TABLE session_meta (
95
+ session_id TEXT PRIMARY KEY,
96
+ workspace TEXT NOT NULL,
97
+ title TEXT NOT NULL,
98
+ updated_at INTEGER NOT NULL,
99
+ message_count INTEGER NOT NULL
100
+ );
101
+ CREATE VIRTUAL TABLE session_docs USING fts5(
102
+ session_id UNINDEXED,
103
+ workspace UNINDEXED,
104
+ title,
105
+ role UNINDEXED,
106
+ message_index UNINDEXED,
107
+ body,
108
+ tokenize='unicode61'
109
+ );
110
+ PRAGMA user_version = ${INDEX_SCHEMA_VERSION};
111
+ `);
112
+ }
113
+ const sessions = listSessions().filter((s) => sameWorkspace(s.workspace, workspaceRoot));
114
+ const selectMeta = db.prepare('SELECT updated_at, message_count FROM session_meta WHERE session_id = ?');
115
+ const deleteDocs = db.prepare('DELETE FROM session_docs WHERE session_id = ?');
116
+ const upsertMeta = db.prepare('INSERT OR REPLACE INTO session_meta (session_id, workspace, title, updated_at, message_count) VALUES (?, ?, ?, ?, ?)');
117
+ const insertDoc = db.prepare('INSERT INTO session_docs (session_id, workspace, title, role, message_index, body) VALUES (?, ?, ?, ?, ?, ?)');
118
+ const normalizedWorkspace = physicalPath(workspaceRoot) || path.resolve(workspaceRoot);
119
+ for (const summary of sessions.slice(0, 120)) {
120
+ const existing = selectMeta.get(summary.id);
121
+ if (existing && existing.updated_at === summary.updatedAt && existing.message_count === summary.messageCount) {
122
+ continue;
123
+ }
124
+ const full = getSession(summary.id);
125
+ if (!full)
126
+ continue;
127
+ deleteDocs.run(summary.id);
128
+ upsertMeta.run(summary.id, normalizedWorkspace, summary.title || '', summary.updatedAt || 0, full.messages.length);
129
+ for (let i = 0; i < full.messages.length; i++) {
130
+ const msg = full.messages[i];
131
+ const body = extractMessagePlainText(msg).slice(0, 16_000);
132
+ if (!body.trim())
133
+ continue;
134
+ insertDoc.run(summary.id, normalizedWorkspace, summary.title || '', String(msg?.role || 'unknown'), i, body);
135
+ }
136
+ }
137
+ const rows = db.prepare(`
138
+ SELECT d.session_id, d.title, d.role, d.message_index, d.body, m.updated_at, bm25(session_docs) AS rank
139
+ FROM session_docs d
140
+ JOIN session_meta m ON m.session_id = d.session_id
141
+ WHERE d.workspace = ? AND session_docs MATCH ?
142
+ ORDER BY rank ASC, m.updated_at DESC
143
+ LIMIT ?
144
+ `).all(normalizedWorkspace, ftsQuery, Math.max(options.limit * 4, 24));
145
+ const bestPerSession = new Map();
146
+ for (const row of rows) {
147
+ if (options.excludeSessionId && row.session_id === options.excludeSessionId)
148
+ continue;
149
+ if (bestPerSession.has(row.session_id))
150
+ continue;
151
+ bestPerSession.set(row.session_id, {
152
+ sessionId: row.session_id,
153
+ title: row.title || 'Untitled session',
154
+ updatedAt: Number(row.updated_at || 0),
155
+ messageIndex: Number(row.message_index || 0),
156
+ role: row.role || 'unknown',
157
+ snippet: buildMatchSnippet(row.body || '', query),
158
+ score: Number.isFinite(row.rank) ? -row.rank : 0
159
+ });
160
+ if (bestPerSession.size >= options.limit)
161
+ break;
162
+ }
163
+ return [...bestPerSession.values()];
164
+ }
165
+ finally {
166
+ try {
167
+ db.close();
168
+ }
169
+ catch { /* ignore */ }
170
+ }
171
+ }
172
+ function searchLinearFallback(workspaceRoot, query, options) {
173
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
174
+ if (terms.length === 0)
175
+ return [];
176
+ const sessions = listSessions().filter((s) => sameWorkspace(s.workspace, workspaceRoot));
177
+ const hits = [];
178
+ for (const summary of sessions.slice(0, 120)) {
179
+ if (options.excludeSessionId && summary.id === options.excludeSessionId)
180
+ continue;
181
+ const full = getSession(summary.id);
182
+ if (!full)
183
+ continue;
184
+ for (let i = full.messages.length - 1; i >= 0; i--) {
185
+ const msg = full.messages[i];
186
+ const text = extractMessagePlainText(msg);
187
+ const lower = text.toLowerCase();
188
+ if (terms.every((t) => lower.includes(t))) {
189
+ hits.push({
190
+ sessionId: summary.id,
191
+ title: summary.title || 'Untitled session',
192
+ updatedAt: summary.updatedAt || 0,
193
+ messageIndex: i,
194
+ role: String(msg?.role || 'unknown'),
195
+ snippet: buildMatchSnippet(text, query),
196
+ score: 1
197
+ });
198
+ break;
199
+ }
200
+ }
201
+ if (hits.length >= options.limit)
202
+ break;
203
+ }
204
+ return hits;
205
+ }
206
+ export async function searchWorkspaceSessions(workspaceRoot, query, options = {}) {
207
+ const trimmed = String(query || '').trim();
208
+ if (!trimmed)
209
+ return [];
210
+ const limit = boundedInteger(options.limit, 8, 1, 25);
211
+ try {
212
+ const fts = await searchWithSqliteFts5(workspaceRoot, trimmed, {
213
+ limit,
214
+ excludeSessionId: options.excludeSessionId
215
+ });
216
+ if (fts !== null)
217
+ return fts;
218
+ }
219
+ catch {
220
+ // Fall back gracefully if SQLite FTS5 is unavailable
221
+ }
222
+ return searchLinearFallback(workspaceRoot, trimmed, {
223
+ limit,
224
+ excludeSessionId: options.excludeSessionId
225
+ });
226
+ }
227
+ export const sessionSearchTool = {
228
+ schema: {
229
+ name: 'session_search',
230
+ description: 'Full-text search across prior saved Causyne sessions in the current workspace (backed by disposable SQLite FTS5). Use to recall prior decisions, commands, file changes, or error resolutions.',
231
+ parameters: {
232
+ type: 'object',
233
+ properties: {
234
+ query: { type: 'string', description: 'Search keywords or phrase (1-300 characters).' },
235
+ limit: { type: 'integer', description: 'Maximum sessions to return (1-25, default 8).' }
236
+ },
237
+ required: ['query'],
238
+ additionalProperties: false
239
+ }
240
+ },
241
+ async execute(args, context = {}) {
242
+ try {
243
+ const query = typeof args?.query === 'string' ? args.query.trim() : '';
244
+ if (!query || query.length > 300) {
245
+ return { success: false, error: 'query must contain 1-300 characters.' };
246
+ }
247
+ const scope = resolveToolWorkspaceRoots(context);
248
+ const workspaceRoot = scope.primaryRoot || process.cwd();
249
+ const hits = await searchWorkspaceSessions(workspaceRoot, query, {
250
+ limit: args.limit,
251
+ excludeSessionId: context.parentLoop?.sessionId
252
+ });
253
+ if (hits.length === 0) {
254
+ return { success: true, hits: [], output: `No matching prior sessions found for "${query}".` };
255
+ }
256
+ const lines = hits.map((h, idx) => `${idx + 1}. [${h.sessionId}] ${h.title} (msg #${h.messageIndex}, ${h.role})\n ${h.snippet}`);
257
+ return {
258
+ success: true,
259
+ hits,
260
+ output: `Found ${hits.length} matching session(s):\n${lines.join('\n')}`
261
+ };
262
+ }
263
+ catch (error) {
264
+ return { success: false, error: sanitizeToolError(error) };
265
+ }
266
+ }
267
+ };