@codelia/cli 0.1.85 → 0.1.89

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.
package/dist/index.js CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ CLI_VERSION,
3
+ resolveLoadedCliPackageRoot
4
+ } from "./chunk-3YQPBHM7.js";
5
+
1
6
  // src/basic-options.ts
2
7
  var TOP_LEVEL_HELP_TEXT = [
3
8
  "usage: codelia [options] [-- <tui-options>]",
@@ -8,11 +13,15 @@ var TOP_LEVEL_HELP_TEXT = [
8
13
  " -p, --prompt <text> Run one headless prompt and exit",
9
14
  "",
10
15
  "Commands:",
16
+ " auth authorize-keychain Authorize this build to access macOS Keychain items",
11
17
  " mcp ... Manage MCP servers and auth",
12
18
  " session ... List, pin, archive, or clean up session run logs",
19
+ " update [--check] Check for a newer release and install it",
13
20
  "",
14
21
  "Runtime options:",
15
- " --approval-mode <minimal|trusted|full-access>",
22
+ " --sandbox-mode <readonly|workspace-write|full-access>",
23
+ " --approval-mode <minimal|trusted|full-access> (legacy)",
24
+ " trusted retains project allow rules. To disable OS isolation, use --sandbox-mode full-access.",
16
25
  "",
17
26
  "TUI options (passed through):",
18
27
  " -r, --resume [session_id]",
@@ -22,7 +31,9 @@ var TOP_LEVEL_HELP_TEXT = [
22
31
  " --initial-user-message <text>",
23
32
  " --tui-mode <auto|inline|alternate>",
24
33
  " --debug-perf[=true|false]",
25
- " --approval-mode <minimal|trusted|full-access>"
34
+ " --sandbox-mode <readonly|workspace-write|full-access>",
35
+ "",
36
+ "In the TUI, use /auto-approve [status|off] to configure Auto approve."
26
37
  ].join("\n");
27
38
  var isHelpFlag = (value) => value === "-h" || value === "--help" || value === "help";
28
39
  var isVersionFlag = (value) => value === "-V" || value === "-v" || value === "--version" || value === "version";
@@ -42,7 +53,9 @@ var hasPromptFlag = (args2) => {
42
53
  return false;
43
54
  };
44
55
  var resolveTopLevelAction = (args2) => {
56
+ if (args2[0] === "auth") return "auth";
45
57
  if (args2[0] === "session") return "session";
58
+ if (args2[0] === "update") return "update";
46
59
  if (args2[0] === "mcp") {
47
60
  return "mcp";
48
61
  }
@@ -71,33 +84,43 @@ var resolvePromptText = (args2) => {
71
84
  }
72
85
  return void 0;
73
86
  };
74
- var resolvePromptModeApproval = (args2) => {
87
+ var resolveRuntimeMode = (args2, flag, values) => {
75
88
  for (let i = 0; i < args2.length; i += 1) {
76
89
  const current = args2[i];
77
90
  if (current === "--") {
78
91
  break;
79
92
  }
80
- if (current === "--approval-mode") {
81
- const next = args2[i + 1];
82
- if (!next || next.trim().length === 0) {
83
- throw new Error(
84
- "--approval-mode requires a value (minimal|trusted|full-access)"
85
- );
86
- }
87
- return next.trim();
88
- }
89
- if (current.startsWith("--approval-mode=")) {
90
- const value = current.slice("--approval-mode=".length).trim();
91
- if (value.length === 0) {
92
- throw new Error(
93
- "--approval-mode requires a value (minimal|trusted|full-access)"
94
- );
95
- }
96
- return value;
93
+ if (current === "-p" || current === "--prompt") {
94
+ i++;
95
+ continue;
97
96
  }
97
+ const value = current === flag ? (args2[i + 1] ?? "").trim() : current.startsWith(`${flag}=`) ? current.slice(flag.length + 1).trim() : void 0;
98
+ if (value === void 0) continue;
99
+ if (!value) throw new Error(`${flag} requires a value (${values})`);
100
+ if (!values.split("|").includes(value))
101
+ throw new Error(`Invalid ${flag} (expected ${values})`);
102
+ return value;
98
103
  }
99
104
  return void 0;
100
105
  };
106
+ var resolvePromptModeApproval = (args2) => resolveRuntimeMode(args2, "--approval-mode", "minimal|trusted|full-access");
107
+ var resolvePromptModeSandbox = (args2) => resolveRuntimeMode(
108
+ args2,
109
+ "--sandbox-mode",
110
+ "readonly|workspace-write|full-access"
111
+ );
112
+ var hasHarborShellApprovalFlag = (args2) => {
113
+ for (let index = 0; index < args2.length; index++) {
114
+ const arg = args2[index];
115
+ if (arg === "--") break;
116
+ if (["-p", "--prompt", "--sandbox-mode", "--approval-mode"].includes(arg)) {
117
+ index++;
118
+ continue;
119
+ }
120
+ if (arg === "--harbor-shell-approval") return true;
121
+ }
122
+ return false;
123
+ };
101
124
  var validatePromptText = (value) => {
102
125
  const text = value?.trim() ?? "";
103
126
  if (text.length === 0) {
@@ -106,1607 +129,9 @@ var validatePromptText = (value) => {
106
129
  return text;
107
130
  };
108
131
 
109
- // src/args.ts
110
- import { cac } from "cac";
111
- var parseWithCac = (values) => {
112
- const cli = cac("codelia-args");
113
- cli.command("[...positionals]").allowUnknownOptions();
114
- const parsed = cli.parse(["node", "codelia-args", ...values], {
115
- run: false
116
- });
117
- return {
118
- args: [...parsed.args],
119
- options: parsed.options
120
- };
121
- };
122
- var parseBoolean = (value, flagName) => {
123
- const normalized = value.trim().toLowerCase();
124
- if (normalized === "true") return true;
125
- if (normalized === "false") return false;
126
- throw new Error(`${flagName} must be true|false`);
127
- };
128
- var parseTimeout = (value) => {
129
- const parsed = Number.parseInt(value, 10);
130
- if (!Number.isFinite(parsed) || parsed <= 0) {
131
- throw new Error("--request-timeout-ms must be a positive integer");
132
- }
133
- return parsed;
134
- };
135
- var parseEpochMs = (value, flagName) => {
136
- const parsed = Number.parseInt(value, 10);
137
- if (!Number.isFinite(parsed) || parsed <= 0) {
138
- throw new Error(`${flagName} must be a positive integer (epoch ms)`);
139
- }
140
- return parsed;
141
- };
142
- var parseKeyValue = (raw, flagName) => {
143
- const [key, ...rest] = raw.split("=");
144
- const value = rest.join("=");
145
- if (!key || !value) {
146
- throw new Error(`${flagName} must be key=value`);
147
- }
148
- return [key, value];
149
- };
150
- var parseCliArgs = (values) => {
151
- const parsed = parseWithCac(values);
152
- return {
153
- positionals: parsed.args,
154
- options: parsed.options
155
- };
156
- };
157
- var readOptionValues = (parsed, flagName) => {
158
- const value = parsed.options[flagName];
159
- if (value == null || value === false || value === true) return [];
160
- const entries = Array.isArray(value) ? value : [value];
161
- return entries.map((entry) => String(entry));
162
- };
163
- var getLastFlagValue = (parsed, flagName) => {
164
- const values = readOptionValues(parsed, flagName);
165
- if (!values || values.length === 0) return void 0;
166
- return values[values.length - 1];
167
- };
168
- var getAllFlagValues = (parsed, flagName) => readOptionValues(parsed, flagName);
169
- var hasBooleanFlag = (parsed, flagName) => parsed.options[flagName] === true;
170
-
171
- // src/mcp/auth-file.ts
172
- import { McpAuthStore } from "@codelia/storage";
173
- var authStore = new McpAuthStore();
174
- var readMcpAuth = async () => {
175
- return authStore.load();
176
- };
177
- var writeMcpAuth = async (auth) => {
178
- await authStore.save(auth);
179
- };
180
-
181
- // src/commands/mcp-auth.ts
182
- var runMcpAuthCommand = async (values) => {
183
- const [subcommand, ...rest] = values;
184
- const parsed = parseCliArgs(rest);
185
- if (!subcommand) {
186
- console.error("usage: codelia mcp auth <list|set|clear> ...");
187
- return 1;
188
- }
189
- if (subcommand === "list") {
190
- const auth = await readMcpAuth();
191
- const entries = Object.entries(auth.servers).sort(
192
- ([a], [b]) => a.localeCompare(b)
193
- );
194
- if (!entries.length) {
195
- console.log("no MCP auth tokens configured");
196
- return 0;
197
- }
198
- console.log("server_id has_refresh expires_at");
199
- for (const [serverId, tokens] of entries) {
200
- console.log(
201
- `${serverId} ${tokens.refresh_token ? "yes" : "no"} ${tokens.expires_at ?? "-"}`
202
- );
203
- }
204
- return 0;
205
- }
206
- if (subcommand === "set") {
207
- const serverId = parsed.positionals[0];
208
- if (!serverId) {
209
- console.error(
210
- "usage: codelia mcp auth set <server-id> --access-token <token> [--refresh-token <token>] [--expires-at <epoch_ms>] [--expires-in <sec>] [--scope <scope>] [--token-type <type>]"
211
- );
212
- return 1;
213
- }
214
- const accessToken = getLastFlagValue(parsed, "access-token");
215
- if (!accessToken) {
216
- console.error("--access-token is required");
217
- return 1;
218
- }
219
- const refreshToken = getLastFlagValue(parsed, "refresh-token");
220
- const expiresAtRaw = getLastFlagValue(parsed, "expires-at");
221
- const expiresInRaw = getLastFlagValue(parsed, "expires-in");
222
- let expiresAt;
223
- if (expiresAtRaw) {
224
- expiresAt = parseEpochMs(expiresAtRaw, "--expires-at");
225
- } else if (expiresInRaw) {
226
- expiresAt = Date.now() + parseTimeout(expiresInRaw) * 1e3;
227
- }
228
- const scope = getLastFlagValue(parsed, "scope");
229
- const tokenType = getLastFlagValue(parsed, "token-type");
230
- const auth = await readMcpAuth();
231
- auth.servers[serverId] = {
232
- access_token: accessToken,
233
- ...refreshToken ? { refresh_token: refreshToken } : {},
234
- ...expiresAt ? { expires_at: expiresAt } : {},
235
- ...scope ? { scope } : {},
236
- ...tokenType ? { token_type: tokenType } : {}
237
- };
238
- await writeMcpAuth(auth);
239
- console.log(`stored MCP auth token for '${serverId}'`);
240
- return 0;
241
- }
242
- if (subcommand === "clear") {
243
- const serverId = parsed.positionals[0];
244
- if (!serverId) {
245
- console.error("usage: codelia mcp auth clear <server-id>");
246
- return 1;
247
- }
248
- const auth = await readMcpAuth();
249
- if (!auth.servers[serverId]) {
250
- console.error(`no token found for server: ${serverId}`);
251
- return 1;
252
- }
253
- delete auth.servers[serverId];
254
- await writeMcpAuth(auth);
255
- console.log(`cleared MCP auth token for '${serverId}'`);
256
- return 0;
257
- }
258
- console.error(`unknown auth subcommand: ${subcommand}`);
259
- return 1;
260
- };
261
-
262
- // src/commands/mcp-config.ts
263
- import path from "path";
264
- import {
265
- loadMcpServers,
266
- removeMcpServerConfig,
267
- setMcpServerEnabled,
268
- upsertMcpServerConfig
269
- } from "@codelia/config-loader";
270
- import { resolveStoragePaths } from "@codelia/storage";
271
- import { z } from "zod";
272
-
273
- // src/mcp/probe.ts
274
- import { spawn } from "child_process";
275
- import { createInterface } from "readline";
276
-
277
- // src/mcp/protocol.ts
278
- import {
279
- assertSupportedMcpProtocolVersion,
280
- getInitializeProtocolVersion,
281
- getMcpProtocolVersion
282
- } from "@codelia/protocol";
283
- var assertSupportedProtocolVersion = (value) => {
284
- assertSupportedMcpProtocolVersion(value);
285
- };
286
-
287
- // src/mcp/probe.ts
288
- var DEFAULT_MCP_TIMEOUT_MS = 3e4;
289
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
290
- var describeError = (error) => error instanceof Error ? error.message : String(error);
291
- var postHttpJson = async (url, body, headers, timeoutMs) => {
292
- const controller = new AbortController();
293
- const timer = setTimeout(() => controller.abort(), timeoutMs);
294
- try {
295
- const response = await fetch(url, {
296
- method: "POST",
297
- headers,
298
- body: JSON.stringify(body),
299
- signal: controller.signal
300
- });
301
- if (!response.ok) {
302
- const bodyText = await response.text().catch(() => "");
303
- throw new Error(`HTTP ${response.status}: ${bodyText.slice(0, 300)}`);
304
- }
305
- const text = await response.text();
306
- const sessionId = response.headers.get("MCP-Session-Id") ?? void 0;
307
- if (!text.trim()) return { body: null, sessionId };
308
- return { body: JSON.parse(text), sessionId };
309
- } catch (error) {
310
- if (controller.signal.aborted) {
311
- throw new Error(`request timed out after ${timeoutMs}ms`);
312
- }
313
- throw error;
314
- } finally {
315
- clearTimeout(timer);
316
- }
317
- };
318
- var parseRpcResult = (raw, requestId) => {
319
- if (Array.isArray(raw)) {
320
- const found = raw.find(
321
- (entry) => isRecord(entry) && String(entry.id ?? "") === requestId
322
- );
323
- if (!found) {
324
- throw new Error(`missing response id=${requestId}`);
325
- }
326
- return parseRpcResult(found, requestId);
327
- }
328
- if (!isRecord(raw)) {
329
- throw new Error("invalid JSON-RPC response");
330
- }
331
- if (isRecord(raw.error)) {
332
- throw new Error(
333
- `RPC ${String(raw.error.code)}: ${String(raw.error.message)}`
334
- );
335
- }
336
- return raw.result;
337
- };
338
- var parseToolsResponse = (raw) => {
339
- if (!isRecord(raw)) return { count: 0 };
340
- const tools = Array.isArray(raw.tools) ? raw.tools.length : 0;
341
- const nextCursor = typeof raw.nextCursor === "string" ? raw.nextCursor : typeof raw.next_cursor === "string" ? raw.next_cursor : void 0;
342
- return { count: tools, nextCursor };
343
- };
344
- var probeHttpServer = async (config) => {
345
- let seq = 0;
346
- let sessionId;
347
- const timeoutMs = config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS;
348
- const protocolVersion = getMcpProtocolVersion();
349
- const baseHeaders = {
350
- "Content-Type": "application/json",
351
- Accept: "application/json, text/event-stream",
352
- "MCP-Protocol-Version": protocolVersion,
353
- ...config.headers ?? {}
354
- };
355
- const request = async (method, params) => {
356
- seq += 1;
357
- const requestId = `cli-${seq}`;
358
- const headers = {
359
- ...baseHeaders,
360
- ...sessionId ? { "MCP-Session-Id": sessionId } : {}
361
- };
362
- const raw = await postHttpJson(
363
- config.url ?? "",
364
- {
365
- jsonrpc: "2.0",
366
- id: requestId,
367
- method,
368
- params
369
- },
370
- headers,
371
- timeoutMs
372
- );
373
- if (raw.sessionId) {
374
- sessionId = raw.sessionId;
375
- }
376
- return parseRpcResult(raw.body, requestId);
377
- };
378
- const notify = async (method, params) => {
379
- const headers = {
380
- ...baseHeaders,
381
- ...sessionId ? { "MCP-Session-Id": sessionId } : {}
382
- };
383
- const raw = await postHttpJson(
384
- config.url ?? "",
385
- {
386
- jsonrpc: "2.0",
387
- method,
388
- params
389
- },
390
- headers,
391
- timeoutMs
392
- );
393
- if (raw.sessionId) {
394
- sessionId = raw.sessionId;
395
- }
396
- };
397
- const initResult = await request("initialize", {
398
- protocolVersion,
399
- clientInfo: { name: "codelia-cli", version: "0.1.0" },
400
- capabilities: {}
401
- });
402
- assertSupportedProtocolVersion(initResult);
403
- await notify("notifications/initialized", {});
404
- let total = 0;
405
- let cursor;
406
- for (let page = 0; page < 100; page += 1) {
407
- const result = await request("tools/list", cursor ? { cursor } : {});
408
- const parsed = parseToolsResponse(result);
409
- total += parsed.count;
410
- if (!parsed.nextCursor) break;
411
- cursor = parsed.nextCursor;
412
- }
413
- return total;
414
- };
415
- var probeStdioServer = async (config) => {
416
- const timeoutMs = config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS;
417
- const child = spawn(config.command ?? "", config.args ?? [], {
418
- cwd: config.cwd,
419
- env: {
420
- ...process.env,
421
- ...config.env ?? {}
422
- },
423
- stdio: ["pipe", "pipe", "pipe"]
424
- });
425
- let seq = 0;
426
- const pending = /* @__PURE__ */ new Map();
427
- const stdoutReader = createInterface({ input: child.stdout });
428
- stdoutReader.on("line", (line) => {
429
- const trimmed = line.trim();
430
- if (!trimmed) return;
431
- let parsed;
432
- try {
433
- parsed = JSON.parse(trimmed);
434
- } catch {
435
- return;
436
- }
437
- if (!isRecord(parsed) || parsed.id === void 0 || parsed.id === null) {
438
- return;
439
- }
440
- const id = String(parsed.id);
441
- const entry = pending.get(id);
442
- if (!entry) return;
443
- pending.delete(id);
444
- clearTimeout(entry.timeout);
445
- if (isRecord(parsed.error)) {
446
- entry.reject(
447
- new Error(
448
- `RPC ${String(parsed.error.code)}: ${String(parsed.error.message)}`
449
- )
450
- );
451
- return;
452
- }
453
- entry.resolve(parsed.result);
454
- });
455
- const stderrReader = createInterface({ input: child.stderr });
456
- stderrReader.on("line", () => void 0);
457
- const failPending = (error) => {
458
- for (const [id, entry] of pending) {
459
- pending.delete(id);
460
- clearTimeout(entry.timeout);
461
- entry.reject(error);
462
- }
463
- };
464
- child.once("error", (error) => {
465
- failPending(new Error(`stdio process error: ${describeError(error)}`));
466
- });
467
- child.once("exit", (code, signal) => {
468
- failPending(
469
- new Error(`stdio exited: code=${String(code)} signal=${String(signal)}`)
470
- );
471
- });
472
- const send = (payload) => new Promise((resolve, reject) => {
473
- child.stdin.write(`${JSON.stringify(payload)}
474
- `, (error) => {
475
- if (error) {
476
- reject(error);
477
- return;
478
- }
479
- resolve();
480
- });
481
- });
482
- const request = (method, params) => {
483
- seq += 1;
484
- const requestId = `cli-${seq}`;
485
- return new Promise((resolve, reject) => {
486
- const timeout = setTimeout(() => {
487
- pending.delete(requestId);
488
- reject(new Error(`request timed out after ${timeoutMs}ms`));
489
- }, timeoutMs);
490
- pending.set(requestId, { resolve, reject, timeout });
491
- void send({
492
- jsonrpc: "2.0",
493
- id: requestId,
494
- method,
495
- params
496
- }).catch((error) => {
497
- const entry = pending.get(requestId);
498
- if (!entry) return;
499
- pending.delete(requestId);
500
- clearTimeout(entry.timeout);
501
- reject(new Error(`failed to send request: ${describeError(error)}`));
502
- });
503
- });
504
- };
505
- const notify = async (method, params) => {
506
- await send({ jsonrpc: "2.0", method, params });
507
- };
508
- try {
509
- const initResult = await request("initialize", {
510
- protocolVersion: getMcpProtocolVersion(),
511
- clientInfo: { name: "codelia-cli", version: "0.1.0" },
512
- capabilities: {}
513
- });
514
- assertSupportedProtocolVersion(initResult);
515
- await notify("notifications/initialized", {});
516
- let total = 0;
517
- let cursor;
518
- for (let page = 0; page < 100; page += 1) {
519
- const result = await request("tools/list", cursor ? { cursor } : {});
520
- const parsed = parseToolsResponse(result);
521
- total += parsed.count;
522
- if (!parsed.nextCursor) break;
523
- cursor = parsed.nextCursor;
524
- }
525
- return total;
526
- } finally {
527
- child.kill("SIGTERM");
528
- stdoutReader.close();
529
- stderrReader.close();
530
- }
531
- };
532
- var probeServer = async (config) => {
533
- if (config.transport === "http") {
534
- return probeHttpServer(config);
535
- }
536
- return probeStdioServer(config);
537
- };
538
-
539
- // src/commands/mcp-config.ts
540
- var TIMEOUT_SCHEMA = z.number().positive().transform((value) => Math.round(value));
541
- var OAUTH_SCHEMA = z.object({
542
- authorization_url: z.string(),
543
- token_url: z.string(),
544
- registration_url: z.string(),
545
- client_id: z.string(),
546
- client_secret: z.string(),
547
- scope: z.string()
548
- }).partial();
549
- var HTTP_SERVER_CONFIG_SCHEMA = z.object({
550
- transport: z.literal("http"),
551
- enabled: z.boolean().optional(),
552
- url: z.string(),
553
- headers: z.record(z.string(), z.string()).optional(),
554
- env: z.record(z.string(), z.string()).optional(),
555
- request_timeout_ms: TIMEOUT_SCHEMA.optional(),
556
- oauth: OAUTH_SCHEMA.optional()
557
- });
558
- var STDIO_SERVER_CONFIG_SCHEMA = z.object({
559
- transport: z.literal("stdio"),
560
- enabled: z.boolean().optional(),
561
- command: z.string(),
562
- args: z.array(z.string()).optional(),
563
- cwd: z.string().optional(),
564
- env: z.record(z.string(), z.string()).optional(),
565
- request_timeout_ms: TIMEOUT_SCHEMA.optional(),
566
- oauth: OAUTH_SCHEMA.optional()
567
- });
568
- var MCP_SERVER_CONFIG_SCHEMA = z.union([
569
- HTTP_SERVER_CONFIG_SCHEMA,
570
- STDIO_SERVER_CONFIG_SCHEMA
571
- ]);
572
- var describeError2 = (error) => error instanceof Error ? error.message : String(error);
573
- var readEnvValue = (key) => {
574
- const value = process.env[key];
575
- if (!value) return void 0;
576
- const trimmed = value.trim();
577
- return trimmed ? trimmed : void 0;
578
- };
579
- var resolveGlobalConfigPath = () => {
580
- const envPath = readEnvValue("CODELIA_CONFIG_PATH");
581
- if (envPath) return path.resolve(envPath);
582
- const storage = resolveStoragePaths();
583
- return storage.configFile;
584
- };
585
- var resolveProjectConfigPath = () => path.resolve(process.cwd(), ".codelia", "config.json");
586
- var normalizeServerConfig = (value) => {
587
- const parsed = MCP_SERVER_CONFIG_SCHEMA.safeParse(value);
588
- return parsed.success ? parsed.data : null;
589
- };
590
- var normalizeEntries = (servers, source) => {
591
- const entries = [];
592
- for (const [id, rawConfig] of Object.entries(servers)) {
593
- const config = normalizeServerConfig(rawConfig);
594
- if (!config) continue;
595
- entries.push({ id, config, source });
596
- }
597
- return entries.sort((left, right) => left.id.localeCompare(right.id));
598
- };
599
- var loadEntriesByScope = async (scope) => {
600
- const globalServers = await loadMcpServers(resolveGlobalConfigPath());
601
- const projectServers = await loadMcpServers(resolveProjectConfigPath());
602
- if (scope === "global") {
603
- return normalizeEntries(globalServers, "global");
604
- }
605
- if (scope === "project") {
606
- return normalizeEntries(projectServers, "project");
607
- }
608
- const merged = /* @__PURE__ */ new Map();
609
- for (const entry of normalizeEntries(globalServers, "global")) {
610
- merged.set(entry.id, entry);
611
- }
612
- for (const entry of normalizeEntries(projectServers, "project")) {
613
- merged.set(entry.id, entry);
614
- }
615
- return Array.from(merged.values()).sort(
616
- (left, right) => left.id.localeCompare(right.id)
617
- );
618
- };
619
- var resolveMutableScope = (parsed) => {
620
- const scopeRaw = getLastFlagValue(parsed, "scope") ?? "project";
621
- if (scopeRaw === "project" || scopeRaw === "global") {
622
- return scopeRaw;
623
- }
624
- throw new Error("--scope must be project|global");
625
- };
626
- var resolveListScope = (parsed) => {
627
- const scopeRaw = getLastFlagValue(parsed, "scope") ?? "effective";
628
- if (scopeRaw === "project" || scopeRaw === "global" || scopeRaw === "effective") {
629
- return scopeRaw;
630
- }
631
- throw new Error("--scope must be effective|project|global");
632
- };
633
- var buildServerConfigFromAdd = (parsed) => {
634
- const transport = getLastFlagValue(parsed, "transport");
635
- if (transport !== "http" && transport !== "stdio") {
636
- throw new Error("--transport must be http|stdio");
637
- }
638
- const enabledRaw = getLastFlagValue(parsed, "enabled");
639
- const enabled = enabledRaw ? parseBoolean(enabledRaw, "--enabled") : true;
640
- const timeoutRaw = getLastFlagValue(parsed, "request-timeout-ms");
641
- const requestTimeoutMs = timeoutRaw ? parseTimeout(timeoutRaw) : void 0;
642
- const oauth = {
643
- authorization_url: getLastFlagValue(parsed, "oauth-authorization-url"),
644
- token_url: getLastFlagValue(parsed, "oauth-token-url"),
645
- registration_url: getLastFlagValue(parsed, "oauth-registration-url"),
646
- client_id: getLastFlagValue(parsed, "oauth-client-id"),
647
- client_secret: getLastFlagValue(parsed, "oauth-client-secret"),
648
- scope: getLastFlagValue(parsed, "oauth-scope")
649
- };
650
- const oauthConfig = Object.fromEntries(
651
- Object.entries(oauth).filter(([, value]) => !!value)
652
- );
653
- if (transport === "http") {
654
- const url = getLastFlagValue(parsed, "url");
655
- if (!url) throw new Error("--url is required when --transport=http");
656
- const headers = Object.fromEntries(
657
- getAllFlagValues(parsed, "header").map(
658
- (value) => parseKeyValue(value, "--header")
659
- )
660
- );
661
- return {
662
- transport,
663
- ...enabled !== true ? { enabled } : {},
664
- url,
665
- ...Object.keys(headers).length ? { headers } : {},
666
- ...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
667
- ...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
668
- };
669
- }
670
- const command = getLastFlagValue(parsed, "command");
671
- if (!command) {
672
- throw new Error("--command is required when --transport=stdio");
673
- }
674
- const env = Object.fromEntries(
675
- getAllFlagValues(parsed, "env").map(
676
- (value) => parseKeyValue(value, "--env")
677
- )
678
- );
679
- const args2 = getAllFlagValues(parsed, "arg");
680
- const cwd = getLastFlagValue(parsed, "cwd");
681
- return {
682
- transport,
683
- ...enabled !== true ? { enabled } : {},
684
- command,
685
- ...args2.length ? { args: args2 } : {},
686
- ...cwd ? { cwd } : {},
687
- ...Object.keys(env).length ? { env } : {},
688
- ...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
689
- ...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
690
- };
691
- };
692
- var printStaticList = (entries) => {
693
- if (!entries.length) {
694
- console.log("no MCP servers configured");
695
- return;
696
- }
697
- console.log("id transport source enabled");
698
- for (const entry of entries) {
699
- const enabled = entry.config.enabled !== false;
700
- console.log(
701
- `${entry.id} ${entry.config.transport} ${entry.source} ${enabled}`
702
- );
703
- }
704
- };
705
- var runMcpConfigCommand = async (subcommand, rest) => {
706
- const parsed = parseCliArgs(rest);
707
- if (subcommand === "list") {
708
- const scope = resolveListScope(parsed);
709
- const entries = await loadEntriesByScope(scope);
710
- printStaticList(entries);
711
- return 0;
712
- }
713
- if (subcommand === "add") {
714
- const serverId = parsed.positionals[0];
715
- if (!serverId) {
716
- console.error(
717
- "usage: codelia mcp add <server-id> --transport <http|stdio> ..."
718
- );
719
- return 1;
720
- }
721
- const scope = resolveMutableScope(parsed);
722
- const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveProjectConfigPath();
723
- const servers = await loadMcpServers(configPath);
724
- const replace = hasBooleanFlag(parsed, "replace");
725
- if (servers[serverId] !== void 0 && !replace) {
726
- console.error(`server already exists in ${scope} scope: ${serverId}`);
727
- console.error("pass --replace to overwrite");
728
- return 1;
729
- }
730
- const serverConfig = buildServerConfigFromAdd(parsed);
731
- await upsertMcpServerConfig(configPath, serverId, serverConfig);
732
- console.log(`added MCP server '${serverId}' (${scope})`);
733
- return 0;
734
- }
735
- if (subcommand === "remove" || subcommand === "enable" || subcommand === "disable") {
736
- const serverId = parsed.positionals[0];
737
- if (!serverId) {
738
- console.error(
739
- `usage: codelia mcp ${subcommand} <server-id> [--scope project|global]`
740
- );
741
- return 1;
742
- }
743
- const scope = resolveMutableScope(parsed);
744
- const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveProjectConfigPath();
745
- if (subcommand === "remove") {
746
- const removed = await removeMcpServerConfig(configPath, serverId);
747
- if (!removed) {
748
- console.error(`server not found in ${scope} scope: ${serverId}`);
749
- return 1;
750
- }
751
- } else {
752
- const updated = await setMcpServerEnabled(
753
- configPath,
754
- serverId,
755
- subcommand === "enable"
756
- );
757
- if (!updated) {
758
- console.error(`server not found in ${scope} scope: ${serverId}`);
759
- return 1;
760
- }
761
- }
762
- console.log(`${subcommand}d MCP server '${serverId}' (${scope})`);
763
- return 0;
764
- }
765
- if (subcommand === "test") {
766
- const serverId = parsed.positionals[0];
767
- if (!serverId) {
768
- console.error(
769
- "usage: codelia mcp test <server-id> [--scope effective|project|global]"
770
- );
771
- return 1;
772
- }
773
- const scope = resolveListScope(parsed);
774
- const entries = await loadEntriesByScope(scope);
775
- const target = entries.find((entry) => entry.id === serverId);
776
- if (!target) {
777
- console.error(`server not found: ${serverId} (scope=${scope})`);
778
- return 1;
779
- }
780
- try {
781
- const auth = await readMcpAuth();
782
- const accessToken = auth.servers[target.id]?.access_token;
783
- const configForTest = target.config.transport === "http" && accessToken ? {
784
- ...target.config,
785
- headers: {
786
- ...target.config.headers ?? {},
787
- Authorization: `Bearer ${accessToken}`
788
- }
789
- } : target.config;
790
- const tools = await probeServer(configForTest);
791
- console.log(
792
- `MCP test succeeded: id=${target.id} transport=${target.config.transport} source=${target.source} tools=${tools}`
793
- );
794
- return 0;
795
- } catch (error) {
796
- console.error(
797
- `MCP test failed: id=${target.id} transport=${target.config.transport}: ${describeError2(error)}`
798
- );
799
- return 1;
800
- }
801
- }
802
- return -1;
803
- };
804
-
805
- // src/commands/mcp.ts
806
- var runMcpCommand = async (values) => {
807
- const [subcommand, ...rest] = values;
808
- if (!subcommand) {
809
- console.error(
810
- "usage: codelia mcp <add|list|remove|enable|disable|test|auth> ..."
811
- );
812
- return 1;
813
- }
814
- if (subcommand === "auth") {
815
- return runMcpAuthCommand(rest);
816
- }
817
- const handled = await runMcpConfigCommand(subcommand, rest);
818
- if (handled >= 0) {
819
- return handled;
820
- }
821
- console.error(`unknown subcommand: ${subcommand}`);
822
- return 1;
823
- };
824
-
825
- // src/commands/session.ts
826
- import {
827
- cleanupRunLogs,
828
- resolveStoragePaths as resolveStoragePaths2,
829
- SessionStateStoreImpl
830
- } from "@codelia/storage";
831
- var HELP = "usage: codelia session list | pin|unpin|archive|unarchive <session_id> | cleanup\nArchive removes diagnostics and compresses unpinned run events, including legacy gzip. Original messages, active context and reference data remain; diagnostic dumps may expire.";
832
- async function runSessionCommand(args2) {
833
- const [action, sessionId, extra] = args2;
834
- if (!action || action === "--help" || action === "help") {
835
- console.log(HELP);
836
- return 0;
837
- }
838
- if (action === "list" || action === "cleanup" ? sessionId !== void 0 : !["pin", "unpin", "archive", "unarchive"].includes(action) || !sessionId || extra !== void 0 || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(sessionId)) {
839
- console.error(HELP);
840
- return 1;
841
- }
842
- const paths = resolveStoragePaths2();
843
- const sessions = new SessionStateStoreImpl({ paths });
844
- try {
845
- if (action === "list") {
846
- for (const session2 of (await sessions.list()).sort(
847
- (a, b) => b.updated_at.localeCompare(a.updated_at)
848
- ))
849
- console.log(
850
- `${session2.session_id} ${session2.updated_at} ${session2.pinned ? "pinned" : "unpinned"} ${session2.archived_at ? "archived" : "active"}`
851
- );
852
- return 0;
853
- }
854
- if (action === "cleanup") {
855
- console.log(JSON.stringify(await cleanupRunLogs({ paths, sessions })));
856
- return 0;
857
- }
858
- if (!sessionId) return 1;
859
- const patch = action === "pin" || action === "unpin" ? { pinned: action === "pin" } : { archived: action === "archive" };
860
- const session = await sessions.updateMetadata(sessionId, patch);
861
- console.log(JSON.stringify(session));
862
- if (!session.pinned && action !== "unarchive")
863
- console.log(
864
- JSON.stringify(await cleanupRunLogs({ paths, sessions, sessionId }))
865
- );
866
- return 0;
867
- } catch (error) {
868
- console.error(
869
- `Session command failed: ${error instanceof Error ? error.message : String(error)}`
870
- );
871
- return 1;
872
- }
873
- }
874
-
875
- // src/prompt-mode.ts
876
- import { spawn as spawn3 } from "child_process";
877
-
878
- // src/atif.ts
879
- import { mkdir, rename, writeFile } from "fs/promises";
880
- import path2 from "path";
881
- import { readRunLogLines } from "@codelia/storage";
882
- var asRecord = (value) => typeof value === "object" && value !== null ? value : null;
883
- var asString = (value) => typeof value === "string" && value.trim().length > 0 ? value : void 0;
884
- var stringifyContent = (value) => {
885
- if (typeof value === "string") return value;
886
- if (value == null) return "";
887
- try {
888
- return JSON.stringify(value);
889
- } catch {
890
- return String(value);
891
- }
892
- };
893
- var normalizeTimestamp = (value) => {
894
- const raw = asString(value);
895
- if (!raw) return void 0;
896
- const date = new Date(raw);
897
- if (Number.isNaN(date.getTime())) return raw;
898
- return date.toISOString();
899
- };
900
- var extractInputText = (input) => {
901
- const direct = asRecord(input);
902
- if (!direct) return asString(input);
903
- if (direct.type === "text") return asString(direct.text);
904
- return stringifyContent(direct);
905
- };
906
- var extractModelName = (record) => {
907
- const model = asRecord(record?.model);
908
- return asString(model?.name) ?? asString(model?.id);
909
- };
910
- var extractSessionId = (header, runStart, fallbackRunId) => asString(header?.session_id) ?? asString(runStart?.session_id) ?? asString(asRecord(runStart?.output)?.session_id) ?? fallbackRunId;
911
- var createStepIdAllocator = () => {
912
- let next = 1;
913
- return () => next++;
914
- };
915
- var pushTextStep = (steps, nextStepId, source, message, timestamp, extra) => {
916
- if (!message?.trim()) return;
917
- steps.push({
918
- step_id: nextStepId(),
919
- ...timestamp ? { timestamp } : {},
920
- source,
921
- message,
922
- ...extra ? { extra } : {}
923
- });
924
- };
925
- var getOrCreateToolStep = (steps, nextStepId, callId, timestamp) => {
926
- const existing = steps.find(
927
- (step2) => step2.tool_calls?.some((call) => call.tool_call_id === callId)
928
- );
929
- if (existing) return existing;
930
- const step = {
931
- step_id: nextStepId(),
932
- ...timestamp ? { timestamp } : {},
933
- source: "agent",
934
- message: "",
935
- tool_calls: []
936
- };
937
- steps.push(step);
938
- return step;
939
- };
940
- var extractUsageMetrics = (records) => {
941
- return records.map((record) => asRecord(asRecord(record.output)?.usage)).filter((usage) => !!usage).reduce(
942
- (acc, usage) => {
943
- acc.total_prompt_tokens += Number(usage.input_tokens ?? 0);
944
- acc.total_completion_tokens += Number(usage.output_tokens ?? 0);
945
- acc.total_cached_tokens += Number(
946
- usage.input_cached_tokens ?? asRecord(usage.input_tokens_details)?.cached_tokens ?? 0
947
- );
948
- return acc;
949
- },
950
- {
951
- total_prompt_tokens: 0,
952
- total_completion_tokens: 0,
953
- total_cached_tokens: 0
954
- }
955
- );
956
- };
957
- var sessionRecordsToAtif = (records, runId) => {
958
- const header = records.find((record) => record.type === "header");
959
- const runStart = records.find((record) => record.type === "run.start");
960
- const modelName = extractModelName(header);
961
- const nextStepId = createStepIdAllocator();
962
- const steps = [];
963
- pushTextStep(
964
- steps,
965
- nextStepId,
966
- "user",
967
- extractInputText(asRecord(runStart?.input)),
968
- normalizeTimestamp(runStart?.ts),
969
- { source_record: "run.start" }
970
- );
971
- for (const record of records) {
972
- if (record.type !== "agent.event") continue;
973
- const event = asRecord(record.event);
974
- if (!event) continue;
975
- const timestamp = normalizeTimestamp(record.ts);
976
- const eventType = asString(event.type);
977
- if (eventType === "text") {
978
- pushTextStep(
979
- steps,
980
- nextStepId,
981
- "agent",
982
- asString(event.content),
983
- timestamp,
984
- { source_record: "agent.event.text" }
985
- );
986
- continue;
987
- }
988
- if (eventType === "reasoning") {
989
- const content = asString(event.content);
990
- if (!content) continue;
991
- steps.push({
992
- step_id: nextStepId(),
993
- ...timestamp ? { timestamp } : {},
994
- source: "agent",
995
- message: "",
996
- reasoning_content: content,
997
- extra: { source_record: "agent.event.reasoning" }
998
- });
999
- continue;
1000
- }
1001
- if (eventType === "tool_call") {
1002
- const callId = asString(event.tool_call_id) ?? `tool_call_${String(steps.length + 1)}`;
1003
- const step = getOrCreateToolStep(steps, nextStepId, callId, timestamp);
1004
- step.tool_calls ??= [];
1005
- step.tool_calls.push({
1006
- tool_call_id: callId,
1007
- function_name: asString(event.tool) ?? "unknown",
1008
- arguments: asRecord(event.args) ?? {}
1009
- });
1010
- continue;
1011
- }
1012
- if (eventType === "tool_result") {
1013
- const callId = asString(event.tool_call_id);
1014
- const step = callId ? getOrCreateToolStep(steps, nextStepId, callId, timestamp) : {
1015
- step_id: nextStepId(),
1016
- ...timestamp ? { timestamp } : {},
1017
- source: "agent",
1018
- message: ""
1019
- };
1020
- if (!callId) steps.push(step);
1021
- step.observation ??= { results: [] };
1022
- step.observation.results.push({
1023
- ...callId ? { source_call_id: callId } : {},
1024
- content: stringifyContent(event.result)
1025
- });
1026
- continue;
1027
- }
1028
- if (eventType === "final") {
1029
- pushTextStep(
1030
- steps,
1031
- nextStepId,
1032
- "agent",
1033
- asString(event.content),
1034
- timestamp,
1035
- { source_record: "agent.event.final" }
1036
- );
1037
- }
1038
- }
1039
- if (steps.length === 0) {
1040
- steps.push({
1041
- step_id: nextStepId(),
1042
- source: "user",
1043
- message: "(no prompt captured)",
1044
- extra: { source_record: "fallback" }
1045
- });
1046
- }
1047
- const compactUsage = records.filter((record) => record.type === "llm.usage");
1048
- const compactSequences = new Set(compactUsage.map((record) => record.seq));
1049
- const usage = extractUsageMetrics([
1050
- ...compactUsage,
1051
- ...records.filter(
1052
- (record) => record.type === "llm.response" && !compactSequences.has(record.seq)
1053
- )
1054
- ]);
1055
- return {
1056
- schema_version: "ATIF-v1.6",
1057
- session_id: extractSessionId(header, runStart, runId),
1058
- agent: {
1059
- name: "codelia",
1060
- version: "unknown",
1061
- ...modelName ? { model_name: modelName } : {}
1062
- },
1063
- steps,
1064
- final_metrics: {
1065
- ...usage,
1066
- total_steps: steps.length
1067
- },
1068
- extra: {
1069
- run_id: runId,
1070
- source: "codelia-session-jsonl",
1071
- conversion: "session-records-to-atif-v1.6"
1072
- }
1073
- };
1074
- };
1075
- var parseSessionJsonl = (raw) => {
1076
- const out = [];
1077
- for (const line of raw.split("\n")) {
1078
- if (!line.trim()) continue;
1079
- try {
1080
- out.push(JSON.parse(line));
1081
- } catch {
1082
- }
1083
- }
1084
- return out;
1085
- };
1086
- var readSessionJsonl = async (filePath) => {
1087
- const lines = [];
1088
- for await (const line of readRunLogLines(filePath)) lines.push(line);
1089
- return parseSessionJsonl(lines.join("\n"));
1090
- };
1091
- var writeAtifFromSessionJsonl = async ({
1092
- sessionLogPath,
1093
- runId,
1094
- outPath
1095
- }) => {
1096
- const records = await readSessionJsonl(sessionLogPath);
1097
- const trajectory = sessionRecordsToAtif(records, runId);
1098
- await mkdir(path2.dirname(outPath), { recursive: true });
1099
- const tempPath = `${outPath}.tmp-${process.pid}-${Date.now()}`;
1100
- await writeFile(tempPath, `${JSON.stringify(trajectory, null, 2)}
1101
- `, "utf8");
1102
- await rename(tempPath, outPath);
1103
- return trajectory;
1104
- };
1105
-
1106
- // src/tui/launcher.ts
1107
- import { spawn as spawn2 } from "child_process";
1108
- import fsSync from "fs";
1109
- import { createRequire } from "module";
1110
- import path3 from "path";
1111
- import { ensureStorageDirs, resolveStoragePaths as resolveStoragePaths3 } from "@codelia/storage";
1112
-
1113
- // src/version.ts
1114
- var CLI_VERSION = "0.1.85".trim().length > 0 ? "0.1.85" : "0.0.0";
1115
-
1116
- // src/tui/launcher.ts
1117
- var resolveTuiBinaryName = (platform) => platform === "win32" ? "codelia-tui.exe" : "codelia-tui";
1118
- var TUI_PACKAGE_BY_TARGET = {
1119
- "darwin-arm64": "@codelia/tui-darwin-arm64",
1120
- "darwin-x64": "@codelia/tui-darwin-x64",
1121
- "linux-arm64": "@codelia/tui-linux-arm64",
1122
- "linux-x64": "@codelia/tui-linux-x64",
1123
- "win32-x64": "@codelia/tui-win32-x64"
1124
- };
1125
- var describeError3 = (error) => error instanceof Error ? error.message : String(error);
1126
- var splitArgs = (value) => value.split(/\s+/).map((part) => part.trim()).filter((part) => part.length > 0);
1127
- var quoteShellWord = (value) => `'${value.replace(/'/g, "'\\''")}'`;
1128
- var isExecutable = (candidate) => {
1129
- try {
1130
- fsSync.accessSync(candidate, fsSync.constants.X_OK);
1131
- return true;
1132
- } catch {
1133
- return false;
1134
- }
1135
- };
1136
- var initStorage = async () => {
1137
- try {
1138
- const paths = resolveStoragePaths3();
1139
- await ensureStorageDirs(paths);
1140
- } catch (error) {
1141
- console.warn(
1142
- `Failed to initialize storage directories: ${describeError3(error)}`
1143
- );
1144
- }
1145
- };
1146
- var resolveCliPackageRoot = () => {
1147
- const scriptPath = process.argv[1];
1148
- if (!scriptPath) return null;
1149
- try {
1150
- const resolvedScriptPath = fsSync.realpathSync(scriptPath);
1151
- const scriptDir = path3.dirname(resolvedScriptPath);
1152
- if (path3.basename(scriptDir) === "dist") {
1153
- return path3.dirname(scriptDir);
1154
- }
1155
- return scriptDir;
1156
- } catch {
1157
- return null;
1158
- }
1159
- };
1160
- var resolveRuntimeRequireBase = () => {
1161
- const cliPackageRoot = resolveCliPackageRoot();
1162
- if (cliPackageRoot) {
1163
- return path3.resolve(cliPackageRoot, "package.json");
1164
- }
1165
- return path3.resolve(process.cwd(), "package.json");
1166
- };
1167
- var runtimeRequire = createRequire(resolveRuntimeRequireBase());
1168
- var resolveBundledRuntimeEntry = () => {
1169
- try {
1170
- return runtimeRequire.resolve("@codelia/runtime");
1171
- } catch {
1172
- return null;
1173
- }
1174
- };
1175
- var resolveInstalledPackageJson = (packageName) => {
1176
- try {
1177
- return runtimeRequire.resolve(`${packageName}/package.json`);
1178
- } catch {
1179
- return null;
1180
- }
1181
- };
1182
- var resolvePlatformTuiPackageName = (platform = process.platform, arch = process.arch) => TUI_PACKAGE_BY_TARGET[`${platform}-${arch}`] ?? null;
1183
- var resolveOptionalTuiBinaryPath = (platform = process.platform, arch = process.arch, resolvePackageJson = resolveInstalledPackageJson) => {
1184
- const packageName = resolvePlatformTuiPackageName(platform, arch);
1185
- if (!packageName) {
1186
- return null;
1187
- }
1188
- const packageJsonPath = resolvePackageJson(packageName);
1189
- if (!packageJsonPath) {
1190
- return null;
1191
- }
1192
- return path3.resolve(
1193
- path3.dirname(packageJsonPath),
1194
- "bin",
1195
- resolveTuiBinaryName(platform)
1196
- );
1197
- };
1198
- var resolveRuntimeEnvForTui = (env, resolveRuntimeEntry = resolveBundledRuntimeEntry) => {
1199
- if (env.CODELIA_RUNTIME_CMD || env.CODELIA_RUNTIME_ARGS) {
1200
- return env;
1201
- }
1202
- const runtimeEntry = resolveRuntimeEntry();
1203
- if (!runtimeEntry) {
1204
- return env;
1205
- }
1206
- return {
1207
- ...env,
1208
- CODELIA_RUNTIME_CMD: process.execPath,
1209
- CODELIA_RUNTIME_ARGS: quoteShellWord(runtimeEntry)
1210
- };
1211
- };
1212
- var resolveLaunchEnvForTui = (env, cliVersion = CLI_VERSION, resolveRuntimeEntry = resolveBundledRuntimeEntry) => {
1213
- const runtimeEnv = resolveRuntimeEnvForTui(env, resolveRuntimeEntry);
1214
- if (runtimeEnv.CODELIA_CLI_VERSION || cliVersion.trim().length === 0) {
1215
- return runtimeEnv;
1216
- }
1217
- return {
1218
- ...runtimeEnv,
1219
- CODELIA_CLI_VERSION: cliVersion
1220
- };
1221
- };
1222
- var resolveTuiCommand = (options = {}) => {
1223
- const env = options.env ?? process.env;
1224
- if (env.CODELIA_TUI_CMD) {
1225
- return env.CODELIA_TUI_CMD;
1226
- }
1227
- const platform = options.platform ?? process.platform;
1228
- const arch = options.arch ?? process.arch;
1229
- const resolveOptionalBinary = options.resolveOptionalTuiBinary ?? resolveOptionalTuiBinaryPath;
1230
- const isExecutableCandidate = options.isExecutableCandidate ?? isExecutable;
1231
- const tuiBinaryName = resolveTuiBinaryName(platform);
1232
- const cwd = options.cwd ?? process.cwd();
1233
- const cliPackageRoot = options.cliPackageRoot === void 0 ? resolveCliPackageRoot() : options.cliPackageRoot;
1234
- const seen = /* @__PURE__ */ new Set();
1235
- const optionalTuiBinary = resolveOptionalBinary(platform, arch);
1236
- const localCandidates = [
1237
- ...cliPackageRoot ? [
1238
- path3.resolve(cliPackageRoot, "dist/bin", tuiBinaryName),
1239
- path3.resolve(
1240
- cliPackageRoot,
1241
- "../../crates/tui/target/release",
1242
- tuiBinaryName
1243
- ),
1244
- path3.resolve(
1245
- cliPackageRoot,
1246
- "../../crates/tui/target/debug",
1247
- tuiBinaryName
1248
- )
1249
- ] : [],
1250
- path3.resolve(cwd, "target/release", tuiBinaryName),
1251
- path3.resolve(cwd, "target/debug", tuiBinaryName),
1252
- path3.resolve(cwd, "crates/tui/target/release", tuiBinaryName),
1253
- path3.resolve(cwd, "crates/tui/target/debug", tuiBinaryName)
1254
- ];
1255
- const candidates = [
1256
- ...localCandidates,
1257
- ...optionalTuiBinary ? [optionalTuiBinary] : []
1258
- ];
1259
- for (const candidate of candidates) {
1260
- if (seen.has(candidate)) continue;
1261
- seen.add(candidate);
1262
- if (isExecutableCandidate(candidate)) {
1263
- return candidate;
1264
- }
1265
- }
1266
- return tuiBinaryName;
1267
- };
1268
- var runTui = (args2) => {
1269
- void initStorage();
1270
- const tuiCmd = resolveTuiCommand();
1271
- const tuiArgs = process.env.CODELIA_TUI_ARGS ? splitArgs(process.env.CODELIA_TUI_ARGS) : [];
1272
- const child = spawn2(tuiCmd, [...tuiArgs, ...args2], {
1273
- stdio: "inherit",
1274
- env: resolveLaunchEnvForTui(process.env)
1275
- });
1276
- child.on("exit", (code) => {
1277
- process.exitCode = code ?? 0;
1278
- });
1279
- child.on("error", (error) => {
1280
- const code = typeof error === "object" && error !== null && "code" in error ? String(error.code ?? "") : "";
1281
- const expectedPackage = resolvePlatformTuiPackageName();
1282
- console.error(`Failed to launch TUI (${tuiCmd}): ${describeError3(error)}`);
1283
- if (code === "EACCES") {
1284
- console.error(
1285
- "Permission denied while launching TUI. Verify execute permission and PATH entries."
1286
- );
1287
- } else if (code === "ENOENT") {
1288
- console.error(
1289
- expectedPackage ? `TUI binary not found. Ensure \`${expectedPackage}\` is installed, or run \`bun run build\` (or \`bun run tui:build\`) and retry.` : "TUI binary not found. Run `bun run build` (or `bun run tui:build`) and retry."
1290
- );
1291
- }
1292
- console.error(
1293
- "Set CODELIA_TUI_CMD/CODELIA_TUI_ARGS to use a custom TUI command."
1294
- );
1295
- process.exitCode = 1;
1296
- });
1297
- };
1298
-
1299
- // src/prompt-mode.ts
1300
- var parseShellLikeArgs = (value) => {
1301
- const out = [];
1302
- let current = "";
1303
- let quote = null;
1304
- let escaping = false;
1305
- for (let i = 0; i < value.length; i += 1) {
1306
- const ch = value[i];
1307
- if (escaping) {
1308
- current += ch;
1309
- escaping = false;
1310
- continue;
1311
- }
1312
- if (ch === "\\" && quote !== "single") {
1313
- escaping = true;
1314
- continue;
1315
- }
1316
- if (quote === "single") {
1317
- if (ch === "'") {
1318
- quote = null;
1319
- } else {
1320
- current += ch;
1321
- }
1322
- continue;
1323
- }
1324
- if (quote === "double") {
1325
- if (ch === '"') {
1326
- quote = null;
1327
- } else {
1328
- current += ch;
1329
- }
1330
- continue;
1331
- }
1332
- if (ch === "'") {
1333
- quote = "single";
1334
- continue;
1335
- }
1336
- if (ch === '"') {
1337
- quote = "double";
1338
- continue;
1339
- }
1340
- if (/\s/.test(ch)) {
1341
- if (current.length > 0) {
1342
- out.push(current);
1343
- current = "";
1344
- }
1345
- continue;
1346
- }
1347
- current += ch;
1348
- }
1349
- if (current.length > 0) {
1350
- out.push(current);
1351
- }
1352
- return out;
1353
- };
1354
- var toLine = (value) => `${JSON.stringify(value)}
1355
- `;
1356
- var envTruthy = (value) => {
1357
- if (!value) return false;
1358
- const normalized = value.trim().toLowerCase();
1359
- return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
1360
- };
1361
- var toSingleLine = (value, maxChars = 240) => {
1362
- const normalized = value.replace(/\s+/g, " ").trim();
1363
- if (normalized.length <= maxChars) return normalized;
1364
- return `${normalized.slice(0, maxChars)}...`;
1365
- };
1366
- var summarizeProgressEvent = (event) => {
1367
- const type = typeof event.type === "string" ? event.type : "";
1368
- switch (type) {
1369
- case "text": {
1370
- const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
1371
- return content ? `[text] ${content}` : "[text]";
1372
- }
1373
- case "reasoning": {
1374
- const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
1375
- return content ? `[reasoning] ${content}` : "[reasoning]";
1376
- }
1377
- case "step_start": {
1378
- const title = typeof event.title === "string" ? toSingleLine(event.title) : "";
1379
- const stepNumber = typeof event.step_number === "number" ? `#${String(event.step_number)} ` : "";
1380
- return `[step_start] ${stepNumber}${title || "unnamed step"}`;
1381
- }
1382
- case "step_complete": {
1383
- const status = typeof event.status === "string" ? event.status : "unknown";
1384
- const duration = typeof event.duration_ms === "number" ? ` ${String(event.duration_ms)}ms` : "";
1385
- return `[step_complete] ${status}${duration}`;
1386
- }
1387
- case "tool_call": {
1388
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1389
- return `[tool_call] ${tool}`;
1390
- }
1391
- case "tool_result": {
1392
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1393
- const isError = event.is_error === true ? "error" : "ok";
1394
- return `[tool_result] ${tool} (${isError})`;
1395
- }
1396
- case "permission.preview": {
1397
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1398
- return `[permission.preview] ${tool}`;
1399
- }
1400
- case "permission.ready": {
1401
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1402
- return `[permission.ready] ${tool}`;
1403
- }
1404
- case "compaction_start":
1405
- return "[compaction_start]";
1406
- case "compaction_complete": {
1407
- const compacted = typeof event.compacted === "boolean" ? ` compacted=${String(event.compacted)}` : "";
1408
- return `[compaction_complete]${compacted}`;
1409
- }
1410
- case "hidden_user_message":
1411
- return "[hidden_user_message]";
1412
- default:
1413
- return type ? `[${type}]` : null;
1414
- }
1415
- };
1416
- var isRpcResponse = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "id" in value && !value.method;
1417
- var isRpcNotification = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "method" in value && !value.id;
1418
- var writePromptModeAtif = async ({
1419
- atifOut,
1420
- sessionLogPath,
1421
- runId
1422
- }) => {
1423
- if (!atifOut) {
1424
- return "skipped";
1425
- }
1426
- if (!sessionLogPath || !runId) {
1427
- throw new Error("CODELIA_ATIF_OUT was set but session log path is missing");
1428
- }
1429
- await writeAtifFromSessionJsonl({
1430
- sessionLogPath,
1431
- runId,
1432
- outPath: atifOut
1433
- });
1434
- return "written";
1435
- };
1436
- var runPromptMode = async (options) => {
1437
- const emitProgressToStderr = envTruthy(
1438
- process.env.CODELIA_PROMPT_PROGRESS_STDERR
1439
- );
1440
- const atifOut = process.env.CODELIA_ATIF_OUT?.trim();
1441
- const runtimeEnv = resolveRuntimeEnvForTui(process.env);
1442
- const runtimeCmd = runtimeEnv.CODELIA_RUNTIME_CMD ?? process.execPath;
1443
- const runtimeArgsValue = runtimeEnv.CODELIA_RUNTIME_ARGS ?? "packages/runtime/src/index.ts";
1444
- const runtimeArgs = parseShellLikeArgs(runtimeArgsValue);
1445
- if (runtimeArgs.length === 0) {
1446
- runtimeArgs.push("packages/runtime/src/index.ts");
1447
- }
1448
- if (options.approvalMode) {
1449
- runtimeArgs.push("--approval-mode", options.approvalMode);
1450
- }
1451
- const child = spawn3(runtimeCmd, runtimeArgs, {
1452
- env: runtimeEnv,
1453
- stdio: ["pipe", "pipe", "pipe"]
1454
- });
1455
- let buffer = "";
1456
- let runId = null;
1457
- let sessionLogPath = null;
1458
- let finalText = "";
1459
- let terminalStatus = null;
1460
- let terminalMessage;
1461
- let atifWritten = false;
1462
- let atifWriteInFlight = null;
1463
- const pendingResponses = /* @__PURE__ */ new Map();
1464
- let startupFailure = null;
1465
- const failPending = (error) => {
1466
- if (startupFailure) return;
1467
- startupFailure = error;
1468
- for (const pending of pendingResponses.values()) {
1469
- pending.reject(error);
1470
- }
1471
- pendingResponses.clear();
1472
- };
1473
- const waitResponse = (id) => {
1474
- if (startupFailure) {
1475
- return Promise.reject(startupFailure);
1476
- }
1477
- return new Promise((resolve, reject) => {
1478
- pendingResponses.set(id, { resolve, reject });
1479
- });
1480
- };
1481
- const sendRequest = (request) => {
1482
- if (startupFailure) {
1483
- throw startupFailure;
1484
- }
1485
- const wrote = child.stdin.write(toLine(request));
1486
- if (!wrote) {
1487
- }
1488
- };
1489
- const writeAtifOnce = async () => {
1490
- if (atifWritten) {
1491
- return "written";
1492
- }
1493
- atifWriteInFlight ??= writePromptModeAtif({
1494
- atifOut,
1495
- sessionLogPath,
1496
- runId
1497
- });
1498
- const result = await atifWriteInFlight;
1499
- if (result === "written") {
1500
- atifWritten = true;
1501
- }
1502
- return result;
1503
- };
1504
- const signalNumbers = {
1505
- SIGHUP: 1,
1506
- SIGINT: 2,
1507
- SIGTERM: 15
1508
- };
1509
- const handledSignals = Object.keys(signalNumbers);
1510
- const handleTerminationSignal = (signal) => {
1511
- void (async () => {
1512
- try {
1513
- await writeAtifOnce();
1514
- } catch (error) {
1515
- console.error(
1516
- `Failed to write partial ATIF trajectory on ${signal}: ${error instanceof Error ? error.message : String(error)}`
1517
- );
1518
- } finally {
1519
- if (!child.killed) {
1520
- child.kill(signal);
1521
- }
1522
- process.exit(
1523
- 128 + (signalNumbers[signal] ?? 1)
1524
- );
1525
- }
1526
- })();
1527
- };
1528
- for (const signal of handledSignals) {
1529
- process.once(signal, handleTerminationSignal);
1530
- }
1531
- const cleanupSignalHandlers = () => {
1532
- for (const signal of handledSignals) {
1533
- process.removeListener(signal, handleTerminationSignal);
1534
- }
1535
- };
1536
- const maybeTrackRunLifecycle = (value) => {
1537
- if (!isRpcNotification(value)) return;
1538
- if (value.method === "run.status") {
1539
- const params = value.params ?? {};
1540
- if (!runId || params.run_id !== runId) return;
1541
- if (params.status === "completed" || params.status === "error" || params.status === "cancelled") {
1542
- terminalStatus = params.status;
1543
- terminalMessage = params.message;
1544
- }
1545
- return;
1546
- }
1547
- if (value.method === "run.end") {
1548
- const params = value.params ?? {};
1549
- if (!runId || params.run_id !== runId) return;
1550
- if (typeof params.final === "string") {
1551
- finalText = params.final;
1552
- }
1553
- return;
1554
- }
1555
- if (value.method === "agent.event") {
1556
- const params = value.params ?? {};
1557
- if (!runId || params.run_id !== runId) return;
1558
- if (params.event?.type === "final" && typeof params.event.content === "string") {
1559
- finalText = params.event.content;
1560
- }
1561
- const event = params.event;
1562
- if (emitProgressToStderr && event && event.type !== "final") {
1563
- const summary = summarizeProgressEvent(event);
1564
- if (summary) {
1565
- process.stderr.write(`${summary}
1566
- `);
1567
- }
1568
- }
1569
- }
1570
- };
1571
- child.on("error", (error) => {
1572
- failPending(
1573
- error instanceof Error ? error : new Error(`runtime process error: ${String(error)}`)
1574
- );
1575
- });
1576
- child.on("close", (code, signal) => {
1577
- if (terminalStatus) return;
1578
- failPending(
1579
- new Error(
1580
- `runtime exited before completion (code=${String(code)} signal=${String(signal)})`
1581
- )
1582
- );
1583
- });
1584
- child.stdin.on("error", (error) => {
1585
- failPending(
1586
- error instanceof Error ? error : new Error(`runtime stdin error: ${String(error)}`)
1587
- );
1588
- });
1589
- child.stdout.setEncoding("utf8");
1590
- child.stdout.on("data", (chunk) => {
1591
- buffer += chunk;
1592
- let index = buffer.indexOf("\n");
1593
- while (index >= 0) {
1594
- const line = buffer.slice(0, index).trim();
1595
- buffer = buffer.slice(index + 1);
1596
- if (line.length > 0) {
1597
- try {
1598
- const parsed = JSON.parse(line);
1599
- if (isRpcResponse(parsed)) {
1600
- const pending = pendingResponses.get(String(parsed.id));
1601
- if (pending) {
1602
- pendingResponses.delete(String(parsed.id));
1603
- pending.resolve(parsed);
1604
- }
1605
- }
1606
- maybeTrackRunLifecycle(parsed);
1607
- } catch {
1608
- }
1609
- }
1610
- index = buffer.indexOf("\n");
1611
- }
1612
- });
1613
- child.stderr.setEncoding("utf8");
1614
- child.stderr.on("data", (chunk) => {
1615
- process.stderr.write(chunk);
1616
- });
1617
- try {
1618
- sendRequest({
1619
- jsonrpc: "2.0",
1620
- id: "init-1",
1621
- method: "initialize",
1622
- params: {
1623
- protocol_version: "0",
1624
- client: { name: "codelia-cli-prompt", version: "0.1.0" },
1625
- ui_capabilities: {
1626
- supports_confirm: false,
1627
- supports_prompt: false,
1628
- supports_pick: false
1629
- }
1630
- }
1631
- });
1632
- const initResponse = await waitResponse("init-1");
1633
- if (initResponse.error) {
1634
- throw new Error(`initialize failed: ${initResponse.error.message}`);
1635
- }
1636
- sendRequest({
1637
- jsonrpc: "2.0",
1638
- id: "run-1",
1639
- method: "run.start",
1640
- params: {
1641
- input: { type: "text", text: options.prompt }
1642
- }
1643
- });
1644
- const runResponse = await waitResponse("run-1");
1645
- if (runResponse.error) {
1646
- throw new Error(`run.start failed: ${runResponse.error.message}`);
1647
- }
1648
- const runResult = typeof runResponse.result === "object" && runResponse.result !== null ? runResponse.result : null;
1649
- runId = typeof runResult?.run_id === "string" ? runResult.run_id : null;
1650
- sessionLogPath = typeof runResult?.session_log_path === "string" ? runResult.session_log_path : null;
1651
- if (!runId) {
1652
- throw new Error("run.start did not return run_id");
1653
- }
1654
- await new Promise((resolve, reject) => {
1655
- const timeout = setInterval(() => {
1656
- if (terminalStatus) {
1657
- clearInterval(timeout);
1658
- resolve();
1659
- return;
1660
- }
1661
- if (startupFailure) {
1662
- clearInterval(timeout);
1663
- reject(startupFailure);
1664
- }
1665
- }, 50);
1666
- });
1667
- } catch (error) {
1668
- cleanupSignalHandlers();
1669
- console.error(
1670
- `Prompt run failed: ${error instanceof Error ? error.message : String(error)}`
1671
- );
1672
- return 1;
1673
- } finally {
1674
- if (!child.killed) {
1675
- child.kill();
1676
- }
1677
- }
1678
- if (terminalStatus === "completed") {
1679
- try {
1680
- await writeAtifOnce();
1681
- } catch (error) {
1682
- cleanupSignalHandlers();
1683
- console.error(
1684
- `Failed to write ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
1685
- );
1686
- return 1;
1687
- }
1688
- cleanupSignalHandlers();
1689
- if (finalText.trim().length > 0) {
1690
- console.log(finalText);
1691
- }
1692
- return 0;
1693
- }
1694
- try {
1695
- await writeAtifOnce();
1696
- } catch (error) {
1697
- console.error(
1698
- `Failed to write partial ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
1699
- );
1700
- }
1701
- cleanupSignalHandlers();
1702
- if (terminalMessage) {
1703
- console.error(terminalMessage);
1704
- }
1705
- return terminalStatus === "cancelled" ? 130 : 1;
1706
- };
1707
-
1708
132
  // src/index.ts
1709
133
  var args = process.argv.slice(2);
134
+ var packageRoot = resolveLoadedCliPackageRoot();
1710
135
  var main = async () => {
1711
136
  switch (resolveTopLevelAction(args)) {
1712
137
  case "help":
@@ -1715,28 +140,62 @@ var main = async () => {
1715
140
  case "version":
1716
141
  console.log(CLI_VERSION);
1717
142
  return;
143
+ case "auth": {
144
+ const { runAuthCommand } = await import("./auth-VNP4GLGX.js");
145
+ process.exitCode = await runAuthCommand(args.slice(1));
146
+ return;
147
+ }
1718
148
  case "mcp": {
1719
- const exitCode = await runMcpCommand(args.slice(1));
1720
- process.exitCode = exitCode;
149
+ const { runMcpCommand } = await import("./mcp-GB4CGP6K.js");
150
+ process.exitCode = await runMcpCommand(args.slice(1));
1721
151
  return;
1722
152
  }
1723
153
  case "session": {
154
+ const { runSessionCommand } = await import("./session-2EB4JKFW.js");
1724
155
  process.exitCode = await runSessionCommand(args.slice(1));
1725
156
  return;
1726
157
  }
158
+ case "update": {
159
+ const { runUpdateCommand } = await import("./update-IM6H3PZR.js");
160
+ process.exitCode = await runUpdateCommand(args.slice(1), { packageRoot });
161
+ return;
162
+ }
1727
163
  case "prompt": {
1728
164
  const prompt = validatePromptText(resolvePromptText(args));
1729
- const approvalMode = resolvePromptModeApproval(args);
1730
- const exitCode = await runPromptMode({
165
+ const sandboxMode = resolvePromptModeSandbox(args);
166
+ const approvalMode = sandboxMode ? void 0 : resolvePromptModeApproval(args);
167
+ const { runPromptMode } = await import("./prompt-mode-CNJKMBMF.js");
168
+ process.exitCode = await runPromptMode({
1731
169
  prompt,
1732
- approvalMode
170
+ approvalMode,
171
+ sandboxMode,
172
+ harborShellApproval: hasHarborShellApprovalFlag(args)
1733
173
  });
1734
- process.exitCode = exitCode;
1735
174
  return;
1736
175
  }
1737
- case "tui":
1738
- runTui(args);
176
+ case "tui": {
177
+ const { prepareTuiLaunch } = await import("./launch-OTCP4VZR.js");
178
+ const prepared = await prepareTuiLaunch({
179
+ args,
180
+ currentVersion: CLI_VERSION,
181
+ packageRoot
182
+ });
183
+ if (prepared.kind === "exit") {
184
+ process.exitCode = prepared.exitCode;
185
+ return;
186
+ }
187
+ try {
188
+ const { runTui } = await import("./launcher-2HVS2HZE.js");
189
+ runTui(args, prepared.session, packageRoot);
190
+ } catch (error) {
191
+ prepared.session.dispose();
192
+ throw error;
193
+ }
1739
194
  return;
195
+ }
1740
196
  }
1741
197
  };
1742
- void main();
198
+ void main().catch((error) => {
199
+ console.error(error instanceof Error ? error.message : String(error));
200
+ process.exitCode = 1;
201
+ });