-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontroller.ts
More file actions
3955 lines (3823 loc) · 135 KB
/
controller.ts
File metadata and controls
3955 lines (3823 loc) · 135 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
import { execFile } from "node:child_process";
import { existsSync, promises as fs } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import type {
PluginConversationBindingResolvedEvent,
OpenClawPluginApi,
OpenClawPluginService,
PluginCommandContext,
PluginInteractiveButtons,
PluginInteractiveDiscordHandlerContext,
PluginInteractiveTelegramHandlerContext,
ReplyPayload,
ConversationRef,
} from "openclaw/plugin-sdk";
import {
buildDiscordComponentMessage,
editDiscordComponentMessage,
registerBuiltDiscordComponentMessage,
type DiscordComponentMessageSpec,
resolveDiscordAccount,
} from "openclaw/plugin-sdk/discord";
import { resolvePluginSettings, resolveWorkspaceDir } from "./config.js";
import { CodexAppServerClient, type ActiveCodexRun, isMissingThreadError } from "./client.js";
import {
formatAccountSummary,
formatBinding,
formatBoundThreadSummary,
formatCodexPlanAttachmentFallback,
formatCodexPlanAttachmentSummary,
formatCodexPlanInlineText,
formatCodexReviewFindingMessage,
formatCodexStatusText,
formatExperimentalFeatures,
formatMcpServers,
formatModels,
parseCodexReviewOutput,
formatProjectPickerIntro,
formatReviewCompletion,
formatSkills,
formatThreadButtonLabel,
formatThreadPickerIntro,
formatThreadState,
formatTurnCompletion,
} from "./format.js";
import type { AccountSummary, CollaborationMode, TurnTerminalError } from "./types.js";
import {
buildPendingQuestionnaireResponse,
formatPendingQuestionnairePrompt,
questionnaireCurrentQuestionHasAnswer,
questionnaireIsComplete,
requestToken,
} from "./pending-input.js";
import {
buildConversationKey,
buildPluginSessionKey,
PluginStateStore,
} from "./state.js";
import {
parseThreadSelectionArgs,
selectThreadFromMatches,
} from "./thread-selection.js";
import {
filterThreadsByProjectName,
getProjectName,
listProjects,
paginateItems,
} from "./thread-picker.js";
import {
INTERACTIVE_NAMESPACE,
PLUGIN_ID,
type CallbackAction,
type ConversationTarget,
type PendingInputState,
type StoredBinding,
type StoredPendingBind,
type StoredPendingRequest,
} from "./types.js";
type ActiveRunRecord = {
conversation: ConversationTarget;
workspaceDir: string;
mode: "default" | "plan" | "review";
handle: ActiveCodexRun;
};
const execFileAsync = promisify(execFile);
const require = createRequire(import.meta.url);
const PLUGIN_VERSION = (() => {
try {
const packageJson = require("../package.json") as { version?: unknown };
return typeof packageJson.version === "string" && packageJson.version.trim()
? packageJson.version.trim()
: "unknown";
} catch {
return "unknown";
}
})();
type PickerRender = {
text: string;
buttons: PluginInteractiveButtons | undefined;
};
type PickerResponders = {
conversation: ConversationTarget;
clear: () => Promise<void>;
reply: (text: string) => Promise<void>;
editPicker: (picker: PickerRender) => Promise<void>;
requestConversationBinding?: (
params?: { summary?: string },
) => Promise<
| { status: "bound" }
| { status: "pending"; reply: ReplyPayload }
| { status: "error"; message: string }
>;
};
type ScopedBindingApi = {
requestConversationBinding?: (
params?: { summary?: string },
) => Promise<
| { status: "bound" }
| { status: "pending"; reply: ReplyPayload }
| { status: "error"; message: string }
>;
detachConversationBinding?: () => Promise<{ removed: boolean }>;
getCurrentConversationBinding?: () => Promise<unknown>;
};
type HydratedBindingResult = {
binding: StoredBinding;
pendingBind?: StoredPendingBind;
};
type PlanDelivery = {
summaryText: string;
attachmentPath?: string;
attachmentFallbackText?: string;
};
type DeliveredMessageRef =
| {
provider: "telegram";
messageId: string;
chatId: string;
}
| {
provider: "discord";
messageId: string;
channelId: string;
};
function asRecord(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function asScopedBindingApi(value: object): ScopedBindingApi {
return value as ScopedBindingApi;
}
function isTelegramChannel(channel: string): boolean {
return channel.trim().toLowerCase() === "telegram";
}
function isDiscordChannel(channel: string): boolean {
return channel.trim().toLowerCase() === "discord";
}
function buildPlainReply(text: string): ReplyPayload {
return { text };
}
function normalizeTelegramChatId(raw: string | undefined): string | undefined {
if (!raw) {
return undefined;
}
const trimmed = raw.trim();
if (!trimmed) {
return undefined;
}
if (trimmed.startsWith("telegram:")) {
return trimmed.slice("telegram:".length);
}
return trimmed;
}
function normalizeDiscordConversationId(raw: string | undefined): string | undefined {
if (!raw) {
return undefined;
}
const trimmed = raw.trim();
if (!trimmed) {
return undefined;
}
if (trimmed.startsWith("discord:channel:")) {
return `channel:${trimmed.slice("discord:channel:".length)}`;
}
if (trimmed.startsWith("discord:group:")) {
return `channel:${trimmed.slice("discord:group:".length)}`;
}
if (trimmed.startsWith("discord:user:")) {
return `user:${trimmed.slice("discord:user:".length)}`;
}
if (trimmed.startsWith("discord:")) {
return `user:${trimmed.slice("discord:".length)}`;
}
if (trimmed.startsWith("slash:")) {
return undefined;
}
return trimmed;
}
function denormalizeDiscordConversationId(raw: string | undefined): string | undefined {
if (!raw) {
return undefined;
}
const trimmed = raw.trim();
if (!trimmed) {
return undefined;
}
if (trimmed.startsWith("channel:")) {
return trimmed.slice("channel:".length);
}
if (trimmed.startsWith("user:")) {
return trimmed.slice("user:".length);
}
if (trimmed.startsWith("discord:channel:")) {
return trimmed.slice("discord:channel:".length);
}
if (trimmed.startsWith("discord:user:")) {
return trimmed.slice("discord:user:".length);
}
if (trimmed.startsWith("discord:")) {
return trimmed.slice("discord:".length);
}
return trimmed;
}
function normalizeDiscordInteractiveConversationId(params: {
conversationId?: string;
guildId?: string;
}): string | undefined {
const normalized = normalizeDiscordConversationId(params.conversationId);
if (!normalized) {
return undefined;
}
if (normalized.includes(":")) {
return normalized;
}
return params.guildId ? `channel:${normalized}` : `user:${normalized}`;
}
function toConversationTargetFromCommand(ctx: PluginCommandContext): ConversationTarget | null {
if (isTelegramChannel(ctx.channel)) {
const chatId = normalizeTelegramChatId(ctx.to ?? ctx.from ?? ctx.senderId);
if (!chatId) {
return null;
}
return {
channel: "telegram",
accountId: ctx.accountId ?? "default",
conversationId:
typeof ctx.messageThreadId === "number" ? `${chatId}:topic:${ctx.messageThreadId}` : chatId,
parentConversationId: typeof ctx.messageThreadId === "number" ? chatId : undefined,
threadId: ctx.messageThreadId,
};
}
if (isDiscordChannel(ctx.channel)) {
const conversationId = normalizeDiscordConversationId(ctx.from ?? ctx.to);
if (!conversationId) {
return null;
}
return {
channel: "discord",
accountId: ctx.accountId ?? "default",
conversationId,
};
}
return null;
}
function toConversationTargetFromInbound(event: {
channel: string;
accountId?: string;
conversationId?: string;
parentConversationId?: string;
threadId?: string | number;
isGroup?: boolean;
metadata?: Record<string, unknown>;
}): ConversationTarget | null {
if (!event.accountId || !event.conversationId) {
return null;
}
const channel = event.channel.trim().toLowerCase();
const conversationIdRaw = event.conversationId?.trim();
const conversationId =
channel === "discord"
? (() => {
const normalized = normalizeDiscordConversationId(conversationIdRaw);
if (!normalized) {
return undefined;
}
if (normalized.includes(":")) {
return normalized;
}
const guildId =
typeof event.metadata?.guildId === "string" ? event.metadata.guildId.trim() : "";
const isChannel = Boolean(event.parentConversationId?.trim() || event.isGroup || guildId);
return `${isChannel ? "channel" : "user"}:${normalized}`;
})()
: event.conversationId;
const parentConversationId =
channel === "discord"
? normalizeDiscordConversationId(event.parentConversationId)
: event.parentConversationId;
if (!conversationId) {
return null;
}
return {
channel,
accountId: event.accountId,
conversationId,
parentConversationId,
threadId:
typeof event.threadId === "number"
? event.threadId
: typeof event.threadId === "string"
? Number.isFinite(Number(event.threadId))
? Number(event.threadId)
: undefined
: undefined,
};
}
function buildReplyWithButtons(text: string, buttons?: PluginInteractiveButtons): ReplyPayload {
return buttons
? {
text,
channelData: {
telegram: {
buttons,
},
},
}
: { text };
}
function extractReplyButtons(reply: ReplyPayload): PluginInteractiveButtons | undefined {
const telegramButtons = asRecord(reply.channelData?.telegram)?.buttons;
if (Array.isArray(telegramButtons)) {
return telegramButtons as PluginInteractiveButtons;
}
const interactive = asRecord((reply as ReplyPayload & { interactive?: unknown }).interactive);
const blocks = Array.isArray(interactive?.blocks) ? interactive.blocks : [];
const rows: PluginInteractiveButtons = [];
for (const block of blocks) {
const blockRecord = asRecord(block);
if (blockRecord?.type !== "buttons") {
continue;
}
const buttons = Array.isArray(blockRecord.buttons) ? blockRecord.buttons : [];
const row = buttons
.map((button) => {
const buttonRecord = asRecord(button);
if (!buttonRecord) {
return null;
}
const text = typeof buttonRecord?.label === "string" ? buttonRecord.label.trim() : "";
const callbackData =
typeof buttonRecord?.value === "string" ? buttonRecord.value.trim() : "";
if (!text || !callbackData) {
return null;
}
const style: "danger" | "success" | "primary" | undefined =
buttonRecord.style === "danger" ||
buttonRecord.style === "success" ||
buttonRecord.style === "primary"
? buttonRecord.style
: undefined;
return {
text,
callback_data: callbackData,
style,
};
})
.filter((button): button is NonNullable<typeof button> => Boolean(button));
if (row.length > 0) {
rows.push(row);
}
}
return rows.length > 0 ? rows : undefined;
}
function parseFastAction(
argsText: string,
): "toggle" | "on" | "off" | "status" | { error: string } {
const normalized = argsText.trim().toLowerCase();
if (!normalized) {
return "toggle";
}
if (normalized === "on" || normalized === "off" || normalized === "status") {
return normalized;
}
return { error: "Usage: /cas_fast [on|off|status]" };
}
function normalizeServiceTier(value: string | undefined | null): string | undefined {
const normalized = value?.trim().toLowerCase();
return normalized ? normalized : undefined;
}
function formatFastModeValue(value: string | undefined): string {
const normalized = normalizeServiceTier(value);
if (!normalized || normalized === "default" || normalized === "auto") {
return "off";
}
if (normalized === "fast" || normalized === "priority") {
return "on";
}
return normalized;
}
const PLAN_PROGRESS_DELAY_MS = 12_000;
const REVIEW_PROGRESS_DELAY_MS = 12_000;
const COMPACT_PROGRESS_DELAY_MS = 12_000;
const COMPACT_PROGRESS_INTERVAL_MS = 15_000;
const PLAN_INLINE_TEXT_LIMIT = 2600;
function isTransportClosedMessage(error: unknown): boolean {
const text = error instanceof Error ? error.message : String(error);
const normalized = text.trim().toLowerCase();
return (
normalized.includes("stdio not connected") ||
normalized.includes("websocket not connected") ||
normalized.includes("stdio closed") ||
normalized.includes("websocket closed") ||
normalized.includes("socket closed") ||
normalized.includes("broken pipe")
);
}
function formatFailureText(kind: "plan" | "review" | "compact", error: unknown): string {
if (isTransportClosedMessage(error)) {
return `Codex ${kind} failed because the App Server connection closed. Please retry the command or rejoin the thread.`;
}
const message = error instanceof Error ? error.message : String(error);
return `Codex ${kind} failed: ${message}`;
}
function formatInterruptedText(kind: "plan" | "review"): string {
return `Codex ${kind} was interrupted before it finished.`;
}
function formatContextUsageText(usage: { totalTokens?: number; contextWindow?: number }): string | undefined {
if (typeof usage.totalTokens !== "number") {
return undefined;
}
const total = usage.totalTokens >= 1000 ? `${(usage.totalTokens / 1000).toFixed(usage.totalTokens >= 10000 ? 0 : 1)}k` : String(usage.totalTokens);
const context =
typeof usage.contextWindow === "number"
? usage.contextWindow >= 1000
? `${(usage.contextWindow / 1000).toFixed(usage.contextWindow >= 10000 ? 0 : 1)}k`
: String(usage.contextWindow)
: "?";
const percent =
typeof usage.contextWindow === "number" && usage.contextWindow > 0
? Math.round((usage.totalTokens / usage.contextWindow) * 100)
: undefined;
return `${total} / ${context} tokens used${typeof percent === "number" ? ` (${percent}% full)` : ""}`;
}
function normalizeOptionDashes(text: string): string {
return text
.replace(/(^|\s)[\u2010-\u2015\u2212](?=\S)/g, "$1--")
.replace(/[\u2010-\u2015\u2212]/g, "-");
}
function parsePlanArgs(args: string): { mode: "off" } | { mode: "start"; prompt: string } {
const normalized = normalizeOptionDashes(args).trim();
if (!normalized) {
return { mode: "start", prompt: "" };
}
if (normalized === "off" || normalized === "--off") {
return { mode: "off" };
}
return { mode: "start", prompt: args.trim() };
}
function parseRenameArgs(args: string): { syncTopic: boolean; name: string } | null {
const tokens = normalizeOptionDashes(args)
.split(/\s+/)
.map((token) => token.trim())
.filter(Boolean);
let syncTopic = false;
const nameParts: string[] = [];
for (const token of tokens) {
if (token === "--sync") {
syncTopic = true;
continue;
}
nameParts.push(token);
}
const name = nameParts.join(" ").trim();
if (!syncTopic && !name) {
return null;
}
return { syncTopic, name };
}
function buildResumeTopicName(params: { title?: string; projectKey?: string; threadId: string }): string | undefined {
const threadName = params.title?.trim() || params.threadId.trim();
if (!threadName) {
return undefined;
}
const projectName = path.basename(params.projectKey?.replace(/[\\/]+$/, "").trim() || "");
const normalizedThreadName = normalizeThreadTitleProjectSuffix(threadName, projectName);
return projectName ? `${normalizedThreadName} (${projectName})` : normalizedThreadName;
}
function buildThreadOnlyName(params: { title?: string; projectKey?: string; threadId: string }): string | undefined {
const threadName = params.title?.trim() || params.threadId.trim();
const projectName = path.basename(params.projectKey?.replace(/[\\/]+$/, "").trim() || "");
return normalizeThreadTitleProjectSuffix(threadName, projectName) || undefined;
}
function normalizeThreadTitleProjectSuffix(threadName: string, projectName?: string): string {
let normalized = threadName.trim();
if (!normalized) {
return normalized;
}
// Collapse duplicated trailing parenthetical groups from repeated sync renames.
normalized = normalized.replace(/(?: (\(([^()]+)\)))(?: \(\2\))+$/, " $1").trim();
if (projectName) {
const repeatedProjectSuffix = new RegExp(`(?: \\(${escapeRegExp(projectName)}\\))+$`);
normalized = normalized.replace(repeatedProjectSuffix, "").trim();
}
return normalized;
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function truncateDiscordLabel(text: string, maxChars = 80): string {
const trimmed = text.trim();
if (trimmed.length <= maxChars) {
return trimmed;
}
return `${trimmed.slice(0, Math.max(1, maxChars - 1)).trimEnd()}…`;
}
function summarizeTextForLog(text: string, maxChars = 120): string {
const normalized = text.replace(/\s+/g, " ").trim();
if (!normalized) {
return "<empty>";
}
if (normalized.length <= maxChars) {
return normalized;
}
return `${normalized.slice(0, Math.max(1, maxChars - 1)).trimEnd()}…`;
}
export class CodexPluginController {
private readonly settings;
private readonly client;
private readonly activeRuns = new Map<string, ActiveRunRecord>();
private readonly threadChangesCache = new Map<string, Promise<boolean | undefined>>();
private readonly store;
private serviceWorkspaceDir?: string;
private lastRuntimeConfig?: unknown;
private started = false;
constructor(private readonly api: OpenClawPluginApi) {
this.settings = resolvePluginSettings(this.api.pluginConfig);
this.client = new CodexAppServerClient(this.settings, this.api.logger);
this.store = new PluginStateStore(this.api.runtime.state.resolveStateDir());
}
createService(): OpenClawPluginService {
return {
id: `${PLUGIN_ID}-service`,
start: async (ctx) => {
this.serviceWorkspaceDir = ctx.workspaceDir;
await this.start();
},
stop: async () => {
await this.stop();
},
};
}
async start(): Promise<void> {
if (this.started) {
return;
}
await this.store.load();
await this.client.logStartupProbe().catch(() => undefined);
this.started = true;
}
async stop(): Promise<void> {
if (!this.started) {
return;
}
for (const active of this.activeRuns.values()) {
await active.handle.interrupt().catch(() => undefined);
}
this.activeRuns.clear();
await this.client.close().catch(() => undefined);
this.started = false;
}
async handleConversationBindingResolved(
event: PluginConversationBindingResolvedEvent,
): Promise<void> {
await this.start();
const conversation: ConversationTarget = {
channel: event.request.conversation.channel,
accountId: event.request.conversation.accountId,
conversationId: event.request.conversation.conversationId,
parentConversationId: event.request.conversation.parentConversationId,
threadId: (() => {
if (typeof event.request.conversation.threadId === "number") {
return event.request.conversation.threadId;
}
if (typeof event.request.conversation.threadId !== "string") {
return undefined;
}
const normalized = Number(event.request.conversation.threadId.trim());
return Number.isFinite(normalized) ? normalized : undefined;
})(),
};
const pending = this.store.getPendingBind(conversation);
if (!pending) {
this.api.logger.debug?.(
`codex binding approved without pending local bind conversation=${conversation.conversationId}`,
);
return;
}
if (event.status === "denied") {
await this.store.removePendingBind(conversation);
return;
}
await this.bindConversation(conversation, {
threadId: pending.threadId,
workspaceDir: pending.workspaceDir,
threadTitle: pending.threadTitle,
});
if (pending.syncTopic) {
const syncedName = buildResumeTopicName({
title: pending.threadTitle,
projectKey: pending.workspaceDir,
threadId: pending.threadId,
});
if (syncedName) {
await this.renameConversationIfSupported(conversation, syncedName);
}
}
if (pending.notifyBound) {
await this.sendBoundConversationSummary(conversation);
}
}
private formatConversationForLog(conversation: ConversationTarget): string {
return [
`channel=${conversation.channel}`,
`account=${conversation.accountId ?? "<none>"}`,
`conversation=${conversation.conversationId}`,
`parent=${conversation.parentConversationId ?? "<none>"}`,
`thread=${conversation.threadId == null ? "<none>" : String(conversation.threadId)}`,
].join(" ");
}
async handleInboundClaim(event: {
content: string;
channel: string;
accountId?: string;
conversationId?: string;
parentConversationId?: string;
threadId?: string | number;
isGroup?: boolean;
metadata?: Record<string, unknown>;
}): Promise<{ handled: boolean }> {
try {
if (!this.settings.enabled) {
return { handled: false };
}
await this.start();
const conversation = toConversationTargetFromInbound(event);
if (!conversation) {
return { handled: false };
}
const activeKey = buildConversationKey(conversation);
const active = this.activeRuns.get(activeKey);
if (active) {
if (active.mode === "plan") {
this.api.logger.debug?.(
`codex inbound claim restarting active plan run conversation=${conversation.conversationId}`,
);
this.activeRuns.delete(activeKey);
await active.handle.interrupt().catch(() => undefined);
} else {
const pending = this.store.getPendingRequestByConversation(conversation);
if (pending?.state.questionnaire && !event.content.trim().startsWith("/")) {
const handled = await this.handlePendingQuestionnaireFreeformAnswer(
conversation,
pending,
active.handle,
event.content,
);
if (handled) {
return { handled: true };
}
}
try {
const handled = await active.handle.queueMessage(event.content);
if (handled) {
return { handled: true };
}
this.api.logger.warn(
`codex inbound claim could not enqueue message for active run; restarting thread conversation=${conversation.conversationId}`,
);
} catch (error) {
this.api.logger.warn(
`codex inbound claim active run enqueue failed; restarting thread conversation=${conversation.conversationId}: ${String(error)}`,
);
}
this.activeRuns.delete(activeKey);
await active.handle.interrupt().catch(() => undefined);
}
}
const existingBinding = this.store.getBinding(conversation);
const hydratedBinding = existingBinding ? null : await this.hydrateApprovedBinding(conversation);
const resolvedBinding = existingBinding ?? hydratedBinding?.binding ?? null;
this.api.logger.debug?.(
`codex inbound claim channel=${conversation.channel} account=${conversation.accountId} conversation=${conversation.conversationId} parent=${conversation.parentConversationId ?? "<none>"} local=${resolvedBinding ? "yes" : "no"}`,
);
if (!resolvedBinding) {
return { handled: false };
}
if (hydratedBinding?.pendingBind?.syncTopic) {
const syncedName = buildResumeTopicName({
title: hydratedBinding.pendingBind.threadTitle,
projectKey: hydratedBinding.pendingBind.workspaceDir,
threadId: hydratedBinding.pendingBind.threadId,
});
if (syncedName) {
await this.renameConversationIfSupported(conversation, syncedName);
}
}
this.api.logger.debug?.(
`codex inbound claim starting turn ${this.formatConversationForLog(conversation)} workspace=${resolvedBinding.workspaceDir} thread=${resolvedBinding.threadId} prompt="${summarizeTextForLog(event.content)}"`,
);
await this.startTurn({
conversation,
binding: resolvedBinding,
workspaceDir: resolvedBinding.workspaceDir,
prompt: event.content,
reason: "inbound",
});
this.api.logger.debug?.(
`codex inbound claim turn accepted ${this.formatConversationForLog(conversation)}`,
);
return { handled: true };
} catch (error) {
const detail =
error instanceof Error ? `${error.message}\n${error.stack ?? ""}`.trim() : String(error);
this.api.logger.error(`codex inbound claim failed: ${detail}`);
throw error;
}
}
async handleTelegramInteractive(ctx: PluginInteractiveTelegramHandlerContext): Promise<void> {
await this.start();
const bindingApi = asScopedBindingApi(ctx);
const callback = this.store.getCallback(ctx.callback.payload);
if (!callback) {
await ctx.respond.reply({ text: "That Codex action expired. Please retry the command." });
return;
}
await this.dispatchCallbackAction(callback, {
conversation: {
channel: "telegram",
accountId: ctx.accountId,
conversationId: ctx.conversationId,
parentConversationId: ctx.parentConversationId,
threadId: ctx.threadId,
},
clear: async () => {
await ctx.respond.clearButtons().catch(() => undefined);
},
reply: async (text) => {
await ctx.respond.reply({ text });
},
editPicker: async (picker) => {
await ctx.respond.editMessage({
text: picker.text,
buttons: picker.buttons,
});
},
requestConversationBinding: async (params) => {
const requestConversationBinding = bindingApi.requestConversationBinding;
if (!requestConversationBinding) {
return { status: "error", message: "Conversation binding is unavailable." } as const;
}
const result = await requestConversationBinding(params);
if (result.status === "pending") {
const buttons = extractReplyButtons(result.reply);
await ctx.respond.reply({
text: result.reply.text ?? "Bind approval requested.",
buttons,
});
return { status: "pending", reply: result.reply } as const;
}
return result;
},
});
}
async handleDiscordInteractive(ctx: PluginInteractiveDiscordHandlerContext): Promise<void> {
await this.start();
const bindingApi = asScopedBindingApi(ctx);
const callback = this.store.getCallback(ctx.interaction.payload);
if (!callback) {
await ctx.respond.reply({ text: "That Codex action expired. Please retry the command.", ephemeral: true });
return;
}
const callbackConversationId =
callback.conversation.channel === "discord"
? normalizeDiscordConversationId(callback.conversation.conversationId)
: undefined;
const conversationId =
callbackConversationId ??
normalizeDiscordInteractiveConversationId({
conversationId: ctx.conversationId,
guildId: ctx.guildId,
});
if (!conversationId) {
await ctx.respond.reply({
text: "I couldn’t determine the Discord conversation for that action. Please retry the command.",
ephemeral: true,
});
return;
}
const conversation: ConversationTarget = {
channel: "discord",
accountId: callback.conversation.accountId ?? ctx.accountId,
conversationId,
parentConversationId: callback.conversation.parentConversationId ?? ctx.parentConversationId,
};
let interactionSettled = false;
try {
if (callback.kind === "resume-thread") {
await ctx.respond
.acknowledge()
.then(() => {
interactionSettled = true;
})
.catch(() => undefined);
}
await this.dispatchCallbackAction(callback, {
conversation,
clear: async () => {
const messageId = ctx.interaction.messageId?.trim();
if ((callback.kind === "pending-input" || callback.kind === "pending-questionnaire") && messageId) {
await ctx.respond
.acknowledge()
.then(() => {
interactionSettled = true;
})
.catch(() => undefined);
const completionText =
callback.kind === "pending-questionnaire"
? "Recorded your answers and sent them to Codex."
: "Sent to Codex.";
await editDiscordComponentMessage(
conversation.conversationId,
messageId,
{
text: completionText,
},
{
accountId: conversation.accountId,
},
).catch((error) => {
this.api.logger.warn(
`codex discord ${callback.kind} clear failed conversation=${conversationId}: ${String(error)}`,
);
});
return;
}
try {
await ctx.respond.clearComponents();
interactionSettled = true;
} catch {
await ctx.respond
.acknowledge()
.then(() => {
interactionSettled = true;
})
.catch(() => undefined);
}
},
reply: async (text) => {
if (interactionSettled) {
await ctx.respond.followUp({ text, ephemeral: true });
return;
}
await ctx.respond.reply({ text, ephemeral: true });
interactionSettled = true;
},
editPicker: async (picker) => {
this.api.logger.debug(
`codex discord picker refresh conversation=${conversationId} rows=${picker.buttons?.length ?? 0}`,
);
const messageId = ctx.interaction.messageId?.trim();
const builtPicker = this.buildDiscordPickerMessage(picker);
try {
await ctx.respond.editMessage({
components: builtPicker.components,
});
interactionSettled = true;
if (messageId) {
registerBuiltDiscordComponentMessage({
buildResult: builtPicker,
messageId,
});
}
return;
} catch (error) {
const detail = String(error);
this.api.logger.warn(
`codex discord picker edit failed conversation=${conversationId}: ${detail}`,
);
if (messageId) {
if (!detail.includes("already been acknowledged")) {
await ctx.respond
.acknowledge()
.then(() => {
interactionSettled = true;
})
.catch(() => undefined);
}
await editDiscordComponentMessage(
conversation.conversationId,
messageId,
this.buildDiscordPickerSpec(picker),
{
accountId: conversation.accountId,
},
);
return;
}
}
await this.sendDiscordPicker(conversation, picker);
},
requestConversationBinding: async (params) => {
const requestConversationBinding = bindingApi.requestConversationBinding;
if (!requestConversationBinding) {
return { status: "error", message: "Conversation binding is unavailable." } as const;
}
const result = await requestConversationBinding(params);
if (result.status === "pending") {
const buttons = extractReplyButtons(result.reply);
await this.sendDiscordPicker(conversation, {
text: result.reply.text ?? "Bind approval requested.",
buttons,
});
const originalMessageId = ctx.interaction.messageId?.trim();
if (callback.kind === "resume-thread" && originalMessageId) {
await editDiscordComponentMessage(
conversation.conversationId,
originalMessageId,
{
text: "Binding approval requested below.",
},
{
accountId: conversation.accountId,
},
).catch(() => undefined);
}
return { status: "pending", reply: result.reply } as const;
}
return result;
},
});
} catch (error) {
const detail = error instanceof Error ? error.stack ?? error.message : String(error);
this.api.logger.warn(`codex discord interactive failed conversation=${conversationId}: ${detail}`);
const errorReply = {
text: "Codex hit an error handling that action. Please retry the command.",
ephemeral: true,
} as const;
const sendError = interactionSettled ? ctx.respond.followUp(errorReply) : ctx.respond.reply(errorReply);
await sendError.catch(() => undefined);