sentinelayer-cli 0.6.2 → 0.8.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 (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -0,0 +1,388 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+ import process from "node:process";
5
+
6
+ import { collectCodebaseIngest } from "../ingest/engine.js";
7
+ import { resolveSessionPaths, resolveSessionsRoot } from "./paths.js";
8
+ import { appendToStream } from "./stream.js";
9
+
10
+ const SESSION_SCHEMA_VERSION = "1.0.0";
11
+ const DEFAULT_TTL_SECONDS = 24 * 60 * 60;
12
+ const RENEWAL_SECONDS = 24 * 60 * 60;
13
+ const MAX_SESSION_LIFETIME_SECONDS = 72 * 60 * 60;
14
+ const SESSION_STATUS_ACTIVE = "active";
15
+ const SESSION_STATUS_EXPIRED = "expired";
16
+ const SESSION_STATUS_ARCHIVED = "archived";
17
+
18
+ function normalizeString(value) {
19
+ return String(value || "").trim();
20
+ }
21
+
22
+ function normalizePositiveInteger(value, fallbackValue) {
23
+ if (value === undefined || value === null || normalizeString(value) === "") {
24
+ return fallbackValue;
25
+ }
26
+ const normalized = Number(value);
27
+ if (!Number.isFinite(normalized) || normalized <= 0) {
28
+ throw new Error("Value must be a positive integer.");
29
+ }
30
+ return Math.floor(normalized);
31
+ }
32
+
33
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
34
+ const normalized = normalizeString(value);
35
+ if (!normalized) {
36
+ return fallbackIso;
37
+ }
38
+ const epoch = Date.parse(normalized);
39
+ if (!Number.isFinite(epoch)) {
40
+ return fallbackIso;
41
+ }
42
+ return new Date(epoch).toISOString();
43
+ }
44
+
45
+ function toIsoAfterSeconds(nowIso, seconds) {
46
+ const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso));
47
+ return new Date(nowEpoch + seconds * 1000).toISOString();
48
+ }
49
+
50
+ function buildElapsedTimer(fromIso, nowIso = new Date().toISOString()) {
51
+ const fromEpoch = Date.parse(normalizeIsoTimestamp(fromIso, nowIso));
52
+ const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
53
+ if (!Number.isFinite(fromEpoch) || !Number.isFinite(nowEpoch) || nowEpoch <= fromEpoch) {
54
+ return "0m";
55
+ }
56
+ const totalSeconds = Math.floor((nowEpoch - fromEpoch) / 1000);
57
+ const totalMinutes = Math.floor(totalSeconds / 60);
58
+ const hours = Math.floor(totalMinutes / 60);
59
+ const minutes = totalMinutes % 60;
60
+ if (hours <= 0) {
61
+ return `${Math.max(0, minutes)}m`;
62
+ }
63
+ return `${hours}h ${minutes}m`;
64
+ }
65
+
66
+ async function readJsonFile(filePath, { allowMissing = true } = {}) {
67
+ try {
68
+ const raw = await fsp.readFile(filePath, "utf-8");
69
+ return JSON.parse(raw);
70
+ } catch (error) {
71
+ if (
72
+ allowMissing &&
73
+ error &&
74
+ typeof error === "object" &&
75
+ error.code === "ENOENT"
76
+ ) {
77
+ return null;
78
+ }
79
+ throw error;
80
+ }
81
+ }
82
+
83
+ async function writeJsonFile(filePath, payload) {
84
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
85
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
86
+ await fsp.writeFile(tmpPath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
87
+ await fsp.rename(tmpPath, filePath);
88
+ }
89
+
90
+ function normalizeCodebaseContext(ingest = {}) {
91
+ return {
92
+ summary:
93
+ ingest && typeof ingest.summary === "object" && ingest.summary
94
+ ? {
95
+ filesScanned: Number(ingest.summary.filesScanned || 0),
96
+ directoriesScanned: Number(ingest.summary.directoriesScanned || 0),
97
+ totalLoc: Number(ingest.summary.totalLoc || 0),
98
+ totalBytes: Number(ingest.summary.totalBytes || 0),
99
+ }
100
+ : {
101
+ filesScanned: 0,
102
+ directoriesScanned: 0,
103
+ totalLoc: 0,
104
+ totalBytes: 0,
105
+ },
106
+ frameworks: Array.isArray(ingest.frameworks) ? [...ingest.frameworks] : [],
107
+ entryPoints: Array.isArray(ingest.entryPoints) ? [...ingest.entryPoints] : [],
108
+ riskSurfaces: Array.isArray(ingest.riskSurfaces) ? [...ingest.riskSurfaces] : [],
109
+ };
110
+ }
111
+
112
+ async function collectSessionCodebaseContext(targetPath) {
113
+ const cachedIngestPath = path.join(targetPath, ".sentinelayer", "CODEBASE_INGEST.json");
114
+ const cachedIngest = await readJsonFile(cachedIngestPath, { allowMissing: true });
115
+ if (cachedIngest && typeof cachedIngest === "object") {
116
+ return normalizeCodebaseContext(cachedIngest);
117
+ }
118
+ const ingest = await collectCodebaseIngest({ rootPath: targetPath });
119
+ return normalizeCodebaseContext(ingest);
120
+ }
121
+
122
+ function normalizeSessionStatus(value) {
123
+ const normalized = normalizeString(value).toLowerCase();
124
+ if (normalized === SESSION_STATUS_EXPIRED) return SESSION_STATUS_EXPIRED;
125
+ if (normalized === SESSION_STATUS_ARCHIVED) return SESSION_STATUS_ARCHIVED;
126
+ return SESSION_STATUS_ACTIVE;
127
+ }
128
+
129
+ function normalizeMetadata(raw = {}, { sessionId, targetPath, nowIso } = {}) {
130
+ const createdAt = normalizeIsoTimestamp(raw.createdAt, nowIso);
131
+ const ttlSeconds = normalizePositiveInteger(raw.ttlSeconds, DEFAULT_TTL_SECONDS);
132
+ const expiresAt = normalizeIsoTimestamp(raw.expiresAt, toIsoAfterSeconds(createdAt, ttlSeconds));
133
+ return {
134
+ schemaVersion: SESSION_SCHEMA_VERSION,
135
+ sessionId: normalizeString(raw.sessionId) || sessionId,
136
+ targetPath: path.resolve(normalizeString(raw.targetPath) || targetPath),
137
+ createdAt,
138
+ updatedAt: normalizeIsoTimestamp(raw.updatedAt, nowIso),
139
+ expiresAt,
140
+ ttlSeconds,
141
+ renewalCount: Math.max(0, Number(raw.renewalCount || 0)),
142
+ maxLifetimeSeconds: normalizePositiveInteger(raw.maxLifetimeSeconds, MAX_SESSION_LIFETIME_SECONDS),
143
+ status: normalizeSessionStatus(raw.status),
144
+ lastInteractionAt: normalizeIsoTimestamp(raw.lastInteractionAt, createdAt),
145
+ expiredAt: raw.expiredAt ? normalizeIsoTimestamp(raw.expiredAt, nowIso) : null,
146
+ archivedAt: raw.archivedAt ? normalizeIsoTimestamp(raw.archivedAt, nowIso) : null,
147
+ s3Path: normalizeString(raw.s3Path) || null,
148
+ archiveStatus: normalizeString(raw.archiveStatus) || "pending",
149
+ codebaseContext: normalizeCodebaseContext(raw.codebaseContext || {}),
150
+ };
151
+ }
152
+
153
+ function isExpired(metadata, nowIso = new Date().toISOString()) {
154
+ if (!metadata || normalizeSessionStatus(metadata.status) === SESSION_STATUS_EXPIRED) {
155
+ return true;
156
+ }
157
+ const expiryEpoch = Date.parse(normalizeIsoTimestamp(metadata.expiresAt, nowIso));
158
+ const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
159
+ if (!Number.isFinite(expiryEpoch) || !Number.isFinite(nowEpoch)) {
160
+ return false;
161
+ }
162
+ return nowEpoch >= expiryEpoch;
163
+ }
164
+
165
+ function buildSessionPayload(metadata, paths, nowIso = new Date().toISOString()) {
166
+ return {
167
+ sessionId: metadata.sessionId,
168
+ sessionDir: paths.sessionDir,
169
+ metadataPath: paths.metadataPath,
170
+ streamPath: paths.streamPath,
171
+ createdAt: metadata.createdAt,
172
+ expiresAt: metadata.expiresAt,
173
+ elapsedTimer: buildElapsedTimer(metadata.createdAt, nowIso),
174
+ renewalCount: metadata.renewalCount,
175
+ status: metadata.status,
176
+ archivedAt: metadata.archivedAt,
177
+ s3Path: metadata.s3Path,
178
+ codebaseContext: metadata.codebaseContext,
179
+ };
180
+ }
181
+
182
+ async function loadMetadata(sessionId, { targetPath = process.cwd() } = {}) {
183
+ const resolvedTargetPath = path.resolve(String(targetPath || "."));
184
+ const paths = resolveSessionPaths(sessionId, { targetPath: resolvedTargetPath });
185
+ const nowIso = new Date().toISOString();
186
+ const raw = await readJsonFile(paths.metadataPath, { allowMissing: true });
187
+ if (!raw || typeof raw !== "object") {
188
+ return null;
189
+ }
190
+ const metadata = normalizeMetadata(raw, {
191
+ sessionId: paths.sessionId,
192
+ targetPath: resolvedTargetPath,
193
+ nowIso,
194
+ });
195
+ return { metadata, paths, targetPath: resolvedTargetPath };
196
+ }
197
+
198
+ async function saveMetadata(metadata, paths) {
199
+ const normalized = normalizeMetadata(metadata, {
200
+ sessionId: paths.sessionId,
201
+ targetPath: metadata.targetPath,
202
+ nowIso: new Date().toISOString(),
203
+ });
204
+ await writeJsonFile(paths.metadataPath, normalized);
205
+ return normalized;
206
+ }
207
+
208
+ export async function createSession({
209
+ targetPath = process.cwd(),
210
+ ttlSeconds = DEFAULT_TTL_SECONDS,
211
+ } = {}) {
212
+ const resolvedTargetPath = path.resolve(String(targetPath || "."));
213
+ const normalizedTtlSeconds = normalizePositiveInteger(ttlSeconds, DEFAULT_TTL_SECONDS);
214
+ const sessionId = randomUUID();
215
+ const nowIso = new Date().toISOString();
216
+ const paths = resolveSessionPaths(sessionId, { targetPath: resolvedTargetPath });
217
+ const codebaseContext = await collectSessionCodebaseContext(resolvedTargetPath);
218
+
219
+ const metadata = normalizeMetadata(
220
+ {
221
+ schemaVersion: SESSION_SCHEMA_VERSION,
222
+ sessionId,
223
+ targetPath: resolvedTargetPath,
224
+ createdAt: nowIso,
225
+ updatedAt: nowIso,
226
+ expiresAt: toIsoAfterSeconds(nowIso, normalizedTtlSeconds),
227
+ ttlSeconds: normalizedTtlSeconds,
228
+ renewalCount: 0,
229
+ maxLifetimeSeconds: MAX_SESSION_LIFETIME_SECONDS,
230
+ status: SESSION_STATUS_ACTIVE,
231
+ lastInteractionAt: nowIso,
232
+ expiredAt: null,
233
+ archivedAt: null,
234
+ s3Path: null,
235
+ archiveStatus: "pending",
236
+ codebaseContext,
237
+ },
238
+ {
239
+ sessionId,
240
+ targetPath: resolvedTargetPath,
241
+ nowIso,
242
+ }
243
+ );
244
+
245
+ await fsp.mkdir(paths.agentsDir, { recursive: true });
246
+ await saveMetadata(metadata, paths);
247
+ await fsp.writeFile(paths.streamPath, "", { encoding: "utf-8", flag: "a" });
248
+
249
+ return buildSessionPayload(metadata, paths, nowIso);
250
+ }
251
+
252
+ export async function getSession(sessionId, { targetPath = process.cwd() } = {}) {
253
+ const loaded = await loadMetadata(sessionId, { targetPath });
254
+ if (!loaded) {
255
+ return null;
256
+ }
257
+ return buildSessionPayload(loaded.metadata, loaded.paths);
258
+ }
259
+
260
+ export async function listActiveSessions({ targetPath = process.cwd() } = {}) {
261
+ const resolvedTargetPath = path.resolve(String(targetPath || "."));
262
+ const sessionsRoot = resolveSessionsRoot({ targetPath: resolvedTargetPath });
263
+ let entries = [];
264
+ try {
265
+ entries = await fsp.readdir(sessionsRoot, { withFileTypes: true });
266
+ } catch (error) {
267
+ if (error && typeof error === "object" && error.code === "ENOENT") {
268
+ return [];
269
+ }
270
+ throw error;
271
+ }
272
+
273
+ const sessions = [];
274
+ for (const entry of entries) {
275
+ if (!entry.isDirectory()) continue;
276
+ const loaded = await loadMetadata(entry.name, { targetPath: resolvedTargetPath });
277
+ if (!loaded) continue;
278
+ if (isExpired(loaded.metadata)) continue;
279
+ if (loaded.metadata.status === SESSION_STATUS_ARCHIVED) continue;
280
+ sessions.push(buildSessionPayload(loaded.metadata, loaded.paths));
281
+ }
282
+
283
+ sessions.sort((left, right) => left.createdAt.localeCompare(right.createdAt));
284
+ return sessions;
285
+ }
286
+
287
+ export async function renewSession(sessionId, { targetPath = process.cwd() } = {}) {
288
+ const loaded = await loadMetadata(sessionId, { targetPath });
289
+ if (!loaded) {
290
+ throw new Error(`Session '${sessionId}' was not found.`);
291
+ }
292
+
293
+ const nowIso = new Date().toISOString();
294
+ const createdEpoch = Date.parse(normalizeIsoTimestamp(loaded.metadata.createdAt, nowIso));
295
+ const expiresEpoch = Date.parse(normalizeIsoTimestamp(loaded.metadata.expiresAt, nowIso));
296
+ if (!Number.isFinite(createdEpoch) || !Number.isFinite(expiresEpoch)) {
297
+ throw new Error(`Session '${sessionId}' has invalid timestamps.`);
298
+ }
299
+
300
+ const maxExpiryEpoch = createdEpoch + loaded.metadata.maxLifetimeSeconds * 1000;
301
+ const nextExpiryEpoch = Math.min(expiresEpoch + RENEWAL_SECONDS * 1000, maxExpiryEpoch);
302
+ if (nextExpiryEpoch <= expiresEpoch) {
303
+ return buildSessionPayload(loaded.metadata, loaded.paths, nowIso);
304
+ }
305
+
306
+ loaded.metadata.expiresAt = new Date(nextExpiryEpoch).toISOString();
307
+ loaded.metadata.renewalCount = Math.max(0, Number(loaded.metadata.renewalCount || 0)) + 1;
308
+ loaded.metadata.updatedAt = nowIso;
309
+ loaded.metadata.lastInteractionAt = nowIso;
310
+ loaded.metadata.status = SESSION_STATUS_ACTIVE;
311
+ loaded.metadata.expiredAt = null;
312
+
313
+ const saved = await saveMetadata(loaded.metadata, loaded.paths);
314
+
315
+ try {
316
+ await appendToStream(
317
+ loaded.paths.sessionId,
318
+ {
319
+ event: "daemon_alert",
320
+ agentId: "senti",
321
+ payload: {
322
+ alert: "session_renewed",
323
+ expiresAt: saved.expiresAt,
324
+ renewalCount: saved.renewalCount,
325
+ },
326
+ ts: nowIso,
327
+ },
328
+ { targetPath: loaded.targetPath }
329
+ );
330
+ } catch {
331
+ // Renewal should not fail if stream event persistence is unavailable.
332
+ }
333
+
334
+ return buildSessionPayload(saved, loaded.paths, nowIso);
335
+ }
336
+
337
+ export async function expireSession(sessionId, { targetPath = process.cwd() } = {}) {
338
+ const loaded = await loadMetadata(sessionId, { targetPath });
339
+ if (!loaded) {
340
+ throw new Error(`Session '${sessionId}' was not found.`);
341
+ }
342
+ const nowIso = new Date().toISOString();
343
+ loaded.metadata.status = SESSION_STATUS_EXPIRED;
344
+ loaded.metadata.expiredAt = nowIso;
345
+ loaded.metadata.updatedAt = nowIso;
346
+ const saved = await saveMetadata(loaded.metadata, loaded.paths);
347
+ return buildSessionPayload(saved, loaded.paths, nowIso);
348
+ }
349
+
350
+ export async function archiveSession(
351
+ sessionId,
352
+ { s3Bucket, s3Prefix = "", targetPath = process.cwd() } = {}
353
+ ) {
354
+ const loaded = await loadMetadata(sessionId, { targetPath });
355
+ if (!loaded) {
356
+ throw new Error(`Session '${sessionId}' was not found.`);
357
+ }
358
+ const normalizedBucket = normalizeString(s3Bucket);
359
+ if (!normalizedBucket) {
360
+ throw new Error("archiveSession requires s3Bucket.");
361
+ }
362
+ const normalizedPrefix = normalizeString(s3Prefix).replace(/^\/+|\/+$/g, "");
363
+ const prefixSegment = normalizedPrefix ? `${normalizedPrefix}/` : "";
364
+ const s3Path = `s3://${normalizedBucket}/${prefixSegment}sessions/${loaded.paths.sessionId}/`;
365
+ const nowIso = new Date().toISOString();
366
+
367
+ loaded.metadata.status = SESSION_STATUS_ARCHIVED;
368
+ loaded.metadata.archivedAt = nowIso;
369
+ loaded.metadata.updatedAt = nowIso;
370
+ loaded.metadata.archiveStatus = "archived";
371
+ loaded.metadata.s3Path = s3Path;
372
+ const saved = await saveMetadata(loaded.metadata, loaded.paths);
373
+
374
+ await writeJsonFile(path.join(loaded.paths.sessionDir, "archive-manifest.json"), {
375
+ sessionId: loaded.paths.sessionId,
376
+ archivedAt: nowIso,
377
+ s3Path,
378
+ files: ["metadata.json", "stream.ndjson", "stream.1.ndjson", "agents/"],
379
+ });
380
+
381
+ return buildSessionPayload(saved, loaded.paths, nowIso);
382
+ }
383
+
384
+ export {
385
+ DEFAULT_TTL_SECONDS,
386
+ MAX_SESSION_LIFETIME_SECONDS,
387
+ RENEWAL_SECONDS,
388
+ };
@@ -0,0 +1,325 @@
1
+ import fsp from "node:fs/promises";
2
+ import process from "node:process";
3
+ import { setTimeout as sleep } from "node:timers/promises";
4
+
5
+ import { createAgentEvent, normalizeAgentEvent } from "../events/schema.js";
6
+ import { resolveSessionPaths } from "./paths.js";
7
+
8
+ const DEFAULT_POLL_MS = 500;
9
+ const DEFAULT_LOCK_TIMEOUT_MS = 10_000;
10
+ const DEFAULT_LOCK_STALE_MS = 30_000;
11
+ const DEFAULT_LOCK_POLL_MS = 25;
12
+ const DEFAULT_MAX_STREAM_EVENTS = 10_000;
13
+
14
+ function normalizeString(value) {
15
+ return String(value || "").trim();
16
+ }
17
+
18
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
19
+ const normalized = normalizeString(value);
20
+ if (!normalized) {
21
+ return fallbackIso;
22
+ }
23
+ const epoch = Date.parse(normalized);
24
+ if (!Number.isFinite(epoch)) {
25
+ return fallbackIso;
26
+ }
27
+ return new Date(epoch).toISOString();
28
+ }
29
+
30
+ function normalizePositiveInteger(value, fallbackValue) {
31
+ if (value === undefined || value === null || normalizeString(value) === "") {
32
+ return fallbackValue;
33
+ }
34
+ const normalized = Number(value);
35
+ if (!Number.isFinite(normalized) || normalized <= 0) {
36
+ throw new Error("Value must be a positive integer.");
37
+ }
38
+ return Math.floor(normalized);
39
+ }
40
+
41
+ async function readSessionMetadata(paths) {
42
+ try {
43
+ const raw = await fsp.readFile(paths.metadataPath, "utf-8");
44
+ const parsed = JSON.parse(raw);
45
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
46
+ return null;
47
+ }
48
+ return parsed;
49
+ } catch (error) {
50
+ if (error && typeof error === "object" && error.code === "ENOENT") {
51
+ return null;
52
+ }
53
+ throw error;
54
+ }
55
+ }
56
+
57
+ async function writeSessionMetadata(paths, metadata = {}) {
58
+ await fsp.mkdir(paths.sessionDir, { recursive: true });
59
+ const tmpPath = `${paths.metadataPath}.${process.pid}.${Date.now()}.tmp`;
60
+ await fsp.writeFile(tmpPath, `${JSON.stringify(metadata, null, 2)}\n`, "utf-8");
61
+ await fsp.rename(tmpPath, paths.metadataPath);
62
+ }
63
+
64
+ function isSessionExpired(metadata = {}, nowIso = new Date().toISOString()) {
65
+ const status = normalizeString(metadata.status).toLowerCase();
66
+ if (status === "expired" || status === "archived") {
67
+ return true;
68
+ }
69
+ const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
70
+ const expiryEpoch = Date.parse(normalizeIsoTimestamp(metadata.expiresAt, nowIso));
71
+ if (!Number.isFinite(nowEpoch) || !Number.isFinite(expiryEpoch)) {
72
+ return false;
73
+ }
74
+ return nowEpoch >= expiryEpoch;
75
+ }
76
+
77
+ function materializeCanonicalEvent(sessionId, event = {}) {
78
+ const strictNormalized = normalizeAgentEvent(event, { allowLegacy: false });
79
+ if (strictNormalized) {
80
+ if (strictNormalized.sessionId) {
81
+ return strictNormalized;
82
+ }
83
+ return createAgentEvent({
84
+ ...strictNormalized,
85
+ sessionId,
86
+ });
87
+ }
88
+
89
+ if (!event || typeof event !== "object" || Array.isArray(event)) {
90
+ throw new Error("appendToStream requires a valid event payload.");
91
+ }
92
+
93
+ const payload = {
94
+ ...event,
95
+ sessionId: normalizeString(event.sessionId) || sessionId,
96
+ };
97
+ return createAgentEvent(payload);
98
+ }
99
+
100
+ async function acquireLock(lockPath, {
101
+ timeoutMs = DEFAULT_LOCK_TIMEOUT_MS,
102
+ staleMs = DEFAULT_LOCK_STALE_MS,
103
+ pollMs = DEFAULT_LOCK_POLL_MS,
104
+ } = {}) {
105
+ const start = Date.now();
106
+ while (true) {
107
+ try {
108
+ await fsp.mkdir(lockPath);
109
+ return;
110
+ } catch (error) {
111
+ const code = error && typeof error === "object" ? error.code : "";
112
+ // Windows can raise EPERM/EACCES during lock contention when another writer
113
+ // is creating/removing the lock directory at the same time.
114
+ if (!(code === "EEXIST" || code === "EPERM" || code === "EACCES")) {
115
+ throw error;
116
+ }
117
+
118
+ try {
119
+ const stat = await fsp.stat(lockPath);
120
+ const ageMs = Date.now() - Number(stat.mtimeMs || 0);
121
+ if (Number.isFinite(ageMs) && ageMs > staleMs) {
122
+ await fsp.rm(lockPath, { recursive: true, force: true });
123
+ continue;
124
+ }
125
+ } catch {
126
+ // If stat/remove fails, continue waiting.
127
+ }
128
+
129
+ if (Date.now() - start >= timeoutMs) {
130
+ throw new Error("Timed out waiting for session stream lock.");
131
+ }
132
+ await sleep(pollMs);
133
+ }
134
+ }
135
+ }
136
+
137
+ async function releaseLock(lockPath) {
138
+ await fsp.rm(lockPath, { recursive: true, force: true }).catch(() => {});
139
+ }
140
+
141
+ async function readEventsFromFile(filePath) {
142
+ try {
143
+ const raw = await fsp.readFile(filePath, "utf-8");
144
+ if (!raw) {
145
+ return [];
146
+ }
147
+ const events = [];
148
+ for (const line of raw.split(/\r?\n/)) {
149
+ if (!line.trim()) {
150
+ continue;
151
+ }
152
+ try {
153
+ const parsed = JSON.parse(line);
154
+ const normalized = normalizeAgentEvent(parsed, { allowLegacy: false });
155
+ if (normalized) {
156
+ events.push(normalized);
157
+ }
158
+ } catch {
159
+ // Ignore malformed historical lines.
160
+ }
161
+ }
162
+ return events;
163
+ } catch (error) {
164
+ if (error && typeof error === "object" && error.code === "ENOENT") {
165
+ return [];
166
+ }
167
+ throw error;
168
+ }
169
+ }
170
+
171
+ async function readAllEvents(paths) {
172
+ const [rotated, current] = await Promise.all([
173
+ readEventsFromFile(paths.rotatedStreamPath),
174
+ readEventsFromFile(paths.streamPath),
175
+ ]);
176
+ return [...rotated, ...current];
177
+ }
178
+
179
+ async function rotateStreamIfNeeded(paths, maxEvents) {
180
+ const raw = await fsp.readFile(paths.streamPath, "utf-8").catch((error) => {
181
+ if (error && typeof error === "object" && error.code === "ENOENT") {
182
+ return "";
183
+ }
184
+ throw error;
185
+ });
186
+ const lines = raw
187
+ .split(/\r?\n/)
188
+ .map((line) => line.trim())
189
+ .filter(Boolean);
190
+ if (lines.length <= maxEvents) {
191
+ return;
192
+ }
193
+
194
+ const overflowCount = lines.length - maxEvents;
195
+ const overflowLines = lines.slice(0, overflowCount);
196
+ const retainedLines = lines.slice(overflowCount);
197
+
198
+ await fsp.mkdir(paths.sessionDir, { recursive: true });
199
+ if (overflowLines.length > 0) {
200
+ await fsp.appendFile(paths.rotatedStreamPath, `${overflowLines.join("\n")}\n`, "utf-8");
201
+ }
202
+ const retainedPayload = retainedLines.length > 0 ? `${retainedLines.join("\n")}\n` : "";
203
+ await fsp.writeFile(paths.streamPath, retainedPayload, "utf-8");
204
+ }
205
+
206
+ function filterBySince(events = [], since) {
207
+ const normalizedSince = normalizeString(since);
208
+ if (!normalizedSince) {
209
+ return events;
210
+ }
211
+ const sinceEpoch = Date.parse(normalizedSince);
212
+ if (!Number.isFinite(sinceEpoch)) {
213
+ return events;
214
+ }
215
+ return events.filter((event) => {
216
+ const eventEpoch = Date.parse(normalizeIsoTimestamp(event.ts, "1970-01-01T00:00:00.000Z"));
217
+ return Number.isFinite(eventEpoch) && eventEpoch >= sinceEpoch;
218
+ });
219
+ }
220
+
221
+ export async function appendToStream(
222
+ sessionId,
223
+ event,
224
+ { targetPath = process.cwd(), maxEvents = DEFAULT_MAX_STREAM_EVENTS } = {}
225
+ ) {
226
+ const paths = resolveSessionPaths(sessionId, { targetPath });
227
+ const metadata = await readSessionMetadata(paths);
228
+ if (!metadata) {
229
+ throw new Error(`Session '${paths.sessionId}' was not found.`);
230
+ }
231
+ if (isSessionExpired(metadata)) {
232
+ throw new Error(`Session '${paths.sessionId}' is expired and does not accept new events.`);
233
+ }
234
+
235
+ const canonicalEvent = materializeCanonicalEvent(paths.sessionId, event);
236
+ const nowIso = new Date().toISOString();
237
+ const normalizedMaxEvents = normalizePositiveInteger(maxEvents, DEFAULT_MAX_STREAM_EVENTS);
238
+
239
+ await acquireLock(paths.lockPath);
240
+ try {
241
+ await fsp.mkdir(paths.sessionDir, { recursive: true });
242
+ await fsp.appendFile(paths.streamPath, `${JSON.stringify(canonicalEvent)}\n`, "utf-8");
243
+ await rotateStreamIfNeeded(paths, normalizedMaxEvents);
244
+
245
+ metadata.lastInteractionAt = nowIso;
246
+ metadata.updatedAt = nowIso;
247
+ await writeSessionMetadata(paths, metadata);
248
+ } finally {
249
+ await releaseLock(paths.lockPath);
250
+ }
251
+
252
+ return canonicalEvent;
253
+ }
254
+
255
+ export async function readStream(
256
+ sessionId,
257
+ { tail = 20, since = null, targetPath = process.cwd() } = {}
258
+ ) {
259
+ const paths = resolveSessionPaths(sessionId, { targetPath });
260
+ const events = await readAllEvents(paths);
261
+ const filtered = filterBySince(events, since);
262
+ const normalizedTail = Number(tail);
263
+ if (!Number.isFinite(normalizedTail) || normalizedTail <= 0) {
264
+ return filtered;
265
+ }
266
+ return filtered.slice(-Math.floor(normalizedTail));
267
+ }
268
+
269
+ export async function* tailStream(
270
+ sessionId,
271
+ {
272
+ onEvent = null,
273
+ signal = null,
274
+ pollMs = DEFAULT_POLL_MS,
275
+ targetPath = process.cwd(),
276
+ since = null,
277
+ replayTail = 0,
278
+ } = {}
279
+ ) {
280
+ const normalizedPollMs = normalizePositiveInteger(pollMs, DEFAULT_POLL_MS);
281
+ let allEvents = await readStream(sessionId, { tail: 0, since, targetPath });
282
+ let cursor = allEvents.length;
283
+
284
+ const replayCount = Math.max(0, Math.floor(Number(replayTail) || 0));
285
+ if (replayCount > 0) {
286
+ const replayEvents = allEvents.slice(-replayCount);
287
+ for (const event of replayEvents) {
288
+ if (typeof onEvent === "function") {
289
+ await onEvent(event);
290
+ }
291
+ yield event;
292
+ }
293
+ }
294
+
295
+ while (true) {
296
+ if (signal && signal.aborted) {
297
+ return;
298
+ }
299
+
300
+ allEvents = await readStream(sessionId, { tail: 0, since, targetPath });
301
+ if (allEvents.length < cursor) {
302
+ cursor = 0;
303
+ }
304
+ if (allEvents.length > cursor) {
305
+ for (const event of allEvents.slice(cursor)) {
306
+ if (typeof onEvent === "function") {
307
+ await onEvent(event);
308
+ }
309
+ yield event;
310
+ }
311
+ cursor = allEvents.length;
312
+ }
313
+
314
+ try {
315
+ await sleep(normalizedPollMs, null, signal ? { signal } : undefined);
316
+ } catch (error) {
317
+ if (error && typeof error === "object" && error.name === "AbortError") {
318
+ return;
319
+ }
320
+ throw error;
321
+ }
322
+ }
323
+ }
324
+
325
+ export { DEFAULT_MAX_STREAM_EVENTS };