@indigoai-us/hq-cli 5.68.2 → 5.70.0
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/CHANGELOG.md +30 -0
- package/dist/commands/channels.js +6 -3
- package/dist/commands/dm.d.ts +76 -0
- package/dist/commands/dm.js +317 -3
- package/dist/commands/outposts.d.ts +16 -1
- package/dist/commands/outposts.js +230 -3
- package/dist/main.js +6 -2
- package/dist/utils/cli-telemetry.d.ts +6 -0
- package/dist/utils/cli-telemetry.js +60 -0
- package/dist/utils/cognito-session.d.ts +2 -1
- package/dist/utils/cognito-session.js +5 -2
- package/dist/utils/vault-api.d.ts +1 -0
- package/dist/utils/vault-api.js +3 -2
- package/package.json +1 -1
- package/src/commands/channels.ts +4 -1
- package/src/commands/dm.test.ts +265 -0
- package/src/commands/dm.ts +449 -1
- package/src/commands/outposts-self-deploy.test.ts +243 -0
- package/src/commands/outposts.ts +346 -1
- package/src/main.ts +5 -0
- package/src/utils/cli-telemetry.test.ts +153 -0
- package/src/utils/cli-telemetry.ts +61 -0
- package/src/utils/cognito-session.ts +4 -0
- package/src/utils/vault-api.test.ts +18 -0
- package/src/utils/vault-api.ts +2 -0
package/src/commands/dm.ts
CHANGED
|
@@ -702,11 +702,422 @@ async function runDmRequests(): Promise<void> {
|
|
|
702
702
|
}
|
|
703
703
|
}
|
|
704
704
|
|
|
705
|
+
// ---------------------------------------------------------------------------
|
|
706
|
+
// Receive side — reading DMs (inbox, 1:1 thread, channel/group history).
|
|
707
|
+
// The backend read endpoints (GET /v1/notify/inbox, GET /v1/notify/thread,
|
|
708
|
+
// GET /v1/notify/channels/{id}/messages) already back the HQ Sync menubar; the
|
|
709
|
+
// commands below expose the same reads from the CLI.
|
|
710
|
+
// ---------------------------------------------------------------------------
|
|
711
|
+
|
|
712
|
+
/** One incoming DM as returned by GET /v1/notify/inbox. */
|
|
713
|
+
export interface DmInboxEvent {
|
|
714
|
+
eventId: string;
|
|
715
|
+
fromPersonUid?: string;
|
|
716
|
+
fromEmail?: string;
|
|
717
|
+
fromDisplayName?: string;
|
|
718
|
+
body: string;
|
|
719
|
+
createdAt: string;
|
|
720
|
+
details?: string;
|
|
721
|
+
prompt?: string;
|
|
722
|
+
acknowledgedAt?: string;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
/** One message in a 1:1 thread as returned by GET /v1/notify/thread. */
|
|
726
|
+
export interface DmThreadMessage {
|
|
727
|
+
eventId: string;
|
|
728
|
+
fromPersonUid?: string;
|
|
729
|
+
fromEmail?: string;
|
|
730
|
+
fromDisplayName?: string;
|
|
731
|
+
body: string;
|
|
732
|
+
createdAt: string;
|
|
733
|
+
direction: "in" | "out";
|
|
734
|
+
details?: string;
|
|
735
|
+
prompt?: string;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** One channel/group message from GET /v1/notify/channels/{id}/messages. */
|
|
739
|
+
export interface ChannelMessageItem {
|
|
740
|
+
eventId?: string;
|
|
741
|
+
messageId?: string;
|
|
742
|
+
fromPersonUid?: string;
|
|
743
|
+
fromEmail?: string;
|
|
744
|
+
fromDisplayName?: string;
|
|
745
|
+
body: string;
|
|
746
|
+
createdAt: string;
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
/**
|
|
750
|
+
* Human label for a message sender — display name, else email, else uid. Pure →
|
|
751
|
+
* unit-testable.
|
|
752
|
+
*/
|
|
753
|
+
export function senderLabel(m: {
|
|
754
|
+
fromDisplayName?: string;
|
|
755
|
+
fromEmail?: string;
|
|
756
|
+
fromPersonUid?: string;
|
|
757
|
+
}): string {
|
|
758
|
+
return (
|
|
759
|
+
m.fromDisplayName?.trim() ||
|
|
760
|
+
m.fromEmail?.trim() ||
|
|
761
|
+
m.fromPersonUid?.trim() ||
|
|
762
|
+
"unknown"
|
|
763
|
+
);
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* Render an ISO timestamp as a compact relative age ("3m ago", "2h ago",
|
|
768
|
+
* "5d ago"), falling back to a YYYY-MM-DD date for anything older than a week or
|
|
769
|
+
* an unparseable input. `nowMs` is injected so the formatting is unit-testable.
|
|
770
|
+
* Pure.
|
|
771
|
+
*/
|
|
772
|
+
export function formatRelativeTime(iso: string, nowMs: number): string {
|
|
773
|
+
const t = new Date(iso).getTime();
|
|
774
|
+
if (isNaN(t)) return iso;
|
|
775
|
+
const diff = nowMs - t;
|
|
776
|
+
if (diff < 60_000) return "just now";
|
|
777
|
+
const mins = Math.floor(diff / 60_000);
|
|
778
|
+
if (mins < 60) return `${mins}m ago`;
|
|
779
|
+
const hours = Math.floor(mins / 60);
|
|
780
|
+
if (hours < 24) return `${hours}h ago`;
|
|
781
|
+
const days = Math.floor(hours / 24);
|
|
782
|
+
if (days < 7) return `${days}d ago`;
|
|
783
|
+
return new Date(t).toISOString().slice(0, 10);
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** A DM is unread until the recipient acks it. Pure. */
|
|
787
|
+
export function isUnread(e: { acknowledgedAt?: string }): boolean {
|
|
788
|
+
return !e.acknowledgedAt;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** Event ids of the unread messages in a fetched inbox page. Pure. */
|
|
792
|
+
export function unreadEventIds(events: DmInboxEvent[]): string[] {
|
|
793
|
+
return events
|
|
794
|
+
.filter(isUnread)
|
|
795
|
+
.map((e) => e.eventId)
|
|
796
|
+
.filter((id): id is string => typeof id === "string" && id.length > 0);
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
/** Keep only the unread messages. Pure. */
|
|
800
|
+
export function filterUnread(events: DmInboxEvent[]): DmInboxEvent[] {
|
|
801
|
+
return events.filter(isUnread);
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
/**
|
|
805
|
+
* Collapse a message body to a single trimmed line for list rendering, capped
|
|
806
|
+
* so one row stays readable. Pure.
|
|
807
|
+
*/
|
|
808
|
+
export function firstLine(body: string, max = 240): string {
|
|
809
|
+
const oneLine = (body ?? "").replace(/\s+/g, " ").trim();
|
|
810
|
+
if (oneLine.length <= max) return oneLine;
|
|
811
|
+
return oneLine.slice(0, max - 1) + "…";
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/**
|
|
815
|
+
* Turn a person identifier into the query the thread endpoint expects. An email
|
|
816
|
+
* rides `withEmail` (server resolves it); a prs_/agt_ uid rides `withPersonUid`.
|
|
817
|
+
* A bare name is rejected — resolve it first with `hq people resolve`. Pure →
|
|
818
|
+
* unit-testable. Throws with a user-facing message on an invalid identifier.
|
|
819
|
+
*/
|
|
820
|
+
export function buildThreadQuery(identifier: string): Record<string, string> {
|
|
821
|
+
const rcpt = detectRecipient(identifier);
|
|
822
|
+
if (!rcpt) {
|
|
823
|
+
throw new Error(
|
|
824
|
+
`Invalid person '${identifier}': pass an email or a personUid/agentUid (prs_… / agt_…). Resolve a name first with \`hq people resolve\`.`,
|
|
825
|
+
);
|
|
826
|
+
}
|
|
827
|
+
if (rcpt.toEmail) return { withEmail: rcpt.toEmail };
|
|
828
|
+
return { withPersonUid: rcpt.toPersonUid! };
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** Render one inbox row (marker · age · sender · first line of body). */
|
|
832
|
+
export function formatInboxEvent(e: DmInboxEvent, nowMs: number): string {
|
|
833
|
+
const marker = isUnread(e) ? chalk.cyan("●") : " ";
|
|
834
|
+
const when = chalk.dim(formatRelativeTime(e.createdAt, nowMs));
|
|
835
|
+
const who = chalk.bold(senderLabel(e));
|
|
836
|
+
const email =
|
|
837
|
+
e.fromEmail && e.fromDisplayName ? chalk.dim(` <${e.fromEmail}>`) : "";
|
|
838
|
+
return `${marker} ${when} ${who}${email}\n ${firstLine(e.body)}`;
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/** Render one 1:1 thread line, tagged by direction. */
|
|
842
|
+
export function formatThreadMessage(m: DmThreadMessage, nowMs: number): string {
|
|
843
|
+
const arrow = m.direction === "out" ? chalk.dim("→") : chalk.cyan("←");
|
|
844
|
+
const who = m.direction === "out" ? "you" : senderLabel(m);
|
|
845
|
+
const when = chalk.dim(formatRelativeTime(m.createdAt, nowMs));
|
|
846
|
+
return `${arrow} ${chalk.bold(who)} ${when}\n ${firstLine(m.body)}`;
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/** Render one channel/group message line. */
|
|
850
|
+
export function formatChannelMessage(
|
|
851
|
+
m: ChannelMessageItem,
|
|
852
|
+
nowMs: number,
|
|
853
|
+
): string {
|
|
854
|
+
const who = chalk.bold(senderLabel(m));
|
|
855
|
+
const when = chalk.dim(formatRelativeTime(m.createdAt, nowMs));
|
|
856
|
+
return `${who} ${when}\n ${firstLine(m.body)}`;
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
/** POST /v1/notify/inbox/ack — idempotently mark messages read. */
|
|
860
|
+
async function ackEvents(token: string, eventIds: string[]): Promise<void> {
|
|
861
|
+
if (eventIds.length === 0) return;
|
|
862
|
+
const res = await vaultApiFetch({
|
|
863
|
+
token,
|
|
864
|
+
path: "/v1/notify/inbox/ack",
|
|
865
|
+
method: "POST",
|
|
866
|
+
body: { eventIds },
|
|
867
|
+
});
|
|
868
|
+
if (!res.ok) {
|
|
869
|
+
const err = (await res.json().catch(() => ({}))) as Record<string, string>;
|
|
870
|
+
throw new Error(
|
|
871
|
+
friendlyDmError(res.status, err.code, err.error ?? err.message ?? res.statusText),
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
interface DmInboxOpts {
|
|
877
|
+
limit?: string;
|
|
878
|
+
unread?: boolean;
|
|
879
|
+
markRead?: boolean;
|
|
880
|
+
json?: boolean;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
async function runDmInbox(opts: DmInboxOpts): Promise<void> {
|
|
884
|
+
try {
|
|
885
|
+
const token = await ensureCognitoToken();
|
|
886
|
+
const query: Record<string, string> = {};
|
|
887
|
+
if (opts.limit) query.limit = opts.limit;
|
|
888
|
+
const res = await vaultApiFetch({ token, path: "/v1/notify/inbox", query });
|
|
889
|
+
if (!res.ok) {
|
|
890
|
+
const err = (await res.json().catch(() => ({}))) as Record<string, string>;
|
|
891
|
+
console.error(
|
|
892
|
+
chalk.red(
|
|
893
|
+
friendlyDmError(res.status, err.code, err.error ?? err.message ?? res.statusText),
|
|
894
|
+
),
|
|
895
|
+
);
|
|
896
|
+
process.exit(1);
|
|
897
|
+
}
|
|
898
|
+
const data = (await res.json()) as {
|
|
899
|
+
events?: DmInboxEvent[];
|
|
900
|
+
nextCursor?: string;
|
|
901
|
+
};
|
|
902
|
+
const all = data.events ?? [];
|
|
903
|
+
const shown = opts.unread ? filterUnread(all) : all;
|
|
904
|
+
|
|
905
|
+
if (opts.json) {
|
|
906
|
+
console.log(JSON.stringify(shown, null, 2));
|
|
907
|
+
} else if (shown.length === 0) {
|
|
908
|
+
console.log(
|
|
909
|
+
chalk.dim(opts.unread ? "No unread messages." : "No messages yet."),
|
|
910
|
+
);
|
|
911
|
+
} else {
|
|
912
|
+
const unreadCount = filterUnread(all).length;
|
|
913
|
+
const suffix = unreadCount > 0 ? ` (${unreadCount} unread)` : "";
|
|
914
|
+
console.log(
|
|
915
|
+
chalk.green(
|
|
916
|
+
`${shown.length} message${shown.length === 1 ? "" : "s"}${suffix}:`,
|
|
917
|
+
),
|
|
918
|
+
);
|
|
919
|
+
const now = Date.now();
|
|
920
|
+
for (const e of shown) console.log(`\n${formatInboxEvent(e, now)}`);
|
|
921
|
+
if (data.nextCursor) {
|
|
922
|
+
console.log(
|
|
923
|
+
chalk.dim("\nMore messages available — raise --limit to see them."),
|
|
924
|
+
);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
// Ack every unread message on the fetched page (not just the filtered view).
|
|
929
|
+
if (opts.markRead) {
|
|
930
|
+
const ids = unreadEventIds(all);
|
|
931
|
+
await ackEvents(token, ids);
|
|
932
|
+
if (!opts.json && ids.length > 0) {
|
|
933
|
+
console.log(chalk.dim(`\nMarked ${ids.length} read.`));
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
} catch (err) {
|
|
937
|
+
console.error(
|
|
938
|
+
chalk.red("Error:"),
|
|
939
|
+
err instanceof Error ? err.message : String(err),
|
|
940
|
+
);
|
|
941
|
+
process.exit(1);
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
interface DmThreadOpts {
|
|
946
|
+
limit?: string;
|
|
947
|
+
ack?: boolean;
|
|
948
|
+
json?: boolean;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
async function runDmThread(
|
|
952
|
+
identifier: string,
|
|
953
|
+
opts: DmThreadOpts,
|
|
954
|
+
): Promise<void> {
|
|
955
|
+
try {
|
|
956
|
+
const query = buildThreadQuery(identifier);
|
|
957
|
+
if (opts.limit) query.limit = opts.limit;
|
|
958
|
+
const token = await ensureCognitoToken();
|
|
959
|
+
const res = await vaultApiFetch({
|
|
960
|
+
token,
|
|
961
|
+
path: "/v1/notify/thread",
|
|
962
|
+
query,
|
|
963
|
+
});
|
|
964
|
+
if (!res.ok) {
|
|
965
|
+
const err = (await res.json().catch(() => ({}))) as Record<string, string>;
|
|
966
|
+
console.error(
|
|
967
|
+
chalk.red(
|
|
968
|
+
friendlyDmError(res.status, err.code, err.error ?? err.message ?? res.statusText),
|
|
969
|
+
),
|
|
970
|
+
);
|
|
971
|
+
process.exit(1);
|
|
972
|
+
}
|
|
973
|
+
const data = (await res.json()) as { messages?: DmThreadMessage[] };
|
|
974
|
+
const messages = data.messages ?? [];
|
|
975
|
+
// The server returns newest-first; read a conversation oldest-first.
|
|
976
|
+
const ordered = [...messages].reverse();
|
|
977
|
+
|
|
978
|
+
if (opts.json) {
|
|
979
|
+
console.log(JSON.stringify(ordered, null, 2));
|
|
980
|
+
} else if (ordered.length === 0) {
|
|
981
|
+
console.log(chalk.dim(`No messages with ${identifier} yet.`));
|
|
982
|
+
} else {
|
|
983
|
+
console.log(
|
|
984
|
+
chalk.green(
|
|
985
|
+
`${ordered.length} message${ordered.length === 1 ? "" : "s"} with ${identifier}:`,
|
|
986
|
+
),
|
|
987
|
+
);
|
|
988
|
+
const now = Date.now();
|
|
989
|
+
for (const m of ordered) console.log(`\n${formatThreadMessage(m, now)}`);
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// Mark the incoming messages read unless the caller opted out. Best-effort:
|
|
993
|
+
// a read is a side effect, not the point of the command, so an ack failure
|
|
994
|
+
// is surfaced but does not fail the read.
|
|
995
|
+
if (opts.ack !== false) {
|
|
996
|
+
const inIds = messages
|
|
997
|
+
.filter((m) => m.direction === "in")
|
|
998
|
+
.map((m) => m.eventId)
|
|
999
|
+
.filter((id): id is string => typeof id === "string" && id.length > 0);
|
|
1000
|
+
try {
|
|
1001
|
+
await ackEvents(token, inIds);
|
|
1002
|
+
} catch (ackErr) {
|
|
1003
|
+
console.error(
|
|
1004
|
+
chalk.dim(
|
|
1005
|
+
`(could not mark read: ${
|
|
1006
|
+
ackErr instanceof Error ? ackErr.message : String(ackErr)
|
|
1007
|
+
})`,
|
|
1008
|
+
),
|
|
1009
|
+
);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
} catch (err) {
|
|
1013
|
+
console.error(
|
|
1014
|
+
chalk.red("Error:"),
|
|
1015
|
+
err instanceof Error ? err.message : String(err),
|
|
1016
|
+
);
|
|
1017
|
+
process.exit(1);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
/**
|
|
1022
|
+
* Resolve a `hq dm channel <target>` argument to a channelId. Accepts a channel
|
|
1023
|
+
* name (bare or `#name`) resolved against the caller's channels, or a raw
|
|
1024
|
+
* channelId (the only way to address an unnamed group DM — copy it from
|
|
1025
|
+
* `hq channels`). Throws a user-facing message when nothing matches or a name is
|
|
1026
|
+
* ambiguous.
|
|
1027
|
+
*/
|
|
1028
|
+
async function resolveChannelId(token: string, target: string): Promise<string> {
|
|
1029
|
+
const raw = target.trim().replace(/^#/, "");
|
|
1030
|
+
if (!raw) throw new Error("A channel name or id is required.");
|
|
1031
|
+
const channels = await fetchChannels(token);
|
|
1032
|
+
const named = matchChannelsByName(channels, raw);
|
|
1033
|
+
if (named.length === 1) return named[0].channelId;
|
|
1034
|
+
if (named.length > 1) {
|
|
1035
|
+
throw new Error(
|
|
1036
|
+
`'${raw}' matches ${named.length} channels — pass the channel id instead (see \`hq channels\`).`,
|
|
1037
|
+
);
|
|
1038
|
+
}
|
|
1039
|
+
const byId = channels.find((c) => c.channelId === raw);
|
|
1040
|
+
if (byId) return byId.channelId;
|
|
1041
|
+
throw new Error(
|
|
1042
|
+
`No channel named or with id '${raw}' — run \`hq channels\` to see yours.`,
|
|
1043
|
+
);
|
|
1044
|
+
}
|
|
1045
|
+
|
|
1046
|
+
interface DmChannelOpts {
|
|
1047
|
+
limit?: string;
|
|
1048
|
+
markRead?: boolean;
|
|
1049
|
+
json?: boolean;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
async function runDmChannel(
|
|
1053
|
+
target: string,
|
|
1054
|
+
opts: DmChannelOpts,
|
|
1055
|
+
): Promise<void> {
|
|
1056
|
+
try {
|
|
1057
|
+
const token = await ensureCognitoToken();
|
|
1058
|
+
const channelId = await resolveChannelId(token, target);
|
|
1059
|
+
const query: Record<string, string> = {};
|
|
1060
|
+
if (opts.limit) query.limit = opts.limit;
|
|
1061
|
+
const res = await vaultApiFetch({
|
|
1062
|
+
token,
|
|
1063
|
+
path: `/v1/notify/channels/${encodeURIComponent(channelId)}/messages`,
|
|
1064
|
+
query,
|
|
1065
|
+
});
|
|
1066
|
+
if (!res.ok) {
|
|
1067
|
+
const err = (await res.json().catch(() => ({}))) as Record<string, string>;
|
|
1068
|
+
console.error(
|
|
1069
|
+
chalk.red(
|
|
1070
|
+
friendlyDmError(res.status, err.code, err.error ?? err.message ?? res.statusText),
|
|
1071
|
+
),
|
|
1072
|
+
);
|
|
1073
|
+
process.exit(1);
|
|
1074
|
+
}
|
|
1075
|
+
const data = (await res.json()) as { messages?: ChannelMessageItem[] };
|
|
1076
|
+
const messages = data.messages ?? [];
|
|
1077
|
+
const ordered = [...messages].reverse(); // oldest-first for reading
|
|
1078
|
+
|
|
1079
|
+
if (opts.json) {
|
|
1080
|
+
console.log(JSON.stringify(ordered, null, 2));
|
|
1081
|
+
} else if (ordered.length === 0) {
|
|
1082
|
+
console.log(chalk.dim("No messages in this channel yet."));
|
|
1083
|
+
} else {
|
|
1084
|
+
console.log(
|
|
1085
|
+
chalk.green(
|
|
1086
|
+
`${ordered.length} message${ordered.length === 1 ? "" : "s"}:`,
|
|
1087
|
+
),
|
|
1088
|
+
);
|
|
1089
|
+
const now = Date.now();
|
|
1090
|
+
for (const m of ordered) console.log(`\n${formatChannelMessage(m, now)}`);
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
if (opts.markRead) {
|
|
1094
|
+
// messages are newest-first from the server; advance the read cursor to
|
|
1095
|
+
// the newest one we saw.
|
|
1096
|
+
const newest = messages[0]?.createdAt;
|
|
1097
|
+
const readRes = await vaultApiFetch({
|
|
1098
|
+
token,
|
|
1099
|
+
path: `/v1/notify/channels/${encodeURIComponent(channelId)}/read`,
|
|
1100
|
+
method: "POST",
|
|
1101
|
+
body: newest ? { lastReadAt: newest } : {},
|
|
1102
|
+
});
|
|
1103
|
+
if (!opts.json && readRes.ok) {
|
|
1104
|
+
console.log(chalk.dim("\nMarked read."));
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
} catch (err) {
|
|
1108
|
+
console.error(
|
|
1109
|
+
chalk.red("Error:"),
|
|
1110
|
+
err instanceof Error ? err.message : String(err),
|
|
1111
|
+
);
|
|
1112
|
+
process.exit(1);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
|
|
705
1116
|
export function registerDmCommand(program: Command): void {
|
|
706
1117
|
const dm = program
|
|
707
1118
|
.command("dm")
|
|
708
1119
|
.description(
|
|
709
|
-
"Send
|
|
1120
|
+
"Send and read direct messages, and manage connection requests.",
|
|
710
1121
|
);
|
|
711
1122
|
|
|
712
1123
|
dm
|
|
@@ -746,6 +1157,43 @@ export function registerDmCommand(program: Command): void {
|
|
|
746
1157
|
},
|
|
747
1158
|
);
|
|
748
1159
|
|
|
1160
|
+
dm
|
|
1161
|
+
.command("inbox")
|
|
1162
|
+
.description("List your recent incoming direct messages.")
|
|
1163
|
+
.option("--limit <n>", "Max messages to fetch (server-capped)")
|
|
1164
|
+
.option("--unread", "Show only unread messages")
|
|
1165
|
+
.option("--mark-read", "Mark the fetched messages as read after listing")
|
|
1166
|
+
.option("--json", "Output raw JSON instead of a list")
|
|
1167
|
+
.action(async (opts: DmInboxOpts) => {
|
|
1168
|
+
await runDmInbox(opts);
|
|
1169
|
+
});
|
|
1170
|
+
|
|
1171
|
+
dm
|
|
1172
|
+
.command("thread <person>")
|
|
1173
|
+
.alias("read")
|
|
1174
|
+
.description(
|
|
1175
|
+
"Show your two-way conversation with a person (email, personUid, or agentUid). Reads oldest-first and marks their messages read unless --no-ack.",
|
|
1176
|
+
)
|
|
1177
|
+
.option("--limit <n>", "Max messages to fetch (server-capped)")
|
|
1178
|
+
.option("--no-ack", "Do not mark the incoming messages as read")
|
|
1179
|
+
.option("--json", "Output raw JSON instead of a transcript")
|
|
1180
|
+
.action(async (person: string, opts: DmThreadOpts) => {
|
|
1181
|
+
await runDmThread(person, opts);
|
|
1182
|
+
});
|
|
1183
|
+
|
|
1184
|
+
dm
|
|
1185
|
+
.command("channel <target>")
|
|
1186
|
+
.alias("history")
|
|
1187
|
+
.description(
|
|
1188
|
+
"Show recent messages in a DM channel or group DM — by name, #name, or a channel id from `hq channels`.",
|
|
1189
|
+
)
|
|
1190
|
+
.option("--limit <n>", "Max messages to fetch (server-capped)")
|
|
1191
|
+
.option("--mark-read", "Advance your read marker to the newest message")
|
|
1192
|
+
.option("--json", "Output raw JSON instead of a transcript")
|
|
1193
|
+
.action(async (target: string, opts: DmChannelOpts) => {
|
|
1194
|
+
await runDmChannel(target, opts);
|
|
1195
|
+
});
|
|
1196
|
+
|
|
749
1197
|
dm
|
|
750
1198
|
.command("requests")
|
|
751
1199
|
.description("List your pending incoming connection requests.")
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { Command } from "commander";
|
|
2
|
+
import {
|
|
3
|
+
afterEach,
|
|
4
|
+
beforeEach,
|
|
5
|
+
describe,
|
|
6
|
+
expect,
|
|
7
|
+
it,
|
|
8
|
+
vi,
|
|
9
|
+
type MockInstance,
|
|
10
|
+
} from "vitest";
|
|
11
|
+
import {
|
|
12
|
+
registerOutpostsCommand,
|
|
13
|
+
type SelfDeployDependencies,
|
|
14
|
+
} from "./outposts.js";
|
|
15
|
+
|
|
16
|
+
type SpawnCall = {
|
|
17
|
+
command: string;
|
|
18
|
+
args: string[];
|
|
19
|
+
options: Parameters<SelfDeployDependencies["spawnSync"]>[2];
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const AL2023 = 'ID="amzn"\nVERSION_ID="2023"\n';
|
|
23
|
+
const SECRET = "refresh-token-that-must-never-be-printed";
|
|
24
|
+
|
|
25
|
+
function successfulSpawn(stdout = "") {
|
|
26
|
+
return {
|
|
27
|
+
status: 0,
|
|
28
|
+
stdout,
|
|
29
|
+
stderr: "",
|
|
30
|
+
error: undefined,
|
|
31
|
+
} as ReturnType<SelfDeployDependencies["spawnSync"]>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function selfDeployDependencies(input: {
|
|
35
|
+
osRelease?: string;
|
|
36
|
+
uname?: string;
|
|
37
|
+
systemd?: boolean;
|
|
38
|
+
sudo?: boolean;
|
|
39
|
+
session?: { refreshToken?: string; idToken?: string } | undefined;
|
|
40
|
+
stdinTty?: boolean;
|
|
41
|
+
uid?: number;
|
|
42
|
+
} = {}): { deps: Partial<SelfDeployDependencies>; calls: SpawnCall[] } {
|
|
43
|
+
const calls: SpawnCall[] = [];
|
|
44
|
+
const deps: Partial<SelfDeployDependencies> = {
|
|
45
|
+
readTextFile: () => input.osRelease ?? AL2023,
|
|
46
|
+
loadCachedTokens: () => input.session ?? { refreshToken: SECRET },
|
|
47
|
+
getUid: () => input.uid ?? 1000,
|
|
48
|
+
isStdinTty: () => input.stdinTty ?? true,
|
|
49
|
+
confirm: async () => true,
|
|
50
|
+
defaultHqRoot: () => "/home/ec2-user/hq",
|
|
51
|
+
invokingUser: () => "ec2-user",
|
|
52
|
+
spawnSync: ((command, args, options) => {
|
|
53
|
+
calls.push({ command, args, options });
|
|
54
|
+
if (command === "uname") return successfulSpawn(input.uname ?? "x86_64\n");
|
|
55
|
+
if (command === "systemctl" && args[0] === "--version") {
|
|
56
|
+
return input.systemd === false
|
|
57
|
+
? { ...successfulSpawn(), status: 1 }
|
|
58
|
+
: successfulSpawn("systemd 252\n");
|
|
59
|
+
}
|
|
60
|
+
if (command === "sudo" && args[0] === "-n") {
|
|
61
|
+
return input.sudo === false ? { ...successfulSpawn(), status: 1 } : successfulSpawn();
|
|
62
|
+
}
|
|
63
|
+
return successfulSpawn();
|
|
64
|
+
}) as SelfDeployDependencies["spawnSync"],
|
|
65
|
+
};
|
|
66
|
+
return { deps, calls };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function buildProgram(deps: Partial<SelfDeployDependencies>): Command {
|
|
70
|
+
const program = new Command();
|
|
71
|
+
program.name("hq").exitOverride();
|
|
72
|
+
registerOutpostsCommand(program, deps);
|
|
73
|
+
return program;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function run(
|
|
77
|
+
deps: Partial<SelfDeployDependencies>,
|
|
78
|
+
args: string[],
|
|
79
|
+
): Promise<void> {
|
|
80
|
+
await buildProgram(deps).parseAsync(["node", "hq", ...args]);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let exitSpy: MockInstance<typeof process.exit>;
|
|
84
|
+
let logSpy: MockInstance<typeof console.log>;
|
|
85
|
+
let errorSpy: MockInstance<typeof console.error>;
|
|
86
|
+
let fetchSpy: MockInstance<typeof fetch>;
|
|
87
|
+
|
|
88
|
+
beforeEach(() => {
|
|
89
|
+
exitSpy = vi.spyOn(process, "exit").mockImplementation((code?: number) => {
|
|
90
|
+
throw new Error(`process.exit(${code})`);
|
|
91
|
+
}) as unknown as MockInstance<typeof process.exit>;
|
|
92
|
+
logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
|
93
|
+
errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
94
|
+
fetchSpy = vi.spyOn(globalThis, "fetch");
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
afterEach(() => {
|
|
98
|
+
vi.restoreAllMocks();
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
function printed(): string {
|
|
102
|
+
return [
|
|
103
|
+
...logSpy.mock.calls.map((call) => call.map(String).join(" ")),
|
|
104
|
+
...errorSpy.mock.calls.map((call) => call.map(String).join(" ")),
|
|
105
|
+
].join("\n");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function installedCommands(calls: SpawnCall[]): SpawnCall[] {
|
|
109
|
+
return calls.filter(
|
|
110
|
+
(call) =>
|
|
111
|
+
call.command === "hq" ||
|
|
112
|
+
(call.command === "sudo" &&
|
|
113
|
+
["tee", "chmod", "systemctl"].includes(call.args[0] ?? "")),
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
describe("hq outposts self-deploy", () => {
|
|
118
|
+
it("is hidden from outposts help but remains invokable", async () => {
|
|
119
|
+
const { deps, calls } = selfDeployDependencies();
|
|
120
|
+
const program = buildProgram(deps);
|
|
121
|
+
const outposts = program.commands.find((command) => command.name() === "outposts");
|
|
122
|
+
|
|
123
|
+
expect(outposts?.helpInformation()).not.toContain("self-deploy");
|
|
124
|
+
|
|
125
|
+
await run(deps, ["outposts", "self-deploy", "--yes"]);
|
|
126
|
+
expect(calls).toContainEqual(
|
|
127
|
+
expect.objectContaining({
|
|
128
|
+
command: "hq",
|
|
129
|
+
args: ["rescue", "--hq-root", "/home/ec2-user/hq", "--yes"],
|
|
130
|
+
}),
|
|
131
|
+
);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it("rejects non-Amazon Linux 2023 before installing anything", async () => {
|
|
135
|
+
const { deps, calls } = selfDeployDependencies({
|
|
136
|
+
osRelease: 'ID="ubuntu"\nVERSION_ID="24.04"\n',
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
await expect(run(deps, ["outposts", "self-deploy", "--yes"])).rejects.toThrow(
|
|
140
|
+
"process.exit(1)",
|
|
141
|
+
);
|
|
142
|
+
expect(printed()).toContain("Amazon Linux 2023 x86_64");
|
|
143
|
+
expect(installedCommands(calls)).toEqual([]);
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
it("rejects a host without systemd before installing anything", async () => {
|
|
147
|
+
const { deps, calls } = selfDeployDependencies({ systemd: false });
|
|
148
|
+
|
|
149
|
+
await expect(run(deps, ["outposts", "self-deploy", "--yes"])).rejects.toThrow(
|
|
150
|
+
"process.exit(1)",
|
|
151
|
+
);
|
|
152
|
+
expect(printed()).toContain("systemd is required");
|
|
153
|
+
expect(installedCommands(calls)).toEqual([]);
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("requires an existing hq login before installing anything", async () => {
|
|
157
|
+
const { deps, calls } = selfDeployDependencies({ session: undefined });
|
|
158
|
+
deps.loadCachedTokens = () => undefined;
|
|
159
|
+
|
|
160
|
+
await expect(run(deps, ["outposts", "self-deploy", "--yes"])).rejects.toThrow(
|
|
161
|
+
"process.exit(1)",
|
|
162
|
+
);
|
|
163
|
+
expect(printed()).toContain("hq login");
|
|
164
|
+
expect(installedCommands(calls)).toEqual([]);
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
it("aborts without a TTY or --yes before running install commands", async () => {
|
|
168
|
+
const idToken = `header.${Buffer.from(JSON.stringify({ email: "person@example.com" })).toString("base64url")}.signature`;
|
|
169
|
+
const { deps, calls } = selfDeployDependencies({
|
|
170
|
+
stdinTty: false,
|
|
171
|
+
session: { refreshToken: SECRET, idToken },
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
await expect(run(deps, ["outposts", "self-deploy"])).rejects.toThrow(
|
|
175
|
+
"process.exit(1)",
|
|
176
|
+
);
|
|
177
|
+
expect(printed()).toContain("HQ identity: person@example.com");
|
|
178
|
+
expect(printed()).toContain("SELF-HOSTED HQ outpost");
|
|
179
|
+
expect(printed()).toMatch(/pass --yes/i);
|
|
180
|
+
expect(installedCommands(calls)).toEqual([]);
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
it("installs the all-company watch sync service locally with --yes", async () => {
|
|
184
|
+
const { deps, calls } = selfDeployDependencies();
|
|
185
|
+
|
|
186
|
+
await run(deps, ["outposts", "self-deploy", "--yes"]);
|
|
187
|
+
|
|
188
|
+
expect(calls).toContainEqual(
|
|
189
|
+
expect.objectContaining({
|
|
190
|
+
command: "hq",
|
|
191
|
+
args: ["rescue", "--hq-root", "/home/ec2-user/hq", "--yes"],
|
|
192
|
+
}),
|
|
193
|
+
);
|
|
194
|
+
const serviceWrite = calls.find(
|
|
195
|
+
(call) =>
|
|
196
|
+
call.command === "sudo" &&
|
|
197
|
+
call.args[0] === "tee" &&
|
|
198
|
+
call.args[1] === "/etc/systemd/system/outpost-sync.service",
|
|
199
|
+
);
|
|
200
|
+
const serviceContents = String(
|
|
201
|
+
(serviceWrite?.options as { input?: unknown } | undefined)?.input,
|
|
202
|
+
);
|
|
203
|
+
expect(serviceContents).toContain("User=ec2-user");
|
|
204
|
+
expect(serviceContents).toContain("WorkingDirectory=\"/home/ec2-user/hq\"");
|
|
205
|
+
expect(serviceContents).toContain("ExecStart=/usr/local/bin/outpost-sync.sh");
|
|
206
|
+
expect(serviceContents).toContain("Restart=always");
|
|
207
|
+
|
|
208
|
+
const scriptWrite = calls.find(
|
|
209
|
+
(call) =>
|
|
210
|
+
call.command === "sudo" &&
|
|
211
|
+
call.args[0] === "tee" &&
|
|
212
|
+
call.args[1] === "/usr/local/bin/outpost-sync.sh",
|
|
213
|
+
);
|
|
214
|
+
const scriptContents = String(
|
|
215
|
+
(scriptWrite?.options as { input?: unknown } | undefined)?.input,
|
|
216
|
+
);
|
|
217
|
+
expect(scriptContents).toContain("hq auth refresh");
|
|
218
|
+
expect(scriptContents).toContain("hq-sync-runner");
|
|
219
|
+
expect(scriptContents).toContain("--companies");
|
|
220
|
+
expect(scriptContents).toContain("--watch");
|
|
221
|
+
expect(scriptContents).toContain("--event-push");
|
|
222
|
+
expect(scriptContents).toContain("--poll-remote-ms 60000");
|
|
223
|
+
expect(calls).toContainEqual(
|
|
224
|
+
expect.objectContaining({
|
|
225
|
+
command: "sudo",
|
|
226
|
+
args: ["systemctl", "enable", "--now", "outpost-sync.service"],
|
|
227
|
+
}),
|
|
228
|
+
);
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it("never exposes session secrets or makes hq-pro requests", async () => {
|
|
232
|
+
const { deps, calls } = selfDeployDependencies({
|
|
233
|
+
session: { refreshToken: SECRET },
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
await run(deps, ["outposts", "self-deploy", "--yes"]);
|
|
237
|
+
|
|
238
|
+
expect(JSON.stringify(calls)).not.toContain(SECRET);
|
|
239
|
+
expect(printed()).not.toContain(SECRET);
|
|
240
|
+
expect(fetchSpy).not.toHaveBeenCalled();
|
|
241
|
+
expect(exitSpy).not.toHaveBeenCalled();
|
|
242
|
+
});
|
|
243
|
+
});
|