-
Notifications
You must be signed in to change notification settings - Fork 883
Expand file tree
/
Copy pathmain.zig
More file actions
6154 lines (5532 loc) · 244 KB
/
main.zig
File metadata and controls
6154 lines (5532 loc) · 244 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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const std_compat = @import("compat");
const builtin = @import("builtin");
const build_options = @import("build_options");
const yc = @import("nullclaw");
const control_plane = yc.control_plane;
const util = yc.util;
pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace, ret_addr: ?usize) noreturn {
_ = error_return_trace;
_ = ret_addr;
std_compat.fs.File.stderr().writeAll("panic: ") catch {};
std_compat.fs.File.stderr().writeAll(msg) catch {};
std_compat.fs.File.stderr().writeAll("\n") catch {};
std_compat.process.exit(1);
}
const log = std.log.scoped(.main);
const Command = enum {
agent,
acp,
gateway,
service,
config,
status,
version,
onboard,
doctor,
cron,
channel,
skills,
hardware,
migrate,
memory,
history,
workspace,
capabilities,
models,
mcp,
auth,
update,
help,
};
const SERVICE_SUBCOMMANDS = "install|start|stop|restart|status|uninstall";
const CONFIG_SUBCOMMANDS = "show|get|set|unset|reload|validate";
const CRON_SUBCOMMANDS = "list|get|status|add|add-agent|once|once-agent|remove|pause|resume|run|update|runs";
const CHANNEL_SUBCOMMANDS = "list|info|start|status|add|remove";
const SKILLS_SUBCOMMANDS = "list|install|remove|info";
const HARDWARE_SUBCOMMANDS = "scan|flash|monitor";
const MEMORY_SUBCOMMANDS = "stats|count|reindex|search|get|list|store|update|delete|drain-outbox|forget";
const HISTORY_SUBCOMMANDS = "list|show";
const WORKSPACE_SUBCOMMANDS = "edit|reset-md";
const MODELS_SUBCOMMANDS = "list|summary|info|benchmark|refresh";
const MCP_SUBCOMMANDS = "list|info";
const AUTH_SUBCOMMANDS = "login|status|logout";
const TOP_LEVEL_USAGE = std.fmt.comptimePrint(
\\nullclaw -- The smallest AI assistant. Zig-powered.
\\
\\USAGE:
\\ nullclaw <command> [options]
\\
\\COMMANDS:
\\ onboard Initialize workspace and configuration
\\ agent Start the AI agent loop
\\ acp Start Agent Client Protocol server (stdio JSON-RPC)
\\ gateway Start the gateway server (HTTP/WebSocket)
\\ service Manage OS service lifecycle
\\ config Inspect resolved config values
\\ status Show system status
\\ version Show CLI version
\\ doctor Run diagnostics
\\ cron Manage scheduled tasks
\\ channel Manage channels (Telegram, Discord, Slack, ...)
\\ skills Manage skills
\\ hardware Discover and manage hardware
\\ migrate Migrate data from other agent runtimes
\\ memory Inspect and maintain memory subsystem
\\ history View session conversation history
\\ workspace Maintain workspace markdown/bootstrap files
\\ capabilities Show runtime capabilities manifest
\\ models Manage provider model catalogs
\\ mcp Inspect configured MCP servers
\\ auth Manage OAuth authentication (OpenAI Codex)
\\ update Check for and install updates
\\ help Show this help
\\
\\OPTIONS:
\\ onboard [--interactive] [--api-key KEY] [--provider PROV] [--model MODEL] [--memory MEM]
\\ agent [-m MESSAGE] [-s SESSION] [--provider PROVIDER] [--model MODEL] [--temperature TEMP] [--workspace PATH] [--skill SKILL]
\\ acp [--provider PROVIDER] [--model MODEL] [--temperature TEMP] [--agent NAME] [--skill NAME]
\\ gateway [--port PORT] [--host HOST] [--workspace PATH]
\\ status [--json]
\\ version | --version | -V
\\ service <{s}>
\\ config <{s}> [ARGS]
\\ cron <{s}> [ARGS]
\\ channel <{s}> [ARGS]
\\ skills <{s}> [ARGS]
\\ hardware <{s}> [ARGS]
\\ migrate openclaw [--dry-run] [--source PATH]
\\ memory <{s}> [ARGS]
\\ history <{s}> [ARGS]
\\ workspace <{s}> [ARGS]
\\ capabilities [--json]
\\ models <{s}> [ARGS]
\\ mcp <{s}> [ARGS]
\\ auth <{s}> <provider> [--import-codex]
\\ update [--check] [--yes]
\\
,
.{
SERVICE_SUBCOMMANDS,
CONFIG_SUBCOMMANDS,
CRON_SUBCOMMANDS,
CHANNEL_SUBCOMMANDS,
SKILLS_SUBCOMMANDS,
HARDWARE_SUBCOMMANDS,
MEMORY_SUBCOMMANDS,
HISTORY_SUBCOMMANDS,
WORKSPACE_SUBCOMMANDS,
MODELS_SUBCOMMANDS,
MCP_SUBCOMMANDS,
AUTH_SUBCOMMANDS,
},
);
fn parseCommand(arg: []const u8) ?Command {
const command_map = std.StaticStringMap(Command).initComptime(.{
.{ "agent", .agent },
.{ "acp", .acp },
.{ "gateway", .gateway },
.{ "service", .service },
.{ "config", .config },
.{ "status", .status },
.{ "version", .version },
.{ "--version", .version },
.{ "-V", .version },
.{ "onboard", .onboard },
.{ "doctor", .doctor },
.{ "cron", .cron },
.{ "channel", .channel },
.{ "skills", .skills },
.{ "hardware", .hardware },
.{ "migrate", .migrate },
.{ "memory", .memory },
.{ "history", .history },
.{ "workspace", .workspace },
.{ "capabilities", .capabilities },
.{ "models", .models },
.{ "mcp", .mcp },
.{ "auth", .auth },
.{ "update", .update },
.{ "help", .help },
.{ "--help", .help },
.{ "-h", .help },
});
return command_map.get(arg);
}
extern "kernel32" fn SetConsoleCP(wCodePageID: std.os.windows.UINT) callconv(.winapi) std.os.windows.BOOL;
extern "kernel32" fn SetConsoleOutputCP(wCodePageID: std.os.windows.UINT) callconv(.winapi) std.os.windows.BOOL;
fn configureWindowsConsoleUtf8() void {
if (comptime builtin.os.tag == .windows) {
// Set both output and input code pages to UTF-8 so interactive
// terminal sessions preserve non-ASCII user input.
_ = SetConsoleOutputCP(65001);
_ = SetConsoleCP(65001);
}
}
pub fn main(init: std.process.Init) !void {
std_compat.initProcess(init);
configureWindowsConsoleUtf8();
const allocator = std.heap.smp_allocator;
const args = try std_compat.process.argsAlloc(allocator);
defer std_compat.process.argsFree(allocator, args);
if (args.len < 2) {
printUsage();
return;
}
// Manifest protocol flags (checked before command dispatch)
if (std.mem.eql(u8, args[1], "--export-manifest")) {
try yc.export_manifest.run();
return;
}
if (std.mem.eql(u8, args[1], "--list-models")) {
try yc.list_models.run(allocator, args[2..]);
return;
}
if (std.mem.eql(u8, args[1], "--probe-provider-health")) {
try yc.provider_probe.run(allocator, args[2..]);
return;
}
if (std.mem.eql(u8, args[1], "--probe-channel-health")) {
try yc.channel_probe.run(allocator, args[2..]);
return;
}
if (std.mem.eql(u8, args[1], "--from-json")) {
try yc.from_json.run(allocator, args[2..]);
return;
}
if (comptime builtin.os.tag == .windows) {
if (yc.service.isWindowsServiceGatewayArg(args[1])) {
try yc.service.runWindowsServiceGateway(allocator);
return;
}
}
const cmd = parseCommand(args[1]) orelse {
std.debug.print("Unknown command: {s}\n\n", .{args[1]});
printUsage();
std_compat.process.exit(1);
};
const sub_args = args[2..];
switch (cmd) {
.version => printVersion(),
.status => try yc.status.run(allocator, args[2..]),
.agent => if (agentAdminRequested(sub_args)) {
try runAgentAdmin(allocator, sub_args);
} else if (agentHelpRequested(sub_args)) {
printAgentUsage();
} else {
try yc.agent.run(allocator, sub_args);
},
.acp => try yc.acp.run(allocator, sub_args),
.onboard => try runOnboard(allocator, sub_args),
.doctor => try runDoctorCommand(allocator, sub_args),
.help => printUsage(),
.gateway => try runGateway(allocator, sub_args),
.service => try runService(allocator, sub_args),
.config => try runConfig(allocator, sub_args),
.cron => try runCron(allocator, sub_args),
.channel => try runChannel(allocator, sub_args),
.skills => try runSkills(allocator, sub_args),
.hardware => try runHardware(allocator, sub_args),
.migrate => try runMigrate(allocator, sub_args),
.memory => try runMemory(allocator, sub_args),
.history => try runHistory(allocator, sub_args),
.workspace => try runWorkspace(allocator, sub_args),
.capabilities => try runCapabilities(allocator, sub_args),
.models => try runModels(allocator, sub_args),
.mcp => try runMcp(allocator, sub_args),
.auth => try runAuth(allocator, sub_args),
.update => try runUpdate(allocator, sub_args),
}
}
fn printVersion() void {
var buf: [256]u8 = undefined;
var bw = std_compat.fs.File.stdout().writer(&buf);
bw.interface.print("nullclaw {s}\n", .{yc.version.string}) catch return;
bw.interface.flush() catch return;
}
const GatewayDaemonOverrideError = error{InvalidPort};
fn applyRuntimeProviderOverrides(config: *const yc.config.Config) void {
yc.http_util.setProxyOverride(config.http_request.proxy) catch |err| {
std.debug.print("Invalid http_request.proxy override: {s}\n", .{@errorName(err)});
std_compat.process.exit(1);
};
yc.providers.setApiErrorLimitOverride(config.diagnostics.api_error_max_chars) catch |err| {
std.debug.print("Invalid diagnostics.api_error_max_chars override: {s}\n", .{@errorName(err)});
std_compat.process.exit(1);
};
}
fn hasVerboseFlag(args: []const []const u8) bool {
for (args) |arg| {
if (std.mem.eql(u8, arg, "--verbose") or std.mem.eql(u8, arg, "-v")) {
return true;
}
}
return false;
}
fn agentHelpRequested(args: []const []const u8) bool {
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg = args[i];
if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
return true;
}
if (std.mem.eql(u8, arg, "-m") or
std.mem.eql(u8, arg, "--message") or
std.mem.eql(u8, arg, "-s") or
std.mem.eql(u8, arg, "--session") or
std.mem.eql(u8, arg, "--provider") or
std.mem.eql(u8, arg, "--model") or
std.mem.eql(u8, arg, "--temperature") or
std.mem.eql(u8, arg, "--agent") or
std.mem.eql(u8, arg, "--workspace") or
std.mem.eql(u8, arg, "--skill"))
{
if (i + 1 < args.len) i += 1;
}
}
return false;
}
fn agentAdminRequested(args: []const []const u8) bool {
if (args.len == 0) return false;
return std.mem.eql(u8, args[0], "invoke") or std.mem.eql(u8, args[0], "sessions");
}
fn gatewayHelpRequested(args: []const []const u8) bool {
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg = args[i];
if (std.mem.eql(u8, arg, "--help") or std.mem.eql(u8, arg, "-h")) {
return true;
}
if (std.mem.eql(u8, arg, "--port") or
std.mem.eql(u8, arg, "-p") or
std.mem.eql(u8, arg, "--host") or
std.mem.eql(u8, arg, "--workspace"))
{
if (i + 1 < args.len) i += 1;
}
}
return false;
}
fn applyGatewayDaemonOverrides(cfg: *yc.config.Config, sub_args: []const []const u8) GatewayDaemonOverrideError!void {
var port: u16 = cfg.gateway.port;
var host: []const u8 = cfg.gateway.host;
var i: usize = 0;
while (i < sub_args.len) : (i += 1) {
if ((std.mem.eql(u8, sub_args[i], "--port") or std.mem.eql(u8, sub_args[i], "-p")) and i + 1 < sub_args.len) {
i += 1;
port = std.fmt.parseInt(u16, sub_args[i], 10) catch return error.InvalidPort;
} else if (std.mem.eql(u8, sub_args[i], "--host") and i + 1 < sub_args.len) {
i += 1;
host = sub_args[i];
} else if (std.mem.eql(u8, sub_args[i], "--workspace") and i + 1 < sub_args.len) {
i += 1;
cfg.workspace_dir = sub_args[i];
}
}
cfg.gateway.port = port;
cfg.gateway.host = host;
}
// ── Gateway ──────────────────────────────────────────────────────
fn printGatewayUsage() void {
std.debug.print(
\\Usage: nullclaw gateway [options]
\\
\\Start the gateway server (HTTP/WebSocket).
\\
\\OPTIONS:
\\ --port PORT, -p PORT Override gateway listen port
\\ --host HOST Override gateway listen host
\\ --workspace PATH Override workspace directory
\\ --verbose, -v Enable verbose logging
\\ --help, -h Show this help
\\
, .{});
}
fn printAgentUsage() void {
std.debug.print(
\\Usage: nullclaw agent [options]
\\
\\Start the AI agent loop.
\\
\\OPTIONS:
\\ invoke --message MESSAGE [--session SESSION] [--workspace PATH] [--skill SKILL] [--json]
\\ Run one machine-readable agent turn
\\ sessions list [--json] List persisted agent sessions
\\ sessions get <session> [--json]
\\ Show persisted session metadata
\\ sessions terminate <session> [--json]
\\ Clear persisted session state
\\
\\INTERACTIVE / SINGLE-TURN MODE:
\\ -m, --message MESSAGE Run a single message (non-interactive)
\\ -s, --session SESSION Resume a specific session
\\ --provider PROVIDER Override default provider
\\ --model MODEL Override default model
\\ --temperature TEMP Override sampling temperature
\\ --workspace PATH Override workspace directory
\\ --skill SKILL Activate a named skill at startup
\\ --verbose, -v Enable verbose logging
\\ --help, -h Show this help
\\
, .{});
}
const HistoryStoreContext = struct {
cfg: yc.config.Config,
mem_rt: yc.memory.MemoryRuntime,
session_store: yc.memory.SessionStore,
fn init(allocator: std.mem.Allocator, workspace_override: ?[]const u8) !HistoryStoreContext {
var cfg = yc.config.Config.load(allocator) catch return error.ConfigNotFound;
errdefer cfg.deinit();
applyHistoryWorkspaceOverride(&cfg, workspace_override);
var history_memory_cfg = buildHistoryMemoryConfig(cfg.memory);
var mem_rt = yc.memory.initRuntime(allocator, &history_memory_cfg, cfg.workspace_dir) orelse return error.MemoryRuntimeUnavailable;
errdefer mem_rt.deinit();
const session_store = mem_rt.session_store orelse return error.SessionStoreUnavailable;
return .{
.cfg = cfg,
.mem_rt = mem_rt,
.session_store = session_store,
};
}
fn deinit(self: *HistoryStoreContext) void {
self.mem_rt.deinit();
self.cfg.deinit();
self.* = undefined;
}
};
fn applyHistoryWorkspaceOverride(cfg: *yc.config.Config, workspace_override: ?[]const u8) void {
if (workspace_override) |workspace| {
cfg.workspace_dir = workspace;
}
}
fn runDoctorCommand(allocator: std.mem.Allocator, sub_args: []const []const u8) !void {
if (sub_args.len == 0) {
try yc.doctor.run(allocator);
return;
}
if (sub_args.len == 1 and std.mem.eql(u8, sub_args[0], "--json")) {
yc.doctor.runJson(allocator) catch |err| {
writeJsonError("doctor_failed", @errorName(err), null);
std_compat.process.exit(1);
};
return;
}
std.debug.print("Usage: nullclaw doctor [--json]\n", .{});
std_compat.process.exit(1);
}
fn selfCommandResult(allocator: std.mem.Allocator, args: []const []const u8) !std_compat.process.Child.RunResult {
const exe_path = try std_compat.fs.selfExePathAlloc(allocator);
defer allocator.free(exe_path);
var argv = std.ArrayListUnmanaged([]const u8).empty;
defer argv.deinit(allocator);
try argv.append(allocator, exe_path);
for (args) |arg| try argv.append(allocator, arg);
return std_compat.process.Child.run(.{
.allocator = allocator,
.argv = argv.items,
});
}
fn trimTrailingNewline(text: []const u8) []const u8 {
var trimmed = text;
while (trimmed.len > 0 and (trimmed[trimmed.len - 1] == '\n' or trimmed[trimmed.len - 1] == '\r')) {
trimmed = trimmed[0 .. trimmed.len - 1];
}
return trimmed;
}
fn appendAgentSessionListJson(out: anytype, sessions: []const yc.memory.SessionInfo, total: u64) !void {
try out.writeAll("{\"sessions\":[");
for (sessions, 0..) |session, idx| {
if (idx > 0) try out.writeAll(",");
try out.writeAll("{\"session_key\":");
try writeJsonString(out, session.session_id);
try out.writeAll(",\"created_at\":");
try writeJsonString(out, session.first_message_at);
try out.writeAll(",\"last_active\":");
try writeJsonString(out, session.last_message_at);
try out.print(",\"turn_count\":{d},\"turn_running\":false}}", .{session.message_count / 2});
}
try out.print("],\"total\":{d}}}", .{total});
}
fn writeAgentSessionListJson(sessions: []const yc.memory.SessionInfo, total: u64) !void {
writeRenderedJsonLine(appendAgentSessionListJson, .{ sessions, total });
}
fn appendAgentSessionDetailJson(out: anytype, session: yc.memory.SessionInfo) !void {
try out.writeAll("{\"session_key\":");
try writeJsonString(out, session.session_id);
try out.writeAll(",\"created_at\":");
try writeJsonString(out, session.first_message_at);
try out.writeAll(",\"last_active\":");
try writeJsonString(out, session.last_message_at);
try out.print(",\"turn_count\":{d},\"turn_running\":false}}", .{session.message_count / 2});
}
fn writeAgentSessionDetailJson(session: yc.memory.SessionInfo) void {
writeRenderedJsonLine(appendAgentSessionDetailJson, .{session});
}
fn appendAgentInvokeResponseJson(out: anytype, session_key: []const u8, response: []const u8, turn_count: u64) !void {
try out.writeAll("{\"session\":");
try writeJsonString(out, session_key);
try out.writeAll(",\"response\":");
try writeJsonString(out, response);
try out.print(",\"turn_count\":{d}}}", .{turn_count});
}
fn runAgentAdmin(allocator: std.mem.Allocator, sub_args: []const []const u8) !void {
if (sub_args.len == 0) {
printAgentUsage();
std_compat.process.exit(1);
}
const subcmd = sub_args[0];
if (std.mem.eql(u8, subcmd, "invoke")) {
try runAgentInvokeJson(allocator, sub_args[1..]);
return;
}
if (std.mem.eql(u8, subcmd, "sessions")) {
try runAgentSessionsAdmin(allocator, sub_args[1..]);
return;
}
printAgentUsage();
std_compat.process.exit(1);
}
const AgentInvokeForwardOptions = struct {
provider: ?[]const u8 = null,
model: ?[]const u8 = null,
temperature: ?[]const u8 = null,
agent_name: ?[]const u8 = null,
workspace: ?[]const u8 = null,
skill_name: ?[]const u8 = null,
};
fn appendAgentInvokeForwardArgs(
allocator: std.mem.Allocator,
argv: *std.ArrayListUnmanaged([]const u8),
message_text: []const u8,
session: []const u8,
options: AgentInvokeForwardOptions,
) !void {
try argv.append(allocator, "agent");
try argv.append(allocator, "-m");
try argv.append(allocator, message_text);
try argv.append(allocator, "-s");
try argv.append(allocator, session);
if (options.provider) |value| {
try argv.append(allocator, "--provider");
try argv.append(allocator, value);
}
if (options.model) |value| {
try argv.append(allocator, "--model");
try argv.append(allocator, value);
}
if (options.temperature) |value| {
try argv.append(allocator, "--temperature");
try argv.append(allocator, value);
}
if (options.agent_name) |value| {
try argv.append(allocator, "--agent");
try argv.append(allocator, value);
}
if (options.workspace) |value| {
try argv.append(allocator, "--workspace");
try argv.append(allocator, value);
}
if (options.skill_name) |value| {
try argv.append(allocator, "--skill");
try argv.append(allocator, value);
}
}
fn runAgentInvokeJson(allocator: std.mem.Allocator, sub_args: []const []const u8) !void {
var message: ?[]const u8 = null;
var session: ?[]const u8 = null;
var provider: ?[]const u8 = null;
var model: ?[]const u8 = null;
var temperature: ?[]const u8 = null;
var agent_name: ?[]const u8 = null;
var workspace: ?[]const u8 = null;
var skill_name: ?[]const u8 = null;
var json_mode = false;
var i: usize = 0;
while (i < sub_args.len) : (i += 1) {
const arg = sub_args[i];
if (std.mem.eql(u8, arg, "--message") or std.mem.eql(u8, arg, "-m")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --message", null);
std_compat.process.exit(1);
}
i += 1;
message = sub_args[i];
} else if (std.mem.eql(u8, arg, "--session") or std.mem.eql(u8, arg, "-s")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --session", null);
std_compat.process.exit(1);
}
i += 1;
session = sub_args[i];
} else if (std.mem.eql(u8, arg, "--provider")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --provider", null);
std_compat.process.exit(1);
}
i += 1;
provider = sub_args[i];
} else if (std.mem.eql(u8, arg, "--model")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --model", null);
std_compat.process.exit(1);
}
i += 1;
model = sub_args[i];
} else if (std.mem.eql(u8, arg, "--temperature")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --temperature", null);
std_compat.process.exit(1);
}
i += 1;
temperature = sub_args[i];
} else if (std.mem.eql(u8, arg, "--agent")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --agent", null);
std_compat.process.exit(1);
}
i += 1;
agent_name = sub_args[i];
} else if (std.mem.eql(u8, arg, "--workspace")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --workspace", null);
std_compat.process.exit(1);
}
i += 1;
workspace = sub_args[i];
} else if (std.mem.eql(u8, arg, "--skill")) {
if (i + 1 >= sub_args.len) {
writeJsonError("bad_request", "Missing value for --skill", null);
std_compat.process.exit(1);
}
i += 1;
skill_name = sub_args[i];
} else if (std.mem.eql(u8, arg, "--json")) {
json_mode = true;
} else {
writeJsonError("bad_request", "Unknown option for agent invoke", null);
std_compat.process.exit(1);
}
}
if (!json_mode) {
writeJsonError("bad_request", "agent invoke requires --json", null);
std_compat.process.exit(1);
}
const message_text = message orelse {
writeJsonError("bad_request", "agent invoke requires --message", null);
std_compat.process.exit(1);
};
if (std.mem.trim(u8, message_text, " \t\r\n").len == 0) {
writeJsonError("bad_request", "agent invoke message must not be empty", null);
std_compat.process.exit(1);
}
var argv = std.ArrayListUnmanaged([]const u8).empty;
defer argv.deinit(allocator);
const effective_session = session orelse "api:default";
try appendAgentInvokeForwardArgs(allocator, &argv, message_text, effective_session, .{
.provider = provider,
.model = model,
.temperature = temperature,
.agent_name = agent_name,
.workspace = workspace,
.skill_name = skill_name,
});
const result = selfCommandResult(allocator, argv.items) catch |err| {
writeJsonError("agent_invoke_failed", @errorName(err), null);
std_compat.process.exit(1);
};
defer allocator.free(result.stdout);
defer allocator.free(result.stderr);
if (switch (result.term) {
.exited => |code| code == 0,
else => false,
}) {
var ctx = HistoryStoreContext.init(allocator, workspace) catch |err| switch (err) {
error.ConfigNotFound => {
writeJsonError("config_not_found", "No config found -- run `nullclaw onboard` first", null);
std_compat.process.exit(1);
},
error.MemoryRuntimeUnavailable => {
writeJsonError("session_store_unavailable", "Failed to initialize session store", null);
std_compat.process.exit(1);
},
error.SessionStoreUnavailable => {
writeJsonError("session_store_unavailable", "Session store not available for configured backend", null);
std_compat.process.exit(1);
},
};
defer ctx.deinit();
const total = ctx.session_store.countDetailedMessages(effective_session) catch 0;
const turn_count: u64 = total / 2;
const response_text = trimTrailingNewline(result.stdout);
writeRenderedJsonLine(appendAgentInvokeResponseJson, .{ effective_session, response_text, turn_count });
return;
}
const stderr_line = trimTrailingNewline(result.stderr);
if (stderr_line.len > 0) {
writeJsonError("agent_invoke_failed", stderr_line, null);
} else {
writeJsonError("agent_invoke_failed", "Agent invocation failed", null);
}
std_compat.process.exit(1);
}
fn runAgentSessionsAdmin(allocator: std.mem.Allocator, sub_args: []const []const u8) !void {
if (sub_args.len == 0) {
writeJsonError("bad_request", "Usage: nullclaw agent sessions <list|get|terminate> ...", null);
std_compat.process.exit(1);
}
const subcmd = sub_args[0];
const json_mode = hasJsonFlag(sub_args[1..]);
var ctx = HistoryStoreContext.init(allocator, null) catch |err| switch (err) {
error.ConfigNotFound => {
if (json_mode) writeJsonError("config_not_found", "No config found -- run `nullclaw onboard` first", null);
std.debug.print("No config found -- run `nullclaw onboard` first\n", .{});
std_compat.process.exit(1);
},
error.MemoryRuntimeUnavailable, error.SessionStoreUnavailable => {
if (json_mode) writeJsonError("session_store_unavailable", "Session store is not available for configured backend", null);
std.debug.print("Session store is not available for configured backend\n", .{});
std_compat.process.exit(1);
},
};
defer ctx.deinit();
if (std.mem.eql(u8, subcmd, "list")) {
if (sub_args.len > 2 or !json_mode) {
writeJsonError("bad_request", "Usage: nullclaw agent sessions list --json", null);
std_compat.process.exit(1);
}
const total = ctx.session_store.countSessions() catch |err| {
writeJsonError("session_list_failed", @errorName(err), ctx.cfg.memory.backend);
std_compat.process.exit(1);
};
const sessions = ctx.session_store.listSessions(allocator, @intCast(@max(total, 1)), 0) catch |err| {
writeJsonError("session_list_failed", @errorName(err), ctx.cfg.memory.backend);
std_compat.process.exit(1);
};
defer yc.memory.freeSessionInfos(allocator, sessions);
try writeAgentSessionListJson(sessions, total);
return;
}
if (sub_args.len < 2 or !json_mode) {
writeJsonError("bad_request", "Usage: nullclaw agent sessions <get|terminate> <session> --json", null);
std_compat.process.exit(1);
}
const session_key = sub_args[1];
const total = ctx.session_store.countSessions() catch |err| {
writeJsonError("session_list_failed", @errorName(err), ctx.cfg.memory.backend);
std_compat.process.exit(1);
};
const sessions = ctx.session_store.listSessions(allocator, @intCast(@max(total, 1)), 0) catch |err| {
writeJsonError("session_list_failed", @errorName(err), ctx.cfg.memory.backend);
std_compat.process.exit(1);
};
defer yc.memory.freeSessionInfos(allocator, sessions);
const session = blk: {
for (sessions) |item| {
if (std.mem.eql(u8, item.session_id, session_key)) break :blk item;
}
break :blk null;
};
if (std.mem.eql(u8, subcmd, "get")) {
if (session) |value| {
writeAgentSessionDetailJson(value);
return;
}
writeJsonError("session_not_found", "No session with that key", ctx.cfg.memory.backend);
std_compat.process.exit(1);
}
if (std.mem.eql(u8, subcmd, "terminate")) {
if (session == null) {
writeJsonError("session_not_found", "No session with that key", ctx.cfg.memory.backend);
std_compat.process.exit(1);
}
ctx.session_store.clearMessages(session_key) catch |err| {
writeJsonError("session_terminate_failed", @errorName(err), ctx.cfg.memory.backend);
std_compat.process.exit(1);
};
ctx.session_store.clearAutoSaved(session_key) catch {};
const entries_opt = ctx.mem_rt.memory.list(allocator, null, session_key) catch null;
if (entries_opt) |entries| {
defer yc.memory.freeEntries(allocator, entries);
for (entries) |entry| {
_ = ctx.mem_rt.memory.forgetScoped(allocator, entry.key, session_key) catch {};
}
}
writeRenderedJsonLine(appendAgentSessionTerminationJson, .{session_key});
return;
}
writeJsonError("bad_request", "Unknown agent sessions command", null);
std_compat.process.exit(1);
}
fn runGateway(allocator: std.mem.Allocator, sub_args: []const []const u8) !void {
if (gatewayHelpRequested(sub_args)) {
printGatewayUsage();
return;
}
var cfg = yc.config.Config.load(allocator) catch {
std.debug.print("No config found -- run `nullclaw onboard` first\n", .{});
std_compat.process.exit(1);
};
defer cfg.deinit();
applyGatewayDaemonOverrides(&cfg, sub_args) catch {
std.debug.print("Invalid port in CLI args.\n", .{});
std_compat.process.exit(1);
};
if (!yc.security.isYoloGatewayAllowed(cfg.autonomy.level, cfg.gateway.host, yc.security.isYoloForceEnabled(allocator))) {
std.debug.print(
"Refusing to start gateway with autonomy.level=yolo on non-local host '{s}'. Use localhost or set NULLCLAW_ALLOW_YOLO=1 to force this insecure mode.\n",
.{cfg.gateway.host},
);
std_compat.process.exit(1);
}
// Check both sub_args and global args for --verbose flag
var verbose = hasVerboseFlag(sub_args);
if (!verbose) {
// Also check global args for --verbose flag
const args = std_compat.process.argsAlloc(allocator) catch &.{};
defer std_compat.process.argsFree(allocator, args);
for (args) |arg| {
if (std.mem.eql(u8, arg, "--verbose") or std.mem.eql(u8, arg, "-v")) {
verbose = true;
break;
}
}
}
if (verbose) {
log.warn("Verbose flag detected, enabling verbose logging", .{});
yc.verbose.setVerbose(true);
}
cfg.validate() catch |err| {
yc.config.Config.printValidationError(err);
std_compat.process.exit(1);
};
applyRuntimeProviderOverrides(&cfg);
try yc.daemon.run(allocator, &cfg, cfg.gateway.host, cfg.gateway.port);
}
// ── Service ──────────────────────────────────────────────────────
fn runService(allocator: std.mem.Allocator, sub_args: []const []const u8) !void {
if (sub_args.len < 1) {
std.debug.print(std.fmt.comptimePrint("Usage: nullclaw service <{s}>\n", .{SERVICE_SUBCOMMANDS}), .{});
std_compat.process.exit(1);
}
const subcmd = sub_args[0];
const service_cmd: yc.service.ServiceCommand = blk: {
const map = .{
.{ "install", yc.service.ServiceCommand.install },
.{ "start", yc.service.ServiceCommand.start },
.{ "stop", yc.service.ServiceCommand.stop },
.{ "restart", yc.service.ServiceCommand.restart },
.{ "status", yc.service.ServiceCommand.status },
.{ "uninstall", yc.service.ServiceCommand.uninstall },
};
inline for (map) |entry| {
if (std.mem.eql(u8, subcmd, entry[0])) break :blk entry[1];
}
std.debug.print("Unknown service command: {s}\n", .{subcmd});
std.debug.print(std.fmt.comptimePrint("Usage: nullclaw service <{s}>\n", .{SERVICE_SUBCOMMANDS}), .{});
std_compat.process.exit(1);
};
yc.service.handleCommand(allocator, service_cmd) catch |err| {
const any_err: anyerror = err;
switch (any_err) {
error.UnsupportedPlatform => {
std.debug.print("Service management is not supported on this platform.\n", .{});
},
error.NoHomeDir => {
std.debug.print("Could not resolve home directory for service files.\n", .{});
},
error.OpenRcUnavailable => {
std.debug.print("OpenRC was detected, but the required OpenRC commands are unavailable.\n", .{});
std.debug.print("Verify `rc-service`, `rc-update`, and `openrc-run` are installed.\n", .{});
},
error.SystemctlUnavailable => {
std.debug.print("`systemctl` is not available and no supported Linux fallback service manager was detected.\n", .{});
std.debug.print("Install OpenRC or SysVinit support, or run `nullclaw gateway` in the foreground.\n", .{});
},
error.SystemdUserUnavailable => {
std.debug.print("systemd user services are unavailable (`systemctl --user`).\n", .{});
std.debug.print("Verify with `systemctl --user status` or run `nullclaw gateway` in the foreground.\n", .{});
},
error.CommandFailed => {
std.debug.print("Service command failed: {s}\n", .{subcmd});
},
else => return any_err,
}
std_compat.process.exit(1);
};
}
// ── Cron ─────────────────────────────────────────────────────────
const CronAddAgentOptions = struct {
model: ?[]const u8 = null,
session_target: yc.cron.SessionTarget = .isolated,
delivery: yc.cron.DeliveryConfig = .{},
};
fn parseCronSessionTargetArg(raw: []const u8) !yc.cron.SessionTarget {
return yc.cron.SessionTarget.parseStrict(raw);
}
fn parseCronAgentOptions(sub_args: []const []const u8, start_index: usize) !CronAddAgentOptions {
var options = CronAddAgentOptions{};
var i: usize = start_index;
while (i < sub_args.len) : (i += 1) {
if (i + 1 < sub_args.len and std.mem.eql(u8, sub_args[i], "--model")) {
options.model = sub_args[i + 1];
i += 1;
} else if (i + 1 < sub_args.len and std.mem.eql(u8, sub_args[i], "--session-target")) {
options.session_target = try parseCronSessionTargetArg(sub_args[i + 1]);
i += 1;
} else if (std.mem.eql(u8, sub_args[i], "--announce")) {
options.delivery.mode = .always;
} else if (i + 1 < sub_args.len and std.mem.eql(u8, sub_args[i], "--channel")) {
options.delivery.channel = sub_args[i + 1];
i += 1;
} else if (i + 1 < sub_args.len and std.mem.eql(u8, sub_args[i], "--account")) {
options.delivery.account_id = sub_args[i + 1];
i += 1;
} else if (i + 1 < sub_args.len and std.mem.eql(u8, sub_args[i], "--to")) {
options.delivery.to = sub_args[i + 1];
i += 1;
}
}
return options;
}
fn parseCronAddAgentOptions(sub_args: []const []const u8) !CronAddAgentOptions {
return parseCronAgentOptions(sub_args, 3);
}
fn runCron(allocator: std.mem.Allocator, sub_args: []const []const u8) !void {
if (sub_args.len < 1) {
std.debug.print(std.fmt.comptimePrint(
\\Usage: nullclaw cron <{s}> [args]
\\
\\Commands:
\\ list [--json] List all scheduled tasks
\\ get <id> [--json] Show one scheduled task
\\ status [--json] Show scheduler daemon status
\\ add <expression> <command> Add a recurring cron job
\\ add-agent <expression> <prompt> [--model <model>] [--announce] [--channel <name>] [--account <id>] [--to <id>]
\\ Add a recurring agent cron job
\\ once <delay> <command> Add a one-shot delayed task
\\ once-agent <delay> <prompt> [--model <model>]
\\ Add a one-shot delayed agent task
\\ remove <id> Remove a scheduled task
\\ pause <id> Pause a scheduled task