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
@@ -1,107 +1,107 @@
1
- import { spawnSync } from "node:child_process";
2
- import process from "node:process";
3
- import fs from "node:fs";
4
-
5
- function getGhCommand() {
6
- return String(process.env.SENTINELAYER_GH_BIN || "").trim() || "gh";
7
- }
8
-
9
- function normalizeRepoSlug(value) {
10
- return String(value || "").trim().replace(/\.git$/i, "");
11
- }
12
-
13
- function isValidRepoSlug(value) {
14
- return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizeRepoSlug(value));
15
- }
16
-
17
- function isValidSecretName(value) {
18
- return /^[A-Z][A-Z0-9_]{1,127}$/.test(String(value || "").trim());
19
- }
20
-
21
- function ensureGhCliAvailable(ghCommand) {
22
- const ghVersion = spawnSync(ghCommand, ["--version"], { encoding: "utf-8" });
23
- if (ghVersion.status !== 0) {
24
- throw new Error("GitHub CLI (gh) is not installed or not in PATH.");
25
- }
26
- }
27
-
28
- function detectRepoSlug(cwd) {
29
- const ghCommand = getGhCommand();
30
- const result = spawnSync(ghCommand, ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"], {
31
- cwd,
32
- encoding: "utf-8",
33
- });
34
- if (result.status === 0 && result.stdout) {
35
- return String(result.stdout).trim();
36
- }
37
- return null;
38
- }
39
-
40
- export function setupSecrets({ repoSlug, secretName, secretValue, dryRun }) {
41
- const normalizedRepo = normalizeRepoSlug(repoSlug);
42
- const ghCommand = getGhCommand();
43
-
44
- if (!isValidRepoSlug(normalizedRepo)) {
45
- return { ok: false, reason: "Invalid repo format. Use owner/repo." };
46
- }
47
- if (!isValidSecretName(secretName)) {
48
- return { ok: false, reason: `Invalid secret name: ${secretName}. Must match /^[A-Z][A-Z0-9_]{1,127}$/.` };
49
- }
50
-
51
- if (dryRun) {
52
- return {
53
- ok: true,
54
- dryRun: true,
55
- repo: normalizedRepo,
56
- secretName,
57
- instructions: [
58
- `gh secret set ${secretName} --repo ${normalizedRepo}`,
59
- `# Paste your SentinelLayer token when prompted`,
60
- `gh secret list --repo ${normalizedRepo}`,
61
- `# Verify ${secretName} appears in the list`,
62
- ],
63
- };
64
- }
65
-
66
- const secretSinkFile = String(process.env.SENTINELAYER_SECRET_SINK_FILE || "").trim();
67
- if (secretSinkFile) {
68
- try {
69
- fs.appendFileSync(secretSinkFile, `${normalizedRepo}|${secretName}|${secretValue}\n`, "utf-8");
70
- return { ok: true, repo: normalizedRepo, secretName, method: "sink-file" };
71
- } catch (error) {
72
- return { ok: false, reason: `Failed to write SENTINELAYER_SECRET_SINK_FILE: ${error instanceof Error ? error.message : String(error)}` };
73
- }
74
- }
75
-
76
- try {
77
- ensureGhCliAvailable(ghCommand);
78
- } catch (error) {
79
- return { ok: false, reason: error instanceof Error ? error.message : String(error) };
80
- }
81
-
82
- const result = spawnSync(ghCommand, ["secret", "set", secretName, "--repo", normalizedRepo], {
83
- encoding: "utf-8",
84
- input: `${secretValue}\n`,
85
- });
86
- if (result.status !== 0) {
87
- return { ok: false, reason: String(result.stderr || result.stdout || "gh secret set failed").trim() };
88
- }
89
-
90
- const verifyResult = spawnSync(ghCommand, ["secret", "list", "--repo", normalizedRepo], {
91
- encoding: "utf-8",
92
- });
93
- if (verifyResult.status !== 0) {
94
- return { ok: false, reason: String(verifyResult.stderr || verifyResult.stdout || "gh secret list failed").trim() };
95
- }
96
-
97
- const listedSecrets = String(verifyResult.stdout || "");
98
- const escapedSecretName = String(secretName || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
99
- const secretRegex = new RegExp(`(^|\\r?\\n)\\s*${escapedSecretName}(\\s|$)`, "m");
100
- if (!secretRegex.test(listedSecrets)) {
101
- return { ok: false, reason: `Secret '${secretName}' was not visible in gh secret list output after injection.` };
102
- }
103
-
104
- return { ok: true, repo: normalizedRepo, secretName, method: "gh-cli" };
105
- }
106
-
107
- export { detectRepoSlug };
1
+ import { spawnSync } from "node:child_process";
2
+ import process from "node:process";
3
+ import fs from "node:fs";
4
+
5
+ function getGhCommand() {
6
+ return String(process.env.SENTINELAYER_GH_BIN || "").trim() || "gh";
7
+ }
8
+
9
+ function normalizeRepoSlug(value) {
10
+ return String(value || "").trim().replace(/\.git$/i, "");
11
+ }
12
+
13
+ function isValidRepoSlug(value) {
14
+ return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalizeRepoSlug(value));
15
+ }
16
+
17
+ function isValidSecretName(value) {
18
+ return /^[A-Z][A-Z0-9_]{1,127}$/.test(String(value || "").trim());
19
+ }
20
+
21
+ function ensureGhCliAvailable(ghCommand) {
22
+ const ghVersion = spawnSync(ghCommand, ["--version"], { encoding: "utf-8" });
23
+ if (ghVersion.status !== 0) {
24
+ throw new Error("GitHub CLI (gh) is not installed or not in PATH.");
25
+ }
26
+ }
27
+
28
+ function detectRepoSlug(cwd) {
29
+ const ghCommand = getGhCommand();
30
+ const result = spawnSync(ghCommand, ["repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner"], {
31
+ cwd,
32
+ encoding: "utf-8",
33
+ });
34
+ if (result.status === 0 && result.stdout) {
35
+ return String(result.stdout).trim();
36
+ }
37
+ return null;
38
+ }
39
+
40
+ export function setupSecrets({ repoSlug, secretName, secretValue, dryRun }) {
41
+ const normalizedRepo = normalizeRepoSlug(repoSlug);
42
+ const ghCommand = getGhCommand();
43
+
44
+ if (!isValidRepoSlug(normalizedRepo)) {
45
+ return { ok: false, reason: "Invalid repo format. Use owner/repo." };
46
+ }
47
+ if (!isValidSecretName(secretName)) {
48
+ return { ok: false, reason: `Invalid secret name: ${secretName}. Must match /^[A-Z][A-Z0-9_]{1,127}$/.` };
49
+ }
50
+
51
+ if (dryRun) {
52
+ return {
53
+ ok: true,
54
+ dryRun: true,
55
+ repo: normalizedRepo,
56
+ secretName,
57
+ instructions: [
58
+ `gh secret set ${secretName} --repo ${normalizedRepo}`,
59
+ `# Paste your SentinelLayer token when prompted`,
60
+ `gh secret list --repo ${normalizedRepo}`,
61
+ `# Verify ${secretName} appears in the list`,
62
+ ],
63
+ };
64
+ }
65
+
66
+ const secretSinkFile = String(process.env.SENTINELAYER_SECRET_SINK_FILE || "").trim();
67
+ if (secretSinkFile) {
68
+ try {
69
+ fs.appendFileSync(secretSinkFile, `${normalizedRepo}|${secretName}|${secretValue}\n`, "utf-8");
70
+ return { ok: true, repo: normalizedRepo, secretName, method: "sink-file" };
71
+ } catch (error) {
72
+ return { ok: false, reason: `Failed to write SENTINELAYER_SECRET_SINK_FILE: ${error instanceof Error ? error.message : String(error)}` };
73
+ }
74
+ }
75
+
76
+ try {
77
+ ensureGhCliAvailable(ghCommand);
78
+ } catch (error) {
79
+ return { ok: false, reason: error instanceof Error ? error.message : String(error) };
80
+ }
81
+
82
+ const result = spawnSync(ghCommand, ["secret", "set", secretName, "--repo", normalizedRepo], {
83
+ encoding: "utf-8",
84
+ input: `${secretValue}\n`,
85
+ });
86
+ if (result.status !== 0) {
87
+ return { ok: false, reason: String(result.stderr || result.stdout || "gh secret set failed").trim() };
88
+ }
89
+
90
+ const verifyResult = spawnSync(ghCommand, ["secret", "list", "--repo", normalizedRepo], {
91
+ encoding: "utf-8",
92
+ });
93
+ if (verifyResult.status !== 0) {
94
+ return { ok: false, reason: String(verifyResult.stderr || verifyResult.stdout || "gh secret list failed").trim() };
95
+ }
96
+
97
+ const listedSecrets = String(verifyResult.stdout || "");
98
+ const escapedSecretName = String(secretName || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
99
+ const secretRegex = new RegExp(`(^|\\r?\\n)\\s*${escapedSecretName}(\\s|$)`, "m");
100
+ if (!secretRegex.test(listedSecrets)) {
101
+ return { ok: false, reason: `Secret '${secretName}' was not visible in gh secret list output after injection.` };
102
+ }
103
+
104
+ return { ok: true, repo: normalizedRepo, secretName, method: "gh-cli" };
105
+ }
106
+
107
+ export { detectRepoSlug };
@@ -0,0 +1,352 @@
1
+ import { randomBytes } 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 { STUCK_THRESHOLDS } from "../agents/jules/pulse.js";
7
+ import { createAgentEvent } from "../events/schema.js";
8
+ import { resolveSessionPaths } from "./paths.js";
9
+ import { appendToStream } from "./stream.js";
10
+
11
+ const AGENT_SNAPSHOT_SCHEMA_VERSION = "1.0.0";
12
+
13
+ const AGENT_ROLES = new Set([
14
+ "coder",
15
+ "reviewer",
16
+ "tester",
17
+ "daemon",
18
+ "observer",
19
+ "persona",
20
+ ]);
21
+
22
+ const AGENT_STATUSES = new Set([
23
+ "coding",
24
+ "reviewing",
25
+ "testing",
26
+ "idle",
27
+ "blocked",
28
+ "watching",
29
+ ]);
30
+
31
+ const LEAVE_REASONS = new Set([
32
+ "task_complete",
33
+ "error",
34
+ "timeout",
35
+ "manual",
36
+ "killed",
37
+ ]);
38
+
39
+ function normalizeString(value) {
40
+ return String(value || "").trim();
41
+ }
42
+
43
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
44
+ const normalized = normalizeString(value);
45
+ if (!normalized) {
46
+ return fallbackIso;
47
+ }
48
+ const epoch = Date.parse(normalized);
49
+ if (!Number.isFinite(epoch)) {
50
+ return fallbackIso;
51
+ }
52
+ return new Date(epoch).toISOString();
53
+ }
54
+
55
+ function normalizeRole(value) {
56
+ const normalized = normalizeString(value).toLowerCase();
57
+ if (!AGENT_ROLES.has(normalized)) {
58
+ throw new Error(`role must be one of: ${[...AGENT_ROLES].join(", ")}.`);
59
+ }
60
+ return normalized;
61
+ }
62
+
63
+ function normalizeStatus(value, fallbackValue = "idle") {
64
+ const normalized = normalizeString(value).toLowerCase();
65
+ if (!normalized) {
66
+ return fallbackValue;
67
+ }
68
+ if (!AGENT_STATUSES.has(normalized)) {
69
+ throw new Error(`status must be one of: ${[...AGENT_STATUSES].join(", ")}.`);
70
+ }
71
+ return normalized;
72
+ }
73
+
74
+ function normalizeLeaveReason(value) {
75
+ const normalized = normalizeString(value).toLowerCase();
76
+ if (!normalized) {
77
+ return "manual";
78
+ }
79
+ if (!LEAVE_REASONS.has(normalized)) {
80
+ throw new Error(`reason must be one of: ${[...LEAVE_REASONS].join(", ")}.`);
81
+ }
82
+ return normalized;
83
+ }
84
+
85
+ function sanitizePrefix(value) {
86
+ const normalized = normalizeString(value)
87
+ .toLowerCase()
88
+ .replace(/[^a-z0-9]+/g, "-")
89
+ .replace(/^-+|-+$/g, "");
90
+ if (!normalized) {
91
+ return "";
92
+ }
93
+ return normalized.slice(0, 12);
94
+ }
95
+
96
+ function deriveModelPrefix(modelName) {
97
+ const normalized = normalizeString(modelName).toLowerCase();
98
+ if (!normalized) {
99
+ return "agent";
100
+ }
101
+ if (normalized.includes("claude")) return "claude";
102
+ if (normalized.includes("codex")) return "codex";
103
+ if (normalized.includes("gpt")) return "codex";
104
+ if (normalized.includes("sonnet")) return "sonnet";
105
+ if (normalized.includes("senti") || normalized.includes("sentinel")) return "senti";
106
+
107
+ const token = normalized.split(/[\s:/_-]+/).find(Boolean) || normalized;
108
+ return sanitizePrefix(token) || "agent";
109
+ }
110
+
111
+ function normalizeAgentSnapshot(snapshot = {}, nowIso = new Date().toISOString()) {
112
+ return {
113
+ schemaVersion: AGENT_SNAPSHOT_SCHEMA_VERSION,
114
+ sessionId: normalizeString(snapshot.sessionId),
115
+ agentId: normalizeString(snapshot.agentId),
116
+ model: normalizeString(snapshot.model) || "unknown",
117
+ role: normalizeRole(snapshot.role || "observer"),
118
+ status: normalizeStatus(snapshot.status, "idle"),
119
+ detail: normalizeString(snapshot.detail) || "",
120
+ file: normalizeString(snapshot.file) || null,
121
+ joinedAt: normalizeIsoTimestamp(snapshot.joinedAt, nowIso),
122
+ lastActivityAt: normalizeIsoTimestamp(snapshot.lastActivityAt, nowIso),
123
+ leftAt: snapshot.leftAt ? normalizeIsoTimestamp(snapshot.leftAt, nowIso) : null,
124
+ leaveReason: snapshot.leaveReason ? normalizeLeaveReason(snapshot.leaveReason) : null,
125
+ active: snapshot.active !== false,
126
+ updatedAt: normalizeIsoTimestamp(snapshot.updatedAt, nowIso),
127
+ };
128
+ }
129
+
130
+ async function readAgentSnapshot(snapshotPath) {
131
+ try {
132
+ const raw = await fsp.readFile(snapshotPath, "utf-8");
133
+ const parsed = JSON.parse(raw);
134
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
135
+ return null;
136
+ }
137
+ return parsed;
138
+ } catch (error) {
139
+ if (error && typeof error === "object" && error.code === "ENOENT") {
140
+ return null;
141
+ }
142
+ throw error;
143
+ }
144
+ }
145
+
146
+ async function writeAgentSnapshot(snapshotPath, snapshot) {
147
+ await fsp.mkdir(path.dirname(snapshotPath), { recursive: true });
148
+ const tmpPath = `${snapshotPath}.${process.pid}.${Date.now()}.tmp`;
149
+ await fsp.writeFile(tmpPath, `${JSON.stringify(snapshot, null, 2)}\n`, "utf-8");
150
+ await fsp.rename(tmpPath, snapshotPath);
151
+ }
152
+
153
+ async function emitAgentEvent(sessionId, event, payload, { targetPath = process.cwd() } = {}) {
154
+ const envelope = createAgentEvent({
155
+ event,
156
+ agentId: payload.agentId,
157
+ sessionId,
158
+ payload,
159
+ });
160
+ await appendToStream(sessionId, envelope, { targetPath });
161
+ }
162
+
163
+ function buildAgentSnapshotPath(paths, agentId) {
164
+ const normalizedAgentId = normalizeString(agentId);
165
+ if (!normalizedAgentId) {
166
+ throw new Error("agentId is required.");
167
+ }
168
+ return path.join(paths.agentsDir, `${normalizedAgentId}.json`);
169
+ }
170
+
171
+ export function generateAgentId(modelName) {
172
+ const prefix = deriveModelPrefix(modelName);
173
+ const suffix = randomBytes(2).toString("hex");
174
+ return `${prefix}-${suffix}`;
175
+ }
176
+
177
+ export async function registerAgent(
178
+ sessionId,
179
+ { agentId = "", model = "", role = "observer", targetPath = process.cwd() } = {}
180
+ ) {
181
+ const paths = resolveSessionPaths(sessionId, { targetPath });
182
+ const nowIso = new Date().toISOString();
183
+ const resolvedAgentId = normalizeString(agentId) || generateAgentId(model);
184
+ const snapshotPath = buildAgentSnapshotPath(paths, resolvedAgentId);
185
+
186
+ const snapshot = normalizeAgentSnapshot(
187
+ {
188
+ sessionId: paths.sessionId,
189
+ agentId: resolvedAgentId,
190
+ model: normalizeString(model) || "unknown",
191
+ role,
192
+ status: "idle",
193
+ detail: "",
194
+ file: null,
195
+ joinedAt: nowIso,
196
+ lastActivityAt: nowIso,
197
+ leftAt: null,
198
+ leaveReason: null,
199
+ active: true,
200
+ updatedAt: nowIso,
201
+ },
202
+ nowIso
203
+ );
204
+
205
+ await writeAgentSnapshot(snapshotPath, snapshot);
206
+ await emitAgentEvent(paths.sessionId, "agent_join", {
207
+ agentId: snapshot.agentId,
208
+ model: snapshot.model,
209
+ role: snapshot.role,
210
+ status: snapshot.status,
211
+ }, { targetPath });
212
+
213
+ return {
214
+ ...snapshot,
215
+ snapshotPath,
216
+ };
217
+ }
218
+
219
+ export async function heartbeatAgent(
220
+ sessionId,
221
+ agentId,
222
+ { status = "", detail = "", file = "", targetPath = process.cwd() } = {}
223
+ ) {
224
+ const paths = resolveSessionPaths(sessionId, { targetPath });
225
+ const nowIso = new Date().toISOString();
226
+ const snapshotPath = buildAgentSnapshotPath(paths, agentId);
227
+ const existing = await readAgentSnapshot(snapshotPath);
228
+ if (!existing) {
229
+ throw new Error(`Agent '${normalizeString(agentId)}' is not registered in session '${paths.sessionId}'.`);
230
+ }
231
+
232
+ const snapshot = normalizeAgentSnapshot(
233
+ {
234
+ ...existing,
235
+ status: normalizeStatus(status, normalizeStatus(existing.status || "idle")),
236
+ detail: normalizeString(detail) || normalizeString(existing.detail),
237
+ file: normalizeString(file) || normalizeString(existing.file) || null,
238
+ lastActivityAt: nowIso,
239
+ updatedAt: nowIso,
240
+ active: true,
241
+ },
242
+ nowIso
243
+ );
244
+
245
+ await writeAgentSnapshot(snapshotPath, snapshot);
246
+ return {
247
+ ...snapshot,
248
+ snapshotPath,
249
+ };
250
+ }
251
+
252
+ export async function unregisterAgent(
253
+ sessionId,
254
+ agentId,
255
+ { reason = "manual", targetPath = process.cwd() } = {}
256
+ ) {
257
+ const paths = resolveSessionPaths(sessionId, { targetPath });
258
+ const nowIso = new Date().toISOString();
259
+ const snapshotPath = buildAgentSnapshotPath(paths, agentId);
260
+ const existing = await readAgentSnapshot(snapshotPath);
261
+ if (!existing) {
262
+ throw new Error(`Agent '${normalizeString(agentId)}' is not registered in session '${paths.sessionId}'.`);
263
+ }
264
+
265
+ const normalizedReason = normalizeLeaveReason(reason);
266
+ const snapshot = normalizeAgentSnapshot(
267
+ {
268
+ ...existing,
269
+ active: false,
270
+ leftAt: nowIso,
271
+ leaveReason: normalizedReason,
272
+ updatedAt: nowIso,
273
+ },
274
+ nowIso
275
+ );
276
+
277
+ await writeAgentSnapshot(snapshotPath, snapshot);
278
+ await emitAgentEvent(paths.sessionId, "agent_leave", {
279
+ agentId: snapshot.agentId,
280
+ reason: normalizedReason,
281
+ role: snapshot.role,
282
+ model: snapshot.model,
283
+ }, { targetPath });
284
+
285
+ return {
286
+ ...snapshot,
287
+ snapshotPath,
288
+ };
289
+ }
290
+
291
+ export async function listAgents(
292
+ sessionId,
293
+ { targetPath = process.cwd(), includeInactive = true } = {}
294
+ ) {
295
+ const paths = resolveSessionPaths(sessionId, { targetPath });
296
+ let entries = [];
297
+ try {
298
+ entries = await fsp.readdir(paths.agentsDir, { withFileTypes: true });
299
+ } catch (error) {
300
+ if (error && typeof error === "object" && error.code === "ENOENT") {
301
+ return [];
302
+ }
303
+ throw error;
304
+ }
305
+
306
+ const agents = [];
307
+ for (const entry of entries) {
308
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
309
+ const snapshotPath = path.join(paths.agentsDir, entry.name);
310
+ const raw = await readAgentSnapshot(snapshotPath);
311
+ if (!raw) continue;
312
+ const normalized = normalizeAgentSnapshot(raw);
313
+ if (normalized.sessionId !== paths.sessionId) continue;
314
+ if (!includeInactive && normalized.active === false) continue;
315
+ agents.push({
316
+ ...normalized,
317
+ snapshotPath,
318
+ });
319
+ }
320
+
321
+ agents.sort((left, right) => right.lastActivityAt.localeCompare(left.lastActivityAt));
322
+ return agents;
323
+ }
324
+
325
+ export function detectStaleAgents(
326
+ agents,
327
+ {
328
+ idleThresholdSeconds = Number(STUCK_THRESHOLDS?.noToolCallSeconds || 90),
329
+ nowIso = new Date().toISOString(),
330
+ } = {}
331
+ ) {
332
+ const normalizedThreshold = Math.max(1, Math.floor(Number(idleThresholdSeconds || 90)));
333
+ const nowEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
334
+ if (!Number.isFinite(nowEpoch)) {
335
+ return [];
336
+ }
337
+ const list = Array.isArray(agents) ? agents : [];
338
+ return list
339
+ .map((agent) => normalizeAgentSnapshot(agent, nowIso))
340
+ .filter((agent) => agent.active !== false)
341
+ .map((agent) => {
342
+ const activityEpoch = Date.parse(normalizeIsoTimestamp(agent.lastActivityAt, agent.joinedAt || nowIso));
343
+ const idleSeconds = Number.isFinite(activityEpoch)
344
+ ? Math.max(0, Math.floor((nowEpoch - activityEpoch) / 1000))
345
+ : normalizedThreshold + 1;
346
+ return {
347
+ ...agent,
348
+ idleSeconds,
349
+ };
350
+ })
351
+ .filter((agent) => agent.idleSeconds >= normalizedThreshold);
352
+ }