@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.cjs CHANGED
@@ -6,6 +6,13 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
  var __copyProps = (to, from, except, desc) => {
10
17
  if (from && typeof from === "object" || typeof from === "function") {
11
18
  for (let key of __getOwnPropNames(from))
@@ -23,824 +30,864 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
30
  mod
24
31
  ));
25
32
 
26
- // src/basic-options.ts
27
- var TOP_LEVEL_HELP_TEXT = [
28
- "usage: codelia [options] [-- <tui-options>]",
29
- "",
30
- "Top-level options:",
31
- " -h, --help Show this help",
32
- " -V, -v, --version Show codelia version",
33
- " -p, --prompt <text> Run one headless prompt and exit",
34
- "",
35
- "Commands:",
36
- " mcp ... Manage MCP servers and auth",
37
- " session ... List, pin, archive, or clean up session run logs",
38
- "",
39
- "Runtime options:",
40
- " --approval-mode <minimal|trusted|full-access>",
41
- "",
42
- "TUI options (passed through):",
43
- " -r, --resume [session_id]",
44
- " --debug[=true|false]",
45
- " --diagnostics[=true|false]",
46
- " --initial-message <text>",
47
- " --initial-user-message <text>",
48
- " --tui-mode <auto|inline|alternate>",
49
- " --debug-perf[=true|false]",
50
- " --approval-mode <minimal|trusted|full-access>"
51
- ].join("\n");
52
- var isHelpFlag = (value) => value === "-h" || value === "--help" || value === "help";
53
- var isVersionFlag = (value) => value === "-V" || value === "-v" || value === "--version" || value === "version";
54
- var hasPromptFlag = (args2) => {
55
- for (let i = 0; i < args2.length; i += 1) {
56
- const current = args2[i];
57
- if (current === "--") {
58
- break;
59
- }
60
- if (current === "-p" || current === "--prompt") {
61
- return true;
62
- }
63
- if (current.startsWith("--prompt=")) {
64
- return true;
65
- }
66
- }
67
- return false;
68
- };
69
- var resolveTopLevelAction = (args2) => {
70
- if (args2[0] === "session") return "session";
71
- if (args2[0] === "mcp") {
72
- return "mcp";
73
- }
74
- if (args2.length === 1 && isHelpFlag(args2[0])) {
75
- return "help";
76
- }
77
- if (args2.length === 1 && isVersionFlag(args2[0])) {
78
- return "version";
79
- }
80
- if (hasPromptFlag(args2)) {
81
- return "prompt";
33
+ // src/package-root.ts
34
+ var import_node_fs, import_node_path, import_node_url, import_meta, installedCliRoot, resolveCliPackageRoot, resolveLoadedCliPackageRoot;
35
+ var init_package_root = __esm({
36
+ "src/package-root.ts"() {
37
+ "use strict";
38
+ import_node_fs = __toESM(require("fs"), 1);
39
+ import_node_path = __toESM(require("path"), 1);
40
+ import_node_url = require("url");
41
+ import_meta = {};
42
+ installedCliRoot = (file) => {
43
+ let candidate = file;
44
+ while (import_node_path.default.dirname(candidate) !== candidate) {
45
+ const scope = import_node_path.default.dirname(candidate);
46
+ if (import_node_path.default.basename(candidate) === "cli" && import_node_path.default.basename(scope) === "@codelia" && import_node_path.default.basename(import_node_path.default.dirname(scope)) === "node_modules") {
47
+ return candidate;
48
+ }
49
+ candidate = scope;
50
+ }
51
+ return null;
52
+ };
53
+ resolveCliPackageRoot = (scriptPath = process.argv[1]) => {
54
+ if (!scriptPath) return null;
55
+ try {
56
+ const resolvedScriptPath = import_node_fs.default.realpathSync(scriptPath);
57
+ const installed = installedCliRoot(resolvedScriptPath);
58
+ if (installed) return installed;
59
+ const scriptDir = import_node_path.default.dirname(resolvedScriptPath);
60
+ if (import_node_path.default.basename(scriptDir) === "dist") {
61
+ return import_node_path.default.dirname(scriptDir);
62
+ }
63
+ return scriptDir;
64
+ } catch {
65
+ return null;
66
+ }
67
+ };
68
+ resolveLoadedCliPackageRoot = () => {
69
+ const fromArgv = resolveCliPackageRoot();
70
+ if (fromArgv) return fromArgv;
71
+ const moduleDir = typeof __dirname === "string" ? __dirname : import_node_path.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
72
+ return installedCliRoot(moduleDir) ?? (import_node_path.default.basename(moduleDir) === "dist" ? import_node_path.default.dirname(moduleDir) : null);
73
+ };
82
74
  }
83
- return "tui";
84
- };
85
- var resolvePromptText = (args2) => {
86
- for (let i = 0; i < args2.length; i += 1) {
87
- const current = args2[i];
88
- if (current === "-p" || current === "--prompt") {
89
- const next = args2[i + 1];
90
- if (!next) return void 0;
91
- return next;
92
- }
93
- if (current.startsWith("--prompt=")) {
94
- return current.slice("--prompt=".length);
95
- }
75
+ });
76
+
77
+ // src/version.ts
78
+ var CLI_VERSION;
79
+ var init_version = __esm({
80
+ "src/version.ts"() {
81
+ "use strict";
82
+ CLI_VERSION = "0.1.89".trim().length > 0 ? "0.1.89" : "0.0.0";
96
83
  }
97
- return void 0;
98
- };
99
- var resolvePromptModeApproval = (args2) => {
100
- for (let i = 0; i < args2.length; i += 1) {
101
- const current = args2[i];
102
- if (current === "--") {
103
- break;
104
- }
105
- if (current === "--approval-mode") {
106
- const next = args2[i + 1];
107
- if (!next || next.trim().length === 0) {
108
- throw new Error(
109
- "--approval-mode requires a value (minimal|trusted|full-access)"
110
- );
84
+ });
85
+
86
+ // src/commands/auth.ts
87
+ var auth_exports = {};
88
+ __export(auth_exports, {
89
+ runAuthCommand: () => runAuthCommand
90
+ });
91
+ var import_storage, USAGE, runAuthCommand;
92
+ var init_auth = __esm({
93
+ "src/commands/auth.ts"() {
94
+ "use strict";
95
+ import_storage = require("@codelia/storage");
96
+ USAGE = "usage: codelia auth authorize-keychain";
97
+ runAuthCommand = async (args2) => {
98
+ if (args2.length === 1 && ["-h", "--help", "help"].includes(args2[0])) {
99
+ console.log(USAGE);
100
+ return 0;
111
101
  }
112
- return next.trim();
113
- }
114
- if (current.startsWith("--approval-mode=")) {
115
- const value = current.slice("--approval-mode=".length).trim();
116
- if (value.length === 0) {
117
- throw new Error(
118
- "--approval-mode requires a value (minimal|trusted|full-access)"
102
+ if (args2.length !== 1 || args2[0] !== "authorize-keychain") {
103
+ console.error(USAGE);
104
+ return 1;
105
+ }
106
+ if (process.platform !== "darwin" || !process.stdin.isTTY || !process.stderr.isTTY) {
107
+ console.error("Run this command from a local macOS terminal.");
108
+ return 1;
109
+ }
110
+ try {
111
+ const paths = (0, import_storage.resolveStoragePaths)();
112
+ const client = new import_storage.MacOsKeychainClient();
113
+ const account = (0, import_storage.keychainAccountForConfigDir)(paths.configDir);
114
+ const probe = await client.probe();
115
+ if (!probe.available) {
116
+ console.error(probe.message);
117
+ return 1;
118
+ }
119
+ console.error(
120
+ "If macOS requests access, choose Always Allow to authorize Keychain access."
121
+ );
122
+ let failed = false;
123
+ await (0, import_storage.withAuthStoreLock)((0, import_storage.authLockPathFor)(paths.credentialsDir), async () => {
124
+ for (const service of [
125
+ import_storage.CODELIA_AUTH_KEYCHAIN_SERVICE,
126
+ import_storage.CODELIA_MCP_AUTH_KEYCHAIN_SERVICE
127
+ ]) {
128
+ try {
129
+ const found = await client.authorize(service, account);
130
+ console.log(
131
+ `${service}: ${found ? "access granted" : "no item found"}`
132
+ );
133
+ } catch (error) {
134
+ failed = true;
135
+ const message = error instanceof import_storage.KeychainError ? error.message : "Keychain authorization failed.";
136
+ console.error(`${service}: ${message}`);
137
+ }
138
+ }
139
+ });
140
+ return failed ? 1 : 0;
141
+ } catch (error) {
142
+ console.error(
143
+ error instanceof import_storage.KeychainError ? error.message : "Keychain authorization failed."
119
144
  );
145
+ return 1;
120
146
  }
121
- return value;
122
- }
123
- }
124
- return void 0;
125
- };
126
- var validatePromptText = (value) => {
127
- const text = value?.trim() ?? "";
128
- if (text.length === 0) {
129
- throw new Error("Prompt is required after -p/--prompt");
147
+ };
130
148
  }
131
- return text;
132
- };
149
+ });
133
150
 
134
151
  // src/args.ts
135
- var import_cac = require("cac");
136
- var parseWithCac = (values) => {
137
- const cli = (0, import_cac.cac)("codelia-args");
138
- cli.command("[...positionals]").allowUnknownOptions();
139
- const parsed = cli.parse(["node", "codelia-args", ...values], {
140
- run: false
141
- });
142
- return {
143
- args: [...parsed.args],
144
- options: parsed.options
145
- };
146
- };
147
- var parseBoolean = (value, flagName) => {
148
- const normalized = value.trim().toLowerCase();
149
- if (normalized === "true") return true;
150
- if (normalized === "false") return false;
151
- throw new Error(`${flagName} must be true|false`);
152
- };
153
- var parseTimeout = (value) => {
154
- const parsed = Number.parseInt(value, 10);
155
- if (!Number.isFinite(parsed) || parsed <= 0) {
156
- throw new Error("--request-timeout-ms must be a positive integer");
157
- }
158
- return parsed;
159
- };
160
- var parseEpochMs = (value, flagName) => {
161
- const parsed = Number.parseInt(value, 10);
162
- if (!Number.isFinite(parsed) || parsed <= 0) {
163
- throw new Error(`${flagName} must be a positive integer (epoch ms)`);
164
- }
165
- return parsed;
166
- };
167
- var parseKeyValue = (raw, flagName) => {
168
- const [key, ...rest] = raw.split("=");
169
- const value = rest.join("=");
170
- if (!key || !value) {
171
- throw new Error(`${flagName} must be key=value`);
152
+ var import_cac, parseWithCac, parseBoolean, parseTimeout, parseEpochMs, parseKeyValue, parseCliArgs, readOptionValues, getLastFlagValue, getAllFlagValues, hasBooleanFlag;
153
+ var init_args = __esm({
154
+ "src/args.ts"() {
155
+ "use strict";
156
+ import_cac = require("cac");
157
+ parseWithCac = (values) => {
158
+ const cli = (0, import_cac.cac)("codelia-args");
159
+ cli.command("[...positionals]").allowUnknownOptions();
160
+ const parsed = cli.parse(["node", "codelia-args", ...values], {
161
+ run: false
162
+ });
163
+ return {
164
+ args: [...parsed.args],
165
+ options: parsed.options
166
+ };
167
+ };
168
+ parseBoolean = (value, flagName) => {
169
+ const normalized = value.trim().toLowerCase();
170
+ if (normalized === "true") return true;
171
+ if (normalized === "false") return false;
172
+ throw new Error(`${flagName} must be true|false`);
173
+ };
174
+ parseTimeout = (value) => {
175
+ const parsed = Number.parseInt(value, 10);
176
+ if (!Number.isFinite(parsed) || parsed <= 0) {
177
+ throw new Error("--request-timeout-ms must be a positive integer");
178
+ }
179
+ return parsed;
180
+ };
181
+ parseEpochMs = (value, flagName) => {
182
+ const parsed = Number.parseInt(value, 10);
183
+ if (!Number.isFinite(parsed) || parsed <= 0) {
184
+ throw new Error(`${flagName} must be a positive integer (epoch ms)`);
185
+ }
186
+ return parsed;
187
+ };
188
+ parseKeyValue = (raw, flagName) => {
189
+ const [key, ...rest] = raw.split("=");
190
+ const value = rest.join("=");
191
+ if (!key || !value) {
192
+ throw new Error(`${flagName} must be key=value`);
193
+ }
194
+ return [key, value];
195
+ };
196
+ parseCliArgs = (values) => {
197
+ const parsed = parseWithCac(values);
198
+ return {
199
+ positionals: parsed.args,
200
+ options: parsed.options
201
+ };
202
+ };
203
+ readOptionValues = (parsed, flagName) => {
204
+ const value = parsed.options[flagName];
205
+ if (value == null || value === false || value === true) return [];
206
+ const entries = Array.isArray(value) ? value : [value];
207
+ return entries.map((entry) => String(entry));
208
+ };
209
+ getLastFlagValue = (parsed, flagName) => {
210
+ const values = readOptionValues(parsed, flagName);
211
+ if (!values || values.length === 0) return void 0;
212
+ return values[values.length - 1];
213
+ };
214
+ getAllFlagValues = (parsed, flagName) => readOptionValues(parsed, flagName);
215
+ hasBooleanFlag = (parsed, flagName) => parsed.options[flagName] === true;
172
216
  }
173
- return [key, value];
174
- };
175
- var parseCliArgs = (values) => {
176
- const parsed = parseWithCac(values);
177
- return {
178
- positionals: parsed.args,
179
- options: parsed.options
180
- };
181
- };
182
- var readOptionValues = (parsed, flagName) => {
183
- const value = parsed.options[flagName];
184
- if (value == null || value === false || value === true) return [];
185
- const entries = Array.isArray(value) ? value : [value];
186
- return entries.map((entry) => String(entry));
187
- };
188
- var getLastFlagValue = (parsed, flagName) => {
189
- const values = readOptionValues(parsed, flagName);
190
- if (!values || values.length === 0) return void 0;
191
- return values[values.length - 1];
192
- };
193
- var getAllFlagValues = (parsed, flagName) => readOptionValues(parsed, flagName);
194
- var hasBooleanFlag = (parsed, flagName) => parsed.options[flagName] === true;
217
+ });
195
218
 
196
219
  // src/mcp/auth-file.ts
197
- var import_storage = require("@codelia/storage");
198
- var authStore = new import_storage.McpAuthStore();
199
- var readMcpAuth = async () => {
200
- return authStore.load();
201
- };
202
- var writeMcpAuth = async (auth) => {
203
- await authStore.save(auth);
204
- };
205
-
206
- // src/commands/mcp-auth.ts
207
- var runMcpAuthCommand = async (values) => {
208
- const [subcommand, ...rest] = values;
209
- const parsed = parseCliArgs(rest);
210
- if (!subcommand) {
211
- console.error("usage: codelia mcp auth <list|set|clear> ...");
212
- return 1;
213
- }
214
- if (subcommand === "list") {
215
- const auth = await readMcpAuth();
216
- const entries = Object.entries(auth.servers).sort(
217
- ([a], [b]) => a.localeCompare(b)
218
- );
219
- if (!entries.length) {
220
- console.log("no MCP auth tokens configured");
221
- return 0;
222
- }
223
- console.log("server_id has_refresh expires_at");
224
- for (const [serverId, tokens] of entries) {
225
- console.log(
226
- `${serverId} ${tokens.refresh_token ? "yes" : "no"} ${tokens.expires_at ?? "-"}`
227
- );
228
- }
229
- return 0;
230
- }
231
- if (subcommand === "set") {
232
- const serverId = parsed.positionals[0];
233
- if (!serverId) {
234
- console.error(
235
- "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>]"
236
- );
237
- return 1;
238
- }
239
- const accessToken = getLastFlagValue(parsed, "access-token");
240
- if (!accessToken) {
241
- console.error("--access-token is required");
242
- return 1;
243
- }
244
- const refreshToken = getLastFlagValue(parsed, "refresh-token");
245
- const expiresAtRaw = getLastFlagValue(parsed, "expires-at");
246
- const expiresInRaw = getLastFlagValue(parsed, "expires-in");
247
- let expiresAt;
248
- if (expiresAtRaw) {
249
- expiresAt = parseEpochMs(expiresAtRaw, "--expires-at");
250
- } else if (expiresInRaw) {
251
- expiresAt = Date.now() + parseTimeout(expiresInRaw) * 1e3;
252
- }
253
- const scope = getLastFlagValue(parsed, "scope");
254
- const tokenType = getLastFlagValue(parsed, "token-type");
255
- const auth = await readMcpAuth();
256
- auth.servers[serverId] = {
257
- access_token: accessToken,
258
- ...refreshToken ? { refresh_token: refreshToken } : {},
259
- ...expiresAt ? { expires_at: expiresAt } : {},
260
- ...scope ? { scope } : {},
261
- ...tokenType ? { token_type: tokenType } : {}
262
- };
263
- await writeMcpAuth(auth);
264
- console.log(`stored MCP auth token for '${serverId}'`);
265
- return 0;
266
- }
267
- if (subcommand === "clear") {
268
- const serverId = parsed.positionals[0];
269
- if (!serverId) {
270
- console.error("usage: codelia mcp auth clear <server-id>");
271
- return 1;
272
- }
273
- const auth = await readMcpAuth();
274
- if (!auth.servers[serverId]) {
275
- console.error(`no token found for server: ${serverId}`);
276
- return 1;
277
- }
278
- delete auth.servers[serverId];
279
- await writeMcpAuth(auth);
280
- console.log(`cleared MCP auth token for '${serverId}'`);
281
- return 0;
220
+ var import_storage2, readMcpAuth, updateMcpAuth;
221
+ var init_auth_file = __esm({
222
+ "src/mcp/auth-file.ts"() {
223
+ "use strict";
224
+ import_storage2 = require("@codelia/storage");
225
+ readMcpAuth = async () => {
226
+ return new import_storage2.McpAuthStore().load();
227
+ };
228
+ updateMcpAuth = async (mutate) => {
229
+ return new import_storage2.McpAuthStore().update(mutate);
230
+ };
282
231
  }
283
- console.error(`unknown auth subcommand: ${subcommand}`);
284
- return 1;
285
- };
286
-
287
- // src/commands/mcp-config.ts
288
- var import_node_path = __toESM(require("path"), 1);
289
- var import_config_loader = require("@codelia/config-loader");
290
- var import_storage2 = require("@codelia/storage");
291
- var import_zod = require("zod");
292
-
293
- // src/mcp/probe.ts
294
- var import_node_child_process = require("child_process");
295
- var import_node_readline = require("readline");
232
+ });
296
233
 
297
234
  // src/mcp/protocol.ts
298
- var import_protocol = require("@codelia/protocol");
299
- var assertSupportedProtocolVersion = (value) => {
300
- (0, import_protocol.assertSupportedMcpProtocolVersion)(value);
301
- };
235
+ var import_protocol, assertSupportedProtocolVersion;
236
+ var init_protocol = __esm({
237
+ "src/mcp/protocol.ts"() {
238
+ "use strict";
239
+ import_protocol = require("@codelia/protocol");
240
+ assertSupportedProtocolVersion = (value) => {
241
+ (0, import_protocol.assertSupportedMcpProtocolVersion)(value);
242
+ };
243
+ }
244
+ });
302
245
 
303
246
  // src/mcp/probe.ts
304
- var DEFAULT_MCP_TIMEOUT_MS = 3e4;
305
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
306
- var describeError = (error) => error instanceof Error ? error.message : String(error);
307
- var postHttpJson = async (url, body, headers, timeoutMs) => {
308
- const controller = new AbortController();
309
- const timer = setTimeout(() => controller.abort(), timeoutMs);
310
- try {
311
- const response = await fetch(url, {
312
- method: "POST",
313
- headers,
314
- body: JSON.stringify(body),
315
- signal: controller.signal
316
- });
317
- if (!response.ok) {
318
- const bodyText = await response.text().catch(() => "");
319
- throw new Error(`HTTP ${response.status}: ${bodyText.slice(0, 300)}`);
320
- }
321
- const text = await response.text();
322
- const sessionId = response.headers.get("MCP-Session-Id") ?? void 0;
323
- if (!text.trim()) return { body: null, sessionId };
324
- return { body: JSON.parse(text), sessionId };
325
- } catch (error) {
326
- if (controller.signal.aborted) {
327
- throw new Error(`request timed out after ${timeoutMs}ms`);
328
- }
329
- throw error;
330
- } finally {
331
- clearTimeout(timer);
332
- }
333
- };
334
- var parseRpcResult = (raw, requestId) => {
335
- if (Array.isArray(raw)) {
336
- const found = raw.find(
337
- (entry) => isRecord(entry) && String(entry.id ?? "") === requestId
338
- );
339
- if (!found) {
340
- throw new Error(`missing response id=${requestId}`);
341
- }
342
- return parseRpcResult(found, requestId);
343
- }
344
- if (!isRecord(raw)) {
345
- throw new Error("invalid JSON-RPC response");
346
- }
347
- if (isRecord(raw.error)) {
348
- throw new Error(
349
- `RPC ${String(raw.error.code)}: ${String(raw.error.message)}`
350
- );
351
- }
352
- return raw.result;
353
- };
354
- var parseToolsResponse = (raw) => {
355
- if (!isRecord(raw)) return { count: 0 };
356
- const tools = Array.isArray(raw.tools) ? raw.tools.length : 0;
357
- const nextCursor = typeof raw.nextCursor === "string" ? raw.nextCursor : typeof raw.next_cursor === "string" ? raw.next_cursor : void 0;
358
- return { count: tools, nextCursor };
359
- };
360
- var probeHttpServer = async (config) => {
361
- let seq = 0;
362
- let sessionId;
363
- const timeoutMs = config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS;
364
- const protocolVersion = (0, import_protocol.getMcpProtocolVersion)();
365
- const baseHeaders = {
366
- "Content-Type": "application/json",
367
- Accept: "application/json, text/event-stream",
368
- "MCP-Protocol-Version": protocolVersion,
369
- ...config.headers ?? {}
370
- };
371
- const request = async (method, params) => {
372
- seq += 1;
373
- const requestId = `cli-${seq}`;
374
- const headers = {
375
- ...baseHeaders,
376
- ...sessionId ? { "MCP-Session-Id": sessionId } : {}
377
- };
378
- const raw = await postHttpJson(
379
- config.url ?? "",
380
- {
381
- jsonrpc: "2.0",
382
- id: requestId,
383
- method,
384
- params
385
- },
386
- headers,
387
- timeoutMs
388
- );
389
- if (raw.sessionId) {
390
- sessionId = raw.sessionId;
391
- }
392
- return parseRpcResult(raw.body, requestId);
393
- };
394
- const notify = async (method, params) => {
395
- const headers = {
396
- ...baseHeaders,
397
- ...sessionId ? { "MCP-Session-Id": sessionId } : {}
398
- };
399
- const raw = await postHttpJson(
400
- config.url ?? "",
401
- {
402
- jsonrpc: "2.0",
403
- method,
404
- params
405
- },
406
- headers,
407
- timeoutMs
408
- );
409
- if (raw.sessionId) {
410
- sessionId = raw.sessionId;
411
- }
412
- };
413
- const initResult = await request("initialize", {
414
- protocolVersion,
415
- clientInfo: { name: "codelia-cli", version: "0.1.0" },
416
- capabilities: {}
417
- });
418
- assertSupportedProtocolVersion(initResult);
419
- await notify("notifications/initialized", {});
420
- let total = 0;
421
- let cursor;
422
- for (let page = 0; page < 100; page += 1) {
423
- const result = await request("tools/list", cursor ? { cursor } : {});
424
- const parsed = parseToolsResponse(result);
425
- total += parsed.count;
426
- if (!parsed.nextCursor) break;
427
- cursor = parsed.nextCursor;
428
- }
429
- return total;
430
- };
431
- var probeStdioServer = async (config) => {
432
- const timeoutMs = config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS;
433
- const child = (0, import_node_child_process.spawn)(config.command ?? "", config.args ?? [], {
434
- cwd: config.cwd,
435
- env: {
436
- ...process.env,
437
- ...config.env ?? {}
438
- },
439
- stdio: ["pipe", "pipe", "pipe"]
440
- });
441
- let seq = 0;
442
- const pending = /* @__PURE__ */ new Map();
443
- const stdoutReader = (0, import_node_readline.createInterface)({ input: child.stdout });
444
- stdoutReader.on("line", (line) => {
445
- const trimmed = line.trim();
446
- if (!trimmed) return;
447
- let parsed;
448
- try {
449
- parsed = JSON.parse(trimmed);
450
- } catch {
451
- return;
452
- }
453
- if (!isRecord(parsed) || parsed.id === void 0 || parsed.id === null) {
454
- return;
455
- }
456
- const id = String(parsed.id);
457
- const entry = pending.get(id);
458
- if (!entry) return;
459
- pending.delete(id);
460
- clearTimeout(entry.timeout);
461
- if (isRecord(parsed.error)) {
462
- entry.reject(
463
- new Error(
464
- `RPC ${String(parsed.error.code)}: ${String(parsed.error.message)}`
465
- )
466
- );
467
- return;
468
- }
469
- entry.resolve(parsed.result);
470
- });
471
- const stderrReader = (0, import_node_readline.createInterface)({ input: child.stderr });
472
- stderrReader.on("line", () => void 0);
473
- const failPending = (error) => {
474
- for (const [id, entry] of pending) {
475
- pending.delete(id);
476
- clearTimeout(entry.timeout);
477
- entry.reject(error);
478
- }
479
- };
480
- child.once("error", (error) => {
481
- failPending(new Error(`stdio process error: ${describeError(error)}`));
482
- });
483
- child.once("exit", (code, signal) => {
484
- failPending(
485
- new Error(`stdio exited: code=${String(code)} signal=${String(signal)}`)
486
- );
487
- });
488
- const send = (payload) => new Promise((resolve, reject) => {
489
- child.stdin.write(`${JSON.stringify(payload)}
490
- `, (error) => {
491
- if (error) {
492
- reject(error);
493
- return;
247
+ var DEFAULT_MCP_TIMEOUT_MS, isRecord, postHttpJson, parseRpcResult, parseToolsResponse, probeHttpServer, probeStdioServer, probeServer;
248
+ var init_probe = __esm({
249
+ "src/mcp/probe.ts"() {
250
+ "use strict";
251
+ init_protocol();
252
+ DEFAULT_MCP_TIMEOUT_MS = 3e4;
253
+ isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
254
+ postHttpJson = async (url, body, headers, timeoutMs, redirect) => {
255
+ const controller = new AbortController();
256
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
257
+ try {
258
+ const response = await fetch(url, {
259
+ method: "POST",
260
+ redirect,
261
+ headers,
262
+ body: JSON.stringify(body),
263
+ signal: controller.signal
264
+ });
265
+ if (!response.ok) {
266
+ const bodyText = await response.text().catch(() => "");
267
+ throw new Error(`HTTP ${response.status}: ${bodyText.slice(0, 300)}`);
268
+ }
269
+ const text = await response.text();
270
+ const sessionId = response.headers.get("MCP-Session-Id") ?? void 0;
271
+ if (!text.trim()) return { body: null, sessionId };
272
+ return { body: JSON.parse(text), sessionId };
273
+ } catch (error) {
274
+ if (controller.signal.aborted) {
275
+ throw new Error(`request timed out after ${timeoutMs}ms`);
276
+ }
277
+ throw error;
278
+ } finally {
279
+ clearTimeout(timer);
494
280
  }
495
- resolve();
496
- });
497
- });
498
- const request = (method, params) => {
499
- seq += 1;
500
- const requestId = `cli-${seq}`;
501
- return new Promise((resolve, reject) => {
502
- const timeout = setTimeout(() => {
503
- pending.delete(requestId);
504
- reject(new Error(`request timed out after ${timeoutMs}ms`));
505
- }, timeoutMs);
506
- pending.set(requestId, { resolve, reject, timeout });
507
- void send({
508
- jsonrpc: "2.0",
509
- id: requestId,
510
- method,
511
- params
512
- }).catch((error) => {
513
- const entry = pending.get(requestId);
514
- if (!entry) return;
515
- pending.delete(requestId);
516
- clearTimeout(entry.timeout);
517
- reject(new Error(`failed to send request: ${describeError(error)}`));
281
+ };
282
+ parseRpcResult = (raw, requestId) => {
283
+ if (Array.isArray(raw)) {
284
+ const found = raw.find(
285
+ (entry) => isRecord(entry) && String(entry.id ?? "") === requestId
286
+ );
287
+ if (!found) {
288
+ throw new Error(`missing response id=${requestId}`);
289
+ }
290
+ return parseRpcResult(found, requestId);
291
+ }
292
+ if (!isRecord(raw)) {
293
+ throw new Error("invalid JSON-RPC response");
294
+ }
295
+ if (isRecord(raw.error)) {
296
+ throw new Error(
297
+ `RPC ${String(raw.error.code)}: ${String(raw.error.message)}`
298
+ );
299
+ }
300
+ return raw.result;
301
+ };
302
+ parseToolsResponse = (raw) => {
303
+ if (!isRecord(raw)) return { count: 0 };
304
+ const tools = Array.isArray(raw.tools) ? raw.tools.length : 0;
305
+ const nextCursor = typeof raw.nextCursor === "string" ? raw.nextCursor : typeof raw.next_cursor === "string" ? raw.next_cursor : void 0;
306
+ return { count: tools, nextCursor };
307
+ };
308
+ probeHttpServer = async (config) => {
309
+ let seq = 0;
310
+ let sessionId;
311
+ const timeoutMs = config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS;
312
+ const protocolVersion = (0, import_protocol.getMcpProtocolVersion)();
313
+ const baseHeaders = {
314
+ "Content-Type": "application/json",
315
+ Accept: "application/json, text/event-stream",
316
+ "MCP-Protocol-Version": protocolVersion,
317
+ ...config.headers ?? {}
318
+ };
319
+ const hasConfiguredHeaders = Object.keys(config.headers ?? {}).length > 0;
320
+ const send = async (message) => {
321
+ const raw = await postHttpJson(
322
+ config.url ?? "",
323
+ { jsonrpc: "2.0", ...message },
324
+ { ...baseHeaders, ...sessionId ? { "MCP-Session-Id": sessionId } : {} },
325
+ timeoutMs,
326
+ hasConfiguredHeaders || sessionId ? "error" : "follow"
327
+ );
328
+ if (raw.sessionId) sessionId = raw.sessionId;
329
+ return raw.body;
330
+ };
331
+ const request = async (method, params) => {
332
+ const id = `cli-${++seq}`;
333
+ return parseRpcResult(await send({ id, method, params }), id);
334
+ };
335
+ const initResult = await request("initialize", {
336
+ protocolVersion,
337
+ clientInfo: { name: "codelia-cli", version: "0.1.0" },
338
+ capabilities: {}
518
339
  });
519
- });
520
- };
521
- const notify = async (method, params) => {
522
- await send({ jsonrpc: "2.0", method, params });
523
- };
524
- try {
525
- const initResult = await request("initialize", {
526
- protocolVersion: (0, import_protocol.getMcpProtocolVersion)(),
527
- clientInfo: { name: "codelia-cli", version: "0.1.0" },
528
- capabilities: {}
529
- });
530
- assertSupportedProtocolVersion(initResult);
531
- await notify("notifications/initialized", {});
532
- let total = 0;
533
- let cursor;
534
- for (let page = 0; page < 100; page += 1) {
535
- const result = await request("tools/list", cursor ? { cursor } : {});
536
- const parsed = parseToolsResponse(result);
537
- total += parsed.count;
538
- if (!parsed.nextCursor) break;
539
- cursor = parsed.nextCursor;
540
- }
541
- return total;
542
- } finally {
543
- child.kill("SIGTERM");
544
- stdoutReader.close();
545
- stderrReader.close();
546
- }
547
- };
548
- var probeServer = async (config) => {
549
- if (config.transport === "http") {
550
- return probeHttpServer(config);
551
- }
552
- return probeStdioServer(config);
553
- };
554
-
555
- // src/commands/mcp-config.ts
556
- var TIMEOUT_SCHEMA = import_zod.z.number().positive().transform((value) => Math.round(value));
557
- var OAUTH_SCHEMA = import_zod.z.object({
558
- authorization_url: import_zod.z.string(),
559
- token_url: import_zod.z.string(),
560
- registration_url: import_zod.z.string(),
561
- client_id: import_zod.z.string(),
562
- client_secret: import_zod.z.string(),
563
- scope: import_zod.z.string()
564
- }).partial();
565
- var HTTP_SERVER_CONFIG_SCHEMA = import_zod.z.object({
566
- transport: import_zod.z.literal("http"),
567
- enabled: import_zod.z.boolean().optional(),
568
- url: import_zod.z.string(),
569
- headers: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional(),
570
- env: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional(),
571
- request_timeout_ms: TIMEOUT_SCHEMA.optional(),
572
- oauth: OAUTH_SCHEMA.optional()
573
- });
574
- var STDIO_SERVER_CONFIG_SCHEMA = import_zod.z.object({
575
- transport: import_zod.z.literal("stdio"),
576
- enabled: import_zod.z.boolean().optional(),
577
- command: import_zod.z.string(),
578
- args: import_zod.z.array(import_zod.z.string()).optional(),
579
- cwd: import_zod.z.string().optional(),
580
- env: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional(),
581
- request_timeout_ms: TIMEOUT_SCHEMA.optional(),
582
- oauth: OAUTH_SCHEMA.optional()
583
- });
584
- var MCP_SERVER_CONFIG_SCHEMA = import_zod.z.union([
585
- HTTP_SERVER_CONFIG_SCHEMA,
586
- STDIO_SERVER_CONFIG_SCHEMA
587
- ]);
588
- var describeError2 = (error) => error instanceof Error ? error.message : String(error);
589
- var readEnvValue = (key) => {
590
- const value = process.env[key];
591
- if (!value) return void 0;
592
- const trimmed = value.trim();
593
- return trimmed ? trimmed : void 0;
594
- };
595
- var resolveGlobalConfigPath = () => {
596
- const envPath = readEnvValue("CODELIA_CONFIG_PATH");
597
- if (envPath) return import_node_path.default.resolve(envPath);
598
- const storage = (0, import_storage2.resolveStoragePaths)();
599
- return storage.configFile;
600
- };
601
- var resolveProjectConfigPath = () => import_node_path.default.resolve(process.cwd(), ".codelia", "config.json");
602
- var normalizeServerConfig = (value) => {
603
- const parsed = MCP_SERVER_CONFIG_SCHEMA.safeParse(value);
604
- return parsed.success ? parsed.data : null;
605
- };
606
- var normalizeEntries = (servers, source) => {
607
- const entries = [];
608
- for (const [id, rawConfig] of Object.entries(servers)) {
609
- const config = normalizeServerConfig(rawConfig);
610
- if (!config) continue;
611
- entries.push({ id, config, source });
612
- }
613
- return entries.sort((left, right) => left.id.localeCompare(right.id));
614
- };
615
- var loadEntriesByScope = async (scope) => {
616
- const globalServers = await (0, import_config_loader.loadMcpServers)(resolveGlobalConfigPath());
617
- const projectServers = await (0, import_config_loader.loadMcpServers)(resolveProjectConfigPath());
618
- if (scope === "global") {
619
- return normalizeEntries(globalServers, "global");
620
- }
621
- if (scope === "project") {
622
- return normalizeEntries(projectServers, "project");
623
- }
624
- const merged = /* @__PURE__ */ new Map();
625
- for (const entry of normalizeEntries(globalServers, "global")) {
626
- merged.set(entry.id, entry);
627
- }
628
- for (const entry of normalizeEntries(projectServers, "project")) {
629
- merged.set(entry.id, entry);
630
- }
631
- return Array.from(merged.values()).sort(
632
- (left, right) => left.id.localeCompare(right.id)
633
- );
634
- };
635
- var resolveMutableScope = (parsed) => {
636
- const scopeRaw = getLastFlagValue(parsed, "scope") ?? "project";
637
- if (scopeRaw === "project" || scopeRaw === "global") {
638
- return scopeRaw;
639
- }
640
- throw new Error("--scope must be project|global");
641
- };
642
- var resolveListScope = (parsed) => {
643
- const scopeRaw = getLastFlagValue(parsed, "scope") ?? "effective";
644
- if (scopeRaw === "project" || scopeRaw === "global" || scopeRaw === "effective") {
645
- return scopeRaw;
646
- }
647
- throw new Error("--scope must be effective|project|global");
648
- };
649
- var buildServerConfigFromAdd = (parsed) => {
650
- const transport = getLastFlagValue(parsed, "transport");
651
- if (transport !== "http" && transport !== "stdio") {
652
- throw new Error("--transport must be http|stdio");
653
- }
654
- const enabledRaw = getLastFlagValue(parsed, "enabled");
655
- const enabled = enabledRaw ? parseBoolean(enabledRaw, "--enabled") : true;
656
- const timeoutRaw = getLastFlagValue(parsed, "request-timeout-ms");
657
- const requestTimeoutMs = timeoutRaw ? parseTimeout(timeoutRaw) : void 0;
658
- const oauth = {
659
- authorization_url: getLastFlagValue(parsed, "oauth-authorization-url"),
660
- token_url: getLastFlagValue(parsed, "oauth-token-url"),
661
- registration_url: getLastFlagValue(parsed, "oauth-registration-url"),
662
- client_id: getLastFlagValue(parsed, "oauth-client-id"),
663
- client_secret: getLastFlagValue(parsed, "oauth-client-secret"),
664
- scope: getLastFlagValue(parsed, "oauth-scope")
665
- };
666
- const oauthConfig = Object.fromEntries(
667
- Object.entries(oauth).filter(([, value]) => !!value)
668
- );
669
- if (transport === "http") {
670
- const url = getLastFlagValue(parsed, "url");
671
- if (!url) throw new Error("--url is required when --transport=http");
672
- const headers = Object.fromEntries(
673
- getAllFlagValues(parsed, "header").map(
674
- (value) => parseKeyValue(value, "--header")
675
- )
676
- );
677
- return {
678
- transport,
679
- ...enabled !== true ? { enabled } : {},
680
- url,
681
- ...Object.keys(headers).length ? { headers } : {},
682
- ...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
683
- ...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
340
+ assertSupportedProtocolVersion(initResult);
341
+ await send({ method: "notifications/initialized", params: {} });
342
+ let total = 0;
343
+ let cursor;
344
+ for (let page = 0; page < 100; page += 1) {
345
+ const result = await request("tools/list", cursor ? { cursor } : {});
346
+ const parsed = parseToolsResponse(result);
347
+ total += parsed.count;
348
+ if (!parsed.nextCursor) break;
349
+ cursor = parsed.nextCursor;
350
+ }
351
+ return total;
352
+ };
353
+ probeStdioServer = async (config, serverId) => {
354
+ const { createLocalMcpStdioProbeClient } = await import("@codelia/runtime/sdk");
355
+ const client = await createLocalMcpStdioProbeClient(serverId, config);
356
+ const options = {
357
+ timeoutMs: config.request_timeout_ms ?? DEFAULT_MCP_TIMEOUT_MS
358
+ };
359
+ try {
360
+ const initResult = await client.request(
361
+ "initialize",
362
+ {
363
+ protocolVersion: (0, import_protocol.getMcpProtocolVersion)(),
364
+ clientInfo: { name: "codelia-cli", version: "0.1.0" },
365
+ capabilities: {}
366
+ },
367
+ options
368
+ );
369
+ assertSupportedProtocolVersion(initResult);
370
+ await client.notify("notifications/initialized", {});
371
+ let total = 0;
372
+ let cursor;
373
+ for (let page = 0; page < 100; page += 1) {
374
+ const result = await client.request(
375
+ "tools/list",
376
+ cursor ? { cursor } : {},
377
+ options
378
+ );
379
+ const parsed = parseToolsResponse(result);
380
+ total += parsed.count;
381
+ if (!parsed.nextCursor) break;
382
+ cursor = parsed.nextCursor;
383
+ }
384
+ return total;
385
+ } finally {
386
+ await client.close();
387
+ }
388
+ };
389
+ probeServer = async (config, serverId) => {
390
+ if (config.transport === "http") {
391
+ return probeHttpServer(config);
392
+ }
393
+ return probeStdioServer(config, serverId);
684
394
  };
685
395
  }
686
- const command = getLastFlagValue(parsed, "command");
687
- if (!command) {
688
- throw new Error("--command is required when --transport=stdio");
689
- }
690
- const env = Object.fromEntries(
691
- getAllFlagValues(parsed, "env").map(
692
- (value) => parseKeyValue(value, "--env")
693
- )
694
- );
695
- const args2 = getAllFlagValues(parsed, "arg");
696
- const cwd = getLastFlagValue(parsed, "cwd");
697
- return {
698
- transport,
699
- ...enabled !== true ? { enabled } : {},
700
- command,
701
- ...args2.length ? { args: args2 } : {},
702
- ...cwd ? { cwd } : {},
703
- ...Object.keys(env).length ? { env } : {},
704
- ...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
705
- ...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
706
- };
707
- };
708
- var printStaticList = (entries) => {
709
- if (!entries.length) {
710
- console.log("no MCP servers configured");
711
- return;
712
- }
713
- console.log("id transport source enabled");
714
- for (const entry of entries) {
715
- const enabled = entry.config.enabled !== false;
716
- console.log(
717
- `${entry.id} ${entry.config.transport} ${entry.source} ${enabled}`
718
- );
719
- }
720
- };
721
- var runMcpConfigCommand = async (subcommand, rest) => {
722
- const parsed = parseCliArgs(rest);
723
- if (subcommand === "list") {
724
- const scope = resolveListScope(parsed);
725
- const entries = await loadEntriesByScope(scope);
726
- printStaticList(entries);
727
- return 0;
728
- }
729
- if (subcommand === "add") {
730
- const serverId = parsed.positionals[0];
731
- if (!serverId) {
732
- console.error(
733
- "usage: codelia mcp add <server-id> --transport <http|stdio> ..."
396
+ });
397
+
398
+ // src/commands/mcp-config.ts
399
+ var import_node_path2, import_config_loader, import_storage3, import_zod, TIMEOUT_SCHEMA, OAUTH_SCHEMA, HTTP_SERVER_CONFIG_SCHEMA, STDIO_SERVER_CONFIG_SCHEMA, MCP_SERVER_CONFIG_SCHEMA, describeError, readEnvValue, resolveGlobalConfigPath, resolveProjectConfigPath, resolveDistinctProjectConfigPath, SHARED_CONFIG_SCOPE_ERROR, normalizeServerConfig, normalizeEntries, loadEntriesByScope, resolveMutableScope, resolveListScope, buildServerConfigFromAdd, printStaticList, runMcpConfigCommand;
400
+ var init_mcp_config = __esm({
401
+ "src/commands/mcp-config.ts"() {
402
+ "use strict";
403
+ import_node_path2 = __toESM(require("path"), 1);
404
+ import_config_loader = require("@codelia/config-loader");
405
+ import_storage3 = require("@codelia/storage");
406
+ import_zod = require("zod");
407
+ init_args();
408
+ init_auth_file();
409
+ init_probe();
410
+ TIMEOUT_SCHEMA = import_zod.z.number().positive().transform((value) => Math.round(value));
411
+ OAUTH_SCHEMA = import_zod.z.object({
412
+ authorization_url: import_zod.z.string(),
413
+ token_url: import_zod.z.string(),
414
+ registration_url: import_zod.z.string(),
415
+ client_id: import_zod.z.string(),
416
+ client_secret: import_zod.z.string(),
417
+ scope: import_zod.z.string()
418
+ }).partial();
419
+ HTTP_SERVER_CONFIG_SCHEMA = import_zod.z.object({
420
+ transport: import_zod.z.literal("http"),
421
+ enabled: import_zod.z.boolean().optional(),
422
+ url: import_zod.z.string(),
423
+ headers: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional(),
424
+ env: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional(),
425
+ request_timeout_ms: TIMEOUT_SCHEMA.optional(),
426
+ oauth: OAUTH_SCHEMA.optional()
427
+ });
428
+ STDIO_SERVER_CONFIG_SCHEMA = import_zod.z.object({
429
+ transport: import_zod.z.literal("stdio"),
430
+ enabled: import_zod.z.boolean().optional(),
431
+ command: import_zod.z.string(),
432
+ args: import_zod.z.array(import_zod.z.string()).optional(),
433
+ cwd: import_zod.z.string().optional(),
434
+ env: import_zod.z.record(import_zod.z.string(), import_zod.z.string()).optional(),
435
+ request_timeout_ms: TIMEOUT_SCHEMA.optional(),
436
+ oauth: OAUTH_SCHEMA.optional()
437
+ });
438
+ MCP_SERVER_CONFIG_SCHEMA = import_zod.z.union([
439
+ HTTP_SERVER_CONFIG_SCHEMA,
440
+ STDIO_SERVER_CONFIG_SCHEMA
441
+ ]);
442
+ describeError = (error) => error instanceof Error ? error.message : String(error);
443
+ readEnvValue = (key) => {
444
+ const value = process.env[key];
445
+ if (!value) return void 0;
446
+ const trimmed = value.trim();
447
+ return trimmed ? trimmed : void 0;
448
+ };
449
+ resolveGlobalConfigPath = () => {
450
+ const envPath = readEnvValue("CODELIA_CONFIG_PATH");
451
+ if (envPath) return import_node_path2.default.resolve(envPath);
452
+ const storage = (0, import_storage3.resolveStoragePaths)();
453
+ return storage.configFile;
454
+ };
455
+ resolveProjectConfigPath = () => import_node_path2.default.resolve(process.cwd(), ".codelia", "config.json");
456
+ resolveDistinctProjectConfigPath = () => {
457
+ const projectPath = resolveProjectConfigPath();
458
+ return (0, import_storage3.isSameConfigFilePath)(resolveGlobalConfigPath(), projectPath) ? null : projectPath;
459
+ };
460
+ SHARED_CONFIG_SCOPE_ERROR = "Project config shares the global config file in this workspace; pass --scope global to update it.";
461
+ normalizeServerConfig = (value) => {
462
+ const parsed = MCP_SERVER_CONFIG_SCHEMA.safeParse(value);
463
+ return parsed.success ? parsed.data : null;
464
+ };
465
+ normalizeEntries = (servers, source) => {
466
+ const entries = [];
467
+ for (const [id, rawConfig] of Object.entries(servers)) {
468
+ const config = normalizeServerConfig(rawConfig);
469
+ if (!config) continue;
470
+ entries.push({ id, config, source });
471
+ }
472
+ return entries.sort((left, right) => left.id.localeCompare(right.id));
473
+ };
474
+ loadEntriesByScope = async (scope) => {
475
+ const globalPath = resolveGlobalConfigPath();
476
+ const projectPath = resolveDistinctProjectConfigPath();
477
+ const globalServers = await (0, import_config_loader.loadMcpServers)(globalPath);
478
+ const projectServers = projectPath ? await (0, import_config_loader.loadMcpServers)(projectPath) : {};
479
+ const globalSource = (0, import_storage3.isTrustedGlobalConfigLocationSync)(
480
+ process.cwd(),
481
+ globalPath
482
+ ) ? "global" : "project";
483
+ if (scope === "global") {
484
+ return normalizeEntries(globalServers, "global");
485
+ }
486
+ if (scope === "project") {
487
+ return normalizeEntries(projectServers, "project");
488
+ }
489
+ const merged = /* @__PURE__ */ new Map();
490
+ for (const entry of normalizeEntries(globalServers, globalSource)) {
491
+ merged.set(entry.id, entry);
492
+ }
493
+ for (const entry of normalizeEntries(projectServers, "project")) {
494
+ merged.set(entry.id, entry);
495
+ }
496
+ return Array.from(merged.values()).sort(
497
+ (left, right) => left.id.localeCompare(right.id)
734
498
  );
735
- return 1;
736
- }
737
- const scope = resolveMutableScope(parsed);
738
- const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveProjectConfigPath();
739
- const servers = await (0, import_config_loader.loadMcpServers)(configPath);
740
- const replace = hasBooleanFlag(parsed, "replace");
741
- if (servers[serverId] !== void 0 && !replace) {
742
- console.error(`server already exists in ${scope} scope: ${serverId}`);
743
- console.error("pass --replace to overwrite");
744
- return 1;
745
- }
746
- const serverConfig = buildServerConfigFromAdd(parsed);
747
- await (0, import_config_loader.upsertMcpServerConfig)(configPath, serverId, serverConfig);
748
- console.log(`added MCP server '${serverId}' (${scope})`);
749
- return 0;
750
- }
751
- if (subcommand === "remove" || subcommand === "enable" || subcommand === "disable") {
752
- const serverId = parsed.positionals[0];
753
- if (!serverId) {
754
- console.error(
755
- `usage: codelia mcp ${subcommand} <server-id> [--scope project|global]`
499
+ };
500
+ resolveMutableScope = (parsed) => {
501
+ const scopeRaw = getLastFlagValue(parsed, "scope") ?? "project";
502
+ if (scopeRaw === "project" || scopeRaw === "global") {
503
+ return scopeRaw;
504
+ }
505
+ throw new Error("--scope must be project|global");
506
+ };
507
+ resolveListScope = (parsed) => {
508
+ const scopeRaw = getLastFlagValue(parsed, "scope") ?? "effective";
509
+ if (scopeRaw === "project" || scopeRaw === "global" || scopeRaw === "effective") {
510
+ return scopeRaw;
511
+ }
512
+ throw new Error("--scope must be effective|project|global");
513
+ };
514
+ buildServerConfigFromAdd = (parsed) => {
515
+ const transport = getLastFlagValue(parsed, "transport");
516
+ if (transport !== "http" && transport !== "stdio") {
517
+ throw new Error("--transport must be http|stdio");
518
+ }
519
+ const enabledRaw = getLastFlagValue(parsed, "enabled");
520
+ const enabled = enabledRaw ? parseBoolean(enabledRaw, "--enabled") : true;
521
+ const timeoutRaw = getLastFlagValue(parsed, "request-timeout-ms");
522
+ const requestTimeoutMs = timeoutRaw ? parseTimeout(timeoutRaw) : void 0;
523
+ const oauth = {
524
+ authorization_url: getLastFlagValue(parsed, "oauth-authorization-url"),
525
+ token_url: getLastFlagValue(parsed, "oauth-token-url"),
526
+ registration_url: getLastFlagValue(parsed, "oauth-registration-url"),
527
+ client_id: getLastFlagValue(parsed, "oauth-client-id"),
528
+ client_secret: getLastFlagValue(parsed, "oauth-client-secret"),
529
+ scope: getLastFlagValue(parsed, "oauth-scope")
530
+ };
531
+ const oauthConfig = Object.fromEntries(
532
+ Object.entries(oauth).filter(([, value]) => !!value)
756
533
  );
757
- return 1;
758
- }
759
- const scope = resolveMutableScope(parsed);
760
- const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveProjectConfigPath();
761
- if (subcommand === "remove") {
762
- const removed = await (0, import_config_loader.removeMcpServerConfig)(configPath, serverId);
763
- if (!removed) {
764
- console.error(`server not found in ${scope} scope: ${serverId}`);
765
- return 1;
534
+ if (transport === "http") {
535
+ const url = getLastFlagValue(parsed, "url");
536
+ if (!url) throw new Error("--url is required when --transport=http");
537
+ const headers = Object.fromEntries(
538
+ getAllFlagValues(parsed, "header").map(
539
+ (value) => parseKeyValue(value, "--header")
540
+ )
541
+ );
542
+ return {
543
+ transport,
544
+ ...enabled !== true ? { enabled } : {},
545
+ url,
546
+ ...Object.keys(headers).length ? { headers } : {},
547
+ ...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
548
+ ...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
549
+ };
550
+ }
551
+ const command = getLastFlagValue(parsed, "command");
552
+ if (!command) {
553
+ throw new Error("--command is required when --transport=stdio");
766
554
  }
767
- } else {
768
- const updated = await (0, import_config_loader.setMcpServerEnabled)(
769
- configPath,
770
- serverId,
771
- subcommand === "enable"
555
+ const env = Object.fromEntries(
556
+ getAllFlagValues(parsed, "env").map(
557
+ (value) => parseKeyValue(value, "--env")
558
+ )
772
559
  );
773
- if (!updated) {
774
- console.error(`server not found in ${scope} scope: ${serverId}`);
775
- return 1;
560
+ const args2 = getAllFlagValues(parsed, "arg");
561
+ const cwd = getLastFlagValue(parsed, "cwd");
562
+ return {
563
+ transport,
564
+ ...enabled !== true ? { enabled } : {},
565
+ command,
566
+ ...args2.length ? { args: args2 } : {},
567
+ ...cwd ? { cwd } : {},
568
+ ...Object.keys(env).length ? { env } : {},
569
+ ...requestTimeoutMs ? { request_timeout_ms: requestTimeoutMs } : {},
570
+ ...oauthConfig && Object.keys(oauthConfig).length ? { oauth: oauthConfig } : {}
571
+ };
572
+ };
573
+ printStaticList = (entries) => {
574
+ if (!entries.length) {
575
+ console.log("no MCP servers configured");
576
+ return;
776
577
  }
777
- }
778
- console.log(`${subcommand}d MCP server '${serverId}' (${scope})`);
779
- return 0;
578
+ console.log("id transport source enabled");
579
+ for (const entry of entries) {
580
+ const enabled = entry.config.enabled !== false;
581
+ console.log(
582
+ `${entry.id} ${entry.config.transport} ${entry.source} ${enabled}`
583
+ );
584
+ }
585
+ };
586
+ runMcpConfigCommand = async (subcommand, rest) => {
587
+ const parsed = parseCliArgs(rest);
588
+ if (subcommand === "list") {
589
+ const scope = resolveListScope(parsed);
590
+ const entries = await loadEntriesByScope(scope);
591
+ printStaticList(entries);
592
+ return 0;
593
+ }
594
+ if (subcommand === "add") {
595
+ const serverId = parsed.positionals[0];
596
+ if (!serverId) {
597
+ console.error(
598
+ "usage: codelia mcp add <server-id> --transport <http|stdio> ..."
599
+ );
600
+ return 1;
601
+ }
602
+ const scope = resolveMutableScope(parsed);
603
+ const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveDistinctProjectConfigPath();
604
+ if (!configPath) {
605
+ console.error(SHARED_CONFIG_SCOPE_ERROR);
606
+ return 1;
607
+ }
608
+ const servers = await (0, import_config_loader.loadMcpServers)(configPath);
609
+ const replace = hasBooleanFlag(parsed, "replace");
610
+ if (servers[serverId] !== void 0 && !replace) {
611
+ console.error(`server already exists in ${scope} scope: ${serverId}`);
612
+ console.error("pass --replace to overwrite");
613
+ return 1;
614
+ }
615
+ const serverConfig = buildServerConfigFromAdd(parsed);
616
+ await (0, import_config_loader.upsertMcpServerConfig)(configPath, serverId, serverConfig);
617
+ console.log(`added MCP server '${serverId}' (${scope})`);
618
+ return 0;
619
+ }
620
+ if (subcommand === "remove" || subcommand === "enable" || subcommand === "disable") {
621
+ const serverId = parsed.positionals[0];
622
+ if (!serverId) {
623
+ console.error(
624
+ `usage: codelia mcp ${subcommand} <server-id> [--scope project|global]`
625
+ );
626
+ return 1;
627
+ }
628
+ const scope = resolveMutableScope(parsed);
629
+ const configPath = scope === "global" ? resolveGlobalConfigPath() : resolveDistinctProjectConfigPath();
630
+ if (!configPath) {
631
+ console.error(SHARED_CONFIG_SCOPE_ERROR);
632
+ return 1;
633
+ }
634
+ if (subcommand === "remove") {
635
+ const removed = await (0, import_config_loader.removeMcpServerConfig)(configPath, serverId);
636
+ if (!removed) {
637
+ console.error(`server not found in ${scope} scope: ${serverId}`);
638
+ return 1;
639
+ }
640
+ } else {
641
+ const updated = await (0, import_config_loader.setMcpServerEnabled)(
642
+ configPath,
643
+ serverId,
644
+ subcommand === "enable"
645
+ );
646
+ if (!updated) {
647
+ console.error(`server not found in ${scope} scope: ${serverId}`);
648
+ return 1;
649
+ }
650
+ }
651
+ console.log(`${subcommand}d MCP server '${serverId}' (${scope})`);
652
+ return 0;
653
+ }
654
+ if (subcommand === "test") {
655
+ const serverId = parsed.positionals[0];
656
+ if (!serverId) {
657
+ console.error(
658
+ "usage: codelia mcp test <server-id> [--scope effective|project|global]"
659
+ );
660
+ return 1;
661
+ }
662
+ const scope = resolveListScope(parsed);
663
+ const entries = await loadEntriesByScope(scope);
664
+ const target = entries.find((entry) => entry.id === serverId);
665
+ if (!target) {
666
+ console.error(`server not found: ${serverId} (scope=${scope})`);
667
+ return 1;
668
+ }
669
+ try {
670
+ const storedEntry = target.config.transport === "http" && target.config.url ? (await readMcpAuth()).servers[target.id] : void 0;
671
+ let accessToken;
672
+ if (target.config.transport === "http" && target.config.url && storedEntry) {
673
+ const { fetchDiscoveredOAuthConfig, mcpEntryMatchesServer } = await import("@codelia/runtime/sdk");
674
+ const discovered = storedEntry.binding.issuer || storedEntry.binding.token_endpoint ? await fetchDiscoveredOAuthConfig(
675
+ target.config.url,
676
+ AbortSignal.timeout(target.config.request_timeout_ms ?? 3e4)
677
+ ) : {};
678
+ if (mcpEntryMatchesServer(storedEntry, target.config, discovered)) {
679
+ accessToken = storedEntry.tokens.access_token;
680
+ }
681
+ }
682
+ const configForTest = target.config.transport === "http" && accessToken ? {
683
+ ...target.config,
684
+ headers: {
685
+ ...target.config.headers ?? {},
686
+ Authorization: `Bearer ${accessToken}`
687
+ }
688
+ } : target.config;
689
+ const tools = await probeServer(configForTest, target.id);
690
+ console.log(
691
+ `MCP test succeeded: id=${target.id} transport=${target.config.transport} source=${target.source} tools=${tools}`
692
+ );
693
+ return 0;
694
+ } catch (error) {
695
+ console.error(
696
+ `MCP test failed: id=${target.id} transport=${target.config.transport}: ${describeError(error)}`
697
+ );
698
+ return 1;
699
+ }
700
+ }
701
+ return -1;
702
+ };
780
703
  }
781
- if (subcommand === "test") {
782
- const serverId = parsed.positionals[0];
783
- if (!serverId) {
784
- console.error(
785
- "usage: codelia mcp test <server-id> [--scope effective|project|global]"
786
- );
787
- return 1;
788
- }
789
- const scope = resolveListScope(parsed);
790
- const entries = await loadEntriesByScope(scope);
791
- const target = entries.find((entry) => entry.id === serverId);
792
- if (!target) {
793
- console.error(`server not found: ${serverId} (scope=${scope})`);
794
- return 1;
795
- }
796
- try {
797
- const auth = await readMcpAuth();
798
- const accessToken = auth.servers[target.id]?.access_token;
799
- const configForTest = target.config.transport === "http" && accessToken ? {
800
- ...target.config,
801
- headers: {
802
- ...target.config.headers ?? {},
803
- Authorization: `Bearer ${accessToken}`
804
- }
805
- } : target.config;
806
- const tools = await probeServer(configForTest);
807
- console.log(
808
- `MCP test succeeded: id=${target.id} transport=${target.config.transport} source=${target.source} tools=${tools}`
809
- );
810
- return 0;
811
- } catch (error) {
812
- console.error(
813
- `MCP test failed: id=${target.id} transport=${target.config.transport}: ${describeError2(error)}`
814
- );
704
+ });
705
+
706
+ // src/commands/mcp-auth.ts
707
+ var import_node_util, runMcpAuthCommand;
708
+ var init_mcp_auth = __esm({
709
+ "src/commands/mcp-auth.ts"() {
710
+ "use strict";
711
+ import_node_util = require("util");
712
+ init_args();
713
+ init_auth_file();
714
+ init_mcp_config();
715
+ runMcpAuthCommand = async (values) => {
716
+ const [subcommand, ...rest] = values;
717
+ const parsed = (0, import_node_util.parseArgs)({
718
+ args: rest,
719
+ allowPositionals: true,
720
+ options: {
721
+ "access-token": { type: "string" },
722
+ "refresh-token": { type: "string" },
723
+ "expires-at": { type: "string" },
724
+ "expires-in": { type: "string" },
725
+ "token-type": { type: "string" },
726
+ "token-url": { type: "string" },
727
+ "client-id": { type: "string" },
728
+ url: { type: "string" },
729
+ issuer: { type: "string" },
730
+ scope: { type: "string" }
731
+ }
732
+ });
733
+ if (!subcommand) {
734
+ console.error("usage: codelia mcp auth <list|set|clear> ...");
735
+ return 1;
736
+ }
737
+ if (subcommand === "list") {
738
+ const auth = await readMcpAuth();
739
+ const entries = Object.entries(auth.servers).sort(
740
+ ([a], [b]) => a.localeCompare(b)
741
+ );
742
+ if (!entries.length) {
743
+ console.log("no MCP auth tokens configured");
744
+ return 0;
745
+ }
746
+ console.log("server_id resource_uri has_refresh expires_at");
747
+ for (const [serverId, entry] of entries) {
748
+ console.log(
749
+ `${serverId} ${entry.binding.resource_uri} ${entry.tokens.refresh_token ? "yes" : "no"} ${entry.tokens.expires_at ?? "-"}`
750
+ );
751
+ }
752
+ return 0;
753
+ }
754
+ if (subcommand === "set") {
755
+ const serverId = parsed.positionals[0];
756
+ if (!serverId) {
757
+ console.error(
758
+ "usage: codelia mcp auth set <server-id> --access-token <token> [--url <resource-uri>] [--issuer <issuer>] [--token-url <url>] [--client-id <id>] [--refresh-token <token>] [--expires-at <epoch_ms>] [--expires-in <sec>] [--scope <scope>] [--token-type <type>]"
759
+ );
760
+ return 1;
761
+ }
762
+ const accessToken = parsed.values["access-token"];
763
+ if (!accessToken) {
764
+ console.error("--access-token is required");
765
+ return 1;
766
+ }
767
+ const configuredEntries = await loadEntriesByScope("effective").catch(
768
+ () => []
769
+ );
770
+ const configuredServer = configuredEntries.find(
771
+ (entry) => entry.id === serverId
772
+ )?.config;
773
+ const resourceUri = parsed.values.url ?? configuredServer?.url;
774
+ if (!resourceUri) {
775
+ console.error(
776
+ "--url is required when the MCP server URL is not configured"
777
+ );
778
+ return 1;
779
+ }
780
+ const { fetchDiscoveredOAuthConfig, resolveMcpServerBinding } = await import("@codelia/runtime/sdk");
781
+ const refreshToken = parsed.values["refresh-token"];
782
+ const issuer = parsed.values.issuer;
783
+ const tokenUrl = parsed.values["token-url"] ?? configuredServer?.oauth?.token_url;
784
+ const clientId = parsed.values["client-id"] ?? configuredServer?.oauth?.client_id;
785
+ const discovered = (refreshToken || configuredServer?.oauth || tokenUrl) && (!issuer || !tokenUrl) ? await fetchDiscoveredOAuthConfig(
786
+ resourceUri,
787
+ AbortSignal.timeout(configuredServer?.request_timeout_ms ?? 3e4)
788
+ ) : {};
789
+ const binding = resolveMcpServerBinding(
790
+ { url: resourceUri },
791
+ {
792
+ issuer: issuer ?? discovered.issuer,
793
+ token_url: tokenUrl ?? discovered.token_url,
794
+ authorization_url: configuredServer?.oauth?.authorization_url ?? discovered.authorization_url,
795
+ client_id: clientId
796
+ }
797
+ );
798
+ if (!binding || refreshToken && !binding.token_endpoint) {
799
+ console.error(
800
+ "A valid MCP URL is required. For a refresh token, configure or specify --token-url if discovery is unavailable."
801
+ );
802
+ return 1;
803
+ }
804
+ const expiresAtRaw = parsed.values["expires-at"];
805
+ const expiresInRaw = parsed.values["expires-in"];
806
+ let expiresAt;
807
+ if (expiresAtRaw) {
808
+ expiresAt = parseEpochMs(expiresAtRaw, "--expires-at");
809
+ } else if (expiresInRaw) {
810
+ expiresAt = Date.now() + parseTimeout(expiresInRaw) * 1e3;
811
+ }
812
+ const scope = parsed.values.scope;
813
+ const tokenType = parsed.values["token-type"];
814
+ await updateMcpAuth((auth) => {
815
+ auth.servers[serverId] = {
816
+ binding,
817
+ tokens: {
818
+ access_token: accessToken,
819
+ ...refreshToken ? { refresh_token: refreshToken } : {},
820
+ ...expiresAt ? { expires_at: expiresAt } : {},
821
+ ...scope ? { scope } : {},
822
+ ...tokenType ? { token_type: tokenType } : {},
823
+ ...clientId ? { client_id: clientId } : {}
824
+ }
825
+ };
826
+ });
827
+ console.log(`stored MCP auth token for '${serverId}'`);
828
+ return 0;
829
+ }
830
+ if (subcommand === "clear") {
831
+ const serverId = parsed.positionals[0];
832
+ if (!serverId) {
833
+ console.error("usage: codelia mcp auth clear <server-id>");
834
+ return 1;
835
+ }
836
+ const existed = await updateMcpAuth((auth) => {
837
+ if (!auth.servers[serverId]) return false;
838
+ delete auth.servers[serverId];
839
+ return true;
840
+ });
841
+ if (!existed) {
842
+ console.error(`no token found for server: ${serverId}`);
843
+ return 1;
844
+ }
845
+ console.log(`cleared MCP auth token for '${serverId}'`);
846
+ return 0;
847
+ }
848
+ console.error(`unknown auth subcommand: ${subcommand}`);
815
849
  return 1;
816
- }
850
+ };
817
851
  }
818
- return -1;
819
- };
852
+ });
820
853
 
821
854
  // src/commands/mcp.ts
822
- var runMcpCommand = async (values) => {
823
- const [subcommand, ...rest] = values;
824
- if (!subcommand) {
825
- console.error(
826
- "usage: codelia mcp <add|list|remove|enable|disable|test|auth> ..."
827
- );
828
- return 1;
829
- }
830
- if (subcommand === "auth") {
831
- return runMcpAuthCommand(rest);
832
- }
833
- const handled = await runMcpConfigCommand(subcommand, rest);
834
- if (handled >= 0) {
835
- return handled;
855
+ var mcp_exports = {};
856
+ __export(mcp_exports, {
857
+ runMcpCommand: () => runMcpCommand
858
+ });
859
+ var runMcpCommand;
860
+ var init_mcp = __esm({
861
+ "src/commands/mcp.ts"() {
862
+ "use strict";
863
+ init_mcp_auth();
864
+ init_mcp_config();
865
+ runMcpCommand = async (values) => {
866
+ const [subcommand, ...rest] = values;
867
+ if (!subcommand) {
868
+ console.error(
869
+ "usage: codelia mcp <add|list|remove|enable|disable|test|auth> ..."
870
+ );
871
+ return 1;
872
+ }
873
+ if (subcommand === "auth") {
874
+ return runMcpAuthCommand(rest);
875
+ }
876
+ const handled = await runMcpConfigCommand(subcommand, rest);
877
+ if (handled >= 0) {
878
+ return handled;
879
+ }
880
+ console.error(`unknown subcommand: ${subcommand}`);
881
+ return 1;
882
+ };
836
883
  }
837
- console.error(`unknown subcommand: ${subcommand}`);
838
- return 1;
839
- };
884
+ });
840
885
 
841
886
  // src/commands/session.ts
842
- var import_storage3 = require("@codelia/storage");
843
- 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.";
887
+ var session_exports = {};
888
+ __export(session_exports, {
889
+ runSessionCommand: () => runSessionCommand
890
+ });
844
891
  async function runSessionCommand(args2) {
845
892
  const [action, sessionId, extra] = args2;
846
893
  if (!action || action === "--help" || action === "help") {
@@ -851,8 +898,8 @@ async function runSessionCommand(args2) {
851
898
  console.error(HELP);
852
899
  return 1;
853
900
  }
854
- const paths = (0, import_storage3.resolveStoragePaths)();
855
- const sessions = new import_storage3.SessionStateStoreImpl({ paths });
901
+ const paths = (0, import_storage4.resolveStoragePaths)();
902
+ const sessions = new import_storage4.SessionStateStoreImpl({ paths });
856
903
  try {
857
904
  if (action === "list") {
858
905
  for (const session2 of (await sessions.list()).sort(
@@ -864,7 +911,7 @@ async function runSessionCommand(args2) {
864
911
  return 0;
865
912
  }
866
913
  if (action === "cleanup") {
867
- console.log(JSON.stringify(await (0, import_storage3.cleanupRunLogs)({ paths, sessions })));
914
+ console.log(JSON.stringify(await (0, import_storage4.cleanupRunLogs)({ paths, sessions })));
868
915
  return 0;
869
916
  }
870
917
  if (!sessionId) return 1;
@@ -873,7 +920,7 @@ async function runSessionCommand(args2) {
873
920
  console.log(JSON.stringify(session));
874
921
  if (!session.pinned && action !== "unarchive")
875
922
  console.log(
876
- JSON.stringify(await (0, import_storage3.cleanupRunLogs)({ paths, sessions, sessionId }))
923
+ JSON.stringify(await (0, import_storage4.cleanupRunLogs)({ paths, sessions, sessionId }))
877
924
  );
878
925
  return 0;
879
926
  } catch (error) {
@@ -883,842 +930,2426 @@ async function runSessionCommand(args2) {
883
930
  return 1;
884
931
  }
885
932
  }
933
+ var import_storage4, HELP;
934
+ var init_session = __esm({
935
+ "src/commands/session.ts"() {
936
+ "use strict";
937
+ import_storage4 = require("@codelia/storage");
938
+ 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.";
939
+ }
940
+ });
886
941
 
887
- // src/prompt-mode.ts
888
- var import_node_child_process3 = require("child_process");
889
-
890
- // src/atif.ts
891
- var import_promises = require("fs/promises");
892
- var import_node_path2 = __toESM(require("path"), 1);
893
- var import_storage4 = require("@codelia/storage");
894
- var asRecord = (value) => typeof value === "object" && value !== null ? value : null;
895
- var asString = (value) => typeof value === "string" && value.trim().length > 0 ? value : void 0;
896
- var stringifyContent = (value) => {
897
- if (typeof value === "string") return value;
898
- if (value == null) return "";
899
- try {
900
- return JSON.stringify(value);
901
- } catch {
902
- return String(value);
942
+ // src/update/semver.ts
943
+ var import_config_loader2, MAX_VERSION_LENGTH, SEMVER_RE, NUMERIC_ID_RE, parseVersion, isValidVersion, compareVersions, isNewerVersion, inferChannelFromVersion;
944
+ var init_semver = __esm({
945
+ "src/update/semver.ts"() {
946
+ "use strict";
947
+ import_config_loader2 = require("@codelia/config-loader");
948
+ MAX_VERSION_LENGTH = 128;
949
+ SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/;
950
+ NUMERIC_ID_RE = /^(0|[1-9]\d*)$/;
951
+ parseVersion = (value) => {
952
+ if (typeof value !== "string") return null;
953
+ const trimmed = value.trim();
954
+ if (trimmed.length === 0 || trimmed.length > MAX_VERSION_LENGTH) return null;
955
+ const match = SEMVER_RE.exec(trimmed);
956
+ if (!match) return null;
957
+ const major = Number.parseInt(match[1], 10);
958
+ const minor = Number.parseInt(match[2], 10);
959
+ const patch = Number.parseInt(match[3], 10);
960
+ if (!Number.isSafeInteger(major) || !Number.isSafeInteger(minor) || !Number.isSafeInteger(patch)) {
961
+ return null;
962
+ }
963
+ const prerelease = [];
964
+ if (match[4]) {
965
+ for (const part of match[4].split(".")) {
966
+ if (NUMERIC_ID_RE.test(part)) {
967
+ const num = Number.parseInt(part, 10);
968
+ if (!Number.isSafeInteger(num)) return null;
969
+ prerelease.push(num);
970
+ } else if (/^0\d+$/.test(part)) {
971
+ return null;
972
+ } else {
973
+ prerelease.push(part);
974
+ }
975
+ }
976
+ }
977
+ return { major, minor, patch, prerelease, raw: trimmed };
978
+ };
979
+ isValidVersion = (value) => parseVersion(value) !== null;
980
+ compareVersions = (a, b) => {
981
+ const left = parseVersion(a);
982
+ const right = parseVersion(b);
983
+ if (!left || !right) return null;
984
+ for (const [l, r] of [
985
+ [left.major, right.major],
986
+ [left.minor, right.minor],
987
+ [left.patch, right.patch]
988
+ ]) {
989
+ if (l !== r) return l > r ? 1 : -1;
990
+ }
991
+ const lp = left.prerelease;
992
+ const rp = right.prerelease;
993
+ if (lp.length === 0 && rp.length === 0) return 0;
994
+ if (lp.length === 0) return 1;
995
+ if (rp.length === 0) return -1;
996
+ const len = Math.min(lp.length, rp.length);
997
+ for (let i = 0; i < len; i += 1) {
998
+ const li = lp[i];
999
+ const ri = rp[i];
1000
+ if (li === ri) continue;
1001
+ const lNum = typeof li === "number";
1002
+ const rNum = typeof ri === "number";
1003
+ if (lNum && rNum) return li > ri ? 1 : -1;
1004
+ if (lNum !== rNum) return lNum ? -1 : 1;
1005
+ return String(li) > String(ri) ? 1 : -1;
1006
+ }
1007
+ if (lp.length === rp.length) return 0;
1008
+ return lp.length > rp.length ? 1 : -1;
1009
+ };
1010
+ isNewerVersion = (candidate, current) => compareVersions(candidate, current) === 1;
1011
+ inferChannelFromVersion = (version) => {
1012
+ const parsed = parseVersion(version);
1013
+ const first = parsed?.prerelease[0];
1014
+ if (typeof first === "string" && (0, import_config_loader2.isValidUpdateChannel)(first)) {
1015
+ return first;
1016
+ }
1017
+ return "latest";
1018
+ };
903
1019
  }
904
- };
905
- var normalizeTimestamp = (value) => {
906
- const raw = asString(value);
907
- if (!raw) return void 0;
908
- const date = new Date(raw);
909
- if (Number.isNaN(date.getTime())) return raw;
910
- return date.toISOString();
911
- };
912
- var extractInputText = (input) => {
913
- const direct = asRecord(input);
914
- if (!direct) return asString(input);
915
- if (direct.type === "text") return asString(direct.text);
916
- return stringifyContent(direct);
917
- };
918
- var extractModelName = (record) => {
919
- const model = asRecord(record?.model);
920
- return asString(model?.name) ?? asString(model?.id);
921
- };
922
- var extractSessionId = (header, runStart, fallbackRunId) => asString(header?.session_id) ?? asString(runStart?.session_id) ?? asString(asRecord(runStart?.output)?.session_id) ?? fallbackRunId;
923
- var createStepIdAllocator = () => {
924
- let next = 1;
925
- return () => next++;
926
- };
927
- var pushTextStep = (steps, nextStepId, source, message, timestamp, extra) => {
928
- if (!message?.trim()) return;
929
- steps.push({
930
- step_id: nextStepId(),
931
- ...timestamp ? { timestamp } : {},
932
- source,
933
- message,
934
- ...extra ? { extra } : {}
935
- });
936
- };
937
- var getOrCreateToolStep = (steps, nextStepId, callId, timestamp) => {
938
- const existing = steps.find(
939
- (step2) => step2.tool_calls?.some((call) => call.tool_call_id === callId)
940
- );
941
- if (existing) return existing;
942
- const step = {
943
- step_id: nextStepId(),
944
- ...timestamp ? { timestamp } : {},
945
- source: "agent",
946
- message: "",
947
- tool_calls: []
948
- };
949
- steps.push(step);
950
- return step;
951
- };
952
- var extractUsageMetrics = (records) => {
953
- return records.map((record) => asRecord(asRecord(record.output)?.usage)).filter((usage) => !!usage).reduce(
954
- (acc, usage) => {
955
- acc.total_prompt_tokens += Number(usage.input_tokens ?? 0);
956
- acc.total_completion_tokens += Number(usage.output_tokens ?? 0);
957
- acc.total_cached_tokens += Number(
958
- usage.input_cached_tokens ?? asRecord(usage.input_tokens_details)?.cached_tokens ?? 0
959
- );
960
- return acc;
961
- },
962
- {
963
- total_prompt_tokens: 0,
964
- total_completion_tokens: 0,
965
- total_cached_tokens: 0
966
- }
967
- );
968
- };
969
- var sessionRecordsToAtif = (records, runId) => {
970
- const header = records.find((record) => record.type === "header");
971
- const runStart = records.find((record) => record.type === "run.start");
972
- const modelName = extractModelName(header);
973
- const nextStepId = createStepIdAllocator();
974
- const steps = [];
975
- pushTextStep(
976
- steps,
977
- nextStepId,
978
- "user",
979
- extractInputText(asRecord(runStart?.input)),
980
- normalizeTimestamp(runStart?.ts),
981
- { source_record: "run.start" }
982
- );
983
- for (const record of records) {
984
- if (record.type !== "agent.event") continue;
985
- const event = asRecord(record.event);
986
- if (!event) continue;
987
- const timestamp = normalizeTimestamp(record.ts);
988
- const eventType = asString(event.type);
989
- if (eventType === "text") {
990
- pushTextStep(
991
- steps,
992
- nextStepId,
993
- "agent",
994
- asString(event.content),
995
- timestamp,
996
- { source_record: "agent.event.text" }
997
- );
998
- continue;
999
- }
1000
- if (eventType === "reasoning") {
1001
- const content = asString(event.content);
1002
- if (!content) continue;
1003
- steps.push({
1004
- step_id: nextStepId(),
1005
- ...timestamp ? { timestamp } : {},
1006
- source: "agent",
1007
- message: "",
1008
- reasoning_content: content,
1009
- extra: { source_record: "agent.event.reasoning" }
1010
- });
1011
- continue;
1012
- }
1013
- if (eventType === "tool_call") {
1014
- const callId = asString(event.tool_call_id) ?? `tool_call_${String(steps.length + 1)}`;
1015
- const step = getOrCreateToolStep(steps, nextStepId, callId, timestamp);
1016
- step.tool_calls ??= [];
1017
- step.tool_calls.push({
1018
- tool_call_id: callId,
1019
- function_name: asString(event.tool) ?? "unknown",
1020
- arguments: asRecord(event.args) ?? {}
1021
- });
1022
- continue;
1023
- }
1024
- if (eventType === "tool_result") {
1025
- const callId = asString(event.tool_call_id);
1026
- const step = callId ? getOrCreateToolStep(steps, nextStepId, callId, timestamp) : {
1027
- step_id: nextStepId(),
1028
- ...timestamp ? { timestamp } : {},
1029
- source: "agent",
1030
- message: ""
1031
- };
1032
- if (!callId) steps.push(step);
1033
- step.observation ??= { results: [] };
1034
- step.observation.results.push({
1035
- ...callId ? { source_call_id: callId } : {},
1036
- content: stringifyContent(event.result)
1020
+ });
1021
+
1022
+ // src/update/launcher-entry.ts
1023
+ var import_node_child_process, import_node_fs2, import_node_path3, UPDATE_REEXEC_ENV, DEFAULT_LAUNCHER_ENTRY, readInstalledVersion, reexecLauncher, launcherEntry;
1024
+ var init_launcher_entry = __esm({
1025
+ "src/update/launcher-entry.ts"() {
1026
+ "use strict";
1027
+ import_node_child_process = require("child_process");
1028
+ import_node_fs2 = __toESM(require("fs"), 1);
1029
+ import_node_path3 = __toESM(require("path"), 1);
1030
+ init_semver();
1031
+ UPDATE_REEXEC_ENV = "CODELIA_UPDATE_REEXEC";
1032
+ DEFAULT_LAUNCHER_ENTRY = import_node_path3.default.join("dist", "index.cjs");
1033
+ readInstalledVersion = (packageRoot2) => {
1034
+ try {
1035
+ const manifest = JSON.parse(
1036
+ import_node_fs2.default.readFileSync(import_node_path3.default.join(packageRoot2, "package.json"), "utf8")
1037
+ );
1038
+ return manifest.name === "@codelia/cli" && isValidVersion(manifest.version) ? manifest.version : null;
1039
+ } catch {
1040
+ return null;
1041
+ }
1042
+ };
1043
+ reexecLauncher = (options) => new Promise((resolve) => {
1044
+ const child = (0, import_node_child_process.spawn)(process.execPath, [options.entry, ...options.args], {
1045
+ stdio: "inherit",
1046
+ env: options.env
1037
1047
  });
1038
- continue;
1039
- }
1040
- if (eventType === "final") {
1041
- pushTextStep(
1042
- steps,
1043
- nextStepId,
1044
- "agent",
1045
- asString(event.content),
1046
- timestamp,
1047
- { source_record: "agent.event.final" }
1048
- );
1049
- }
1050
- }
1051
- if (steps.length === 0) {
1052
- steps.push({
1053
- step_id: nextStepId(),
1054
- source: "user",
1055
- message: "(no prompt captured)",
1056
- extra: { source_record: "fallback" }
1048
+ child.on("error", () => resolve(null));
1049
+ child.on("exit", (code, signal) => resolve(signal ? 1 : code ?? 1));
1057
1050
  });
1051
+ launcherEntry = (packageRoot2) => {
1052
+ const fallback = import_node_path3.default.join(packageRoot2, DEFAULT_LAUNCHER_ENTRY);
1053
+ let bin;
1054
+ try {
1055
+ bin = JSON.parse(
1056
+ import_node_fs2.default.readFileSync(import_node_path3.default.join(packageRoot2, "package.json"), "utf8")
1057
+ ).bin;
1058
+ } catch {
1059
+ return fallback;
1060
+ }
1061
+ const relative = typeof bin === "string" ? bin : typeof bin === "object" && bin !== null ? bin.codelia : void 0;
1062
+ if (typeof relative !== "string" || relative.length === 0) return fallback;
1063
+ const entry = import_node_path3.default.resolve(packageRoot2, relative);
1064
+ const inside = import_node_path3.default.relative(packageRoot2, entry);
1065
+ if (inside.startsWith("..") || import_node_path3.default.isAbsolute(inside)) return fallback;
1066
+ return import_node_fs2.default.existsSync(entry) ? entry : fallback;
1067
+ };
1058
1068
  }
1059
- const compactUsage = records.filter((record) => record.type === "llm.usage");
1060
- const compactSequences = new Set(compactUsage.map((record) => record.seq));
1061
- const usage = extractUsageMetrics([
1062
- ...compactUsage,
1063
- ...records.filter(
1064
- (record) => record.type === "llm.response" && !compactSequences.has(record.seq)
1065
- )
1066
- ]);
1067
- return {
1068
- schema_version: "ATIF-v1.6",
1069
- session_id: extractSessionId(header, runStart, runId),
1070
- agent: {
1071
- name: "codelia",
1072
- version: "unknown",
1073
- ...modelName ? { model_name: modelName } : {}
1074
- },
1075
- steps,
1076
- final_metrics: {
1077
- ...usage,
1078
- total_steps: steps.length
1079
- },
1080
- extra: {
1081
- run_id: runId,
1082
- source: "codelia-session-jsonl",
1083
- conversion: "session-records-to-atif-v1.6"
1084
- }
1085
- };
1086
- };
1087
- var parseSessionJsonl = (raw) => {
1088
- const out = [];
1089
- for (const line of raw.split("\n")) {
1090
- if (!line.trim()) continue;
1091
- try {
1092
- out.push(JSON.parse(line));
1093
- } catch {
1094
- }
1095
- }
1096
- return out;
1097
- };
1098
- var readSessionJsonl = async (filePath) => {
1099
- const lines = [];
1100
- for await (const line of (0, import_storage4.readRunLogLines)(filePath)) lines.push(line);
1101
- return parseSessionJsonl(lines.join("\n"));
1102
- };
1103
- var writeAtifFromSessionJsonl = async ({
1104
- sessionLogPath,
1105
- runId,
1106
- outPath
1107
- }) => {
1108
- const records = await readSessionJsonl(sessionLogPath);
1109
- const trajectory = sessionRecordsToAtif(records, runId);
1110
- await (0, import_promises.mkdir)(import_node_path2.default.dirname(outPath), { recursive: true });
1111
- const tempPath = `${outPath}.tmp-${process.pid}-${Date.now()}`;
1112
- await (0, import_promises.writeFile)(tempPath, `${JSON.stringify(trajectory, null, 2)}
1113
- `, "utf8");
1114
- await (0, import_promises.rename)(tempPath, outPath);
1115
- return trajectory;
1116
- };
1117
-
1118
- // src/tui/launcher.ts
1119
- var import_node_child_process2 = require("child_process");
1120
- var import_node_fs = __toESM(require("fs"), 1);
1121
- var import_node_module = require("module");
1122
- var import_node_path3 = __toESM(require("path"), 1);
1123
- var import_storage5 = require("@codelia/storage");
1124
-
1125
- // src/version.ts
1126
- var CLI_VERSION = "0.1.85".trim().length > 0 ? "0.1.85" : "0.0.0";
1069
+ });
1127
1070
 
1128
- // src/tui/launcher.ts
1129
- var resolveTuiBinaryName = (platform) => platform === "win32" ? "codelia-tui.exe" : "codelia-tui";
1130
- var TUI_PACKAGE_BY_TARGET = {
1131
- "darwin-arm64": "@codelia/tui-darwin-arm64",
1132
- "darwin-x64": "@codelia/tui-darwin-x64",
1133
- "linux-arm64": "@codelia/tui-linux-arm64",
1134
- "linux-x64": "@codelia/tui-linux-x64",
1135
- "win32-x64": "@codelia/tui-win32-x64"
1136
- };
1137
- var describeError3 = (error) => error instanceof Error ? error.message : String(error);
1138
- var splitArgs = (value) => value.split(/\s+/).map((part) => part.trim()).filter((part) => part.length > 0);
1139
- var quoteShellWord = (value) => `'${value.replace(/'/g, "'\\''")}'`;
1140
- var isExecutable = (candidate) => {
1141
- try {
1142
- import_node_fs.default.accessSync(candidate, import_node_fs.default.constants.X_OK);
1143
- return true;
1144
- } catch {
1145
- return false;
1071
+ // src/update/registry.ts
1072
+ var import_node_crypto, DEFAULT_REGISTRY_URL, CLI_PACKAGE_NAME, DEFAULT_FETCH_TIMEOUT_MS, MAX_REGISTRY_RESPONSE_BYTES, normalizeRegistryUrl, resolveRegistryUrl, computeRegistryId, readBoundedText, fetchLatestVersion;
1073
+ var init_registry = __esm({
1074
+ "src/update/registry.ts"() {
1075
+ "use strict";
1076
+ import_node_crypto = require("crypto");
1077
+ init_semver();
1078
+ DEFAULT_REGISTRY_URL = "https://registry.npmjs.org";
1079
+ CLI_PACKAGE_NAME = "@codelia/cli";
1080
+ DEFAULT_FETCH_TIMEOUT_MS = 5e3;
1081
+ MAX_REGISTRY_RESPONSE_BYTES = 256 * 1024;
1082
+ normalizeRegistryUrl = (raw) => {
1083
+ const candidate = (raw ?? "").trim() || DEFAULT_REGISTRY_URL;
1084
+ let parsed;
1085
+ try {
1086
+ parsed = new URL(candidate);
1087
+ } catch {
1088
+ throw new Error("Invalid npm registry URL");
1089
+ }
1090
+ if (parsed.protocol !== "https:") {
1091
+ throw new Error("Registry URL must use https");
1092
+ }
1093
+ if (parsed.username || parsed.password) {
1094
+ throw new Error("Registry URL must not include embedded credentials");
1095
+ }
1096
+ const pathname = parsed.pathname.replace(/\/+$/, "");
1097
+ return `${parsed.origin}${pathname}`;
1098
+ };
1099
+ resolveRegistryUrl = (env = process.env) => normalizeRegistryUrl(env.CODELIA_UPDATE_REGISTRY ?? env.npm_config_registry);
1100
+ computeRegistryId = (registryUrl) => (0, import_node_crypto.createHash)("sha256").update(registryUrl).digest("hex");
1101
+ readBoundedText = async (response, maxBytes) => {
1102
+ const declaredLength = response.headers.get("content-length");
1103
+ if (declaredLength) {
1104
+ const parsedLength = Number.parseInt(declaredLength, 10);
1105
+ if (Number.isFinite(parsedLength) && parsedLength > maxBytes) {
1106
+ throw new Error("Registry response exceeded maximum allowed size");
1107
+ }
1108
+ }
1109
+ if (!response.body) {
1110
+ const text = await response.text();
1111
+ if (Buffer.byteLength(text, "utf8") > maxBytes) {
1112
+ throw new Error("Registry response exceeded maximum allowed size");
1113
+ }
1114
+ return text;
1115
+ }
1116
+ const reader = response.body.getReader();
1117
+ const chunks = [];
1118
+ let total = 0;
1119
+ try {
1120
+ for (; ; ) {
1121
+ const { done, value } = await reader.read();
1122
+ if (done) break;
1123
+ if (!value) continue;
1124
+ total += value.byteLength;
1125
+ if (total > maxBytes) {
1126
+ await reader.cancel();
1127
+ throw new Error("Registry response exceeded maximum allowed size");
1128
+ }
1129
+ chunks.push(value);
1130
+ }
1131
+ } finally {
1132
+ reader.releaseLock();
1133
+ }
1134
+ return Buffer.concat(chunks, total).toString("utf8");
1135
+ };
1136
+ fetchLatestVersion = async (options) => {
1137
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
1138
+ const timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
1139
+ const controller = new AbortController();
1140
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1141
+ const onAbort = () => controller.abort();
1142
+ options.signal?.addEventListener("abort", onAbort, { once: true });
1143
+ try {
1144
+ const endpoint = `${options.registryUrl}/-/package/${encodeURIComponent(CLI_PACKAGE_NAME)}/dist-tags`;
1145
+ const response = await fetchImpl(endpoint, {
1146
+ method: "GET",
1147
+ headers: { accept: "application/json" },
1148
+ redirect: "error",
1149
+ signal: controller.signal
1150
+ });
1151
+ if (!response.ok) {
1152
+ throw new Error(`Registry returned HTTP ${response.status}`);
1153
+ }
1154
+ const raw = await readBoundedText(response, MAX_REGISTRY_RESPONSE_BYTES);
1155
+ let parsed;
1156
+ try {
1157
+ parsed = JSON.parse(raw);
1158
+ } catch {
1159
+ throw new Error("Registry returned invalid JSON");
1160
+ }
1161
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
1162
+ throw new Error("Registry dist-tags response was not an object");
1163
+ }
1164
+ const version = parsed[options.channel];
1165
+ if (!isValidVersion(version)) {
1166
+ throw new Error(
1167
+ `Registry dist-tag "${options.channel}" has no valid semver version`
1168
+ );
1169
+ }
1170
+ return version;
1171
+ } finally {
1172
+ clearTimeout(timer);
1173
+ options.signal?.removeEventListener("abort", onAbort);
1174
+ }
1175
+ };
1146
1176
  }
1147
- };
1148
- var initStorage = async () => {
1149
- try {
1150
- const paths = (0, import_storage5.resolveStoragePaths)();
1151
- await (0, import_storage5.ensureStorageDirs)(paths);
1152
- } catch (error) {
1153
- console.warn(
1154
- `Failed to initialize storage directories: ${describeError3(error)}`
1177
+ });
1178
+
1179
+ // src/update/state.ts
1180
+ var import_node_crypto2, import_node_fs3, import_node_path4, import_promises, import_config_loader3, import_storage5, resolveUpdatePaths, resolveInstallApplyLockFile, MAX_STATE_BYTES, MAX_MESSAGE_LENGTH, isRecord2, isTimestamp, clampMessage, parseUpdateState, readUpdateState, writeJsonAtomic, writeUpdateState, isSqliteBusyError, tryWithSqliteLock, withLockedUpdateState, mutateUpdateState;
1181
+ var init_state = __esm({
1182
+ "src/update/state.ts"() {
1183
+ "use strict";
1184
+ import_node_crypto2 = require("crypto");
1185
+ import_node_fs3 = require("fs");
1186
+ import_node_path4 = __toESM(require("path"), 1);
1187
+ import_promises = require("timers/promises");
1188
+ import_config_loader3 = require("@codelia/config-loader");
1189
+ import_storage5 = require("@codelia/storage");
1190
+ init_semver();
1191
+ resolveUpdatePaths = (cacheDir) => {
1192
+ const dir = import_node_path4.default.join(cacheDir, "update");
1193
+ return {
1194
+ dir,
1195
+ stateFile: import_node_path4.default.join(dir, "state.json"),
1196
+ noticesDir: import_node_path4.default.join(dir, "notices")
1197
+ };
1198
+ };
1199
+ resolveInstallApplyLockFile = (canonicalPackageRoot) => import_node_path4.default.join(
1200
+ import_node_path4.default.dirname(import_node_path4.default.dirname(canonicalPackageRoot)),
1201
+ ".codelia-update.lock.sqlite"
1155
1202
  );
1203
+ MAX_STATE_BYTES = 64 * 1024;
1204
+ MAX_MESSAGE_LENGTH = 300;
1205
+ isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1206
+ isTimestamp = (value) => typeof value === "string" && value.length <= 64 && Number.isFinite(Date.parse(value));
1207
+ clampMessage = (value) => {
1208
+ const singleLine = value.replace(/[\u0000-\u001f\u007f]+/g, " ").trim();
1209
+ return singleLine.length > MAX_MESSAGE_LENGTH ? `${singleLine.slice(0, MAX_MESSAGE_LENGTH - 1)}\u2026` : singleLine;
1210
+ };
1211
+ parseUpdateState = (value) => {
1212
+ const state = { version: 1 };
1213
+ if (!isRecord2(value) || value.version !== 1) return state;
1214
+ if (isTimestamp(value.last_check_at)) {
1215
+ state.last_check_at = value.last_check_at;
1216
+ }
1217
+ if (typeof value.last_check_ok === "boolean") {
1218
+ state.last_check_ok = value.last_check_ok;
1219
+ }
1220
+ if (typeof value.last_check_error === "string") {
1221
+ state.last_check_error = clampMessage(value.last_check_error);
1222
+ }
1223
+ if (typeof value.channel === "string" && (0, import_config_loader3.isValidUpdateChannel)(value.channel)) {
1224
+ state.channel = value.channel;
1225
+ }
1226
+ if (typeof value.registry_id === "string" && /^[0-9a-f]{64}$/.test(value.registry_id)) {
1227
+ state.registry_id = value.registry_id;
1228
+ }
1229
+ if (value.configured_channel === null || typeof value.configured_channel === "string" && (0, import_config_loader3.isValidUpdateChannel)(value.configured_channel)) {
1230
+ state.configured_channel = value.configured_channel;
1231
+ }
1232
+ if (isValidVersion(value.latest_version)) {
1233
+ state.latest_version = value.latest_version;
1234
+ }
1235
+ if (isValidVersion(value.checked_version)) {
1236
+ state.checked_version = value.checked_version;
1237
+ }
1238
+ if (isRecord2(value.apply_failure) && isValidVersion(value.apply_failure.version) && isTimestamp(value.apply_failure.at) && typeof value.apply_failure.message === "string") {
1239
+ state.apply_failure = {
1240
+ version: value.apply_failure.version,
1241
+ at: value.apply_failure.at,
1242
+ message: clampMessage(value.apply_failure.message),
1243
+ ...value.apply_failure.unmanaged === true ? { unmanaged: true } : {}
1244
+ };
1245
+ }
1246
+ if (isRecord2(value.applied) && isValidVersion(value.applied.from) && isValidVersion(value.applied.to) && isTimestamp(value.applied.at)) {
1247
+ state.applied = {
1248
+ from: value.applied.from,
1249
+ to: value.applied.to,
1250
+ at: value.applied.at
1251
+ };
1252
+ }
1253
+ return state;
1254
+ };
1255
+ readUpdateState = async (file) => {
1256
+ try {
1257
+ const info = await import_node_fs3.promises.lstat(file);
1258
+ if (!info.isFile() || info.size > MAX_STATE_BYTES) return { version: 1 };
1259
+ return parseUpdateState(JSON.parse(await import_node_fs3.promises.readFile(file, "utf8")));
1260
+ } catch {
1261
+ return { version: 1 };
1262
+ }
1263
+ };
1264
+ writeJsonAtomic = async (file, value) => {
1265
+ await import_node_fs3.promises.mkdir(import_node_path4.default.dirname(file), { recursive: true });
1266
+ const temp = `${file}.${process.pid}.${(0, import_node_crypto2.randomBytes)(4).toString("hex")}.tmp`;
1267
+ try {
1268
+ await import_node_fs3.promises.writeFile(temp, `${JSON.stringify(value, null, 2)}
1269
+ `, {
1270
+ mode: 384,
1271
+ flag: "wx"
1272
+ });
1273
+ await import_node_fs3.promises.rename(temp, file);
1274
+ } catch (error) {
1275
+ await import_node_fs3.promises.rm(temp, { force: true });
1276
+ throw error;
1277
+ }
1278
+ };
1279
+ writeUpdateState = (file, state) => writeJsonAtomic(file, state);
1280
+ isSqliteBusyError = (error) => ["SQLITE_BUSY", "SQLITE_LOCKED"].includes(
1281
+ error?.code ?? ""
1282
+ );
1283
+ tryWithSqliteLock = async (lockFile, timeoutMs, action) => {
1284
+ await import_node_fs3.promises.mkdir(import_node_path4.default.dirname(lockFile), { recursive: true, mode: 448 });
1285
+ const db = await (0, import_storage5.openSqlite)(lockFile);
1286
+ try {
1287
+ db.exec("PRAGMA busy_timeout = 0");
1288
+ const deadline = performance.now() + timeoutMs;
1289
+ for (; ; ) {
1290
+ try {
1291
+ db.exec("BEGIN IMMEDIATE");
1292
+ break;
1293
+ } catch (error) {
1294
+ if (!isSqliteBusyError(error)) throw error;
1295
+ if (performance.now() >= deadline) {
1296
+ return { acquired: false };
1297
+ }
1298
+ await (0, import_promises.setTimeout)(15);
1299
+ }
1300
+ }
1301
+ try {
1302
+ const value = await action();
1303
+ db.exec("COMMIT");
1304
+ return { acquired: true, value };
1305
+ } catch (error) {
1306
+ try {
1307
+ db.exec("ROLLBACK");
1308
+ } catch {
1309
+ }
1310
+ throw error;
1311
+ }
1312
+ } finally {
1313
+ db.close();
1314
+ }
1315
+ };
1316
+ withLockedUpdateState = async (file, action) => {
1317
+ const result = await tryWithSqliteLock(
1318
+ `${file}.lock.sqlite`,
1319
+ 5e3,
1320
+ async () => action(await readUpdateState(file))
1321
+ );
1322
+ if (!result.acquired) {
1323
+ throw new Error("Timed out waiting for update state lock");
1324
+ }
1325
+ return result.value;
1326
+ };
1327
+ mutateUpdateState = (file, mutate) => withLockedUpdateState(file, async (state) => {
1328
+ const next = mutate(state);
1329
+ await writeUpdateState(file, next);
1330
+ return next;
1331
+ });
1156
1332
  }
1157
- };
1158
- var resolveCliPackageRoot = () => {
1159
- const scriptPath = process.argv[1];
1160
- if (!scriptPath) return null;
1161
- try {
1162
- const resolvedScriptPath = import_node_fs.default.realpathSync(scriptPath);
1163
- const scriptDir = import_node_path3.default.dirname(resolvedScriptPath);
1164
- if (import_node_path3.default.basename(scriptDir) === "dist") {
1165
- return import_node_path3.default.dirname(scriptDir);
1166
- }
1167
- return scriptDir;
1168
- } catch {
1169
- return null;
1170
- }
1171
- };
1172
- var resolveRuntimeRequireBase = () => {
1173
- const cliPackageRoot = resolveCliPackageRoot();
1174
- if (cliPackageRoot) {
1175
- return import_node_path3.default.resolve(cliPackageRoot, "package.json");
1176
- }
1177
- return import_node_path3.default.resolve(process.cwd(), "package.json");
1178
- };
1179
- var runtimeRequire = (0, import_node_module.createRequire)(resolveRuntimeRequireBase());
1180
- var resolveBundledRuntimeEntry = () => {
1181
- try {
1182
- return runtimeRequire.resolve("@codelia/runtime");
1183
- } catch {
1184
- return null;
1185
- }
1186
- };
1187
- var resolveInstalledPackageJson = (packageName) => {
1188
- try {
1189
- return runtimeRequire.resolve(`${packageName}/package.json`);
1190
- } catch {
1191
- return null;
1192
- }
1193
- };
1194
- var resolvePlatformTuiPackageName = (platform = process.platform, arch = process.arch) => TUI_PACKAGE_BY_TARGET[`${platform}-${arch}`] ?? null;
1195
- var resolveOptionalTuiBinaryPath = (platform = process.platform, arch = process.arch, resolvePackageJson = resolveInstalledPackageJson) => {
1196
- const packageName = resolvePlatformTuiPackageName(platform, arch);
1197
- if (!packageName) {
1198
- return null;
1333
+ });
1334
+
1335
+ // src/update/apply.ts
1336
+ var import_node_child_process2, import_node_fs4, import_node_path5, APPLY_LOCK_WAIT_MS, NPM_PREFIX_TIMEOUT_MS, NPM_INSTALL_TIMEOUT_MS, defaultRunner, canonicalDir, summarizeStderr, applyUpdate, recordApplyFailure;
1337
+ var init_apply = __esm({
1338
+ "src/update/apply.ts"() {
1339
+ "use strict";
1340
+ import_node_child_process2 = require("child_process");
1341
+ import_node_fs4 = __toESM(require("fs"), 1);
1342
+ import_node_path5 = __toESM(require("path"), 1);
1343
+ init_launcher_entry();
1344
+ init_registry();
1345
+ init_semver();
1346
+ init_state();
1347
+ APPLY_LOCK_WAIT_MS = 250;
1348
+ NPM_PREFIX_TIMEOUT_MS = 1e4;
1349
+ NPM_INSTALL_TIMEOUT_MS = 12e4;
1350
+ defaultRunner = ({ command, args: args2, env, timeoutMs }) => new Promise((resolve) => {
1351
+ (0, import_node_child_process2.execFile)(
1352
+ command,
1353
+ args2,
1354
+ {
1355
+ env,
1356
+ timeout: timeoutMs,
1357
+ maxBuffer: 4 * 1024 * 1024,
1358
+ encoding: "utf8",
1359
+ windowsHide: true
1360
+ },
1361
+ (error, stdout, stderr) => {
1362
+ if (!error) {
1363
+ resolve({ code: 0, stdout, stderr });
1364
+ return;
1365
+ }
1366
+ const exitCode = typeof error.code === "number" ? error.code : 1;
1367
+ resolve({
1368
+ code: exitCode,
1369
+ stdout: stdout ?? "",
1370
+ stderr: stderr || error.message
1371
+ });
1372
+ }
1373
+ );
1374
+ });
1375
+ canonicalDir = (target) => {
1376
+ const resolved = import_node_path5.default.resolve(target);
1377
+ try {
1378
+ return import_node_fs4.default.realpathSync(resolved);
1379
+ } catch {
1380
+ return resolved;
1381
+ }
1382
+ };
1383
+ summarizeStderr = (stderr, fallback) => {
1384
+ const lines = stderr.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
1385
+ const npmErr = lines.find(
1386
+ (l) => l.startsWith("npm error") || l.startsWith("npm ERR!")
1387
+ );
1388
+ return clampMessage(npmErr ?? lines.at(-1) ?? fallback);
1389
+ };
1390
+ applyUpdate = async (options) => {
1391
+ const env = options.env ?? process.env;
1392
+ const runner = options.runner ?? defaultRunner;
1393
+ const now = options.now ?? Date.now;
1394
+ if (options.method.kind !== "npm-global" || !options.method.prefix || !options.method.autoApply.supported) {
1395
+ return {
1396
+ status: "failed",
1397
+ message: options.method.autoApply.supported ? "Unsupported installation layout" : options.method.autoApply.reason,
1398
+ unmanaged: true
1399
+ };
1400
+ }
1401
+ const npmPath = options.method.autoApply.npmPath;
1402
+ const expectedPrefix = canonicalDir(options.method.prefix);
1403
+ const applyLockFile = resolveInstallApplyLockFile(
1404
+ canonicalDir(options.method.packageRoot)
1405
+ );
1406
+ const locked = await tryWithSqliteLock(
1407
+ applyLockFile,
1408
+ APPLY_LOCK_WAIT_MS,
1409
+ async () => {
1410
+ const onDisk = readInstalledVersion(options.method.packageRoot);
1411
+ if (onDisk && onDisk !== options.from) {
1412
+ return { status: "changed", installed: onDisk };
1413
+ }
1414
+ const currentState = await readUpdateState(options.paths.stateFile);
1415
+ if (currentState.latest_version && (compareVersions(currentState.latest_version, options.to) ?? 0) !== 0) {
1416
+ return { status: "superseded" };
1417
+ }
1418
+ if (!isNewerVersion(options.to, options.from)) {
1419
+ return { status: "changed", installed: options.from };
1420
+ }
1421
+ let registryUrl;
1422
+ try {
1423
+ registryUrl = resolveRegistryUrl(env);
1424
+ } catch (error) {
1425
+ const message = clampMessage(
1426
+ error instanceof Error ? error.message : String(error)
1427
+ );
1428
+ return { status: "failed", message };
1429
+ }
1430
+ const npmEnv = {
1431
+ ...env,
1432
+ npm_config_registry: registryUrl,
1433
+ npm_config_update_notifier: "false"
1434
+ };
1435
+ const failAndRecord = async (message, unmanaged) => {
1436
+ await recordApplyFailure(
1437
+ options.paths.stateFile,
1438
+ options.to,
1439
+ message,
1440
+ now,
1441
+ unmanaged
1442
+ );
1443
+ return unmanaged ? { status: "failed", message, unmanaged } : { status: "failed", message };
1444
+ };
1445
+ const prefixProbe = await runner({
1446
+ command: npmPath,
1447
+ args: ["prefix", "-g"],
1448
+ env: npmEnv,
1449
+ timeoutMs: NPM_PREFIX_TIMEOUT_MS
1450
+ });
1451
+ if (prefixProbe.code !== 0) {
1452
+ return failAndRecord(
1453
+ summarizeStderr(prefixProbe.stderr, "npm prefix check failed")
1454
+ );
1455
+ }
1456
+ const reportedPrefix = canonicalDir(prefixProbe.stdout.trim());
1457
+ if (reportedPrefix !== expectedPrefix) {
1458
+ return failAndRecord(
1459
+ "npm global prefix does not match installation prefix",
1460
+ true
1461
+ );
1462
+ }
1463
+ const install = await runner({
1464
+ command: npmPath,
1465
+ args: [
1466
+ "install",
1467
+ "-g",
1468
+ "--prefix",
1469
+ expectedPrefix,
1470
+ "--no-audit",
1471
+ "--no-fund",
1472
+ `${CLI_PACKAGE_NAME}@${options.to}`
1473
+ ],
1474
+ env: npmEnv,
1475
+ timeoutMs: NPM_INSTALL_TIMEOUT_MS
1476
+ });
1477
+ if (install.code !== 0) {
1478
+ return failAndRecord(
1479
+ summarizeStderr(
1480
+ install.stderr,
1481
+ `npm install exited with status ${install.code}`
1482
+ )
1483
+ );
1484
+ }
1485
+ const verified = readInstalledVersion(options.method.packageRoot);
1486
+ if (verified !== options.to) {
1487
+ return failAndRecord(
1488
+ verified ? `Expected version ${options.to} after install, found ${verified}` : `Could not verify installed version ${options.to} after install`
1489
+ );
1490
+ }
1491
+ const appliedAt = new Date(now()).toISOString();
1492
+ await mutateUpdateState(options.paths.stateFile, (state) => {
1493
+ const next = {
1494
+ ...state,
1495
+ version: 1,
1496
+ applied: { from: options.from, to: options.to, at: appliedAt }
1497
+ };
1498
+ delete next.apply_failure;
1499
+ return next;
1500
+ }).catch(() => void 0);
1501
+ return { status: "installed", from: options.from, to: options.to };
1502
+ }
1503
+ );
1504
+ if (!locked.acquired) {
1505
+ return { status: "deferred" };
1506
+ }
1507
+ return locked.value;
1508
+ };
1509
+ recordApplyFailure = async (stateFile, version, message, now, unmanaged) => {
1510
+ const at = new Date(now()).toISOString();
1511
+ await mutateUpdateState(stateFile, (state) => ({
1512
+ ...state,
1513
+ version: 1,
1514
+ apply_failure: {
1515
+ version,
1516
+ at,
1517
+ message: clampMessage(message),
1518
+ ...unmanaged ? { unmanaged: true } : {}
1519
+ }
1520
+ })).catch(() => void 0);
1521
+ };
1199
1522
  }
1200
- const packageJsonPath = resolvePackageJson(packageName);
1201
- if (!packageJsonPath) {
1202
- return null;
1523
+ });
1524
+
1525
+ // src/update/check.ts
1526
+ var CHECK_SUCCESS_TTL_MS, CHECK_FAILURE_TTL_MS, resolveEffectiveChannel, isMatchingCheckScope, shouldCheckNow, runRegistryCheck;
1527
+ var init_check = __esm({
1528
+ "src/update/check.ts"() {
1529
+ "use strict";
1530
+ init_registry();
1531
+ init_semver();
1532
+ init_state();
1533
+ CHECK_SUCCESS_TTL_MS = 24 * 60 * 60 * 1e3;
1534
+ CHECK_FAILURE_TTL_MS = 60 * 60 * 1e3;
1535
+ resolveEffectiveChannel = (currentVersion, configuredChannel) => configuredChannel ?? inferChannelFromVersion(currentVersion);
1536
+ isMatchingCheckScope = (state, scope) => state.registry_id === scope.registryId && state.channel === scope.channel && state.configured_channel === scope.configuredChannel;
1537
+ shouldCheckNow = (state, options) => {
1538
+ const now = options.now ?? Date.now();
1539
+ const effectiveChannel = resolveEffectiveChannel(
1540
+ options.currentVersion,
1541
+ options.configuredChannel
1542
+ );
1543
+ if (!isMatchingCheckScope(state, {
1544
+ channel: effectiveChannel,
1545
+ configuredChannel: options.configuredChannel,
1546
+ registryId: options.registryId
1547
+ }) || state.checked_version !== options.currentVersion) {
1548
+ return true;
1549
+ }
1550
+ if (!state.last_check_at) return true;
1551
+ const lastMs = Date.parse(state.last_check_at);
1552
+ if (!Number.isFinite(lastMs)) return true;
1553
+ const ttl = state.last_check_ok === true ? CHECK_SUCCESS_TTL_MS : CHECK_FAILURE_TTL_MS;
1554
+ return now - lastMs >= ttl;
1555
+ };
1556
+ runRegistryCheck = async (options) => {
1557
+ const now = options.now ?? Date.now;
1558
+ const channel = resolveEffectiveChannel(
1559
+ options.currentVersion,
1560
+ options.configuredChannel
1561
+ );
1562
+ let registryUrl;
1563
+ try {
1564
+ registryUrl = resolveRegistryUrl(options.env);
1565
+ } catch (error) {
1566
+ const message = clampMessage(
1567
+ error instanceof Error ? error.message : String(error)
1568
+ );
1569
+ return { status: "failed", channel, message };
1570
+ }
1571
+ const regId = computeRegistryId(registryUrl);
1572
+ const checkedAt = new Date(now()).toISOString();
1573
+ try {
1574
+ const latest = await fetchLatestVersion({
1575
+ registryUrl,
1576
+ channel,
1577
+ fetchImpl: options.fetchImpl,
1578
+ signal: options.signal
1579
+ });
1580
+ await mutateUpdateState(options.paths.stateFile, (state) => {
1581
+ const next = {
1582
+ ...state,
1583
+ version: 1,
1584
+ last_check_at: checkedAt,
1585
+ last_check_ok: true,
1586
+ channel,
1587
+ registry_id: regId,
1588
+ configured_channel: options.configuredChannel,
1589
+ latest_version: latest,
1590
+ checked_version: options.currentVersion
1591
+ };
1592
+ delete next.last_check_error;
1593
+ if (next.apply_failure && next.apply_failure.version !== latest) {
1594
+ delete next.apply_failure;
1595
+ }
1596
+ return next;
1597
+ });
1598
+ if (isNewerVersion(latest, options.currentVersion)) {
1599
+ return { status: "update_available", channel, latest };
1600
+ }
1601
+ return { status: "up_to_date", channel, latest };
1602
+ } catch (error) {
1603
+ if (options.signal?.aborted) {
1604
+ return { status: "aborted", channel };
1605
+ }
1606
+ const message = clampMessage(
1607
+ error instanceof Error ? error.message : String(error)
1608
+ );
1609
+ await mutateUpdateState(options.paths.stateFile, (state) => {
1610
+ const scopeChanged = !isMatchingCheckScope(state, {
1611
+ channel,
1612
+ configuredChannel: options.configuredChannel,
1613
+ registryId: regId
1614
+ });
1615
+ const next = {
1616
+ ...state,
1617
+ version: 1,
1618
+ last_check_at: checkedAt,
1619
+ last_check_ok: false,
1620
+ last_check_error: message,
1621
+ channel,
1622
+ registry_id: regId,
1623
+ configured_channel: options.configuredChannel,
1624
+ checked_version: options.currentVersion
1625
+ };
1626
+ if (scopeChanged) {
1627
+ delete next.latest_version;
1628
+ delete next.apply_failure;
1629
+ }
1630
+ return next;
1631
+ }).catch(() => void 0);
1632
+ return { status: "failed", channel, message };
1633
+ }
1634
+ };
1203
1635
  }
1204
- return import_node_path3.default.resolve(
1205
- import_node_path3.default.dirname(packageJsonPath),
1206
- "bin",
1207
- resolveTuiBinaryName(platform)
1208
- );
1209
- };
1210
- var resolveRuntimeEnvForTui = (env, resolveRuntimeEntry = resolveBundledRuntimeEntry) => {
1211
- if (env.CODELIA_RUNTIME_CMD || env.CODELIA_RUNTIME_ARGS) {
1212
- return env;
1636
+ });
1637
+
1638
+ // src/update/install-method.ts
1639
+ var import_node_fs5, import_node_path6, isSafeExecutable, resolveNpmBinary, isWritableDir, splitSegments, hasMatchingBinLink, unsupportedInstall, EXTERNAL_MANAGER_MATCHERS, detectInstallMethod, buildUpdateCommand;
1640
+ var init_install_method = __esm({
1641
+ "src/update/install-method.ts"() {
1642
+ "use strict";
1643
+ import_node_fs5 = __toESM(require("fs"), 1);
1644
+ import_node_path6 = __toESM(require("path"), 1);
1645
+ init_registry();
1646
+ isSafeExecutable = (candidate, platform) => {
1647
+ try {
1648
+ import_node_fs5.default.accessSync(candidate, import_node_fs5.default.constants.X_OK);
1649
+ const real = import_node_fs5.default.realpathSync(candidate);
1650
+ const info = import_node_fs5.default.statSync(real);
1651
+ if (!info.isFile()) return false;
1652
+ if (platform !== "win32" && typeof process.geteuid === "function") {
1653
+ const euid = process.geteuid();
1654
+ if (info.uid !== 0 && info.uid !== euid) return false;
1655
+ if ((info.mode & 18) !== 0) return false;
1656
+ const parentInfo = import_node_fs5.default.statSync(import_node_path6.default.dirname(real));
1657
+ if (parentInfo.uid !== 0 && parentInfo.uid !== euid) return false;
1658
+ if ((parentInfo.mode & 18) !== 0) return false;
1659
+ }
1660
+ return true;
1661
+ } catch {
1662
+ return false;
1663
+ }
1664
+ };
1665
+ resolveNpmBinary = (env = process.env) => {
1666
+ const platform = process.platform;
1667
+ const names = platform === "win32" ? ["npm.cmd", "npm.exe"] : ["npm"];
1668
+ const candidates = [];
1669
+ const execDir = import_node_path6.default.dirname(process.execPath);
1670
+ if (import_node_path6.default.isAbsolute(execDir)) {
1671
+ for (const name of names) {
1672
+ candidates.push(import_node_path6.default.join(execDir, name));
1673
+ }
1674
+ }
1675
+ const rawPath = env.PATH ?? env.Path ?? "";
1676
+ for (const entry of rawPath.split(import_node_path6.default.delimiter)) {
1677
+ const dir = entry.trim();
1678
+ if (!dir || !import_node_path6.default.isAbsolute(dir)) continue;
1679
+ for (const name of names) {
1680
+ candidates.push(import_node_path6.default.join(dir, name));
1681
+ }
1682
+ }
1683
+ const seen = /* @__PURE__ */ new Set();
1684
+ for (const candidate of candidates) {
1685
+ if (seen.has(candidate)) continue;
1686
+ seen.add(candidate);
1687
+ if (isSafeExecutable(candidate, platform)) {
1688
+ return candidate;
1689
+ }
1690
+ }
1691
+ return null;
1692
+ };
1693
+ isWritableDir = (dir) => {
1694
+ try {
1695
+ import_node_fs5.default.accessSync(dir, import_node_fs5.default.constants.W_OK);
1696
+ return true;
1697
+ } catch {
1698
+ return false;
1699
+ }
1700
+ };
1701
+ splitSegments = (target) => import_node_path6.default.normalize(target).split(import_node_path6.default.sep).filter(Boolean);
1702
+ hasMatchingBinLink = (prefix, packageRoot2, platform) => {
1703
+ const binCandidate = platform === "win32" ? import_node_path6.default.join(prefix, "codelia.cmd") : import_node_path6.default.join(prefix, "bin", "codelia");
1704
+ if (!import_node_fs5.default.existsSync(binCandidate)) return false;
1705
+ if (platform === "win32") return true;
1706
+ try {
1707
+ const resolvedBin = import_node_fs5.default.realpathSync(binCandidate);
1708
+ const resolvedRoot = import_node_fs5.default.realpathSync(packageRoot2);
1709
+ const rel = import_node_path6.default.relative(resolvedRoot, resolvedBin);
1710
+ return !rel.startsWith("..") && !import_node_path6.default.isAbsolute(rel);
1711
+ } catch {
1712
+ return false;
1713
+ }
1714
+ };
1715
+ unsupportedInstall = (kind, packageRoot2, reason, prefix) => ({
1716
+ kind,
1717
+ packageRoot: packageRoot2,
1718
+ ...prefix ? { prefix } : {},
1719
+ autoApply: { supported: false, reason }
1720
+ });
1721
+ EXTERNAL_MANAGER_MATCHERS = [
1722
+ {
1723
+ kind: "development",
1724
+ reason: "source checkout",
1725
+ match: (segments) => !segments.includes("node_modules")
1726
+ },
1727
+ {
1728
+ kind: "homebrew",
1729
+ reason: "managed by Homebrew",
1730
+ match: (segments) => segments.includes("Cellar")
1731
+ },
1732
+ {
1733
+ kind: "nix",
1734
+ reason: "managed by Nix/Guix store",
1735
+ match: (segments) => segments[0] === "nix" && segments[1] === "store" || segments[0] === "gnu" && segments[1] === "store"
1736
+ },
1737
+ {
1738
+ kind: "npx",
1739
+ reason: "ephemeral npx cache",
1740
+ match: (_segments, lower) => lower.includes("_npx")
1741
+ },
1742
+ {
1743
+ kind: "pnpm",
1744
+ reason: "managed by pnpm",
1745
+ match: (_segments, lower) => lower.includes(".pnpm") || lower.includes("pnpm")
1746
+ },
1747
+ {
1748
+ kind: "bun",
1749
+ reason: "managed by Bun",
1750
+ match: (_segments, lower) => lower.includes(".bun")
1751
+ },
1752
+ {
1753
+ kind: "yarn",
1754
+ reason: "managed by Yarn",
1755
+ match: (_segments, lower) => lower.includes("yarn")
1756
+ },
1757
+ {
1758
+ kind: "volta",
1759
+ reason: "managed by Volta",
1760
+ match: (_segments, lower) => lower.includes(".volta")
1761
+ },
1762
+ {
1763
+ kind: "mise",
1764
+ reason: "managed by mise",
1765
+ match: (_segments, lower) => lower.includes("mise") && lower.includes("installs") && lower.includes("npm")
1766
+ }
1767
+ ];
1768
+ detectInstallMethod = (options) => {
1769
+ const platform = options.platform ?? process.platform;
1770
+ const env = options.env ?? process.env;
1771
+ const resolveNpm = options.resolveNpm ?? resolveNpmBinary;
1772
+ let packageRoot2 = import_node_path6.default.resolve(options.packageRoot);
1773
+ try {
1774
+ packageRoot2 = import_node_fs5.default.realpathSync(packageRoot2);
1775
+ } catch {
1776
+ }
1777
+ const segments = splitSegments(packageRoot2);
1778
+ const lowerSegments = segments.map((s) => s.toLowerCase());
1779
+ for (const matcher of EXTERNAL_MANAGER_MATCHERS) {
1780
+ if (matcher.match(segments, lowerSegments)) {
1781
+ return unsupportedInstall(matcher.kind, packageRoot2, matcher.reason);
1782
+ }
1783
+ }
1784
+ const scopeDir = import_node_path6.default.dirname(packageRoot2);
1785
+ const nodeModulesDir = import_node_path6.default.dirname(scopeDir);
1786
+ if (import_node_path6.default.basename(packageRoot2) !== "cli" || import_node_path6.default.basename(scopeDir) !== "@codelia" || import_node_path6.default.basename(nodeModulesDir) !== "node_modules") {
1787
+ return unsupportedInstall(
1788
+ "unknown",
1789
+ packageRoot2,
1790
+ "unrecognized package layout"
1791
+ );
1792
+ }
1793
+ const parentOfNodeModules = import_node_path6.default.dirname(nodeModulesDir);
1794
+ const prefix = platform === "win32" ? parentOfNodeModules : import_node_path6.default.basename(parentOfNodeModules) === "lib" ? import_node_path6.default.dirname(parentOfNodeModules) : null;
1795
+ if (!prefix || !hasMatchingBinLink(prefix, packageRoot2, platform)) {
1796
+ return unsupportedInstall(
1797
+ "local",
1798
+ packageRoot2,
1799
+ "project-local installation"
1800
+ );
1801
+ }
1802
+ const npmPath = resolveNpm(env);
1803
+ if (!npmPath) {
1804
+ return unsupportedInstall(
1805
+ "npm-global",
1806
+ packageRoot2,
1807
+ "npm executable not found",
1808
+ prefix
1809
+ );
1810
+ }
1811
+ if (!isWritableDir(nodeModulesDir) || !isWritableDir(scopeDir)) {
1812
+ return unsupportedInstall(
1813
+ "npm-global",
1814
+ packageRoot2,
1815
+ "install directory is not writable",
1816
+ prefix
1817
+ );
1818
+ }
1819
+ return {
1820
+ kind: "npm-global",
1821
+ packageRoot: packageRoot2,
1822
+ prefix,
1823
+ autoApply: { supported: true, npmPath }
1824
+ };
1825
+ };
1826
+ buildUpdateCommand = (method, target) => {
1827
+ const spec = `${CLI_PACKAGE_NAME}@${target.channel}`;
1828
+ switch (method.kind) {
1829
+ case "npm-global":
1830
+ return `npm install -g ${spec}`;
1831
+ case "pnpm":
1832
+ return `pnpm add -g ${spec}`;
1833
+ case "bun":
1834
+ return `bun add -g ${spec}`;
1835
+ case "yarn":
1836
+ return `yarn global add ${spec}`;
1837
+ case "volta":
1838
+ return `volta install ${spec}`;
1839
+ case "homebrew":
1840
+ return "brew upgrade codelia";
1841
+ case "local":
1842
+ return `npm install ${spec}`;
1843
+ case "development":
1844
+ case "nix":
1845
+ case "mise":
1846
+ case "npx":
1847
+ case "unknown":
1848
+ return null;
1849
+ }
1850
+ };
1213
1851
  }
1214
- const runtimeEntry = resolveRuntimeEntry();
1215
- if (!runtimeEntry) {
1216
- return env;
1852
+ });
1853
+
1854
+ // src/update/notices.ts
1855
+ var import_node_crypto3, import_node_fs6, import_node_path7, UPDATE_NOTICE_FILE_ENV, STALE_NOTICE_AGE_MS, commandHint, buildStartupNotices, writeStartupNoticeFile, removeNoticeFileSync, cleanupStaleNotices;
1856
+ var init_notices = __esm({
1857
+ "src/update/notices.ts"() {
1858
+ "use strict";
1859
+ import_node_crypto3 = require("crypto");
1860
+ import_node_fs6 = __toESM(require("fs"), 1);
1861
+ import_node_path7 = __toESM(require("path"), 1);
1862
+ init_install_method();
1863
+ init_semver();
1864
+ init_state();
1865
+ UPDATE_NOTICE_FILE_ENV = "CODELIA_UPDATE_NOTICE_FILE";
1866
+ STALE_NOTICE_AGE_MS = 60 * 60 * 1e3;
1867
+ commandHint = (command) => command ? `Update with: ${command}` : "Update using the package manager that installed Codelia.";
1868
+ buildStartupNotices = (state, options) => {
1869
+ const notices = [];
1870
+ if (options.reexecFrom && options.reexecFrom !== options.currentVersion) {
1871
+ notices.push(
1872
+ `Updated Codelia ${options.reexecFrom} -> ${options.currentVersion}.`
1873
+ );
1874
+ }
1875
+ if (options.mode === "off") return notices;
1876
+ const latest = state.latest_version;
1877
+ if (!latest || !isNewerVersion(latest, options.currentVersion)) {
1878
+ return notices;
1879
+ }
1880
+ const channel = state.channel ?? "latest";
1881
+ const command = options.method ? buildUpdateCommand(options.method, { version: latest, channel }) : null;
1882
+ if (state.apply_failure && state.apply_failure.version === latest) {
1883
+ const hint = state.apply_failure.unmanaged ? commandHint(null) : commandHint(command);
1884
+ notices.push(
1885
+ `Automatic update to ${latest} failed (${state.apply_failure.message}). ${hint}`
1886
+ );
1887
+ return notices;
1888
+ }
1889
+ if (options.mode === "notify" || !options.method?.autoApply.supported) {
1890
+ const hint = options.method?.autoApply.supported ? "Run `codelia update` to install." : commandHint(command);
1891
+ notices.push(
1892
+ `Update available: ${options.currentVersion} -> ${latest}. ${hint}`
1893
+ );
1894
+ }
1895
+ return notices;
1896
+ };
1897
+ writeStartupNoticeFile = async (paths, notices) => {
1898
+ if (notices.length === 0) return null;
1899
+ await import_node_fs6.promises.mkdir(paths.noticesDir, { recursive: true, mode: 448 });
1900
+ void cleanupStaleNotices(paths.noticesDir);
1901
+ const file = import_node_path7.default.join(
1902
+ paths.noticesDir,
1903
+ `notice-${process.pid}-${(0, import_node_crypto3.randomBytes)(4).toString("hex")}.json`
1904
+ );
1905
+ await writeJsonAtomic(file, { notices: [...notices] });
1906
+ return file;
1907
+ };
1908
+ removeNoticeFileSync = (file) => {
1909
+ if (!file) return;
1910
+ try {
1911
+ import_node_fs6.default.rmSync(file, { force: true });
1912
+ } catch {
1913
+ }
1914
+ };
1915
+ cleanupStaleNotices = async (dir) => {
1916
+ try {
1917
+ const cutoff = Date.now() - STALE_NOTICE_AGE_MS;
1918
+ const entries = await import_node_fs6.promises.readdir(dir);
1919
+ for (const entry of entries) {
1920
+ if (!entry.startsWith("notice-") || !entry.endsWith(".json")) continue;
1921
+ const full = import_node_path7.default.join(dir, entry);
1922
+ const stat = await import_node_fs6.promises.lstat(full).catch(() => null);
1923
+ if (stat?.isFile() && stat.mtimeMs < cutoff) {
1924
+ await import_node_fs6.promises.rm(full, { force: true }).catch(() => void 0);
1925
+ }
1926
+ }
1927
+ } catch {
1928
+ }
1929
+ };
1217
1930
  }
1218
- return {
1219
- ...env,
1220
- CODELIA_RUNTIME_CMD: process.execPath,
1221
- CODELIA_RUNTIME_ARGS: quoteShellWord(runtimeEntry)
1222
- };
1223
- };
1224
- var resolveLaunchEnvForTui = (env, cliVersion = CLI_VERSION, resolveRuntimeEntry = resolveBundledRuntimeEntry) => {
1225
- const runtimeEnv = resolveRuntimeEnvForTui(env, resolveRuntimeEntry);
1226
- if (runtimeEnv.CODELIA_CLI_VERSION || cliVersion.trim().length === 0) {
1227
- return runtimeEnv;
1931
+ });
1932
+
1933
+ // src/update/settings.ts
1934
+ var import_node_fs7, import_config_loader4, isRecord3, isCiEnvironment, parseEnvMode, readGlobalUpdateConfig, resolveUpdateSettings;
1935
+ var init_settings = __esm({
1936
+ "src/update/settings.ts"() {
1937
+ "use strict";
1938
+ import_node_fs7 = require("fs");
1939
+ import_config_loader4 = require("@codelia/config-loader");
1940
+ isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1941
+ isCiEnvironment = (env) => {
1942
+ const ci = (env.CI ?? "").trim().toLowerCase();
1943
+ if (ci === "1" || ci === "true" || ci === "yes") return true;
1944
+ return Boolean(
1945
+ env.GITHUB_ACTIONS || env.GITLAB_CI || env.BUILDKITE || env.CIRCLECI || env.JENKINS_URL
1946
+ );
1947
+ };
1948
+ parseEnvMode = (raw) => {
1949
+ if (raw === void 0) return {};
1950
+ const normalized = raw.trim().toLowerCase();
1951
+ if (normalized === "") return {};
1952
+ if (normalized === "0" || normalized === "false" || normalized === "off") {
1953
+ return { value: "off" };
1954
+ }
1955
+ if (normalized === "1" || normalized === "true" || normalized === "auto") {
1956
+ return { value: "auto" };
1957
+ }
1958
+ if (normalized === "notify") {
1959
+ return { value: "notify" };
1960
+ }
1961
+ return { invalid: true };
1962
+ };
1963
+ readGlobalUpdateConfig = async (configFile) => {
1964
+ const warnings = [];
1965
+ let rawText;
1966
+ try {
1967
+ rawText = await import_node_fs7.promises.readFile(configFile, "utf8");
1968
+ } catch {
1969
+ return { warnings };
1970
+ }
1971
+ let parsed;
1972
+ try {
1973
+ parsed = JSON.parse(rawText);
1974
+ } catch {
1975
+ return { warnings };
1976
+ }
1977
+ if (!isRecord3(parsed) || !isRecord3(parsed.update)) {
1978
+ return { warnings };
1979
+ }
1980
+ const update = parsed.update;
1981
+ let mode;
1982
+ if (update.mode !== void 0) {
1983
+ mode = (0, import_config_loader4.parseUpdateMode)(update.mode);
1984
+ if (!mode) {
1985
+ warnings.push(
1986
+ `Ignoring invalid update.mode in ${configFile} (expected "auto", "notify", or "off").`
1987
+ );
1988
+ }
1989
+ }
1990
+ let channel;
1991
+ if (update.channel !== void 0) {
1992
+ if (typeof update.channel === "string" && (0, import_config_loader4.isValidUpdateChannel)(update.channel)) {
1993
+ channel = update.channel;
1994
+ } else {
1995
+ warnings.push(
1996
+ `Ignoring invalid update.channel in ${configFile} (expected an npm dist-tag name).`
1997
+ );
1998
+ }
1999
+ }
2000
+ return { mode, channel, warnings };
2001
+ };
2002
+ resolveUpdateSettings = async (options) => {
2003
+ const env = options.env ?? process.env;
2004
+ const fromConfig = await readGlobalUpdateConfig(options.configFile);
2005
+ const warnings = [...fromConfig.warnings];
2006
+ const envMode = parseEnvMode(env.CODELIA_AUTO_UPDATE);
2007
+ if (envMode.invalid) {
2008
+ warnings.push(
2009
+ `Ignoring invalid CODELIA_AUTO_UPDATE=${env.CODELIA_AUTO_UPDATE} (expected "auto", "notify", or "off").`
2010
+ );
2011
+ }
2012
+ let channel = fromConfig.channel ?? null;
2013
+ if (env.CODELIA_UPDATE_CHANNEL !== void 0) {
2014
+ const trimmed = env.CODELIA_UPDATE_CHANNEL.trim();
2015
+ if (trimmed.length === 0) {
2016
+ channel = null;
2017
+ } else if ((0, import_config_loader4.isValidUpdateChannel)(trimmed)) {
2018
+ channel = trimmed;
2019
+ } else {
2020
+ warnings.push(
2021
+ `Ignoring invalid CODELIA_UPDATE_CHANNEL=${env.CODELIA_UPDATE_CHANNEL}.`
2022
+ );
2023
+ }
2024
+ }
2025
+ let mode = envMode.value ?? fromConfig.mode ?? "notify";
2026
+ if (!options.interactive || isCiEnvironment(env)) {
2027
+ mode = "off";
2028
+ }
2029
+ return { mode, channel, warnings };
2030
+ };
1228
2031
  }
1229
- return {
1230
- ...runtimeEnv,
1231
- CODELIA_CLI_VERSION: cliVersion
1232
- };
1233
- };
1234
- var resolveTuiCommand = (options = {}) => {
1235
- const env = options.env ?? process.env;
1236
- if (env.CODELIA_TUI_CMD) {
1237
- return env.CODELIA_TUI_CMD;
2032
+ });
2033
+
2034
+ // src/commands/update.ts
2035
+ var update_exports = {};
2036
+ __export(update_exports, {
2037
+ runUpdateCommand: () => runUpdateCommand
2038
+ });
2039
+ var import_node_fs8, import_storage6, USAGE2, runUpdateCommand;
2040
+ var init_update = __esm({
2041
+ "src/commands/update.ts"() {
2042
+ "use strict";
2043
+ import_node_fs8 = require("fs");
2044
+ import_storage6 = require("@codelia/storage");
2045
+ init_package_root();
2046
+ init_apply();
2047
+ init_check();
2048
+ init_install_method();
2049
+ init_notices();
2050
+ init_semver();
2051
+ init_settings();
2052
+ init_state();
2053
+ init_version();
2054
+ USAGE2 = "usage: codelia update [--check]";
2055
+ runUpdateCommand = async (args2, deps = {}) => {
2056
+ const out = deps.out ?? ((line) => console.log(line));
2057
+ const err = deps.err ?? ((line) => console.error(line));
2058
+ if (args2.length === 1 && ["-h", "--help", "help"].includes(args2[0])) {
2059
+ out(USAGE2);
2060
+ return 0;
2061
+ }
2062
+ if (args2.length > 1 || args2.length === 1 && args2[0] !== "--check") {
2063
+ err(USAGE2);
2064
+ return 1;
2065
+ }
2066
+ const checkOnly = args2[0] === "--check";
2067
+ const env = deps.env ?? process.env;
2068
+ const currentVersion = deps.currentVersion ?? CLI_VERSION;
2069
+ const packageRoot2 = deps.packageRoot === void 0 ? resolveLoadedCliPackageRoot() : deps.packageRoot;
2070
+ const method = packageRoot2 ? detectInstallMethod({ packageRoot: packageRoot2, env, resolveNpm: deps.resolveNpm }) : null;
2071
+ const storagePaths = (0, import_storage6.resolveStoragePaths)();
2072
+ const paths = resolveUpdatePaths(deps.cacheDir ?? storagePaths.cacheDir);
2073
+ await import_node_fs8.promises.mkdir(paths.dir, { recursive: true });
2074
+ const settings = await resolveUpdateSettings({
2075
+ env,
2076
+ interactive: true,
2077
+ configFile: deps.configFile ?? storagePaths.configFile
2078
+ });
2079
+ for (const warning of settings.warnings) err(warning);
2080
+ const outcome = await runRegistryCheck({
2081
+ paths,
2082
+ currentVersion,
2083
+ configuredChannel: settings.channel,
2084
+ env,
2085
+ fetchImpl: deps.fetchImpl
2086
+ });
2087
+ if (outcome.status === "failed" || outcome.status === "aborted") {
2088
+ err(
2089
+ `Could not check for updates: ${outcome.status === "failed" ? outcome.message : "aborted"}.`
2090
+ );
2091
+ return 1;
2092
+ }
2093
+ out(
2094
+ `Current: ${currentVersion}. Latest (${outcome.channel}): ${outcome.latest}.`
2095
+ );
2096
+ if (outcome.status === "up_to_date") {
2097
+ out("Codelia is up to date.");
2098
+ return 0;
2099
+ }
2100
+ if (!method || method.kind === "development") {
2101
+ out("Running from a source checkout; update it with git.");
2102
+ return checkOnly ? 0 : 1;
2103
+ }
2104
+ const command = buildUpdateCommand(method, {
2105
+ version: outcome.latest,
2106
+ channel: outcome.channel
2107
+ });
2108
+ const hint = method.autoApply.supported ? "Update with: codelia update" : commandHint(command);
2109
+ if (checkOnly) {
2110
+ out(hint);
2111
+ return 0;
2112
+ }
2113
+ if (!method.autoApply.supported) {
2114
+ err(
2115
+ `Automatic update is unavailable (${method.autoApply.reason}). ${hint}`
2116
+ );
2117
+ return 1;
2118
+ }
2119
+ const result = await applyUpdate({
2120
+ paths,
2121
+ method,
2122
+ from: currentVersion,
2123
+ to: outcome.latest,
2124
+ configuredChannel: settings.channel,
2125
+ env,
2126
+ runner: deps.runner
2127
+ });
2128
+ if (result.status === "installed") {
2129
+ out(`Updated Codelia ${result.from} -> ${result.to}.`);
2130
+ return 0;
2131
+ }
2132
+ if (result.status === "changed") {
2133
+ if ((compareVersions(result.installed, outcome.latest) ?? -1) >= 0) {
2134
+ out(`Codelia ${result.installed} is already up to date.`);
2135
+ return 0;
2136
+ }
2137
+ err(
2138
+ "Codelia changed version during the update check. Run codelia update again."
2139
+ );
2140
+ return 1;
2141
+ }
2142
+ if (result.status === "superseded") {
2143
+ err("The cached update target changed. Run codelia update again.");
2144
+ return 1;
2145
+ }
2146
+ if (result.status === "deferred") {
2147
+ err(
2148
+ "Another update is in progress for this installation. Run codelia update again after it finishes."
2149
+ );
2150
+ return 1;
2151
+ }
2152
+ err(
2153
+ `Update failed: ${result.message}. ${result.unmanaged ? commandHint(null) : hint}`
2154
+ );
2155
+ return 1;
2156
+ };
1238
2157
  }
1239
- const platform = options.platform ?? process.platform;
1240
- const arch = options.arch ?? process.arch;
1241
- const resolveOptionalBinary = options.resolveOptionalTuiBinary ?? resolveOptionalTuiBinaryPath;
1242
- const isExecutableCandidate = options.isExecutableCandidate ?? isExecutable;
1243
- const tuiBinaryName = resolveTuiBinaryName(platform);
1244
- const cwd = options.cwd ?? process.cwd();
1245
- const cliPackageRoot = options.cliPackageRoot === void 0 ? resolveCliPackageRoot() : options.cliPackageRoot;
1246
- const seen = /* @__PURE__ */ new Set();
1247
- const optionalTuiBinary = resolveOptionalBinary(platform, arch);
1248
- const localCandidates = [
1249
- ...cliPackageRoot ? [
1250
- import_node_path3.default.resolve(cliPackageRoot, "dist/bin", tuiBinaryName),
1251
- import_node_path3.default.resolve(
1252
- cliPackageRoot,
1253
- "../../crates/tui/target/release",
1254
- tuiBinaryName
1255
- ),
1256
- import_node_path3.default.resolve(
1257
- cliPackageRoot,
1258
- "../../crates/tui/target/debug",
1259
- tuiBinaryName
1260
- )
1261
- ] : [],
1262
- import_node_path3.default.resolve(cwd, "target/release", tuiBinaryName),
1263
- import_node_path3.default.resolve(cwd, "target/debug", tuiBinaryName),
1264
- import_node_path3.default.resolve(cwd, "crates/tui/target/release", tuiBinaryName),
1265
- import_node_path3.default.resolve(cwd, "crates/tui/target/debug", tuiBinaryName)
1266
- ];
1267
- const candidates = [
1268
- ...localCandidates,
1269
- ...optionalTuiBinary ? [optionalTuiBinary] : []
1270
- ];
1271
- for (const candidate of candidates) {
1272
- if (seen.has(candidate)) continue;
1273
- seen.add(candidate);
1274
- if (isExecutableCandidate(candidate)) {
1275
- return candidate;
1276
- }
2158
+ });
2159
+
2160
+ // src/atif.ts
2161
+ var import_promises2, import_node_path8, import_storage7, asRecord, asString, stringifyContent, normalizeTimestamp, extractInputText, extractModelName, extractSessionId, createStepIdAllocator, pushTextStep, getOrCreateToolStep, extractUsageMetrics, sessionRecordsToAtif, parseSessionJsonl, readSessionJsonl, writeAtifFromSessionJsonl;
2162
+ var init_atif = __esm({
2163
+ "src/atif.ts"() {
2164
+ "use strict";
2165
+ import_promises2 = require("fs/promises");
2166
+ import_node_path8 = __toESM(require("path"), 1);
2167
+ import_storage7 = require("@codelia/storage");
2168
+ asRecord = (value) => typeof value === "object" && value !== null ? value : null;
2169
+ asString = (value) => typeof value === "string" && value.trim().length > 0 ? value : void 0;
2170
+ stringifyContent = (value) => {
2171
+ if (typeof value === "string") return value;
2172
+ if (value == null) return "";
2173
+ try {
2174
+ return JSON.stringify(value);
2175
+ } catch {
2176
+ return String(value);
2177
+ }
2178
+ };
2179
+ normalizeTimestamp = (value) => {
2180
+ const raw = asString(value);
2181
+ if (!raw) return void 0;
2182
+ const date = new Date(raw);
2183
+ if (Number.isNaN(date.getTime())) return raw;
2184
+ return date.toISOString();
2185
+ };
2186
+ extractInputText = (input) => {
2187
+ const direct = asRecord(input);
2188
+ if (!direct) return asString(input);
2189
+ if (direct.type === "text") return asString(direct.text);
2190
+ return stringifyContent(direct);
2191
+ };
2192
+ extractModelName = (record) => {
2193
+ const model = asRecord(record?.model);
2194
+ return asString(model?.name) ?? asString(model?.id);
2195
+ };
2196
+ extractSessionId = (header, runStart, fallbackRunId) => asString(header?.session_id) ?? asString(runStart?.session_id) ?? asString(asRecord(runStart?.output)?.session_id) ?? fallbackRunId;
2197
+ createStepIdAllocator = () => {
2198
+ let next = 1;
2199
+ return () => next++;
2200
+ };
2201
+ pushTextStep = (steps, nextStepId, source, message, timestamp, extra) => {
2202
+ if (!message?.trim()) return;
2203
+ steps.push({
2204
+ step_id: nextStepId(),
2205
+ ...timestamp ? { timestamp } : {},
2206
+ source,
2207
+ message,
2208
+ ...extra ? { extra } : {}
2209
+ });
2210
+ };
2211
+ getOrCreateToolStep = (steps, nextStepId, callId, timestamp) => {
2212
+ const existing = steps.find(
2213
+ (step2) => step2.tool_calls?.some((call) => call.tool_call_id === callId)
2214
+ );
2215
+ if (existing) return existing;
2216
+ const step = {
2217
+ step_id: nextStepId(),
2218
+ ...timestamp ? { timestamp } : {},
2219
+ source: "agent",
2220
+ message: "",
2221
+ tool_calls: []
2222
+ };
2223
+ steps.push(step);
2224
+ return step;
2225
+ };
2226
+ extractUsageMetrics = (records) => {
2227
+ return records.map((record) => asRecord(asRecord(record.output)?.usage)).filter((usage) => !!usage).reduce(
2228
+ (acc, usage) => {
2229
+ acc.total_prompt_tokens += Number(usage.input_tokens ?? 0);
2230
+ acc.total_completion_tokens += Number(usage.output_tokens ?? 0);
2231
+ acc.total_cached_tokens += Number(
2232
+ usage.input_cached_tokens ?? asRecord(usage.input_tokens_details)?.cached_tokens ?? 0
2233
+ );
2234
+ return acc;
2235
+ },
2236
+ {
2237
+ total_prompt_tokens: 0,
2238
+ total_completion_tokens: 0,
2239
+ total_cached_tokens: 0
2240
+ }
2241
+ );
2242
+ };
2243
+ sessionRecordsToAtif = (records, runId) => {
2244
+ const header = records.find((record) => record.type === "header");
2245
+ const runStart = records.find((record) => record.type === "run.start");
2246
+ const modelName = extractModelName(header);
2247
+ const nextStepId = createStepIdAllocator();
2248
+ const steps = [];
2249
+ pushTextStep(
2250
+ steps,
2251
+ nextStepId,
2252
+ "user",
2253
+ extractInputText(asRecord(runStart?.input)),
2254
+ normalizeTimestamp(runStart?.ts),
2255
+ { source_record: "run.start" }
2256
+ );
2257
+ for (const record of records) {
2258
+ if (record.type !== "agent.event") continue;
2259
+ const event = asRecord(record.event);
2260
+ if (!event) continue;
2261
+ const timestamp = normalizeTimestamp(record.ts);
2262
+ const eventType = asString(event.type);
2263
+ if (eventType === "text") {
2264
+ pushTextStep(
2265
+ steps,
2266
+ nextStepId,
2267
+ "agent",
2268
+ asString(event.content),
2269
+ timestamp,
2270
+ { source_record: "agent.event.text" }
2271
+ );
2272
+ continue;
2273
+ }
2274
+ if (eventType === "reasoning") {
2275
+ const content = asString(event.content);
2276
+ if (!content) continue;
2277
+ steps.push({
2278
+ step_id: nextStepId(),
2279
+ ...timestamp ? { timestamp } : {},
2280
+ source: "agent",
2281
+ message: "",
2282
+ reasoning_content: content,
2283
+ extra: { source_record: "agent.event.reasoning" }
2284
+ });
2285
+ continue;
2286
+ }
2287
+ if (eventType === "tool_call") {
2288
+ const callId = asString(event.tool_call_id) ?? `tool_call_${String(steps.length + 1)}`;
2289
+ const step = getOrCreateToolStep(steps, nextStepId, callId, timestamp);
2290
+ step.tool_calls ??= [];
2291
+ step.tool_calls.push({
2292
+ tool_call_id: callId,
2293
+ function_name: asString(event.tool) ?? "unknown",
2294
+ arguments: asRecord(event.args) ?? {}
2295
+ });
2296
+ continue;
2297
+ }
2298
+ if (eventType === "tool_result") {
2299
+ const callId = asString(event.tool_call_id);
2300
+ const step = callId ? getOrCreateToolStep(steps, nextStepId, callId, timestamp) : {
2301
+ step_id: nextStepId(),
2302
+ ...timestamp ? { timestamp } : {},
2303
+ source: "agent",
2304
+ message: ""
2305
+ };
2306
+ if (!callId) steps.push(step);
2307
+ step.observation ??= { results: [] };
2308
+ step.observation.results.push({
2309
+ ...callId ? { source_call_id: callId } : {},
2310
+ content: stringifyContent(event.result)
2311
+ });
2312
+ continue;
2313
+ }
2314
+ if (eventType === "final") {
2315
+ pushTextStep(
2316
+ steps,
2317
+ nextStepId,
2318
+ "agent",
2319
+ asString(event.content),
2320
+ timestamp,
2321
+ { source_record: "agent.event.final" }
2322
+ );
2323
+ }
2324
+ }
2325
+ if (steps.length === 0) {
2326
+ steps.push({
2327
+ step_id: nextStepId(),
2328
+ source: "user",
2329
+ message: "(no prompt captured)",
2330
+ extra: { source_record: "fallback" }
2331
+ });
2332
+ }
2333
+ const compactUsage = records.filter((record) => record.type === "llm.usage");
2334
+ const compactSequences = new Set(compactUsage.map((record) => record.seq));
2335
+ const usage = extractUsageMetrics([
2336
+ ...compactUsage,
2337
+ ...records.filter(
2338
+ (record) => record.type === "llm.response" && !compactSequences.has(record.seq)
2339
+ )
2340
+ ]);
2341
+ return {
2342
+ schema_version: "ATIF-v1.6",
2343
+ session_id: extractSessionId(header, runStart, runId),
2344
+ agent: {
2345
+ name: "codelia",
2346
+ version: "unknown",
2347
+ ...modelName ? { model_name: modelName } : {}
2348
+ },
2349
+ steps,
2350
+ final_metrics: {
2351
+ ...usage,
2352
+ total_steps: steps.length
2353
+ },
2354
+ extra: {
2355
+ run_id: runId,
2356
+ source: "codelia-session-jsonl",
2357
+ conversion: "session-records-to-atif-v1.6"
2358
+ }
2359
+ };
2360
+ };
2361
+ parseSessionJsonl = (raw) => {
2362
+ const out = [];
2363
+ for (const line of raw.split("\n")) {
2364
+ if (!line.trim()) continue;
2365
+ try {
2366
+ out.push(JSON.parse(line));
2367
+ } catch {
2368
+ }
2369
+ }
2370
+ return out;
2371
+ };
2372
+ readSessionJsonl = async (filePath) => {
2373
+ const lines = [];
2374
+ for await (const line of (0, import_storage7.readRunLogLines)(filePath)) lines.push(line);
2375
+ return parseSessionJsonl(lines.join("\n"));
2376
+ };
2377
+ writeAtifFromSessionJsonl = async ({
2378
+ sessionLogPath,
2379
+ runId,
2380
+ outPath,
2381
+ extra
2382
+ }) => {
2383
+ const records = await readSessionJsonl(sessionLogPath);
2384
+ const trajectory = sessionRecordsToAtif(records, runId);
2385
+ if (extra) trajectory.extra = { ...extra, ...trajectory.extra };
2386
+ await (0, import_promises2.mkdir)(import_node_path8.default.dirname(outPath), { recursive: true });
2387
+ const tempPath = `${outPath}.tmp-${process.pid}-${Date.now()}`;
2388
+ await (0, import_promises2.writeFile)(tempPath, `${JSON.stringify(trajectory, null, 2)}
2389
+ `, "utf8");
2390
+ await (0, import_promises2.rename)(tempPath, outPath);
2391
+ return trajectory;
2392
+ };
1277
2393
  }
1278
- return tuiBinaryName;
1279
- };
1280
- var runTui = (args2) => {
1281
- void initStorage();
1282
- const tuiCmd = resolveTuiCommand();
1283
- const tuiArgs = process.env.CODELIA_TUI_ARGS ? splitArgs(process.env.CODELIA_TUI_ARGS) : [];
1284
- const child = (0, import_node_child_process2.spawn)(tuiCmd, [...tuiArgs, ...args2], {
1285
- stdio: "inherit",
1286
- env: resolveLaunchEnvForTui(process.env)
1287
- });
1288
- child.on("exit", (code) => {
1289
- process.exitCode = code ?? 0;
1290
- });
1291
- child.on("error", (error) => {
1292
- const code = typeof error === "object" && error !== null && "code" in error ? String(error.code ?? "") : "";
1293
- const expectedPackage = resolvePlatformTuiPackageName();
1294
- console.error(`Failed to launch TUI (${tuiCmd}): ${describeError3(error)}`);
1295
- if (code === "EACCES") {
1296
- console.error(
1297
- "Permission denied while launching TUI. Verify execute permission and PATH entries."
2394
+ });
2395
+
2396
+ // src/update/launch.ts
2397
+ var launch_exports = {};
2398
+ __export(launch_exports, {
2399
+ NOOP_LAUNCH_UPDATE_SESSION: () => NOOP_LAUNCH_UPDATE_SESSION,
2400
+ prepareTuiLaunch: () => prepareTuiLaunch
2401
+ });
2402
+ var import_storage8, NOOP_LAUNCH_UPDATE_SESSION, tryResolveRegistryId, prepareTuiLaunch;
2403
+ var init_launch = __esm({
2404
+ "src/update/launch.ts"() {
2405
+ "use strict";
2406
+ import_storage8 = require("@codelia/storage");
2407
+ init_apply();
2408
+ init_check();
2409
+ init_install_method();
2410
+ init_launcher_entry();
2411
+ init_notices();
2412
+ init_registry();
2413
+ init_semver();
2414
+ init_settings();
2415
+ init_state();
2416
+ NOOP_LAUNCH_UPDATE_SESSION = {
2417
+ tuiEnv: {},
2418
+ startBackground: async () => void 0,
2419
+ dispose: () => void 0
2420
+ };
2421
+ tryResolveRegistryId = (env) => {
2422
+ try {
2423
+ return computeRegistryId(resolveRegistryUrl(env));
2424
+ } catch {
2425
+ return null;
2426
+ }
2427
+ };
2428
+ prepareTuiLaunch = async (options) => {
2429
+ const env = options.env ?? process.env;
2430
+ const interactive = options.interactive ?? Boolean(process.stdin.isTTY && process.stdout.isTTY);
2431
+ const storage = (0, import_storage8.resolveStoragePaths)();
2432
+ const paths = resolveUpdatePaths(options.cacheDir ?? storage.cacheDir);
2433
+ const configFile = options.configFile ?? storage.configFile;
2434
+ const settings = await resolveUpdateSettings({
2435
+ env,
2436
+ interactive,
2437
+ configFile
2438
+ });
2439
+ const method = options.packageRoot ? detectInstallMethod({
2440
+ packageRoot: options.packageRoot,
2441
+ env,
2442
+ resolveNpm: options.resolveNpm
2443
+ }) : null;
2444
+ const rawReexecFrom = env[UPDATE_REEXEC_ENV];
2445
+ const reexecFrom = isValidVersion(rawReexecFrom) ? rawReexecFrom : void 0;
2446
+ if (settings.mode === "off" && !reexecFrom) {
2447
+ return { kind: "launch", session: NOOP_LAUNCH_UPDATE_SESSION };
2448
+ }
2449
+ let state = await readUpdateState(paths.stateFile);
2450
+ const currentRegistryId = tryResolveRegistryId(env);
2451
+ const effectiveChannel = resolveEffectiveChannel(
2452
+ options.currentVersion,
2453
+ settings.channel
1298
2454
  );
1299
- } else if (code === "ENOENT") {
1300
- console.error(
1301
- 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."
2455
+ const cacheMatchesScope = currentRegistryId !== null && isMatchingCheckScope(state, {
2456
+ channel: effectiveChannel,
2457
+ configuredChannel: settings.channel,
2458
+ registryId: currentRegistryId
2459
+ });
2460
+ const cachedTarget = cacheMatchesScope ? state.latest_version : void 0;
2461
+ const canAutoApply = settings.mode === "auto" && !reexecFrom && Boolean(method?.autoApply.supported) && Boolean(cachedTarget) && isNewerVersion(cachedTarget, options.currentVersion) && state.apply_failure?.version !== cachedTarget;
2462
+ if (canAutoApply && method && cachedTarget) {
2463
+ const applied = await applyUpdate({
2464
+ paths,
2465
+ method,
2466
+ from: options.currentVersion,
2467
+ to: cachedTarget,
2468
+ configuredChannel: settings.channel,
2469
+ env,
2470
+ runner: options.runner,
2471
+ now: options.now
2472
+ });
2473
+ if (applied.status === "installed") {
2474
+ const reexec = options.reexec ?? reexecLauncher;
2475
+ const exitCode = await reexec({
2476
+ entry: launcherEntry(method.packageRoot),
2477
+ args: options.args,
2478
+ env: {
2479
+ ...env,
2480
+ [UPDATE_REEXEC_ENV]: options.currentVersion
2481
+ }
2482
+ });
2483
+ if (exitCode !== null) {
2484
+ return { kind: "exit", exitCode };
2485
+ }
2486
+ }
2487
+ state = await readUpdateState(paths.stateFile);
2488
+ }
2489
+ const notices = buildStartupNotices(
2490
+ cacheMatchesScope ? state : { version: 1 },
2491
+ {
2492
+ currentVersion: options.currentVersion,
2493
+ mode: settings.mode,
2494
+ method,
2495
+ reexecFrom
2496
+ }
1302
2497
  );
1303
- }
1304
- console.error(
1305
- "Set CODELIA_TUI_CMD/CODELIA_TUI_ARGS to use a custom TUI command."
1306
- );
1307
- process.exitCode = 1;
1308
- });
1309
- };
2498
+ let noticeFile = null;
2499
+ try {
2500
+ noticeFile = await writeStartupNoticeFile(paths, notices);
2501
+ } catch {
2502
+ noticeFile = null;
2503
+ }
2504
+ const abortController = new AbortController();
2505
+ const startBackground = async () => {
2506
+ if (settings.mode === "off" || method?.kind === "development") return;
2507
+ const regId = tryResolveRegistryId(env);
2508
+ if (!regId) return;
2509
+ const latestState = await readUpdateState(paths.stateFile);
2510
+ if (!shouldCheckNow(latestState, {
2511
+ now: options.now?.(),
2512
+ currentVersion: options.currentVersion,
2513
+ configuredChannel: settings.channel,
2514
+ registryId: regId
2515
+ })) {
2516
+ return;
2517
+ }
2518
+ await runRegistryCheck({
2519
+ paths,
2520
+ currentVersion: options.currentVersion,
2521
+ configuredChannel: settings.channel,
2522
+ env,
2523
+ fetchImpl: options.fetchImpl,
2524
+ signal: abortController.signal,
2525
+ now: options.now
2526
+ }).catch(() => void 0);
2527
+ };
2528
+ const dispose = () => {
2529
+ abortController.abort();
2530
+ removeNoticeFileSync(noticeFile);
2531
+ noticeFile = null;
2532
+ };
2533
+ return {
2534
+ kind: "launch",
2535
+ session: {
2536
+ tuiEnv: noticeFile ? { [UPDATE_NOTICE_FILE_ENV]: noticeFile } : {},
2537
+ startBackground,
2538
+ dispose
2539
+ }
2540
+ };
2541
+ };
2542
+ }
2543
+ });
1310
2544
 
1311
- // src/prompt-mode.ts
1312
- var parseShellLikeArgs = (value) => {
1313
- const out = [];
1314
- let current = "";
1315
- let quote = null;
1316
- let escaping = false;
1317
- for (let i = 0; i < value.length; i += 1) {
1318
- const ch = value[i];
1319
- if (escaping) {
1320
- current += ch;
1321
- escaping = false;
1322
- continue;
1323
- }
1324
- if (ch === "\\" && quote !== "single") {
1325
- escaping = true;
1326
- continue;
1327
- }
1328
- if (quote === "single") {
1329
- if (ch === "'") {
1330
- quote = null;
1331
- } else {
1332
- current += ch;
2545
+ // src/tui/launcher.ts
2546
+ var launcher_exports = {};
2547
+ __export(launcher_exports, {
2548
+ resolveLaunchEnvForTui: () => resolveLaunchEnvForTui,
2549
+ resolveOptionalTuiBinaryPath: () => resolveOptionalTuiBinaryPath,
2550
+ resolvePlatformTuiPackageName: () => resolvePlatformTuiPackageName,
2551
+ resolveRuntimeEnvForTui: () => resolveRuntimeEnvForTui,
2552
+ resolveTuiCommand: () => resolveTuiCommand,
2553
+ runTui: () => runTui
2554
+ });
2555
+ var import_node_child_process3, import_node_fs9, import_node_module, import_node_path9, import_storage9, resolveTuiBinaryName, TUI_PACKAGE_BY_TARGET, describeError2, splitArgs, quoteShellWord, isExecutable, initStorage, resolveRuntimeRequireBase, runtimeRequire, resolveBundledRuntimeEntry, resolveInstalledPackageJson, resolvePlatformTuiPackageName, resolveOptionalTuiBinaryPath, resolveRuntimeEnvForTui, resolveLaunchEnvForTui, resolveTuiCommand, runTui;
2556
+ var init_launcher = __esm({
2557
+ "src/tui/launcher.ts"() {
2558
+ "use strict";
2559
+ import_node_child_process3 = require("child_process");
2560
+ import_node_fs9 = __toESM(require("fs"), 1);
2561
+ import_node_module = require("module");
2562
+ import_node_path9 = __toESM(require("path"), 1);
2563
+ import_storage9 = require("@codelia/storage");
2564
+ init_package_root();
2565
+ init_launch();
2566
+ init_launcher_entry();
2567
+ init_version();
2568
+ resolveTuiBinaryName = (platform) => platform === "win32" ? "codelia-tui.exe" : "codelia-tui";
2569
+ TUI_PACKAGE_BY_TARGET = {
2570
+ "darwin-arm64": "@codelia/tui-darwin-arm64",
2571
+ "darwin-x64": "@codelia/tui-darwin-x64",
2572
+ "linux-arm64": "@codelia/tui-linux-arm64",
2573
+ "linux-x64": "@codelia/tui-linux-x64",
2574
+ "win32-x64": "@codelia/tui-win32-x64"
2575
+ };
2576
+ describeError2 = (error) => error instanceof Error ? error.message : String(error);
2577
+ splitArgs = (value) => value.split(/\s+/).map((part) => part.trim()).filter((part) => part.length > 0);
2578
+ quoteShellWord = (value) => `'${value.replace(/'/g, "'\\''")}'`;
2579
+ isExecutable = (candidate) => {
2580
+ try {
2581
+ import_node_fs9.default.accessSync(candidate, import_node_fs9.default.constants.X_OK);
2582
+ return true;
2583
+ } catch {
2584
+ return false;
1333
2585
  }
1334
- continue;
1335
- }
1336
- if (quote === "double") {
1337
- if (ch === '"') {
1338
- quote = null;
1339
- } else {
2586
+ };
2587
+ initStorage = async () => {
2588
+ try {
2589
+ const paths = (0, import_storage9.resolveStoragePaths)();
2590
+ await (0, import_storage9.ensureStorageDirs)(paths);
2591
+ } catch (error) {
2592
+ console.warn(
2593
+ `Failed to initialize storage directories: ${describeError2(error)}`
2594
+ );
2595
+ }
2596
+ };
2597
+ resolveRuntimeRequireBase = () => {
2598
+ const cliPackageRoot = resolveCliPackageRoot();
2599
+ if (cliPackageRoot) {
2600
+ return import_node_path9.default.resolve(cliPackageRoot, "package.json");
2601
+ }
2602
+ return import_node_path9.default.resolve(process.cwd(), "package.json");
2603
+ };
2604
+ runtimeRequire = (0, import_node_module.createRequire)(resolveRuntimeRequireBase());
2605
+ resolveBundledRuntimeEntry = () => {
2606
+ try {
2607
+ return runtimeRequire.resolve("@codelia/runtime");
2608
+ } catch {
2609
+ return null;
2610
+ }
2611
+ };
2612
+ resolveInstalledPackageJson = (packageName) => {
2613
+ try {
2614
+ return runtimeRequire.resolve(`${packageName}/package.json`);
2615
+ } catch {
2616
+ return null;
2617
+ }
2618
+ };
2619
+ resolvePlatformTuiPackageName = (platform = process.platform, arch = process.arch) => TUI_PACKAGE_BY_TARGET[`${platform}-${arch}`] ?? null;
2620
+ resolveOptionalTuiBinaryPath = (platform = process.platform, arch = process.arch, resolvePackageJson = resolveInstalledPackageJson) => {
2621
+ const packageName = resolvePlatformTuiPackageName(platform, arch);
2622
+ if (!packageName) {
2623
+ return null;
2624
+ }
2625
+ const packageJsonPath = resolvePackageJson(packageName);
2626
+ if (!packageJsonPath) {
2627
+ return null;
2628
+ }
2629
+ return import_node_path9.default.resolve(
2630
+ import_node_path9.default.dirname(packageJsonPath),
2631
+ "bin",
2632
+ resolveTuiBinaryName(platform)
2633
+ );
2634
+ };
2635
+ resolveRuntimeEnvForTui = (env, resolveRuntimeEntry = resolveBundledRuntimeEntry) => {
2636
+ if (env.CODELIA_RUNTIME_CMD || env.CODELIA_RUNTIME_ARGS) {
2637
+ return env;
2638
+ }
2639
+ const runtimeEntry = resolveRuntimeEntry();
2640
+ if (!runtimeEntry) {
2641
+ return env;
2642
+ }
2643
+ return {
2644
+ ...env,
2645
+ CODELIA_RUNTIME_CMD: process.execPath,
2646
+ CODELIA_RUNTIME_ARGS: quoteShellWord(runtimeEntry)
2647
+ };
2648
+ };
2649
+ resolveLaunchEnvForTui = (env, cliVersion = CLI_VERSION, resolveRuntimeEntry = resolveBundledRuntimeEntry) => {
2650
+ const runtimeEnv = resolveRuntimeEnvForTui(env, resolveRuntimeEntry);
2651
+ if (runtimeEnv.CODELIA_CLI_VERSION || cliVersion.trim().length === 0) {
2652
+ return runtimeEnv;
2653
+ }
2654
+ return {
2655
+ ...runtimeEnv,
2656
+ CODELIA_CLI_VERSION: cliVersion
2657
+ };
2658
+ };
2659
+ resolveTuiCommand = (options = {}) => {
2660
+ const env = options.env ?? process.env;
2661
+ if (env.CODELIA_TUI_CMD) {
2662
+ return env.CODELIA_TUI_CMD;
2663
+ }
2664
+ const platform = options.platform ?? process.platform;
2665
+ const arch = options.arch ?? process.arch;
2666
+ const resolveOptionalBinary = options.resolveOptionalTuiBinary ?? resolveOptionalTuiBinaryPath;
2667
+ const isExecutableCandidate = options.isExecutableCandidate ?? isExecutable;
2668
+ const tuiBinaryName = resolveTuiBinaryName(platform);
2669
+ const cwd = options.cwd ?? process.cwd();
2670
+ const cliPackageRoot = options.cliPackageRoot === void 0 ? resolveCliPackageRoot() : options.cliPackageRoot;
2671
+ const seen = /* @__PURE__ */ new Set();
2672
+ const optionalTuiBinary = resolveOptionalBinary(platform, arch);
2673
+ const localCandidates = [
2674
+ ...cliPackageRoot ? [
2675
+ import_node_path9.default.resolve(cliPackageRoot, "dist/bin", tuiBinaryName),
2676
+ import_node_path9.default.resolve(
2677
+ cliPackageRoot,
2678
+ "../../crates/tui/target/release",
2679
+ tuiBinaryName
2680
+ ),
2681
+ import_node_path9.default.resolve(
2682
+ cliPackageRoot,
2683
+ "../../crates/tui/target/debug",
2684
+ tuiBinaryName
2685
+ )
2686
+ ] : [],
2687
+ import_node_path9.default.resolve(cwd, "target/release", tuiBinaryName),
2688
+ import_node_path9.default.resolve(cwd, "target/debug", tuiBinaryName),
2689
+ import_node_path9.default.resolve(cwd, "crates/tui/target/release", tuiBinaryName),
2690
+ import_node_path9.default.resolve(cwd, "crates/tui/target/debug", tuiBinaryName)
2691
+ ];
2692
+ const candidates = [
2693
+ ...localCandidates,
2694
+ ...optionalTuiBinary ? [optionalTuiBinary] : []
2695
+ ];
2696
+ for (const candidate of candidates) {
2697
+ if (seen.has(candidate)) continue;
2698
+ seen.add(candidate);
2699
+ if (isExecutableCandidate(candidate)) {
2700
+ return candidate;
2701
+ }
2702
+ }
2703
+ return tuiBinaryName;
2704
+ };
2705
+ runTui = (args2, update = NOOP_LAUNCH_UPDATE_SESSION, cliPackageRoot = resolveLoadedCliPackageRoot()) => {
2706
+ void initStorage();
2707
+ const tuiCmd = resolveTuiCommand({ cliPackageRoot });
2708
+ const tuiArgs = process.env.CODELIA_TUI_ARGS ? splitArgs(process.env.CODELIA_TUI_ARGS) : [];
2709
+ const tuiEnv = { ...resolveLaunchEnvForTui(process.env), ...update.tuiEnv };
2710
+ delete tuiEnv[UPDATE_REEXEC_ENV];
2711
+ const child = (0, import_node_child_process3.spawn)(tuiCmd, [...tuiArgs, ...args2], {
2712
+ stdio: "inherit",
2713
+ env: tuiEnv
2714
+ });
2715
+ process.once("exit", () => update.dispose());
2716
+ child.once("spawn", () => {
2717
+ void update.startBackground();
2718
+ });
2719
+ child.on("exit", (code) => {
2720
+ update.dispose();
2721
+ process.exitCode = code ?? 0;
2722
+ });
2723
+ child.on("error", (error) => {
2724
+ update.dispose();
2725
+ const code = typeof error === "object" && error !== null && "code" in error ? String(error.code ?? "") : "";
2726
+ const expectedPackage = resolvePlatformTuiPackageName();
2727
+ console.error(`Failed to launch TUI (${tuiCmd}): ${describeError2(error)}`);
2728
+ if (code === "EACCES") {
2729
+ console.error(
2730
+ "Permission denied while launching TUI. Verify execute permission and PATH entries."
2731
+ );
2732
+ } else if (code === "ENOENT") {
2733
+ console.error(
2734
+ 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."
2735
+ );
2736
+ }
2737
+ console.error(
2738
+ "Set CODELIA_TUI_CMD/CODELIA_TUI_ARGS to use a custom TUI command."
2739
+ );
2740
+ process.exitCode = 1;
2741
+ });
2742
+ };
2743
+ }
2744
+ });
2745
+
2746
+ // src/prompt-mode.ts
2747
+ var prompt_mode_exports = {};
2748
+ __export(prompt_mode_exports, {
2749
+ runPromptMode: () => runPromptMode,
2750
+ writePromptModeAtif: () => writePromptModeAtif
2751
+ });
2752
+ var import_node_child_process4, parseShellLikeArgs, toLine, envTruthy, toSingleLine, summarizeProgressEvent, isRpcResponse, isRpcNotification, asRecord2, harborUiResponse, writePromptModeAtif, runPromptMode;
2753
+ var init_prompt_mode = __esm({
2754
+ "src/prompt-mode.ts"() {
2755
+ "use strict";
2756
+ import_node_child_process4 = require("child_process");
2757
+ init_atif();
2758
+ init_launcher();
2759
+ parseShellLikeArgs = (value) => {
2760
+ const out = [];
2761
+ let current = "";
2762
+ let quote = null;
2763
+ let escaping = false;
2764
+ for (let i = 0; i < value.length; i += 1) {
2765
+ const ch = value[i];
2766
+ if (escaping) {
2767
+ current += ch;
2768
+ escaping = false;
2769
+ continue;
2770
+ }
2771
+ if (ch === "\\" && quote !== "single") {
2772
+ escaping = true;
2773
+ continue;
2774
+ }
2775
+ if (quote === "single") {
2776
+ if (ch === "'") {
2777
+ quote = null;
2778
+ } else {
2779
+ current += ch;
2780
+ }
2781
+ continue;
2782
+ }
2783
+ if (quote === "double") {
2784
+ if (ch === '"') {
2785
+ quote = null;
2786
+ } else {
2787
+ current += ch;
2788
+ }
2789
+ continue;
2790
+ }
2791
+ if (ch === "'") {
2792
+ quote = "single";
2793
+ continue;
2794
+ }
2795
+ if (ch === '"') {
2796
+ quote = "double";
2797
+ continue;
2798
+ }
2799
+ if (/\s/.test(ch)) {
2800
+ if (current.length > 0) {
2801
+ out.push(current);
2802
+ current = "";
2803
+ }
2804
+ continue;
2805
+ }
1340
2806
  current += ch;
1341
2807
  }
1342
- continue;
1343
- }
1344
- if (ch === "'") {
1345
- quote = "single";
1346
- continue;
1347
- }
1348
- if (ch === '"') {
1349
- quote = "double";
1350
- continue;
1351
- }
1352
- if (/\s/.test(ch)) {
1353
2808
  if (current.length > 0) {
1354
2809
  out.push(current);
1355
- current = "";
1356
2810
  }
1357
- continue;
1358
- }
1359
- current += ch;
1360
- }
1361
- if (current.length > 0) {
1362
- out.push(current);
1363
- }
1364
- return out;
1365
- };
1366
- var toLine = (value) => `${JSON.stringify(value)}
2811
+ return out;
2812
+ };
2813
+ toLine = (value) => `${JSON.stringify(value)}
1367
2814
  `;
1368
- var envTruthy = (value) => {
1369
- if (!value) return false;
1370
- const normalized = value.trim().toLowerCase();
1371
- return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
1372
- };
1373
- var toSingleLine = (value, maxChars = 240) => {
1374
- const normalized = value.replace(/\s+/g, " ").trim();
1375
- if (normalized.length <= maxChars) return normalized;
1376
- return `${normalized.slice(0, maxChars)}...`;
1377
- };
1378
- var summarizeProgressEvent = (event) => {
1379
- const type = typeof event.type === "string" ? event.type : "";
1380
- switch (type) {
1381
- case "text": {
1382
- const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
1383
- return content ? `[text] ${content}` : "[text]";
1384
- }
1385
- case "reasoning": {
1386
- const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
1387
- return content ? `[reasoning] ${content}` : "[reasoning]";
1388
- }
1389
- case "step_start": {
1390
- const title = typeof event.title === "string" ? toSingleLine(event.title) : "";
1391
- const stepNumber = typeof event.step_number === "number" ? `#${String(event.step_number)} ` : "";
1392
- return `[step_start] ${stepNumber}${title || "unnamed step"}`;
1393
- }
1394
- case "step_complete": {
1395
- const status = typeof event.status === "string" ? event.status : "unknown";
1396
- const duration = typeof event.duration_ms === "number" ? ` ${String(event.duration_ms)}ms` : "";
1397
- return `[step_complete] ${status}${duration}`;
1398
- }
1399
- case "tool_call": {
1400
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1401
- return `[tool_call] ${tool}`;
1402
- }
1403
- case "tool_result": {
1404
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1405
- const isError = event.is_error === true ? "error" : "ok";
1406
- return `[tool_result] ${tool} (${isError})`;
1407
- }
1408
- case "permission.preview": {
1409
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1410
- return `[permission.preview] ${tool}`;
1411
- }
1412
- case "permission.ready": {
1413
- const tool = typeof event.tool === "string" ? event.tool : "unknown";
1414
- return `[permission.ready] ${tool}`;
1415
- }
1416
- case "compaction_start":
1417
- return "[compaction_start]";
1418
- case "compaction_complete": {
1419
- const compacted = typeof event.compacted === "boolean" ? ` compacted=${String(event.compacted)}` : "";
1420
- return `[compaction_complete]${compacted}`;
1421
- }
1422
- case "hidden_user_message":
1423
- return "[hidden_user_message]";
1424
- default:
1425
- return type ? `[${type}]` : null;
1426
- }
1427
- };
1428
- var isRpcResponse = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "id" in value && !value.method;
1429
- var isRpcNotification = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "method" in value && !value.id;
1430
- var writePromptModeAtif = async ({
1431
- atifOut,
1432
- sessionLogPath,
1433
- runId
1434
- }) => {
1435
- if (!atifOut) {
1436
- return "skipped";
1437
- }
1438
- if (!sessionLogPath || !runId) {
1439
- throw new Error("CODELIA_ATIF_OUT was set but session log path is missing");
1440
- }
1441
- await writeAtifFromSessionJsonl({
1442
- sessionLogPath,
1443
- runId,
1444
- outPath: atifOut
1445
- });
1446
- return "written";
1447
- };
1448
- var runPromptMode = async (options) => {
1449
- const emitProgressToStderr = envTruthy(
1450
- process.env.CODELIA_PROMPT_PROGRESS_STDERR
1451
- );
1452
- const atifOut = process.env.CODELIA_ATIF_OUT?.trim();
1453
- const runtimeEnv = resolveRuntimeEnvForTui(process.env);
1454
- const runtimeCmd = runtimeEnv.CODELIA_RUNTIME_CMD ?? process.execPath;
1455
- const runtimeArgsValue = runtimeEnv.CODELIA_RUNTIME_ARGS ?? "packages/runtime/src/index.ts";
1456
- const runtimeArgs = parseShellLikeArgs(runtimeArgsValue);
1457
- if (runtimeArgs.length === 0) {
1458
- runtimeArgs.push("packages/runtime/src/index.ts");
1459
- }
1460
- if (options.approvalMode) {
1461
- runtimeArgs.push("--approval-mode", options.approvalMode);
1462
- }
1463
- const child = (0, import_node_child_process3.spawn)(runtimeCmd, runtimeArgs, {
1464
- env: runtimeEnv,
1465
- stdio: ["pipe", "pipe", "pipe"]
1466
- });
1467
- let buffer = "";
1468
- let runId = null;
1469
- let sessionLogPath = null;
1470
- let finalText = "";
1471
- let terminalStatus = null;
1472
- let terminalMessage;
1473
- let atifWritten = false;
1474
- let atifWriteInFlight = null;
1475
- const pendingResponses = /* @__PURE__ */ new Map();
1476
- let startupFailure = null;
1477
- const failPending = (error) => {
1478
- if (startupFailure) return;
1479
- startupFailure = error;
1480
- for (const pending of pendingResponses.values()) {
1481
- pending.reject(error);
1482
- }
1483
- pendingResponses.clear();
1484
- };
1485
- const waitResponse = (id) => {
1486
- if (startupFailure) {
1487
- return Promise.reject(startupFailure);
1488
- }
1489
- return new Promise((resolve, reject) => {
1490
- pendingResponses.set(id, { resolve, reject });
1491
- });
1492
- };
1493
- const sendRequest = (request) => {
1494
- if (startupFailure) {
1495
- throw startupFailure;
1496
- }
1497
- const wrote = child.stdin.write(toLine(request));
1498
- if (!wrote) {
1499
- }
1500
- };
1501
- const writeAtifOnce = async () => {
1502
- if (atifWritten) {
1503
- return "written";
1504
- }
1505
- atifWriteInFlight ??= writePromptModeAtif({
2815
+ envTruthy = (value) => {
2816
+ if (!value) return false;
2817
+ const normalized = value.trim().toLowerCase();
2818
+ return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
2819
+ };
2820
+ toSingleLine = (value, maxChars = 240) => {
2821
+ const normalized = value.replace(/\s+/g, " ").trim();
2822
+ if (normalized.length <= maxChars) return normalized;
2823
+ return `${normalized.slice(0, maxChars)}...`;
2824
+ };
2825
+ summarizeProgressEvent = (event) => {
2826
+ const type = typeof event.type === "string" ? event.type : "";
2827
+ switch (type) {
2828
+ case "text": {
2829
+ const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
2830
+ return content ? `[text] ${content}` : "[text]";
2831
+ }
2832
+ case "reasoning": {
2833
+ const content = typeof event.content === "string" ? toSingleLine(event.content) : "";
2834
+ return content ? `[reasoning] ${content}` : "[reasoning]";
2835
+ }
2836
+ case "step_start": {
2837
+ const title = typeof event.title === "string" ? toSingleLine(event.title) : "";
2838
+ const stepNumber = typeof event.step_number === "number" ? `#${String(event.step_number)} ` : "";
2839
+ return `[step_start] ${stepNumber}${title || "unnamed step"}`;
2840
+ }
2841
+ case "step_complete": {
2842
+ const status = typeof event.status === "string" ? event.status : "unknown";
2843
+ const duration = typeof event.duration_ms === "number" ? ` ${String(event.duration_ms)}ms` : "";
2844
+ return `[step_complete] ${status}${duration}`;
2845
+ }
2846
+ case "tool_call": {
2847
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
2848
+ return `[tool_call] ${tool}`;
2849
+ }
2850
+ case "tool_result": {
2851
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
2852
+ const isError = event.is_error === true ? "error" : "ok";
2853
+ return `[tool_result] ${tool} (${isError})`;
2854
+ }
2855
+ case "permission.preview": {
2856
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
2857
+ return `[permission.preview] ${tool}`;
2858
+ }
2859
+ case "permission.ready": {
2860
+ const tool = typeof event.tool === "string" ? event.tool : "unknown";
2861
+ return `[permission.ready] ${tool}`;
2862
+ }
2863
+ case "compaction_start":
2864
+ return "[compaction_start]";
2865
+ case "compaction_complete": {
2866
+ const compacted = typeof event.compacted === "boolean" ? ` compacted=${String(event.compacted)}` : "";
2867
+ return `[compaction_complete]${compacted}`;
2868
+ }
2869
+ case "hidden_user_message":
2870
+ return "[hidden_user_message]";
2871
+ default:
2872
+ return type ? `[${type}]` : null;
2873
+ }
2874
+ };
2875
+ isRpcResponse = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "id" in value && !value.method;
2876
+ isRpcNotification = (value) => typeof value === "object" && value !== null && "jsonrpc" in value && "method" in value && !value.id;
2877
+ asRecord2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
2878
+ harborUiResponse = (value, runId, allowShell) => {
2879
+ const request = asRecord2(value);
2880
+ if (request?.jsonrpc !== "2.0" || typeof request.id !== "string" || !/^ui_[1-9]\d*$/u.test(request.id))
2881
+ return void 0;
2882
+ const response = { jsonrpc: "2.0", id: request.id };
2883
+ switch (request.method) {
2884
+ case "ui.confirm.request":
2885
+ return { ...response, result: { ok: false } };
2886
+ case "ui.prompt.request":
2887
+ return { ...response, result: { value: null } };
2888
+ case "ui.pick.request": {
2889
+ const params = asRecord2(request.params);
2890
+ 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 : [];
2891
+ const once = choices.map((item) => asRecord2(item)?.id).filter(
2892
+ (id) => typeof id === "string" && /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}\/allow_once$/u.test(id)
2893
+ );
2894
+ return { ...response, result: { ids: once.length === 1 ? once : [] } };
2895
+ }
2896
+ }
2897
+ };
2898
+ writePromptModeAtif = async ({
1506
2899
  atifOut,
1507
2900
  sessionLogPath,
1508
- runId
1509
- });
1510
- const result = await atifWriteInFlight;
1511
- if (result === "written") {
1512
- atifWritten = true;
1513
- }
1514
- return result;
1515
- };
1516
- const signalNumbers = {
1517
- SIGHUP: 1,
1518
- SIGINT: 2,
1519
- SIGTERM: 15
1520
- };
1521
- const handledSignals = Object.keys(signalNumbers);
1522
- const handleTerminationSignal = (signal) => {
1523
- void (async () => {
2901
+ runId,
2902
+ sandboxModeRequested,
2903
+ sandboxModeReported
2904
+ }) => {
2905
+ if (!atifOut) {
2906
+ return "skipped";
2907
+ }
2908
+ if (!sessionLogPath || !runId) {
2909
+ throw new Error("CODELIA_ATIF_OUT was set but session log path is missing");
2910
+ }
2911
+ await writeAtifFromSessionJsonl({
2912
+ sessionLogPath,
2913
+ runId,
2914
+ outPath: atifOut,
2915
+ ...sandboxModeRequested ? {
2916
+ extra: {
2917
+ sandbox_mode_requested: sandboxModeRequested,
2918
+ sandbox_mode: sandboxModeReported ?? null
2919
+ }
2920
+ } : {}
2921
+ });
2922
+ return "written";
2923
+ };
2924
+ runPromptMode = async (options) => {
2925
+ const emitProgressToStderr = envTruthy(
2926
+ process.env.CODELIA_PROMPT_PROGRESS_STDERR
2927
+ );
2928
+ const atifOut = process.env.CODELIA_ATIF_OUT?.trim();
2929
+ const harborShellRequested = options.harborShellApproval === true && options.sandboxMode === "full-access" && process.env.CODELIA_HARBOR_SHELL_APPROVAL === "1";
2930
+ const runtimeEnv = resolveRuntimeEnvForTui(process.env);
2931
+ const runtimeCmd = runtimeEnv.CODELIA_RUNTIME_CMD ?? process.execPath;
2932
+ const runtimeArgsValue = runtimeEnv.CODELIA_RUNTIME_ARGS ?? "packages/runtime/src/index.ts";
2933
+ const runtimeArgs = parseShellLikeArgs(runtimeArgsValue);
2934
+ if (runtimeArgs.length === 0) {
2935
+ runtimeArgs.push("packages/runtime/src/index.ts");
2936
+ }
2937
+ if (options.sandboxMode) {
2938
+ runtimeArgs.push("--sandbox-mode", options.sandboxMode);
2939
+ }
2940
+ if (options.approvalMode) {
2941
+ runtimeArgs.push("--approval-mode", options.approvalMode);
2942
+ }
2943
+ const child = (0, import_node_child_process4.spawn)(runtimeCmd, runtimeArgs, {
2944
+ env: runtimeEnv,
2945
+ stdio: ["pipe", "pipe", "pipe"]
2946
+ });
2947
+ let buffer = "";
2948
+ let runId = null;
2949
+ let reportedSandbox = null;
2950
+ let harborShellAllowed = false;
2951
+ let sessionLogPath = null;
2952
+ let finalText = "";
2953
+ let terminalStatus = null;
2954
+ let terminalMessage;
2955
+ let atifWritten = false;
2956
+ let atifWriteInFlight = null;
2957
+ const pendingResponses = /* @__PURE__ */ new Map();
2958
+ let startupFailure = null;
2959
+ const failPending = (error) => {
2960
+ if (startupFailure) return;
2961
+ startupFailure = error;
2962
+ for (const pending of pendingResponses.values()) {
2963
+ pending.reject(error);
2964
+ }
2965
+ pendingResponses.clear();
2966
+ };
2967
+ const waitResponse = (id) => {
2968
+ if (startupFailure) {
2969
+ return Promise.reject(startupFailure);
2970
+ }
2971
+ return new Promise((resolve, reject) => {
2972
+ pendingResponses.set(id, { resolve, reject });
2973
+ });
2974
+ };
2975
+ const sendMessage = (request) => {
2976
+ if (startupFailure) {
2977
+ throw startupFailure;
2978
+ }
2979
+ const wrote = child.stdin.write(toLine(request));
2980
+ if (!wrote) {
2981
+ }
2982
+ };
2983
+ const writeAtifOnce = async () => {
2984
+ if (atifWritten) {
2985
+ return "written";
2986
+ }
2987
+ atifWriteInFlight ??= writePromptModeAtif({
2988
+ atifOut,
2989
+ sessionLogPath,
2990
+ runId,
2991
+ sandboxModeRequested: options.sandboxMode,
2992
+ sandboxModeReported: reportedSandbox
2993
+ });
2994
+ const result = await atifWriteInFlight;
2995
+ if (result === "written") {
2996
+ atifWritten = true;
2997
+ }
2998
+ return result;
2999
+ };
3000
+ const signalNumbers = {
3001
+ SIGHUP: 1,
3002
+ SIGINT: 2,
3003
+ SIGTERM: 15
3004
+ };
3005
+ const handledSignals = Object.keys(signalNumbers);
3006
+ const handleTerminationSignal = (signal) => {
3007
+ void (async () => {
3008
+ try {
3009
+ await writeAtifOnce();
3010
+ } catch (error) {
3011
+ console.error(
3012
+ `Failed to write partial ATIF trajectory on ${signal}: ${error instanceof Error ? error.message : String(error)}`
3013
+ );
3014
+ } finally {
3015
+ if (!child.killed) {
3016
+ child.kill(signal);
3017
+ }
3018
+ process.exit(
3019
+ 128 + (signalNumbers[signal] ?? 1)
3020
+ );
3021
+ }
3022
+ })();
3023
+ };
3024
+ for (const signal of handledSignals) {
3025
+ process.once(signal, handleTerminationSignal);
3026
+ }
3027
+ const cleanupSignalHandlers = () => {
3028
+ for (const signal of handledSignals) {
3029
+ process.removeListener(signal, handleTerminationSignal);
3030
+ }
3031
+ };
3032
+ const maybeTrackRunLifecycle = (value) => {
3033
+ if (!isRpcNotification(value)) return;
3034
+ if (value.method === "run.status") {
3035
+ const params = value.params ?? {};
3036
+ if (!runId || params.run_id !== runId) return;
3037
+ if (params.status === "completed" || params.status === "error" || params.status === "cancelled") {
3038
+ terminalStatus = params.status;
3039
+ terminalMessage = params.message;
3040
+ }
3041
+ return;
3042
+ }
3043
+ if (value.method === "run.end") {
3044
+ const params = value.params ?? {};
3045
+ if (!runId || params.run_id !== runId) return;
3046
+ if (typeof params.final === "string") {
3047
+ finalText = params.final;
3048
+ }
3049
+ return;
3050
+ }
3051
+ if (value.method === "agent.event") {
3052
+ const params = value.params ?? {};
3053
+ if (!runId || params.run_id !== runId) return;
3054
+ if (params.event?.type === "final" && typeof params.event.content === "string") {
3055
+ finalText = params.event.content;
3056
+ }
3057
+ const event = params.event;
3058
+ if (emitProgressToStderr && event && event.type !== "final") {
3059
+ const summary = summarizeProgressEvent(event);
3060
+ if (summary) {
3061
+ process.stderr.write(`${summary}
3062
+ `);
3063
+ }
3064
+ }
3065
+ }
3066
+ };
3067
+ child.on("error", (error) => {
3068
+ failPending(
3069
+ error instanceof Error ? error : new Error(`runtime process error: ${String(error)}`)
3070
+ );
3071
+ });
3072
+ child.on("close", (code, signal) => {
3073
+ if (terminalStatus) return;
3074
+ failPending(
3075
+ new Error(
3076
+ `runtime exited before completion (code=${String(code)} signal=${String(signal)})`
3077
+ )
3078
+ );
3079
+ });
3080
+ child.stdin.on("error", (error) => {
3081
+ failPending(
3082
+ error instanceof Error ? error : new Error(`runtime stdin error: ${String(error)}`)
3083
+ );
3084
+ });
3085
+ child.stdout.setEncoding("utf8");
3086
+ child.stdout.on("data", (chunk) => {
3087
+ buffer += chunk;
3088
+ let index = buffer.indexOf("\n");
3089
+ while (index >= 0) {
3090
+ const line = buffer.slice(0, index).trim();
3091
+ buffer = buffer.slice(index + 1);
3092
+ if (line.length > 0) {
3093
+ try {
3094
+ const parsed = JSON.parse(line);
3095
+ if (isRpcResponse(parsed)) {
3096
+ const pending = pendingResponses.get(String(parsed.id));
3097
+ if (pending) {
3098
+ pendingResponses.delete(String(parsed.id));
3099
+ if (parsed.id === "run-1") {
3100
+ const result = asRecord2(parsed.result);
3101
+ runId = typeof result?.run_id === "string" ? result.run_id : null;
3102
+ }
3103
+ pending.resolve(parsed);
3104
+ }
3105
+ }
3106
+ if (harborShellRequested) {
3107
+ const response = harborUiResponse(
3108
+ parsed,
3109
+ terminalStatus ? null : runId,
3110
+ harborShellAllowed
3111
+ );
3112
+ if (response) sendMessage(response);
3113
+ }
3114
+ maybeTrackRunLifecycle(parsed);
3115
+ } catch {
3116
+ }
3117
+ }
3118
+ index = buffer.indexOf("\n");
3119
+ }
3120
+ });
3121
+ child.stderr.setEncoding("utf8");
3122
+ child.stderr.on("data", (chunk) => {
3123
+ process.stderr.write(chunk);
3124
+ });
1524
3125
  try {
1525
- await writeAtifOnce();
3126
+ sendMessage({
3127
+ jsonrpc: "2.0",
3128
+ id: "init-1",
3129
+ method: "initialize",
3130
+ params: {
3131
+ protocol_version: "0",
3132
+ client: { name: "codelia-cli-prompt", version: "0.1.0" },
3133
+ ui_capabilities: {
3134
+ supports_confirm: false,
3135
+ supports_prompt: false,
3136
+ supports_pick: harborShellRequested,
3137
+ ...harborShellRequested ? { supports_structured_approval: true } : {}
3138
+ }
3139
+ }
3140
+ });
3141
+ const initResponse = await waitResponse("init-1");
3142
+ if (initResponse.error) {
3143
+ throw new Error(`initialize failed: ${initResponse.error.message}`);
3144
+ }
3145
+ const init = initResponse.result;
3146
+ const mode = init?.sandbox_mode?.value;
3147
+ reportedSandbox = mode === "readonly" || mode === "workspace-write" || mode === "full-access" ? mode : null;
3148
+ harborShellAllowed = harborShellRequested && init?.server_capabilities?.supports_structured_approval === true && reportedSandbox === "full-access";
3149
+ sendMessage({
3150
+ jsonrpc: "2.0",
3151
+ id: "run-1",
3152
+ method: "run.start",
3153
+ params: {
3154
+ input: { type: "text", text: options.prompt }
3155
+ }
3156
+ });
3157
+ const runResponse = await waitResponse("run-1");
3158
+ if (runResponse.error) {
3159
+ throw new Error(`run.start failed: ${runResponse.error.message}`);
3160
+ }
3161
+ const runResult = typeof runResponse.result === "object" && runResponse.result !== null ? runResponse.result : null;
3162
+ sessionLogPath = typeof runResult?.session_log_path === "string" ? runResult.session_log_path : null;
3163
+ if (!runId) {
3164
+ throw new Error("run.start did not return run_id");
3165
+ }
3166
+ await new Promise((resolve, reject) => {
3167
+ const timeout = setInterval(() => {
3168
+ if (terminalStatus) {
3169
+ clearInterval(timeout);
3170
+ resolve();
3171
+ return;
3172
+ }
3173
+ if (startupFailure) {
3174
+ clearInterval(timeout);
3175
+ reject(startupFailure);
3176
+ }
3177
+ }, 50);
3178
+ });
1526
3179
  } catch (error) {
3180
+ cleanupSignalHandlers();
1527
3181
  console.error(
1528
- `Failed to write partial ATIF trajectory on ${signal}: ${error instanceof Error ? error.message : String(error)}`
3182
+ `Prompt run failed: ${error instanceof Error ? error.message : String(error)}`
1529
3183
  );
3184
+ return 1;
1530
3185
  } finally {
1531
3186
  if (!child.killed) {
1532
- child.kill(signal);
1533
- }
1534
- process.exit(
1535
- 128 + (signalNumbers[signal] ?? 1)
1536
- );
1537
- }
1538
- })();
1539
- };
1540
- for (const signal of handledSignals) {
1541
- process.once(signal, handleTerminationSignal);
1542
- }
1543
- const cleanupSignalHandlers = () => {
1544
- for (const signal of handledSignals) {
1545
- process.removeListener(signal, handleTerminationSignal);
1546
- }
1547
- };
1548
- const maybeTrackRunLifecycle = (value) => {
1549
- if (!isRpcNotification(value)) return;
1550
- if (value.method === "run.status") {
1551
- const params = value.params ?? {};
1552
- if (!runId || params.run_id !== runId) return;
1553
- if (params.status === "completed" || params.status === "error" || params.status === "cancelled") {
1554
- terminalStatus = params.status;
1555
- terminalMessage = params.message;
1556
- }
1557
- return;
1558
- }
1559
- if (value.method === "run.end") {
1560
- const params = value.params ?? {};
1561
- if (!runId || params.run_id !== runId) return;
1562
- if (typeof params.final === "string") {
1563
- finalText = params.final;
1564
- }
1565
- return;
1566
- }
1567
- if (value.method === "agent.event") {
1568
- const params = value.params ?? {};
1569
- if (!runId || params.run_id !== runId) return;
1570
- if (params.event?.type === "final" && typeof params.event.content === "string") {
1571
- finalText = params.event.content;
1572
- }
1573
- const event = params.event;
1574
- if (emitProgressToStderr && event && event.type !== "final") {
1575
- const summary = summarizeProgressEvent(event);
1576
- if (summary) {
1577
- process.stderr.write(`${summary}
1578
- `);
3187
+ child.kill();
1579
3188
  }
1580
3189
  }
1581
- }
1582
- };
1583
- child.on("error", (error) => {
1584
- failPending(
1585
- error instanceof Error ? error : new Error(`runtime process error: ${String(error)}`)
1586
- );
1587
- });
1588
- child.on("close", (code, signal) => {
1589
- if (terminalStatus) return;
1590
- failPending(
1591
- new Error(
1592
- `runtime exited before completion (code=${String(code)} signal=${String(signal)})`
1593
- )
1594
- );
1595
- });
1596
- child.stdin.on("error", (error) => {
1597
- failPending(
1598
- error instanceof Error ? error : new Error(`runtime stdin error: ${String(error)}`)
1599
- );
1600
- });
1601
- child.stdout.setEncoding("utf8");
1602
- child.stdout.on("data", (chunk) => {
1603
- buffer += chunk;
1604
- let index = buffer.indexOf("\n");
1605
- while (index >= 0) {
1606
- const line = buffer.slice(0, index).trim();
1607
- buffer = buffer.slice(index + 1);
1608
- if (line.length > 0) {
3190
+ if (terminalStatus === "completed") {
1609
3191
  try {
1610
- const parsed = JSON.parse(line);
1611
- if (isRpcResponse(parsed)) {
1612
- const pending = pendingResponses.get(String(parsed.id));
1613
- if (pending) {
1614
- pendingResponses.delete(String(parsed.id));
1615
- pending.resolve(parsed);
1616
- }
1617
- }
1618
- maybeTrackRunLifecycle(parsed);
1619
- } catch {
3192
+ await writeAtifOnce();
3193
+ } catch (error) {
3194
+ cleanupSignalHandlers();
3195
+ console.error(
3196
+ `Failed to write ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
3197
+ );
3198
+ return 1;
1620
3199
  }
1621
- }
1622
- index = buffer.indexOf("\n");
1623
- }
1624
- });
1625
- child.stderr.setEncoding("utf8");
1626
- child.stderr.on("data", (chunk) => {
1627
- process.stderr.write(chunk);
1628
- });
1629
- try {
1630
- sendRequest({
1631
- jsonrpc: "2.0",
1632
- id: "init-1",
1633
- method: "initialize",
1634
- params: {
1635
- protocol_version: "0",
1636
- client: { name: "codelia-cli-prompt", version: "0.1.0" },
1637
- ui_capabilities: {
1638
- supports_confirm: false,
1639
- supports_prompt: false,
1640
- supports_pick: false
3200
+ cleanupSignalHandlers();
3201
+ if (finalText.trim().length > 0) {
3202
+ console.log(finalText);
1641
3203
  }
3204
+ return 0;
1642
3205
  }
1643
- });
1644
- const initResponse = await waitResponse("init-1");
1645
- if (initResponse.error) {
1646
- throw new Error(`initialize failed: ${initResponse.error.message}`);
1647
- }
1648
- sendRequest({
1649
- jsonrpc: "2.0",
1650
- id: "run-1",
1651
- method: "run.start",
1652
- params: {
1653
- input: { type: "text", text: options.prompt }
3206
+ try {
3207
+ await writeAtifOnce();
3208
+ } catch (error) {
3209
+ console.error(
3210
+ `Failed to write partial ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
3211
+ );
1654
3212
  }
1655
- });
1656
- const runResponse = await waitResponse("run-1");
1657
- if (runResponse.error) {
1658
- throw new Error(`run.start failed: ${runResponse.error.message}`);
3213
+ cleanupSignalHandlers();
3214
+ if (terminalMessage) {
3215
+ console.error(terminalMessage);
3216
+ }
3217
+ return terminalStatus === "cancelled" ? 130 : 1;
3218
+ };
3219
+ }
3220
+ });
3221
+
3222
+ // src/basic-options.ts
3223
+ var TOP_LEVEL_HELP_TEXT = [
3224
+ "usage: codelia [options] [-- <tui-options>]",
3225
+ "",
3226
+ "Top-level options:",
3227
+ " -h, --help Show this help",
3228
+ " -V, -v, --version Show codelia version",
3229
+ " -p, --prompt <text> Run one headless prompt and exit",
3230
+ "",
3231
+ "Commands:",
3232
+ " auth authorize-keychain Authorize this build to access macOS Keychain items",
3233
+ " mcp ... Manage MCP servers and auth",
3234
+ " session ... List, pin, archive, or clean up session run logs",
3235
+ " update [--check] Check for a newer release and install it",
3236
+ "",
3237
+ "Runtime options:",
3238
+ " --sandbox-mode <readonly|workspace-write|full-access>",
3239
+ " --approval-mode <minimal|trusted|full-access> (legacy)",
3240
+ " trusted retains project allow rules. To disable OS isolation, use --sandbox-mode full-access.",
3241
+ "",
3242
+ "TUI options (passed through):",
3243
+ " -r, --resume [session_id]",
3244
+ " --debug[=true|false]",
3245
+ " --diagnostics[=true|false]",
3246
+ " --initial-message <text>",
3247
+ " --initial-user-message <text>",
3248
+ " --tui-mode <auto|inline|alternate>",
3249
+ " --debug-perf[=true|false]",
3250
+ " --sandbox-mode <readonly|workspace-write|full-access>",
3251
+ "",
3252
+ "In the TUI, use /auto-approve [status|off] to configure Auto approve."
3253
+ ].join("\n");
3254
+ var isHelpFlag = (value) => value === "-h" || value === "--help" || value === "help";
3255
+ var isVersionFlag = (value) => value === "-V" || value === "-v" || value === "--version" || value === "version";
3256
+ var hasPromptFlag = (args2) => {
3257
+ for (let i = 0; i < args2.length; i += 1) {
3258
+ const current = args2[i];
3259
+ if (current === "--") {
3260
+ break;
1659
3261
  }
1660
- const runResult = typeof runResponse.result === "object" && runResponse.result !== null ? runResponse.result : null;
1661
- runId = typeof runResult?.run_id === "string" ? runResult.run_id : null;
1662
- sessionLogPath = typeof runResult?.session_log_path === "string" ? runResult.session_log_path : null;
1663
- if (!runId) {
1664
- throw new Error("run.start did not return run_id");
3262
+ if (current === "-p" || current === "--prompt") {
3263
+ return true;
1665
3264
  }
1666
- await new Promise((resolve, reject) => {
1667
- const timeout = setInterval(() => {
1668
- if (terminalStatus) {
1669
- clearInterval(timeout);
1670
- resolve();
1671
- return;
1672
- }
1673
- if (startupFailure) {
1674
- clearInterval(timeout);
1675
- reject(startupFailure);
1676
- }
1677
- }, 50);
1678
- });
1679
- } catch (error) {
1680
- cleanupSignalHandlers();
1681
- console.error(
1682
- `Prompt run failed: ${error instanceof Error ? error.message : String(error)}`
1683
- );
1684
- return 1;
1685
- } finally {
1686
- if (!child.killed) {
1687
- child.kill();
3265
+ if (current.startsWith("--prompt=")) {
3266
+ return true;
1688
3267
  }
1689
3268
  }
1690
- if (terminalStatus === "completed") {
1691
- try {
1692
- await writeAtifOnce();
1693
- } catch (error) {
1694
- cleanupSignalHandlers();
1695
- console.error(
1696
- `Failed to write ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
1697
- );
1698
- return 1;
3269
+ return false;
3270
+ };
3271
+ var resolveTopLevelAction = (args2) => {
3272
+ if (args2[0] === "auth") return "auth";
3273
+ if (args2[0] === "session") return "session";
3274
+ if (args2[0] === "update") return "update";
3275
+ if (args2[0] === "mcp") {
3276
+ return "mcp";
3277
+ }
3278
+ if (args2.length === 1 && isHelpFlag(args2[0])) {
3279
+ return "help";
3280
+ }
3281
+ if (args2.length === 1 && isVersionFlag(args2[0])) {
3282
+ return "version";
3283
+ }
3284
+ if (hasPromptFlag(args2)) {
3285
+ return "prompt";
3286
+ }
3287
+ return "tui";
3288
+ };
3289
+ var resolvePromptText = (args2) => {
3290
+ for (let i = 0; i < args2.length; i += 1) {
3291
+ const current = args2[i];
3292
+ if (current === "-p" || current === "--prompt") {
3293
+ const next = args2[i + 1];
3294
+ if (!next) return void 0;
3295
+ return next;
1699
3296
  }
1700
- cleanupSignalHandlers();
1701
- if (finalText.trim().length > 0) {
1702
- console.log(finalText);
3297
+ if (current.startsWith("--prompt=")) {
3298
+ return current.slice("--prompt=".length);
1703
3299
  }
1704
- return 0;
1705
3300
  }
1706
- try {
1707
- await writeAtifOnce();
1708
- } catch (error) {
1709
- console.error(
1710
- `Failed to write partial ATIF trajectory: ${error instanceof Error ? error.message : String(error)}`
1711
- );
3301
+ return void 0;
3302
+ };
3303
+ var resolveRuntimeMode = (args2, flag, values) => {
3304
+ for (let i = 0; i < args2.length; i += 1) {
3305
+ const current = args2[i];
3306
+ if (current === "--") {
3307
+ break;
3308
+ }
3309
+ if (current === "-p" || current === "--prompt") {
3310
+ i++;
3311
+ continue;
3312
+ }
3313
+ const value = current === flag ? (args2[i + 1] ?? "").trim() : current.startsWith(`${flag}=`) ? current.slice(flag.length + 1).trim() : void 0;
3314
+ if (value === void 0) continue;
3315
+ if (!value) throw new Error(`${flag} requires a value (${values})`);
3316
+ if (!values.split("|").includes(value))
3317
+ throw new Error(`Invalid ${flag} (expected ${values})`);
3318
+ return value;
1712
3319
  }
1713
- cleanupSignalHandlers();
1714
- if (terminalMessage) {
1715
- console.error(terminalMessage);
3320
+ return void 0;
3321
+ };
3322
+ var resolvePromptModeApproval = (args2) => resolveRuntimeMode(args2, "--approval-mode", "minimal|trusted|full-access");
3323
+ var resolvePromptModeSandbox = (args2) => resolveRuntimeMode(
3324
+ args2,
3325
+ "--sandbox-mode",
3326
+ "readonly|workspace-write|full-access"
3327
+ );
3328
+ var hasHarborShellApprovalFlag = (args2) => {
3329
+ for (let index = 0; index < args2.length; index++) {
3330
+ const arg = args2[index];
3331
+ if (arg === "--") break;
3332
+ if (["-p", "--prompt", "--sandbox-mode", "--approval-mode"].includes(arg)) {
3333
+ index++;
3334
+ continue;
3335
+ }
3336
+ if (arg === "--harbor-shell-approval") return true;
3337
+ }
3338
+ return false;
3339
+ };
3340
+ var validatePromptText = (value) => {
3341
+ const text = value?.trim() ?? "";
3342
+ if (text.length === 0) {
3343
+ throw new Error("Prompt is required after -p/--prompt");
1716
3344
  }
1717
- return terminalStatus === "cancelled" ? 130 : 1;
3345
+ return text;
1718
3346
  };
1719
3347
 
1720
3348
  // src/index.ts
3349
+ init_package_root();
3350
+ init_version();
1721
3351
  var args = process.argv.slice(2);
3352
+ var packageRoot = resolveLoadedCliPackageRoot();
1722
3353
  var main = async () => {
1723
3354
  switch (resolveTopLevelAction(args)) {
1724
3355
  case "help":
@@ -1727,28 +3358,62 @@ var main = async () => {
1727
3358
  case "version":
1728
3359
  console.log(CLI_VERSION);
1729
3360
  return;
3361
+ case "auth": {
3362
+ const { runAuthCommand: runAuthCommand2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
3363
+ process.exitCode = await runAuthCommand2(args.slice(1));
3364
+ return;
3365
+ }
1730
3366
  case "mcp": {
1731
- const exitCode = await runMcpCommand(args.slice(1));
1732
- process.exitCode = exitCode;
3367
+ const { runMcpCommand: runMcpCommand2 } = await Promise.resolve().then(() => (init_mcp(), mcp_exports));
3368
+ process.exitCode = await runMcpCommand2(args.slice(1));
1733
3369
  return;
1734
3370
  }
1735
3371
  case "session": {
1736
- process.exitCode = await runSessionCommand(args.slice(1));
3372
+ const { runSessionCommand: runSessionCommand2 } = await Promise.resolve().then(() => (init_session(), session_exports));
3373
+ process.exitCode = await runSessionCommand2(args.slice(1));
3374
+ return;
3375
+ }
3376
+ case "update": {
3377
+ const { runUpdateCommand: runUpdateCommand2 } = await Promise.resolve().then(() => (init_update(), update_exports));
3378
+ process.exitCode = await runUpdateCommand2(args.slice(1), { packageRoot });
1737
3379
  return;
1738
3380
  }
1739
3381
  case "prompt": {
1740
3382
  const prompt = validatePromptText(resolvePromptText(args));
1741
- const approvalMode = resolvePromptModeApproval(args);
1742
- const exitCode = await runPromptMode({
3383
+ const sandboxMode = resolvePromptModeSandbox(args);
3384
+ const approvalMode = sandboxMode ? void 0 : resolvePromptModeApproval(args);
3385
+ const { runPromptMode: runPromptMode2 } = await Promise.resolve().then(() => (init_prompt_mode(), prompt_mode_exports));
3386
+ process.exitCode = await runPromptMode2({
1743
3387
  prompt,
1744
- approvalMode
3388
+ approvalMode,
3389
+ sandboxMode,
3390
+ harborShellApproval: hasHarborShellApprovalFlag(args)
1745
3391
  });
1746
- process.exitCode = exitCode;
1747
3392
  return;
1748
3393
  }
1749
- case "tui":
1750
- runTui(args);
3394
+ case "tui": {
3395
+ const { prepareTuiLaunch: prepareTuiLaunch2 } = await Promise.resolve().then(() => (init_launch(), launch_exports));
3396
+ const prepared = await prepareTuiLaunch2({
3397
+ args,
3398
+ currentVersion: CLI_VERSION,
3399
+ packageRoot
3400
+ });
3401
+ if (prepared.kind === "exit") {
3402
+ process.exitCode = prepared.exitCode;
3403
+ return;
3404
+ }
3405
+ try {
3406
+ const { runTui: runTui2 } = await Promise.resolve().then(() => (init_launcher(), launcher_exports));
3407
+ runTui2(args, prepared.session, packageRoot);
3408
+ } catch (error) {
3409
+ prepared.session.dispose();
3410
+ throw error;
3411
+ }
1751
3412
  return;
3413
+ }
1752
3414
  }
1753
3415
  };
1754
- void main();
3416
+ void main().catch((error) => {
3417
+ console.error(error instanceof Error ? error.message : String(error));
3418
+ process.exitCode = 1;
3419
+ });