sentinelayer-cli 0.4.5 → 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 (72) hide show
  1. package/README.md +16 -18
  2. package/package.json +7 -6
  3. package/src/agents/jules/config/definition.js +13 -62
  4. package/src/agents/jules/config/system-prompt.js +8 -1
  5. package/src/agents/jules/fix-cycle.js +12 -372
  6. package/src/agents/jules/loop.js +116 -26
  7. package/src/agents/jules/pulse.js +10 -327
  8. package/src/agents/jules/stream.js +13 -12
  9. package/src/agents/jules/swarm/orchestrator.js +3 -3
  10. package/src/agents/jules/swarm/sub-agent.js +6 -3
  11. package/src/agents/jules/tools/aidenid-email.js +189 -0
  12. package/src/agents/jules/tools/auth-audit.js +1187 -45
  13. package/src/agents/jules/tools/dispatch.js +25 -12
  14. package/src/agents/jules/tools/file-edit.js +2 -180
  15. package/src/agents/jules/tools/file-read.js +2 -100
  16. package/src/agents/jules/tools/glob.js +2 -168
  17. package/src/agents/jules/tools/grep.js +2 -228
  18. package/src/agents/jules/tools/path-guards.js +2 -161
  19. package/src/agents/jules/tools/runtime-audit.js +6 -2
  20. package/src/agents/jules/tools/shell.js +2 -383
  21. package/src/agents/persona-visuals.js +64 -0
  22. package/src/agents/shared-tools/dispatch-core.js +320 -0
  23. package/src/agents/shared-tools/file-edit.js +180 -0
  24. package/src/agents/shared-tools/file-read.js +100 -0
  25. package/src/agents/shared-tools/glob.js +168 -0
  26. package/src/agents/shared-tools/grep.js +228 -0
  27. package/src/agents/shared-tools/index.js +46 -0
  28. package/src/agents/shared-tools/path-guards.js +161 -0
  29. package/src/agents/shared-tools/shell.js +383 -0
  30. package/src/ai/aidenid.js +56 -7
  31. package/src/ai/client.js +45 -0
  32. package/src/ai/proxy.js +137 -0
  33. package/src/auth/gate.js +290 -16
  34. package/src/auth/http.js +450 -39
  35. package/src/auth/service.js +262 -47
  36. package/src/auth/session-store.js +475 -21
  37. package/src/cli.js +5 -0
  38. package/src/commands/audit.js +13 -8
  39. package/src/commands/auth.js +53 -9
  40. package/src/commands/omargate.js +10 -2
  41. package/src/commands/scan.js +10 -4
  42. package/src/commands/session.js +590 -0
  43. package/src/commands/spec.js +62 -0
  44. package/src/commands/watch.js +3 -2
  45. package/src/daemon/assignment-ledger.js +196 -0
  46. package/src/daemon/error-worker.js +599 -16
  47. package/src/daemon/fix-cycle.js +384 -0
  48. package/src/daemon/ingest-refresh.js +10 -9
  49. package/src/daemon/jira-lifecycle.js +135 -0
  50. package/src/daemon/pulse.js +327 -0
  51. package/src/daemon/scope-engine.js +1068 -0
  52. package/src/events/schema.js +190 -0
  53. package/src/interactive/index.js +18 -16
  54. package/src/legacy-cli.js +606 -37
  55. package/src/prompt/generator.js +19 -1
  56. package/src/review/ai-review.js +11 -1
  57. package/src/review/local-review.js +75 -19
  58. package/src/review/omargate-interactive.js +68 -0
  59. package/src/review/omargate-orchestrator.js +404 -0
  60. package/src/review/persona-prompts.js +296 -0
  61. package/src/review/scan-modes.js +48 -0
  62. package/src/scan/generator.js +1 -1
  63. package/src/session/agent-registry.js +352 -0
  64. package/src/session/daemon.js +801 -0
  65. package/src/session/paths.js +33 -0
  66. package/src/session/runtime-bridge.js +739 -0
  67. package/src/session/store.js +388 -0
  68. package/src/session/stream.js +325 -0
  69. package/src/spec/generator.js +100 -0
  70. package/src/telemetry/session-tracker.js +148 -32
  71. package/src/telemetry/sync.js +6 -2
  72. package/src/ui/command-hints.js +13 -0
@@ -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 };