@codelia/cli 0.1.86 → 0.1.90

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