-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcli.cpp
More file actions
471 lines (442 loc) · 18.7 KB
/
Copy pathcli.cpp
File metadata and controls
471 lines (442 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
#include "cli.hpp"
#include "platform.hpp"
#include "runtime_files.hpp"
#include "startup_diagnostics.hpp"
#include "worker.hpp"
#include "../cli/interactive_options.hpp"
#include "../config/config.hpp"
#include "../hooks/hook_manager.hpp"
#include "../skills/default_skill_seeder.hpp"
#include "../utils/logger.hpp"
#include "../utils/paths.hpp"
#include "../utils/utf8_path.hpp"
#include "../web/http_address.hpp"
#include "../web/remote_web.hpp"
#include <chrono>
#include <filesystem>
#include <iostream>
#include <system_error>
#include <thread>
namespace fs = std::filesystem;
namespace acecode::daemon::cli {
namespace {
void print_help(std::ostream& os) {
os << "Usage: acecode daemon [subcommand] [options]\n"
<< "\n"
<< "Subcommands:\n"
<< " (none) start detached daemon (default)\n"
<< " start explicit alias for the default detached start\n"
<< " stop terminate running worker, clean runtime files\n"
<< " status print {pid, port, guid, uptime}\n"
<< " --foreground run worker in current console (debug mode)\n"
<< "\n"
<< "Options (advanced):\n"
<< " --cwd=<PATH> worker directory (default: current directory)\n"
<< " --port=<N> override web.port (unconfigured default: 12399)\n"
<< " --static-dir=<PATH> serve front-end assets from PATH\n"
<< " --run-dir=<PATH> isolate runtime files (heartbeat/pid/port/token) to PATH\n"
<< " --native-folder-picker enable Desktop native folder picker API\n"
<< " --supervised --guid=G launcher-internal: launched by Service supervisor\n"
<< " --desktop-managed Desktop-internal managed lifecycle metadata\n"
<< " --yolo, --dangerous skip permission checks (loopback bind only)\n"
<< " --question-policy=<P> AskUserQuestion policy: ask | deny | timeout[:seconds]\n";
}
// 简单 starts_with(C++17 没有 string::starts_with)
bool starts_with(const std::string& s, const std::string& p) {
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
}
std::string executable_dir_from_path(const std::string& exe_path) {
if (exe_path.empty()) return "";
std::error_code ec;
fs::path native_exe = path_from_utf8(exe_path);
fs::path abs = fs::weakly_canonical(native_exe, ec);
if (!ec) return path_to_utf8(abs.parent_path());
return path_to_utf8(native_exe.parent_path());
}
void reconcile_default_skills_on_startup(const std::string& exe_path) {
auto result = acecode::reconcile_default_global_skills_on_startup(
path_from_utf8(acecode::get_acecode_dir()),
executable_dir_from_path(exe_path));
if (!result.attempted) return;
if (!result.error.empty()) {
LOG_WARN("[seed] Default resource reconciliation issue: " + result.error);
}
}
} // namespace
Args parse(const std::vector<std::string>& tokens) {
Args a;
for (std::size_t i = 0; i < tokens.size(); ++i) {
const auto& t = tokens[i];
if (t == "start" || t == "stop" || t == "status") {
if (!a.sub.empty()) {
a.error = "multiple subcommands specified: " + a.sub + " and " + t;
return a;
}
a.sub = t;
} else if (t == "--foreground" || t == "-foreground") {
if (!a.sub.empty() && a.sub != "foreground") {
a.error = "--foreground cannot combine with " + a.sub;
return a;
}
a.sub = "foreground";
} else if (t == "--supervised") {
a.supervised = true;
} else if (starts_with(t, "--guid=")) {
a.guid = t.substr(7);
} else if (starts_with(t, "--port=")) {
// desktop 父进程预选空闲端口后通过 --port=N 注入。0 视为非法(直接走配置文件)。
std::string v = t.substr(7);
try {
int p = std::stoi(v);
if (p <= 0 || p > 65535) {
a.error = "--port=<N> out of range (1..65535): " + v;
return a;
}
a.port_override = p;
} catch (...) {
a.error = "--port=<N> not an integer: " + v;
return a;
}
} else if (starts_with(t, "--token=")) {
// desktop 父进程预生成 token,父子两端不必跨进程读 token 文件。
a.token_override = t.substr(8);
if (a.token_override.empty()) {
a.error = "--token=<T> empty value";
return a;
}
} else if (starts_with(t, "--static-dir=")) {
// dev 模式: desktop 探测到仓库 web/ 后通过这个 flag 让 daemon 走
// FileSystemAssetSource(每次请求重读),改 web/ 文件 + F5 即生效。
a.static_dir_override = t.substr(13);
if (a.static_dir_override.empty()) {
a.error = "--static-dir=<path> empty value";
return a;
}
} else if (starts_with(t, "--cwd=")) {
a.cwd_override = t.substr(6);
if (a.cwd_override.empty()) {
a.error = "--cwd=<path> empty value";
return a;
}
} else if (t == "--cwd") {
if (i + 1 >= tokens.size() || tokens[i + 1].empty()) {
a.error = "--cwd requires a path";
return a;
}
a.cwd_override = tokens[++i];
} else if (starts_with(t, "--run-dir=")) {
a.run_dir_override = t.substr(10);
if (a.run_dir_override.empty()) {
a.error = "--run-dir=<path> empty value";
return a;
}
} else if (t == "--run-dir") {
if (i + 1 >= tokens.size() || tokens[i + 1].empty()) {
a.error = "--run-dir requires a path";
return a;
}
a.run_dir_override = tokens[++i];
} else if (t == "--native-folder-picker") {
a.native_folder_picker_enabled = true;
} else if (t == "--desktop-managed") {
a.desktop_managed = true;
} else if (starts_with(t, "--desktop-protocol=")) {
try {
a.desktop_protocol_version = std::stoi(t.substr(19));
} catch (...) {
a.error = "--desktop-protocol=<N> not an integer";
return a;
}
if (a.desktop_protocol_version <= 0) {
a.error = "--desktop-protocol=<N> must be positive";
return a;
}
} else if (starts_with(t, "--desktop-owner-pid=")) {
try {
a.desktop_owner_pid = std::stoll(t.substr(20));
} catch (...) {
a.error = "--desktop-owner-pid=<PID> not an integer";
return a;
}
if (a.desktop_owner_pid <= 0) {
a.error = "--desktop-owner-pid=<PID> must be positive";
return a;
}
} else if (starts_with(t, "--desktop-owner-instance=")) {
a.desktop_owner_instance = t.substr(25);
if (a.desktop_owner_instance.empty()) {
a.error = "--desktop-owner-instance=<ID> empty value";
return a;
}
} else if (starts_with(t, "--question-policy=")) {
std::string err;
if (!parse_question_policy_value(
t.substr(18), a.question_policy_override,
a.question_timeout_seconds_override, err)) {
a.error = err;
return a;
}
} else if (t == "--question-policy") {
if (i + 1 >= tokens.size() || tokens[i + 1].empty()) {
a.error = "--question-policy requires a value: ask | deny | timeout[:seconds]";
return a;
}
std::string err;
if (!parse_question_policy_value(
tokens[++i], a.question_policy_override,
a.question_timeout_seconds_override, err)) {
a.error = err;
return a;
}
} else if (t == "-dangerous" || t == "--dangerous" ||
t == "-yolo" || t == "--yolo") {
a.dangerous = true;
} else if (t == "--help" || t == "-h") {
a.sub = "help";
} else {
a.error = "unknown daemon argument: " + t;
return a;
}
}
if (a.sub.empty()) {
a.sub = "start";
}
if (a.supervised && a.guid.empty()) {
a.error = "--supervised requires --guid=<G>";
}
const bool has_desktop_lifecycle_fields =
a.desktop_protocol_version > 0 || a.desktop_owner_pid > 0 ||
!a.desktop_owner_instance.empty();
if (!a.desktop_managed && has_desktop_lifecycle_fields) {
a.error = "desktop lifecycle fields require --desktop-managed";
} else if (a.desktop_managed &&
(a.sub != "foreground" || !a.supervised || a.guid.empty() ||
a.desktop_protocol_version <= 0 ||
a.desktop_owner_pid <= 0 ||
a.desktop_owner_instance.empty())) {
a.error = "--desktop-managed requires --supervised, --guid, "
"--foreground, --desktop-protocol, --desktop-owner-pid, "
"and --desktop-owner-instance";
}
return a;
}
std::string resolve_startup_cwd(const Args& args,
const std::string& caller_cwd) {
return args.cwd_override.empty() ? caller_cwd : args.cwd_override;
}
static int do_foreground(const Args& a, const std::string& exe_path) {
// run_dir override 必须在 load_config / validate_can_start / runtime_files
// 任何路径解析之前 set,否则 daemon 仍会读写默认 ~/.acecode/run/。config 的
// 路径仍走默认 — 我们只隔离 run/,sessions / memory / config 仍共享。
if (!a.run_dir_override.empty()) {
acecode::set_run_dir_override(a.run_dir_override);
}
append_startup_diagnostic(
"[daemon] stage=process_entry mode=foreground");
std::string hook_config_error;
append_startup_diagnostic(
"[daemon] stage=startup_hooks_begin "
"startup.before_model_load dispatch begin cwd=" +
acecode::current_path_utf8());
acecode::dispatch_startup_before_model_load_hooks(
acecode::current_path_utf8(), &hook_config_error);
if (!hook_config_error.empty()) {
append_startup_diagnostic("[hooks] WARNING: " + hook_config_error);
}
append_startup_diagnostic(
"[daemon] stage=startup_hooks_end "
"startup.before_model_load dispatch end" +
std::string(hook_config_error.empty() ? "" : " with warnings"));
if (!hook_config_error.empty()) {
std::cerr << "[hooks] WARNING: " << hook_config_error << "\n";
}
append_startup_diagnostic("[daemon] stage=config_load_begin");
AppConfig cfg = load_config();
append_startup_diagnostic("[daemon] stage=config_load_end");
append_startup_diagnostic("[daemon] stage=default_skills_sync_begin");
reconcile_default_skills_on_startup(exe_path);
append_startup_diagnostic("[daemon] stage=default_skills_sync_end");
auto errs = validate_config(cfg);
if (!errs.empty()) {
for (const auto& e : errs) std::cerr << "config error: " << e << "\n";
return 5;
}
// --question-policy 覆盖:只写运行时 CLI 字段(不落盘),SessionRegistry
// 经 deps_.config->agent_loop 对该 daemon 全部会话生效。
if (!a.question_policy_override.empty()) {
cfg.agent_loop.question_policy_cli = a.question_policy_override;
cfg.agent_loop.question_timeout_seconds_cli =
a.question_timeout_seconds_override;
}
WorkerOptions opts;
opts.foreground = true;
opts.supervised = a.supervised;
opts.guid = a.guid;
opts.dangerous = a.dangerous;
opts.port_override = a.port_override;
opts.token_override = a.token_override;
opts.static_dir_override = a.static_dir_override;
opts.cwd_override = a.cwd_override;
opts.native_folder_picker_enabled = a.native_folder_picker_enabled;
opts.desktop_managed = a.desktop_managed;
opts.desktop_protocol_version = a.desktop_protocol_version;
opts.desktop_owner_pid = a.desktop_owner_pid;
opts.desktop_owner_instance = a.desktop_owner_instance;
append_startup_diagnostic("[daemon] stage=worker_handoff");
return run_worker(opts, cfg);
}
static int do_start(const Args& a, const std::string& exe_path) {
if (!a.run_dir_override.empty()) {
acecode::set_run_dir_override(a.run_dir_override);
}
// 检查是否已有 daemon 在跑
auto snapshot = read_runtime_snapshot();
auto reuse = validate_runtime_snapshot_for_reuse(snapshot);
if (reuse.reusable && snapshot.pid.has_value()) {
std::cerr << "daemon already running (pid=" << *snapshot.pid
<< "); stop it first or check `acecode daemon status`\n";
return 6;
}
if (snapshot.pid.has_value() || snapshot.heartbeat.has_value()) {
std::cerr << "ignoring stale daemon runtime files: " << reuse.reason << "\n";
}
// 派生自身的 detached 副本: <exe> daemon --foreground
std::vector<std::string> argv = {exe_path, "daemon", "--foreground"};
if (a.port_override > 0) {
argv.push_back("--port=" + std::to_string(a.port_override));
}
if (!a.token_override.empty()) {
argv.push_back("--token=" + a.token_override);
}
if (!a.static_dir_override.empty()) {
argv.push_back("--static-dir=" + a.static_dir_override);
}
if (!a.cwd_override.empty()) {
argv.push_back("--cwd=" + a.cwd_override);
}
if (!a.run_dir_override.empty()) {
argv.push_back("--run-dir=" + a.run_dir_override);
}
if (a.native_folder_picker_enabled) {
argv.push_back("--native-folder-picker");
}
if (!a.question_policy_override.empty()) {
std::string v = a.question_policy_override;
if (v == "timeout" && a.question_timeout_seconds_override > 0) {
v += ":" + std::to_string(a.question_timeout_seconds_override);
}
argv.push_back("--question-policy=" + v);
}
if (a.dangerous) argv.push_back("-dangerous");
// The spawned worker redirects its stdio to /dev/null before exec, so an
// exec failure there is invisible. Reject an unusable path up front, while
// stderr still reaches the user.
std::error_code exe_ec;
if (!fs::is_regular_file(fs::path(exe_path), exe_ec)) {
std::cerr << "cannot locate the acecode executable to spawn: "
<< exe_path << "\n";
return 7;
}
auto child = spawn_detached(argv);
if (child == 0) {
std::cerr << "spawn_detached failed; check log\n";
return 7;
}
// POSIX double-fork 时返回 -1 哨兵(中间进程已 reap),真正 worker pid 由
// worker 自己写到 daemon.pid。这里轮询 daemon.pid 出现 + 进程存活,5s 超时。
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
while (std::chrono::steady_clock::now() < deadline) {
std::this_thread::sleep_for(std::chrono::milliseconds(150));
auto p = read_pid_file();
auto port = read_port_file();
if (p.has_value() && port.has_value() && is_pid_alive(*p)) {
std::cout << "daemon started pid=" << *p << "\n";
std::cout << "Web UI: "
<< acecode::web::format_http_address(
acecode::web::kRemoteWebLoopbackBind, *port)
<< "\n";
return 0;
}
}
std::cerr << "daemon failed to start within 5s; check ~/.acecode/logs/\n";
return 8;
}
static int do_stop() {
auto pid = read_pid_file();
if (!pid.has_value()) {
std::cerr << "no daemon running (no pid file)\n";
return 1;
}
if (!is_pid_alive(*pid)) {
std::cerr << "stale pid file (pid=" << *pid << " not alive); cleaning up\n";
cleanup_runtime_files();
return 0;
}
if (!terminate_pid(*pid, /*wait_ms=*/10000)) {
std::cerr << "failed to terminate pid=" << *pid << " within 10s\n";
return 9;
}
cleanup_runtime_files();
std::cout << "daemon stopped (pid=" << *pid << ")\n";
return 0;
}
static int do_status() {
auto snapshot = read_runtime_snapshot();
auto reuse = validate_runtime_snapshot_for_reuse(snapshot);
if (!reuse.reusable || !snapshot.pid.has_value()) {
std::cout << "no daemon running\n";
if (!reuse.reason.empty()) {
std::cout << " reason: " << reuse.reason << "\n";
}
return 1;
}
std::cout << "daemon running\n"
<< " pid: " << *snapshot.pid << "\n";
if (snapshot.port.has_value()) std::cout << " port: " << *snapshot.port << "\n";
if (snapshot.guid.has_value()) std::cout << " guid: " << *snapshot.guid << "\n";
if (snapshot.heartbeat.has_value()) {
auto age_ms = now_unix_ms() - snapshot.heartbeat->timestamp_ms;
std::cout << " last_heartbeat_age_ms: " << age_ms << "\n";
}
return 0;
}
int run(const std::vector<std::string>& tokens, const std::string& exe_path) {
Args a = parse(tokens);
if (!a.error.empty()) {
std::cerr << a.error << "\n\n";
print_help(std::cerr);
return 10;
}
if (a.sub == "help") {
print_help(std::cout);
return 0;
}
if (a.sub == "start" || a.sub == "foreground") {
a.cwd_override = resolve_startup_cwd(a, acecode::current_path_utf8());
}
// argv[0] is only ever a hint: a POSIX shell passes the bare word the user
// typed ("acecode" when it was found on PATH), and spawn_detached execv()s
// argv[0] verbatim — execv never searches PATH, so a bare name resolves
// against the current directory and the worker dies before it can log.
// Ask the OS for our own image first (/proc/self/exe on Linux,
// _NSGetExecutablePath on macOS, GetModuleFileName on Windows) and keep
// argv[0] only as a last resort.
std::string exe = current_executable_path();
if (!exe.empty()) {
std::error_code ec;
const fs::path canonical = fs::weakly_canonical(fs::path(exe), ec);
if (!ec) exe = canonical.string();
}
if (exe.empty()) exe = exe_path;
if (a.sub != "stop" && a.sub != "status" && exe.empty()) {
std::cerr << "cannot resolve current executable path\n";
return 12;
}
if (a.sub == "foreground") return do_foreground(a, exe);
if (a.sub == "start") return do_start(a, exe);
if (a.sub == "stop") return do_stop();
if (a.sub == "status") return do_status();
std::cerr << "unknown subcommand: " << a.sub << "\n";
return 10;
}
} // namespace acecode::daemon::cli