sentinelayer-cli 0.1.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 (124) hide show
  1. package/README.md +996 -0
  2. package/bin/create-sentinelayer.js +5 -0
  3. package/bin/sentinelayer-cli.js +5 -0
  4. package/bin/sl.js +5 -0
  5. package/package.json +54 -0
  6. package/src/agents/jules/config/definition.js +209 -0
  7. package/src/agents/jules/config/system-prompt.js +175 -0
  8. package/src/agents/jules/error-intake.js +51 -0
  9. package/src/agents/jules/fix-cycle.js +377 -0
  10. package/src/agents/jules/loop.js +367 -0
  11. package/src/agents/jules/pulse.js +319 -0
  12. package/src/agents/jules/stream.js +186 -0
  13. package/src/agents/jules/swarm/file-scanner.js +74 -0
  14. package/src/agents/jules/swarm/index.js +11 -0
  15. package/src/agents/jules/swarm/orchestrator.js +362 -0
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -0
  17. package/src/agents/jules/swarm/sub-agent.js +308 -0
  18. package/src/agents/jules/tools/auth-audit.js +222 -0
  19. package/src/agents/jules/tools/dispatch.js +327 -0
  20. package/src/agents/jules/tools/file-edit.js +180 -0
  21. package/src/agents/jules/tools/file-read.js +100 -0
  22. package/src/agents/jules/tools/frontend-analyze.js +570 -0
  23. package/src/agents/jules/tools/glob.js +168 -0
  24. package/src/agents/jules/tools/grep.js +228 -0
  25. package/src/agents/jules/tools/index.js +29 -0
  26. package/src/agents/jules/tools/path-guards.js +161 -0
  27. package/src/agents/jules/tools/runtime-audit.js +409 -0
  28. package/src/agents/jules/tools/shell.js +383 -0
  29. package/src/ai/aidenid.js +945 -0
  30. package/src/ai/client.js +508 -0
  31. package/src/ai/domain-target-store.js +268 -0
  32. package/src/ai/identity-store.js +270 -0
  33. package/src/ai/site-store.js +145 -0
  34. package/src/audit/agents/architecture.js +180 -0
  35. package/src/audit/agents/compliance.js +179 -0
  36. package/src/audit/agents/documentation.js +165 -0
  37. package/src/audit/agents/performance.js +145 -0
  38. package/src/audit/agents/security.js +215 -0
  39. package/src/audit/agents/testing.js +172 -0
  40. package/src/audit/orchestrator.js +557 -0
  41. package/src/audit/package.js +204 -0
  42. package/src/audit/registry.js +284 -0
  43. package/src/audit/replay.js +103 -0
  44. package/src/auth/http.js +113 -0
  45. package/src/auth/service.js +848 -0
  46. package/src/auth/session-store.js +345 -0
  47. package/src/cli.js +244 -0
  48. package/src/commands/ai/identity-lifecycle.js +1337 -0
  49. package/src/commands/ai/provision-governance.js +1246 -0
  50. package/src/commands/ai/shared.js +147 -0
  51. package/src/commands/ai.js +11 -0
  52. package/src/commands/apply.js +19 -0
  53. package/src/commands/audit.js +1147 -0
  54. package/src/commands/auth.js +366 -0
  55. package/src/commands/chat.js +191 -0
  56. package/src/commands/config.js +184 -0
  57. package/src/commands/cost.js +311 -0
  58. package/src/commands/daemon/core.js +850 -0
  59. package/src/commands/daemon/extended.js +1048 -0
  60. package/src/commands/daemon/shared.js +213 -0
  61. package/src/commands/daemon.js +11 -0
  62. package/src/commands/guide.js +174 -0
  63. package/src/commands/ingest.js +58 -0
  64. package/src/commands/init.js +55 -0
  65. package/src/commands/legacy-args.js +30 -0
  66. package/src/commands/mcp.js +404 -0
  67. package/src/commands/omargate.js +21 -0
  68. package/src/commands/persona.js +27 -0
  69. package/src/commands/plugin.js +260 -0
  70. package/src/commands/policy.js +132 -0
  71. package/src/commands/prompt.js +238 -0
  72. package/src/commands/review.js +704 -0
  73. package/src/commands/scan.js +788 -0
  74. package/src/commands/spec.js +716 -0
  75. package/src/commands/swarm.js +651 -0
  76. package/src/commands/telemetry.js +202 -0
  77. package/src/commands/watch.js +510 -0
  78. package/src/config/agent-dictionary.js +182 -0
  79. package/src/config/io.js +56 -0
  80. package/src/config/paths.js +18 -0
  81. package/src/config/schema.js +55 -0
  82. package/src/config/service.js +184 -0
  83. package/src/cost/budget.js +235 -0
  84. package/src/cost/history.js +188 -0
  85. package/src/cost/tracker.js +171 -0
  86. package/src/daemon/artifact-lineage.js +534 -0
  87. package/src/daemon/assignment-ledger.js +770 -0
  88. package/src/daemon/ast-parser-layer.js +258 -0
  89. package/src/daemon/budget-governor.js +633 -0
  90. package/src/daemon/callgraph-overlay.js +646 -0
  91. package/src/daemon/error-worker.js +626 -0
  92. package/src/daemon/hybrid-mapper.js +929 -0
  93. package/src/daemon/jira-lifecycle.js +632 -0
  94. package/src/daemon/operator-control.js +657 -0
  95. package/src/daemon/reliability-lane.js +471 -0
  96. package/src/daemon/watchdog.js +971 -0
  97. package/src/guide/generator.js +316 -0
  98. package/src/ingest/engine.js +918 -0
  99. package/src/legacy-cli.js +2435 -0
  100. package/src/mcp/registry.js +695 -0
  101. package/src/memory/blackboard.js +301 -0
  102. package/src/memory/retrieval.js +581 -0
  103. package/src/plugin/manifest.js +553 -0
  104. package/src/policy/packs.js +144 -0
  105. package/src/prompt/generator.js +106 -0
  106. package/src/review/ai-review.js +669 -0
  107. package/src/review/local-review.js +1284 -0
  108. package/src/review/replay.js +235 -0
  109. package/src/review/report.js +664 -0
  110. package/src/review/spec-binding.js +487 -0
  111. package/src/scan/generator.js +351 -0
  112. package/src/spec/generator.js +519 -0
  113. package/src/spec/regenerate.js +237 -0
  114. package/src/spec/templates.js +91 -0
  115. package/src/swarm/dashboard.js +247 -0
  116. package/src/swarm/factory.js +363 -0
  117. package/src/swarm/pentest.js +934 -0
  118. package/src/swarm/registry.js +419 -0
  119. package/src/swarm/report.js +158 -0
  120. package/src/swarm/runtime.js +576 -0
  121. package/src/swarm/scenario-dsl.js +272 -0
  122. package/src/telemetry/ledger.js +302 -0
  123. package/src/ui/markdown.js +220 -0
  124. package/src/ui/progress.js +100 -0
