@indigoai-us/hq-cli 5.69.0 → 5.71.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.
@@ -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 a direct message and manage connection requests.",
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.")