forked from thesongzhu/Friday
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfriday-cli.ts
More file actions
2543 lines (2278 loc) · 79.5 KB
/
Copy pathfriday-cli.ts
File metadata and controls
2543 lines (2278 loc) · 79.5 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
#!/usr/bin/env node
/**
* Phase C — Friday CLI entry point.
*
* Lightweight arg parsing via process.argv; no external CLI framework.
*
* Commands:
* friday start [--skills-dir <path>] [--port <n>] — boot hub, keep running
* friday list [--skills-dir <path>] — list loaded skills
* friday run <skill-id> [--input k=v ...] [--skills-dir <path>] — run a skill
* friday runs backfill-pack-context [--dry-run|--apply] [--json]
* friday status — show hub status
* friday import <source> [--from <format>] — preview conversion only
* friday convert <source> --out <dir> [--from <format>]
* friday converters — list converters
* friday pack <skill-dir> --out <file.tgz>
* friday skills init <skill-id> [--template node|shell] [--out <dir>]
* friday daemon start|stop|restart|status — manage background daemon
* friday tui [--host <addr>] [--port <n>] — open the terminal dashboard
* friday --help — usage info
*/
// ─── Global error handlers (must be first) ───
process.on("unhandledRejection", (reason) => {
console.error("[friday][FATAL] Unhandled promise rejection:", reason instanceof Error ? reason.stack ?? reason.message : String(reason));
process.exit(1);
});
process.on("uncaughtException", (error) => {
console.error("[friday][FATAL] Uncaught exception:", error.stack ?? error.message);
process.exit(1);
});
import { existsSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname, isAbsolute, join, normalize } from "node:path";
import { fileURLToPath } from "node:url";
import {
buildFridayChannelSecretRef,
buildFridayChannelSecretRefKey,
type FridaySupportedChannelKind,
getFridayChannelSecretFieldDescriptors,
isFridayEnvSecretRef,
parseFridayChannelsConfig,
parseFridayChannelSecretRef,
} from "#channels";
import { createFridayHub, resolveFridayHubConfig } from "#hub";
import type { FridayHubConfig } from "#hub";
import {
createFridaySecretRepository,
encryptSecret,
getMasterKey,
} from "#providers";
import {
redactFridaySkillCandidateSourceUri,
redactFridaySkillSourceText,
redactFridaySkillSourceValue,
} from "#skills/converter";
import { parseFridayHttpTrustProxyMode } from "#api";
import { resolveFridayDbPath } from "#state";
import { resolveSafePath, safeJsonParse } from "#utilities";
import Database from "better-sqlite3";
import {
createFridayLocalDaemonService,
formatFridayDaemonStatus,
} from "../daemon/friday-daemon-runtime.js";
import {
createFridayOpenClawPhaseController,
formatFridayOpenClawDoctorReport,
formatFridayOpenClawPhaseStates,
} from "../automation/openclaw-adoption/index.js";
import { runFridayCliLoop } from "./friday-cli-run-loop.js";
import { FRIDAY_VERSION } from "../lib/version.js";
import { resolveStateDir } from "../state/paths/friday-state-dir-resolver.js";
import {
runFridayCliAuthAttachCli,
runFridayCliAuthConnectAnthropicToken,
runFridayCliAuthLoginAnthropic,
runFridayCliAuthStatus,
} from "./friday-cli-auth.js";
import { cmdRuns } from "./friday-cli-runs.js";
// ─── Arg parser ───
export interface ParsedArgs {
command: "start" | "list" | "run" | "runs" | "status" | "help" | "import" | "convert" | "converters" | "pack" | "auth" | "skills" | "daemon" | "phases" | "setup" | "tui";
showHelp: boolean;
skillDirs: string[];
port: number | undefined;
skillId: string | undefined;
input: Record<string, string>;
// Converter-related fields
source: string | undefined;
from: string | undefined;
target: string | undefined;
out: string | undefined;
replace: boolean;
dryRun: boolean;
skillDir: string | undefined;
// New converter option flags
splitOperations: boolean | undefined;
skillIdPrefix: string | undefined;
noRefresh: boolean;
host: string | undefined;
// Auth-related fields
authSubcommand: string | undefined;
authTarget: string | undefined;
providerId: string | undefined;
code: string | undefined;
token: string | undefined;
binaryPath: string | undefined;
noBrowser: boolean;
skillsSubcommand: string | undefined;
template: "node" | "shell" | undefined;
initSkillId: string | undefined;
// Daemon-related fields
daemonSubcommand: "start" | "stop" | "restart" | "status" | undefined;
phasesSubcommand: "doctor" | "list" | "status" | "start-next" | "run-next" | "promote" | "resume" | "stabilize" | "closeout" | undefined;
phaseIdArg: string | undefined;
manifestPath: string | undefined;
prepareNext: boolean;
json: boolean;
apply: boolean;
runsSubcommand: "backfill-pack-context" | undefined;
}
function isHelpFlag(value: string | undefined): boolean {
return value === "--help" || value === "-h" || value === "help";
}
export function parseArgs(argv: string[]): ParsedArgs {
// Strip node + script path
const args = argv.slice(2);
const result: ParsedArgs = {
command: "help",
showHelp: false,
skillDirs: [],
port: undefined,
skillId: undefined,
input: {},
source: undefined,
from: undefined,
target: undefined,
out: undefined,
replace: false,
dryRun: false,
skillDir: undefined,
splitOperations: undefined,
skillIdPrefix: undefined,
noRefresh: false,
host: undefined,
authSubcommand: undefined,
authTarget: undefined,
providerId: undefined,
code: undefined,
token: undefined,
binaryPath: undefined,
noBrowser: false,
skillsSubcommand: undefined,
template: undefined,
initSkillId: undefined,
daemonSubcommand: undefined,
phasesSubcommand: undefined,
phaseIdArg: undefined,
manifestPath: undefined,
prepareNext: true,
json: false,
apply: false,
runsSubcommand: undefined,
};
if (args.length === 0) {
return result;
}
const cmd = args[0]!;
if (isHelpFlag(cmd)) {
result.command = "help";
result.showHelp = true;
return result;
}
const validCommands = ["start", "list", "run", "runs", "status", "import", "convert", "converters", "pack", "auth", "skills", "daemon", "phases", "setup", "tui"] as const;
type ValidCommand = (typeof validCommands)[number];
if ((validCommands as readonly string[]).includes(cmd)) {
result.command = cmd as ValidCommand;
} else {
result.command = "help";
return result;
}
result.showHelp = args.slice(1).some((arg) => isHelpFlag(arg));
let i = 1;
// For "converters" command, no additional args needed
if (cmd === "converters") {
return result;
}
// For "daemon" command, parse the subcommand
if (cmd === "daemon") {
const sub = args[1];
const validSubs = ["start", "stop", "restart", "status"] as const;
if (sub && (validSubs as readonly string[]).includes(sub)) {
result.daemonSubcommand = sub as (typeof validSubs)[number];
}
return result;
}
if (cmd === "phases") {
const sub = args[1];
const validSubs = ["doctor", "list", "status", "start-next", "run-next", "promote", "resume", "stabilize", "closeout"] as const;
if (sub && (validSubs as readonly string[]).includes(sub)) {
result.phasesSubcommand = sub as (typeof validSubs)[number];
}
if ((sub === "promote" || sub === "stabilize" || sub === "resume") && args[2] && !args[2]!.startsWith("--")) {
result.phaseIdArg = args[2]!;
i = 3;
} else {
i = 2;
}
}
if (cmd === "runs") {
const sub = args[1];
const validSubs = ["backfill-pack-context"] as const;
if (sub && (validSubs as readonly string[]).includes(sub)) {
result.runsSubcommand = sub as (typeof validSubs)[number];
}
i = 2;
}
while (i < args.length) {
const arg = args[i]!;
if (arg === "--skills-dir" && i + 1 < args.length) {
result.skillDirs.push(args[i + 1]!);
i += 2;
continue;
}
if (arg === "--port" && i + 1 < args.length) {
const parsed = parseInt(args[i + 1]!, 10);
if (!Number.isNaN(parsed)) {
result.port = parsed;
}
i += 2;
continue;
}
if (arg === "--host" && i + 1 < args.length) {
result.host = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--input" && i + 1 < args.length) {
const kv = args[i + 1]!;
const eqIdx = kv.indexOf("=");
if (eqIdx > 0) {
result.input[kv.slice(0, eqIdx)] = kv.slice(eqIdx + 1);
}
i += 2;
continue;
}
if (arg === "--from" && i + 1 < args.length) {
result.from = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--target" && i + 1 < args.length) {
result.target = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--out" && i + 1 < args.length) {
result.out = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--replace") {
result.replace = true;
i += 1;
continue;
}
if (arg === "--dry-run") {
result.dryRun = true;
i += 1;
continue;
}
if (arg === "--apply") {
result.apply = true;
i += 1;
continue;
}
if (arg === "--manifest" && i + 1 < args.length) {
result.manifestPath = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--json") {
result.json = true;
i += 1;
continue;
}
if (arg === "--split-operations") {
result.splitOperations = true;
i += 1;
continue;
}
if (arg === "--no-split-operations") {
result.splitOperations = false;
i += 1;
continue;
}
if (arg === "--skill-id-prefix" && i + 1 < args.length) {
result.skillIdPrefix = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--no-refresh") {
result.noRefresh = true;
i += 1;
continue;
}
if (arg === "--provider-id" && i + 1 < args.length) {
result.providerId = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--code" && i + 1 < args.length) {
result.code = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--token" && i + 1 < args.length) {
result.token = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--binary-path" && i + 1 < args.length) {
result.binaryPath = args[i + 1]!;
i += 2;
continue;
}
if (arg === "--no-browser") {
result.noBrowser = true;
i += 1;
continue;
}
if (arg === "--prepare-next") {
result.prepareNext = true;
i += 1;
continue;
}
if (arg === "--no-prepare-next") {
result.prepareNext = false;
i += 1;
continue;
}
if (arg === "--template" && i + 1 < args.length) {
const template = args[i + 1]!;
result.template = template === "shell" ? "shell" : template === "node" ? "node" : undefined;
i += 2;
continue;
}
// For `run`, the first positional after the command is the skill ID
if (result.command === "run" && result.skillId === undefined && !arg.startsWith("--")) {
result.skillId = arg;
i += 1;
continue;
}
// For `import` or `convert`, the first positional is the source
if ((result.command === "import" || result.command === "convert") && result.source === undefined && !arg.startsWith("--")) {
result.source = arg;
i += 1;
continue;
}
// For `pack`, the first positional is the skill dir
if (result.command === "pack" && result.skillDir === undefined && !arg.startsWith("--")) {
result.skillDir = arg;
i += 1;
continue;
}
if (result.command === "skills" && !arg.startsWith("--")) {
if (result.skillsSubcommand === undefined) {
result.skillsSubcommand = arg;
i += 1;
continue;
}
if (result.initSkillId === undefined) {
result.initSkillId = arg;
i += 1;
continue;
}
}
// For `auth`, parse subcommand and target: auth login anthropic
if (result.command === "auth" && !arg.startsWith("--")) {
if (result.authSubcommand === undefined) {
result.authSubcommand = arg;
i += 1;
continue;
}
if (result.authTarget === undefined) {
result.authTarget = arg;
i += 1;
continue;
}
}
// Unknown arg — skip
i += 1;
}
return result;
}
// ─── Usage ───
function printUsage(parsed?: ParsedArgs): void {
const command = parsed?.command;
if (command === "start") {
console.log(`
friday start [--skills-dir <path>] [--port <n>] [--host <addr>]
Boot the hub, load skills, and keep the process running.
Default host: 127.0.0.1 (loopback only). Use --host 0.0.0.0 for network access.
`.trim());
return;
}
if (command === "list") {
console.log(`
friday list [--skills-dir <path>]
Load skills and print them in a table, then exit.
`.trim());
return;
}
if (command === "run") {
console.log(`
friday run <skill-id> [--input key=value ...] [--skills-dir <path>]
Boot the hub, run a single skill, print result, then exit.
`.trim());
return;
}
if (command === "runs") {
console.log(`
friday runs backfill-pack-context [--dry-run|--apply] [--json]
Backfill historical packContext metadata onto agent runs using strict session evidence.
`.trim());
return;
}
if (command === "setup") {
console.log(`
friday setup
Interactive setup wizard — walks you through configuring:
1. LLM provider (Anthropic / OpenAI / Ollama)
2. API key (or skip for Ollama)
3. Message channels (optional)
Writes config to ~/.friday/friday.json5 and optionally starts the hub.
`.trim());
return;
}
if (command === "status") {
console.log(`
friday status
Show daemon/runtime status summary for the current state directory.
`.trim());
return;
}
if (command === "import") {
console.log(`
friday import <source> [--from <format>] [--target <path>] [--replace] [--dry-run] [--no-refresh]
Preview conversion only. Candidate staging now requires canonical approval through the lifecycle surface.
`.trim());
return;
}
if (command === "convert") {
console.log(`
friday convert <source> --out <dir> [--from <format>] [--split-operations] [--skill-id-prefix <prefix>]
Convert a skill source to Friday package(s) without installing.
`.trim());
return;
}
if (command === "converters") {
console.log(`
friday converters
List installed converters and supported source formats.
`.trim());
return;
}
if (command === "pack") {
console.log(`
friday pack <skill-dir> --out <file.tgz>
Package a native Friday skill directory into a .friday.tgz archive.
`.trim());
return;
}
if (command === "skills") {
console.log(`
friday skills init <skill-id> [--template node|shell] [--out <dir>]
Create a minimal local skill template with manifest, entrypoint, and SKILL.md.
`.trim());
return;
}
if (command === "auth") {
console.log(`
friday auth login anthropic [--provider-id <id>] [--code <code#state>] [--no-browser]
friday auth setup-token anthropic [--provider-id <id>] [--token <token>]
friday auth paste-token anthropic [--provider-id <id>] [--token <token>]
friday auth attach-cli codex|claude [--provider-id <id>] [--binary-path <path>]
friday auth status [--provider-id <id>]
Authenticate providers through OAuth, setup-token, or CLI-managed external sessions.
`.trim());
return;
}
if (command === "daemon") {
console.log(`
friday daemon start|stop|restart|status
Manage the Friday background daemon process.
`.trim());
return;
}
if (command === "phases") {
console.log(`
friday phases doctor|list|status|start-next|run-next|promote|resume|stabilize <phase-id>|closeout [--manifest <path>] [--dry-run] [--json]
Inspect and drive the OpenClaw adoption phase controller.
`.trim());
return;
}
if (command === "tui") {
console.log(`
friday tui [--host <addr>] [--port <n>]
Open the terminal dashboard against the current Friday API binding.
`.trim());
return;
}
console.log(`
friday — Friday AI automation CLI
Usage:
friday start [--skills-dir <path>] [--port <n>] [--host <addr>]
Boot the hub, load skills, and keep the process running.
Default host: 127.0.0.1 (loopback only). Use --host 0.0.0.0 for network access.
friday list [--skills-dir <path>]
Load skills and print them in a table, then exit.
friday run <skill-id> [--input key=value ...] [--skills-dir <path>]
Boot the hub, run a single skill, print result, then exit.
friday runs backfill-pack-context [--dry-run|--apply] [--json]
Backfill historical packContext metadata onto agent runs using strict session evidence.
friday status
Show hub status (running / stopped).
friday import <source> [--from <format>] [--target <path>] [--replace] [--dry-run] [--no-refresh]
Preview conversion only. Candidate staging now requires canonical approval through the lifecycle surface.
friday convert <source> --out <dir> [--from <format>] [--split-operations] [--skill-id-prefix <prefix>]
Convert a skill source to Friday package(s) without installing.
friday converters
List installed converters and supported source formats.
friday pack <skill-dir> --out <file.tgz>
Package a native Friday skill directory into a .friday.tgz archive.
friday skills init <skill-id> [--template node|shell] [--out <dir>]
Create a minimal local skill template with manifest, entrypoint, and SKILL.md.
friday daemon start|stop|restart|status
Manage the Friday background daemon process.
friday tui [--host <addr>] [--port <n>]
Open the terminal dashboard against the current Friday API binding.
friday phases doctor|list|status|start-next|run-next|promote|resume|stabilize <phase-id>|closeout
Inspect and drive the OpenClaw adoption phase controller.
friday setup
Interactive setup wizard — configure LLM provider, API keys, and channels.
friday --help
Show this help message.
Options:
--skills-dir <path> Directory to discover skills from (repeatable).
--port <n> Port for the API + UI server.
--host <addr> Bind address (default: 127.0.0.1). Use 0.0.0.0 for network access.
--input key=value Input parameter for skill execution (repeatable).
--from <format> Source format hint (auto, clawdbot-skill-md, n8n-node, openai-gpt-action, code-repo, undocumented-api, friday-package).
--target <path> Retired for \`friday import\`; direct install targets require lifecycle promotion.
--out <path> Output directory or file path.
--template <kind> Template runtime for \`friday skills init\` (node or shell).
--manifest <path> Custom phase manifest path for \`friday phases\`.
--json Emit machine-readable JSON for supported phase/status commands.
--replace Retired for \`friday import\`; replacement happens through shadow/canary promotion.
--dry-run Preview conversion; \`friday import\` is always draft-only.
--apply Apply a one-time maintenance command instead of previewing it.
--prepare-next After a successful promotion, mark the next phase as implementing.
--no-prepare-next Do not auto-unlock the next phase after promotion.
--split-operations Create one skill per OpenAPI operation (default).
--no-split-operations Combine all OpenAPI operations into one skill.
--skill-id-prefix <s> Prefix for generated skill IDs.
--no-refresh Retired for \`friday import\`; registry refresh only follows lifecycle promotion.
`.trim());
}
// ─── Commands ───
type JsonObject = Record<string, unknown>;
const channelSecretRepository = createFridaySecretRepository();
interface FridayStartupChannelsResolution {
channels?: JsonObject;
source:
| "env_override"
| "setup_state"
| "migrated_legacy_to_setup_state"
| "legacy_runtime_fallback"
| "none";
migrated: boolean;
scrubbedLegacy: boolean;
compatMode: boolean;
}
interface LegacyFridayJsonDocument {
path: string;
content: JsonObject;
}
interface FridayPersistedSetupChannel {
kind: FridaySupportedChannelKind;
enabled: boolean;
config: JsonObject;
}
function isObject(value: unknown): value is JsonObject {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function asNonEmptyString(value: unknown): string | undefined {
if (typeof value !== "string") return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function asStringArray(value: unknown): string[] | undefined {
if (!Array.isArray(value)) return undefined;
const items = value
.filter((entry): entry is string => typeof entry === "string")
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0);
return items.length > 0 ? items : undefined;
}
function asPositiveInt(value: unknown): number | undefined {
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
return undefined;
}
return value;
}
function warnLegacyChannelSkip(kind: string, reason: string): void {
console.warn(`[friday] Skip legacy channel "${kind}": ${reason}`);
}
function normalizeLegacyChannelEntry(
kind: string,
raw: JsonObject,
): JsonObject | null {
if (raw.enabled === false) return null;
switch (kind) {
case "discord": {
const token = asNonEmptyString(raw.token) ?? asNonEmptyString(raw.botToken);
if (!token) {
warnLegacyChannelSkip(kind, "missing token");
return null;
}
// P2-05: Basic format validation — accept secret refs ($ENV, secret://) and validate raw tokens.
if (!token.startsWith("secret://") && !token.startsWith("$") && (token.length < 50 || !/^[A-Za-z0-9._\-]+$/.test(token))) {
warnLegacyChannelSkip(kind, "token format appears invalid (expected 50+ chars or secret:// / $ENV reference)");
return null;
}
const instance: JsonObject = { kind: "discord", enabled: true, token };
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
const allowedChannels = asStringArray(raw.allowedChannels) ?? asStringArray(raw.allowedChats);
const intents = asPositiveInt(raw.intents);
if (allowedUsers) instance.allowedUsers = allowedUsers;
if (allowedChannels) instance.allowedChannels = allowedChannels;
if (typeof raw.requireMention === "boolean") instance.requireMention = raw.requireMention;
if (asNonEmptyString(raw.botUserId)) instance.botUserId = asNonEmptyString(raw.botUserId);
if (intents) instance.intents = intents;
return instance;
}
case "telegram": {
const botToken = asNonEmptyString(raw.botToken) ?? asNonEmptyString(raw.token);
if (!botToken) {
warnLegacyChannelSkip(kind, "missing botToken/token");
return null;
}
const instance: JsonObject = { kind: "telegram", enabled: true, botToken };
const mode = asNonEmptyString(raw.mode) ?? asNonEmptyString(raw.receiveMode);
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
const allowedChats = asStringArray(raw.allowedChats) ?? asStringArray(raw.allowedChannels);
if (mode === "webhook" || mode === "polling") instance.mode = mode;
if (asNonEmptyString(raw.webhookUrl)) instance.webhookUrl = asNonEmptyString(raw.webhookUrl);
if (allowedUsers) instance.allowedUsers = allowedUsers;
if (allowedChats) instance.allowedChats = allowedChats;
return instance;
}
case "slack": {
const botToken = asNonEmptyString(raw.botToken) ?? asNonEmptyString(raw.token);
if (!botToken) {
warnLegacyChannelSkip(kind, "missing botToken/token");
return null;
}
const instance: JsonObject = { kind: "slack", enabled: true, botToken };
const mode = asNonEmptyString(raw.mode);
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
const allowedChannels = asStringArray(raw.allowedChannels) ?? asStringArray(raw.allowedChats);
if (mode === "socket" || mode === "http") instance.mode = mode;
if (asNonEmptyString(raw.appToken)) instance.appToken = asNonEmptyString(raw.appToken);
if (asNonEmptyString(raw.signingSecret)) instance.signingSecret = asNonEmptyString(raw.signingSecret);
if (allowedUsers) instance.allowedUsers = allowedUsers;
if (allowedChannels) instance.allowedChannels = allowedChannels;
return instance;
}
case "whatsapp": {
const provider = asNonEmptyString(raw.provider) === "bridge" ? "bridge" : "cloud-api";
const instance: JsonObject = { kind: "whatsapp", enabled: true, provider };
if (provider === "bridge") {
const bridgeUrl = asNonEmptyString(raw.bridgeUrl) ?? asNonEmptyString(raw.baseUrl);
if (!bridgeUrl) {
warnLegacyChannelSkip(kind, "missing bridgeUrl/baseUrl for bridge provider");
return null;
}
instance.bridgeUrl = bridgeUrl;
} else {
const accessToken = asNonEmptyString(raw.accessToken) ?? asNonEmptyString(raw.token);
const phoneNumberId = asNonEmptyString(raw.phoneNumberId);
if (!accessToken || !phoneNumberId) {
warnLegacyChannelSkip(kind, "missing accessToken/token or phoneNumberId for cloud-api provider");
return null;
}
instance.accessToken = accessToken;
instance.phoneNumberId = phoneNumberId;
}
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
const allowedChats = asStringArray(raw.allowedChats) ?? asStringArray(raw.allowedChannels);
if (asNonEmptyString(raw.webhookVerifyToken)) {
instance.webhookVerifyToken = asNonEmptyString(raw.webhookVerifyToken);
}
if (asNonEmptyString(raw.appSecret)) instance.appSecret = asNonEmptyString(raw.appSecret);
if (allowedUsers) instance.allowedUsers = allowedUsers;
if (allowedChats) instance.allowedChats = allowedChats;
return instance;
}
case "signal": {
const account =
asNonEmptyString(raw.account) ??
asNonEmptyString(raw.phoneNumber) ??
asNonEmptyString(raw.phone);
if (!account) {
warnLegacyChannelSkip(kind, "missing account/phoneNumber/phone");
return null;
}
const instance: JsonObject = { kind: "signal", enabled: true, account };
if (asNonEmptyString(raw.baseUrl)) instance.baseUrl = asNonEmptyString(raw.baseUrl);
if (asNonEmptyString(raw.cliPath)) instance.cliPath = asNonEmptyString(raw.cliPath);
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
if (allowedUsers) instance.allowedUsers = allowedUsers;
return instance;
}
case "line": {
const channelAccessToken =
asNonEmptyString(raw.channelAccessToken) ??
asNonEmptyString(raw.accessToken) ??
asNonEmptyString(raw.token);
const channelSecret = asNonEmptyString(raw.channelSecret) ?? asNonEmptyString(raw.secret);
if (!channelAccessToken || !channelSecret) {
warnLegacyChannelSkip(kind, "missing channelAccessToken/token or channelSecret");
return null;
}
const instance: JsonObject = {
kind: "line",
enabled: true,
channelAccessToken,
channelSecret,
};
if (asNonEmptyString(raw.webhookPath)) instance.webhookPath = asNonEmptyString(raw.webhookPath);
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
const allowedGroups = asStringArray(raw.allowedGroups) ?? asStringArray(raw.allowedChats);
if (allowedUsers) instance.allowedUsers = allowedUsers;
if (allowedGroups) instance.allowedGroups = allowedGroups;
return instance;
}
case "qq": {
const appId = asNonEmptyString(raw.appId);
const appSecret = asNonEmptyString(raw.appSecret);
if (!appId || !appSecret) {
warnLegacyChannelSkip(kind, "missing appId/appSecret");
return null;
}
const instance: JsonObject = { kind: "qq", enabled: true, appId, appSecret };
if (typeof raw.sandbox === "boolean") instance.sandbox = raw.sandbox;
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
const allowedGroups = asStringArray(raw.allowedGroups) ?? asStringArray(raw.allowedChats);
if (allowedUsers) instance.allowedUsers = allowedUsers;
if (allowedGroups) instance.allowedGroups = allowedGroups;
return instance;
}
case "lark":
case "feishu": {
const appId = asNonEmptyString(raw.appId);
const appSecret = asNonEmptyString(raw.appSecret);
if (!appId || !appSecret) {
warnLegacyChannelSkip(kind, "missing appId/appSecret");
return null;
}
const instance: JsonObject = { kind, enabled: true, appId, appSecret };
const receiveMode = asNonEmptyString(raw.receiveMode) ?? asNonEmptyString(raw.mode);
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
const allowedChats = asStringArray(raw.allowedChats) ?? asStringArray(raw.allowedChannels);
if (kind === "feishu") instance.useFeishu = true;
if (receiveMode === "websocket" || receiveMode === "webhook") {
instance.receiveMode = receiveMode;
}
if (asNonEmptyString(raw.verificationToken)) instance.verificationToken = asNonEmptyString(raw.verificationToken);
if (asNonEmptyString(raw.encryptKey)) instance.encryptKey = asNonEmptyString(raw.encryptKey);
if (allowedUsers) instance.allowedUsers = allowedUsers;
if (allowedChats) instance.allowedChats = allowedChats;
return instance;
}
case "webchat": {
const instance: JsonObject = { kind: "webchat", enabled: true };
if (asNonEmptyString(raw.wsPath)) instance.wsPath = asNonEmptyString(raw.wsPath);
const allowedOrigins = asStringArray(raw.allowedOrigins);
if (allowedOrigins) instance.allowedOrigins = allowedOrigins;
const authMode = asNonEmptyString(raw.authMode);
if (authMode === "none" || authMode === "token" || authMode === "session") {
instance.authMode = authMode;
}
const maxClients = asPositiveInt(raw.maxClients);
if (maxClients) instance.maxClients = maxClients;
return instance;
}
case "irc": {
const host = asNonEmptyString(raw.host);
const nick = asNonEmptyString(raw.nick);
if (!host || !nick) {
warnLegacyChannelSkip(kind, "missing host/nick");
return null;
}
const instance: JsonObject = { kind: "irc", enabled: true, host, nick };
const port = asPositiveInt(raw.port);
if (port) instance.port = port;
if (typeof raw.tls === "boolean") instance.tls = raw.tls;
if (asNonEmptyString(raw.username)) instance.username = asNonEmptyString(raw.username);
if (asNonEmptyString(raw.password)) instance.password = asNonEmptyString(raw.password);
const channels = asStringArray(raw.channels) ?? asStringArray(raw.joinChannels);
const allowedUsers = asStringArray(raw.allowedUsers) ?? asStringArray(raw.allowFrom);
if (channels) instance.channels = channels;
if (allowedUsers) instance.allowedUsers = allowedUsers;
return instance;
}
default:
return null;
}
}
function buildChannelsFromLegacyMap(rawMap: JsonObject): JsonObject | undefined {
const instances: JsonObject[] = [];
for (const [kind, value] of Object.entries(rawMap)) {
if (!isObject(value)) continue;
const normalized = normalizeLegacyChannelEntry(kind, value);
if (normalized) instances.push(normalized);
}
if (instances.length === 0) return undefined;
return { enabled: true, instances };
}
function loadChannelsFromEnv(
env: NodeJS.ProcessEnv = process.env,
): JsonObject | undefined {
const raw = env.FRIDAY_CHANNELS_JSON;
if (!raw || raw.trim() === "") return undefined;
try {
const parsed = JSON.parse(raw) as unknown;
if (!isObject(parsed)) return undefined;
if (Array.isArray(parsed.instances) || typeof parsed.enabled === "boolean") {
return parsed;
}
return buildChannelsFromLegacyMap(parsed);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.warn(`[friday] Failed to parse FRIDAY_CHANNELS_JSON: ${message}`);
return undefined;
}
}
function readLegacyFridayJsonDocument(
env: NodeJS.ProcessEnv = process.env,
): LegacyFridayJsonDocument | undefined {
const home = env.HOME;
if (!home || home.trim() === "") return undefined;
const legacyPath = join(home, ".friday", "friday.json");
if (!existsSync(legacyPath)) return undefined;
try {
const parsed = JSON.parse(readFileSync(legacyPath, "utf8")) as unknown;
if (!isObject(parsed)) return undefined;
return {
path: legacyPath,
content: parsed,
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
console.warn(`[friday] Failed to parse ${legacyPath}: ${message}`);
return undefined;
}
}
function loadChannelsFromLegacyFridayJson(
env: NodeJS.ProcessEnv = process.env,
): JsonObject | undefined {
const legacy = readLegacyFridayJsonDocument(env);
if (!legacy || !isObject(legacy.content.channels)) {
return undefined;
}
return buildChannelsFromLegacyMap(legacy.content.channels);
}
function scrubLegacyChannelsBlock(legacy: LegacyFridayJsonDocument): boolean {
if (!Object.prototype.hasOwnProperty.call(legacy.content, "channels")) {
return false;
}
delete legacy.content.channels;
writeFileSync(legacy.path, `${JSON.stringify(legacy.content, null, 2)}\n`, "utf8");
return true;
}