@codelia/cli 0.1.86 → 0.1.90

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