@@ -0,0 +1,366 @@
1
+ import process from "node:process";
2
+
3
+ import pc from "picocolors";
4
+
5
+ import { SentinelayerApiError } from "../auth/http.js";
6
+ import {
7
+ DEFAULT_API_TOKEN_TTL_DAYS,
8
+ DEFAULT_AUTH_TIMEOUT_MS,
9
+ getAuthStatus,
10
+ listStoredAuthSessions,
11
+ loginAndPersistSession,
12
+ logoutSession,
13
+ revokeAuthToken,
14
+ } from "../auth/service.js";
15
+ import { resolveCredentialsFilePath } from "../auth/session-store.js";
16
+ import { CLI_VERSION } from "../legacy-cli.js";
17
+
18
+ function shouldEmitJson(options, command) {
19
+ const local = Boolean(options && options.json);
20
+ const globalFromCommand =
21
+ command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
22
+ return local || globalFromCommand;
23
+ }
24
+
25
+ function parsePositiveNumber(rawValue, field, fallbackValue) {
26
+ if (rawValue === undefined || rawValue === null || String(rawValue).trim() === "") {
27
+ return fallbackValue;
28
+ }
29
+ const normalized = Number(rawValue);
30
+ if (!Number.isFinite(normalized) || normalized <= 0) {
31
+ throw new Error(`${field} must be a positive number.`);
32
+ }
33
+ return normalized;
34
+ }
35
+
36
+ function normalizeUser(user = {}) {
37
+ return {
38
+ id: String(user.id || "").trim(),
39
+ githubUsername: String(user.githubUsername || user.github_username || "").trim(),
40
+ email: String(user.email || "").trim(),
41
+ avatarUrl: String(user.avatarUrl || user.avatar_url || "").trim(),
42
+ isAdmin: Boolean(user.isAdmin || user.is_admin),
43
+ };
44
+ }
45
+
46
+ function renderUserSummary(user = {}) {
47
+ const normalized = normalizeUser(user);
48
+ const identity = normalized.githubUsername || normalized.email || normalized.id || "unknown";
49
+ return `${identity}${normalized.isAdmin ? " (admin)" : ""}`;
50
+ }
51
+
52
+ function formatApiError(error) {
53
+ if (!(error instanceof SentinelayerApiError)) {
54
+ return error instanceof Error ? error.message : String(error || "Unknown error");
55
+ }
56
+ const requestId = error.requestId ? ` request_id=${error.requestId}` : "";
57
+ return `${error.message} [${error.code}] status=${error.status}${requestId}`;
58
+ }
59
+
60
+ function printAuthHint() {
61
+ console.log(pc.gray("Run `sl auth login` to create a persistent CLI session."));
62
+ }
63
+
64
+ export function registerAuthCommand(program) {
65
+ const auth = program
66
+ .command("auth")
67
+ .description("Manage Sentinelayer CLI authentication and persistent sessions");
68
+
69
+ auth
70
+ .command("login")
71
+ .description("Authenticate in browser and persist a long-lived API token")
72
+ .option("--api-url <url>", "Override Sentinelayer API base URL")
73
+ .option("--skip-browser-open", "Do not auto-open browser; print authorize URL instead")
74
+ .option(
75
+ "--timeout-ms <ms>",
76
+ "Authentication timeout in milliseconds",
77
+ String(DEFAULT_AUTH_TIMEOUT_MS)
78
+ )
79
+ .option("--token-label <label>", "Label to apply to the issued API token")
80
+ .option(
81
+ "--token-ttl-days <days>",
82
+ "Issued API token lifetime in days",
83
+ String(DEFAULT_API_TOKEN_TTL_DAYS)
84
+ )
85
+ .option("--json", "Emit machine-readable output")
86
+ .action(async (options, command) => {
87
+ const timeoutMs = parsePositiveNumber(options.timeoutMs, "timeoutMs", DEFAULT_AUTH_TIMEOUT_MS);
88
+ const tokenTtlDays = parsePositiveNumber(
89
+ options.tokenTtlDays,
90
+ "tokenTtlDays",
91
+ DEFAULT_API_TOKEN_TTL_DAYS
92
+ );
93
+
94
+ let result;
95
+ try {
96
+ result = await loginAndPersistSession({
97
+ cwd: process.cwd(),
98
+ env: process.env,
99
+ explicitApiUrl: options.apiUrl,
100
+ skipBrowserOpen: Boolean(options.skipBrowserOpen),
101
+ timeoutMs,
102
+ tokenLabel: options.tokenLabel,
103
+ tokenTtlDays,
104
+ cliVersion: CLI_VERSION,
105
+ });
106
+ } catch (error) {
107
+ throw new Error(formatApiError(error));
108
+ }
109
+
110
+ const payload = {
111
+ command: "auth login",
112
+ authenticated: true,
113
+ ...result,
114
+ };
115
+
116
+ if (shouldEmitJson(options, command)) {
117
+ console.log(JSON.stringify(payload, null, 2));
118
+ return;
119
+ }
120
+
121
+ console.log(pc.bold("Authentication successful"));
122
+ console.log(pc.gray(`API: ${result.apiUrl}`));
123
+ console.log(pc.gray(`User: ${renderUserSummary(result.user)}`));
124
+ console.log(pc.gray(`Storage: ${result.storage}`));
125
+ if (result.tokenExpiresAt) {
126
+ console.log(pc.gray(`Token expiry: ${result.tokenExpiresAt}`));
127
+ }
128
+ if (result.filePath) {
129
+ console.log(pc.gray(`Session metadata: ${result.filePath}`));
130
+ }
131
+ if (!result.browserOpened && result.authorizeUrl) {
132
+ console.log(pc.yellow("Open this URL to approve sign-in:"));
133
+ console.log(result.authorizeUrl);
134
+ }
135
+ });
136
+
137
+ auth
138
+ .command("status")
139
+ .description("Show current authentication/session status")
140
+ .option("--api-url <url>", "Override Sentinelayer API base URL")
141
+ .option("--offline", "Skip remote token validation (`/auth/me`)")
142
+ .option("--no-auto-rotate", "Disable near-expiry auto-rotation for this command")
143
+ .option("--json", "Emit machine-readable output")
144
+ .action(async (options, command) => {
145
+ let status;
146
+ try {
147
+ status = await getAuthStatus({
148
+ cwd: process.cwd(),
149
+ env: process.env,
150
+ explicitApiUrl: options.apiUrl,
151
+ checkRemote: !options.offline,
152
+ autoRotate: Boolean(options.autoRotate),
153
+ });
154
+ } catch (error) {
155
+ throw new Error(formatApiError(error));
156
+ }
157
+
158
+ const payload = {
159
+ command: "auth status",
160
+ ...status,
161
+ defaultCredentialsPath: resolveCredentialsFilePath(),
162
+ };
163
+
164
+ if (shouldEmitJson(options, command)) {
165
+ console.log(JSON.stringify(payload, null, 2));
166
+ return;
167
+ }
168
+
169
+ console.log(pc.bold("Authentication status"));
170
+ console.log(pc.gray(`API: ${status.apiUrl}`));
171
+ if (!status.source) {
172
+ console.log(pc.yellow("No active session token found."));
173
+ printAuthHint();
174
+ return;
175
+ }
176
+
177
+ console.log(pc.gray(`Token source: ${status.source}`));
178
+ if (status.source === "session") {
179
+ console.log(pc.gray(`Session storage: ${status.storage || "unknown"}`));
180
+ if (status.filePath) {
181
+ console.log(pc.gray(`Session metadata: ${status.filePath}`));
182
+ }
183
+ }
184
+ if (status.tokenExpiresAt) {
185
+ console.log(pc.gray(`Token expiry: ${status.tokenExpiresAt}`));
186
+ }
187
+ if (status.rotated) {
188
+ console.log(pc.yellow("Token was rotated because it was close to expiry."));
189
+ }
190
+
191
+ if (status.authenticated) {
192
+ const displayUser = status.remoteUser || status.user || {};
193
+ console.log(pc.green(`Authenticated as ${renderUserSummary(displayUser)}`));
194
+ return;
195
+ }
196
+
197
+ if (status.remoteError) {
198
+ console.log(pc.red(`Remote validation failed: ${status.remoteError.message}`));
199
+ console.log(
200
+ pc.gray(
201
+ `Error code: ${status.remoteError.code} status=${status.remoteError.status}${
202
+ status.remoteError.requestId ? ` request_id=${status.remoteError.requestId}` : ""
203
+ }`
204
+ )
205
+ );
206
+ } else {
207
+ console.log(pc.yellow("Remote validation was skipped (`--offline`)."));
208
+ }
209
+ printAuthHint();
210
+ });
211
+
212
+ auth
213
+ .command("sessions")
214
+ .alias("list")
215
+ .description("List persisted local session metadata for resume and auditability")
216
+ .option("--api-url <url>", "Override Sentinelayer API base URL")
217
+ .option("--json", "Emit machine-readable output")
218
+ .action(async (options, command) => {
219
+ let result;
220
+ try {
221
+ result = await listStoredAuthSessions({
222
+ cwd: process.cwd(),
223
+ env: process.env,
224
+ explicitApiUrl: options.apiUrl,
225
+ });
226
+ } catch (error) {
227
+ throw new Error(formatApiError(error));
228
+ }
229
+
230
+ const payload = {
231
+ command: "auth sessions",
232
+ ...result,
233
+ defaultCredentialsPath: resolveCredentialsFilePath(),
234
+ };
235
+
236
+ if (shouldEmitJson(options, command)) {
237
+ console.log(JSON.stringify(payload, null, 2));
238
+ return;
239
+ }
240
+
241
+ console.log(pc.bold("Stored sessions"));
242
+ console.log(pc.gray(`API: ${result.apiUrl}`));
243
+ if (!result.sessions.length) {
244
+ console.log(pc.yellow("No persisted sessions found."));
245
+ printAuthHint();
246
+ return;
247
+ }
248
+
249
+ for (const session of result.sessions) {
250
+ console.log(
251
+ `${renderUserSummary(session.user)} | source=${session.source} | storage=${session.storage || "unknown"}`
252
+ );
253
+ if (session.tokenId) {
254
+ console.log(pc.gray(` token_id: ${session.tokenId}`));
255
+ }
256
+ if (session.tokenExpiresAt) {
257
+ console.log(pc.gray(` expires_at: ${session.tokenExpiresAt}`));
258
+ }
259
+ if (session.updatedAt) {
260
+ console.log(pc.gray(` updated_at: ${session.updatedAt}`));
261
+ }
262
+ if (session.filePath) {
263
+ console.log(pc.gray(` metadata: ${session.filePath}`));
264
+ }
265
+ }
266
+ });
267
+
268
+ auth
269
+ .command("revoke")
270
+ .description("Revoke a remote API token and clear matching local session metadata")
271
+ .option("--api-url <url>", "Override Sentinelayer API base URL")
272
+ .option("--token-id <id>", "API token id to revoke (defaults to active session token id)")
273
+ .option("--json", "Emit machine-readable output")
274
+ .action(async (options, command) => {
275
+ let result;
276
+ try {
277
+ result = await revokeAuthToken({
278
+ cwd: process.cwd(),
279
+ env: process.env,
280
+ explicitApiUrl: options.apiUrl,
281
+ tokenId: options.tokenId,
282
+ });
283
+ } catch (error) {
284
+ throw new Error(formatApiError(error));
285
+ }
286
+
287
+ const payload = {
288
+ command: "auth revoke",
289
+ ...result,
290
+ };
291
+
292
+ if (shouldEmitJson(options, command)) {
293
+ console.log(JSON.stringify(payload, null, 2));
294
+ return;
295
+ }
296
+
297
+ console.log(pc.green(`Revoked token: ${result.tokenId}`));
298
+ console.log(pc.gray(`API: ${result.apiUrl}`));
299
+ if (result.matchedStoredSession) {
300
+ console.log(
301
+ pc.gray(
302
+ result.clearedLocal
303
+ ? "Matching local session metadata was cleared."
304
+ : "Matching local session metadata was detected but not cleared."
305
+ )
306
+ );
307
+ } else {
308
+ console.log(pc.gray("No local session metadata matched the revoked token id."));
309
+ }
310
+ if (result.filePath) {
311
+ console.log(pc.gray(`Session metadata path: ${result.filePath}`));
312
+ }
313
+ });
314
+
315
+ auth
316
+ .command("logout")
317
+ .description("Clear local session and optionally revoke remote API token")
318
+ .option("--api-url <url>", "Override Sentinelayer API base URL")
319
+ .option("--local-only", "Clear local session only (skip remote revoke)")
320
+ .option("--json", "Emit machine-readable output")
321
+ .action(async (options, command) => {
322
+ let result;
323
+ try {
324
+ result = await logoutSession({
325
+ cwd: process.cwd(),
326
+ env: process.env,
327
+ explicitApiUrl: options.apiUrl,
328
+ revokeRemote: !options.localOnly,
329
+ });
330
+ } catch (error) {
331
+ throw new Error(formatApiError(error));
332
+ }
333
+
334
+ const payload = {
335
+ command: "auth logout",
336
+ ...result,
337
+ };
338
+
339
+ if (shouldEmitJson(options, command)) {
340
+ console.log(JSON.stringify(payload, null, 2));
341
+ return;
342
+ }
343
+
344
+ if (!result.hadStoredSession) {
345
+ console.log(pc.yellow("No stored session was found."));
346
+ if (result.apiUrl) {
347
+ console.log(pc.gray(`API: ${result.apiUrl}`));
348
+ }
349
+ return;
350
+ }
351
+
352
+ console.log(pc.green("Local session cleared."));
353
+ if (!options.localOnly) {
354
+ console.log(
355
+ pc.gray(
356
+ result.revokedRemote
357
+ ? "Remote API token revoked."
358
+ : "Remote API token revoke skipped or failed."
359
+ )
360
+ );
361
+ }
362
+ if (result.filePath) {
363
+ console.log(pc.gray(`Session metadata path: ${result.filePath}`));
364
+ }
365
+ });
366
+ }
@@ -0,0 +1,191 @@
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+
5
+ import pc from "picocolors";
6
+
7
+ import {
8
+ createMultiProviderApiClient,
9
+ resolveModel,
10
+ resolveProvider,
11
+ } from "../ai/client.js";
12
+ import { resolveOutputRoot } from "../config/service.js";
13
+
14
+ function shouldEmitJson(options, command) {
15
+ const local = Boolean(options && options.json);
16
+ const globalFromCommand =
17
+ command && command.optsWithGlobals ? Boolean(command.optsWithGlobals().json) : false;
18
+ return local || globalFromCommand;
19
+ }
20
+
21
+ function createSessionId() {
22
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\..+/, "").replace("T", "-");
23
+ const random = Math.random().toString(36).slice(2, 8);
24
+ return `${stamp}-${random}`;
25
+ }
26
+
27
+ function estimateTokens(text) {
28
+ const normalized = String(text || "");
29
+ if (!normalized) {
30
+ return 0;
31
+ }
32
+ return Math.max(1, Math.ceil(normalized.length / 4));
33
+ }
34
+
35
+ async function readPromptFromStdin() {
36
+ if (process.stdin.isTTY) {
37
+ return "";
38
+ }
39
+ return new Promise((resolve, reject) => {
40
+ let buffer = "";
41
+ process.stdin.setEncoding("utf-8");
42
+ process.stdin.on("data", (chunk) => {
43
+ buffer += String(chunk || "");
44
+ });
45
+ process.stdin.on("error", reject);
46
+ process.stdin.on("end", () => resolve(buffer.trim()));
47
+ });
48
+ }
49
+
50
+ async function appendTranscriptEntries({ transcriptPath, entries } = {}) {
51
+ await fsp.mkdir(path.dirname(transcriptPath), { recursive: true });
52
+ const rows = entries.map((entry) => JSON.stringify(entry)).join("\n");
53
+ await fsp.appendFile(transcriptPath, `${rows}\n`, "utf-8");
54
+ }
55
+
56
+ export function registerChatCommand(program) {
57
+ const chat = program
58
+ .command("chat")
59
+ .description("Low-latency chat command surface for guided AI interaction");
60
+
61
+ chat
62
+ .command("ask")
63
+ .description("Send one prompt and stream/store the response")
64
+ .option("--prompt <text>", "Prompt text. If omitted, reads from STDIN when piped.")
65
+ .option("--provider <provider>", "Provider override (openai|anthropic|google)")
66
+ .option("--model <model>", "Model override")
67
+ .option("--api-key <key>", "Provider API key override")
68
+ .option("--path <path>", "Workspace path for output/config resolution", ".")
69
+ .option("--output-dir <path>", "Optional artifact output root override")
70
+ .option("--session-id <id>", "Optional existing session id (append mode)")
71
+ .option("--dry-run", "Skip network call and emit deterministic simulated response")
72
+ .option("--no-stream", "Disable streaming output")
73
+ .option("--json", "Emit machine-readable output")
74
+ .action(async (options, command) => {
75
+ const emitJson = shouldEmitJson(options, command);
76
+ const promptFromFlag = String(options.prompt || "").trim();
77
+ const promptFromStdin = promptFromFlag ? "" : await readPromptFromStdin();
78
+ const prompt = String(promptFromFlag || promptFromStdin).trim();
79
+ if (!prompt) {
80
+ throw new Error("Prompt is required. Use --prompt or pipe text to STDIN.");
81
+ }
82
+
83
+ const targetPath = path.resolve(process.cwd(), String(options.path || "."));
84
+ const outputRoot = await resolveOutputRoot({
85
+ cwd: targetPath,
86
+ outputDirOverride: options.outputDir,
87
+ env: process.env,
88
+ });
89
+ const sessionId = String(options.sessionId || "").trim() || createSessionId();
90
+ const transcriptPath = path.join(outputRoot, "chat", "sessions", `${sessionId}.jsonl`);
91
+
92
+ const provider = resolveProvider({
93
+ provider: options.provider,
94
+ env: process.env,
95
+ });
96
+ const model = resolveModel({
97
+ provider,
98
+ model: options.model,
99
+ });
100
+
101
+ const startedAt = Date.now();
102
+ let responseText = "";
103
+
104
+ if (options.dryRun) {
105
+ responseText = `DRY_RUN_RESPONSE: ${prompt.slice(0, 240)}`;
106
+ } else {
107
+ const streamEnabled = Boolean(options.stream);
108
+ let streamedText = "";
109
+ const client = createMultiProviderApiClient();
110
+ const invocation = await client.invoke({
111
+ provider,
112
+ model,
113
+ prompt,
114
+ apiKey: options.apiKey,
115
+ stream: streamEnabled,
116
+ env: process.env,
117
+ onChunk: streamEnabled
118
+ ? (chunk) => {
119
+ streamedText += chunk;
120
+ if (!emitJson) {
121
+ process.stdout.write(chunk);
122
+ }
123
+ }
124
+ : undefined,
125
+ });
126
+
127
+ responseText = streamEnabled ? streamedText || invocation.text : invocation.text;
128
+ if (streamEnabled && !emitJson) {
129
+ process.stdout.write("\n");
130
+ }
131
+ }
132
+
133
+ const durationMs = Date.now() - startedAt;
134
+ const generatedAt = new Date().toISOString();
135
+ const inputTokens = estimateTokens(prompt);
136
+ const outputTokens = estimateTokens(responseText);
137
+
138
+ await appendTranscriptEntries({
139
+ transcriptPath,
140
+ entries: [
141
+ {
142
+ timestamp: generatedAt,
143
+ role: "user",
144
+ provider,
145
+ model,
146
+ session_id: sessionId,
147
+ content: prompt,
148
+ },
149
+ {
150
+ timestamp: generatedAt,
151
+ role: "assistant",
152
+ provider,
153
+ model,
154
+ session_id: sessionId,
155
+ dry_run: Boolean(options.dryRun),
156
+ content: responseText,
157
+ },
158
+ ],
159
+ });
160
+
161
+ const payload = {
162
+ command: "chat ask",
163
+ sessionId,
164
+ provider,
165
+ model,
166
+ dryRun: Boolean(options.dryRun),
167
+ streamed: Boolean(options.stream),
168
+ transcriptPath,
169
+ prompt,
170
+ response: responseText,
171
+ usage: {
172
+ inputTokens,
173
+ outputTokens,
174
+ totalTokens: inputTokens + outputTokens,
175
+ durationMs,
176
+ },
177
+ };
178
+
179
+ if (emitJson) {
180
+ console.log(JSON.stringify(payload, null, 2));
181
+ return;
182
+ }
183
+
184
+ if (!options.stream || options.dryRun) {
185
+ console.log(responseText);
186
+ }
187
+ console.log(pc.gray(`session: ${sessionId}`));
188
+ console.log(pc.gray(`transcript: ${transcriptPath}`));
189
+ console.log(pc.gray(`usage: input=${inputTokens} output=${outputTokens} duration_ms=${durationMs}`));
190
+ });
191
+ }