-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpending-input.ts
More file actions
859 lines (825 loc) · 25 KB
/
pending-input.ts
File metadata and controls
859 lines (825 loc) · 25 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
import crypto from "node:crypto";
import type {
PendingApprovalDecision,
PendingInputAction,
PendingInputState,
PendingQuestionnaireAnswer,
PendingQuestionnaireQuestion,
PendingQuestionnaireState,
} from "./types.js";
const MAX_PENDING_REQUEST_TEXT_CHARS = 1200;
const MAX_PENDING_PROMPT_TEXT_CHARS = 2200;
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function pickString(
record: Record<string, unknown> | undefined,
keys: readonly string[],
): string | undefined {
for (const key of keys) {
const value = record?.[key];
if (typeof value !== "string") {
continue;
}
const trimmed = value.trim();
if (trimmed) {
return trimmed;
}
}
return undefined;
}
function findFirstStringByKeys(
value: unknown,
keys: readonly string[],
depth = 0,
): string | undefined {
if (depth > 5) {
return undefined;
}
if (Array.isArray(value)) {
for (const item of value) {
const match = findFirstStringByKeys(item, keys, depth + 1);
if (match) {
return match;
}
}
return undefined;
}
const record = asRecord(value);
if (!record) {
return undefined;
}
const direct = pickString(record, keys);
if (direct) {
return direct;
}
for (const nested of Object.values(record)) {
const match = findFirstStringByKeys(nested, keys, depth + 1);
if (match) {
return match;
}
}
return undefined;
}
function isFileChangeApprovalMethod(methodLower: string): boolean {
return methodLower.includes("filechange/requestapproval");
}
function isCommandApprovalMethod(methodLower: string): boolean {
return methodLower.includes("commandexecution/requestapproval") || methodLower === "turn/requestapproval";
}
function normalizeApprovalDecision(value: string): PendingApprovalDecision | null {
const normalized = value.trim().toLowerCase();
switch (normalized) {
case "accept":
case "approve":
case "allow":
return "accept";
case "acceptwithexecpolicyamendment":
case "acceptforsession":
case "approveforsession":
case "allowforsession":
return "acceptForSession";
case "decline":
case "deny":
case "reject":
return "decline";
case "cancel":
case "abort":
case "stop":
return "cancel";
default:
return null;
}
}
function humanizeApprovalDecision(
decision: PendingApprovalDecision,
sessionPrefix?: string,
): string {
switch (decision) {
case "accept":
return "Approve Once";
case "acceptForSession":
return sessionPrefix ? `Approve for Session (${sessionPrefix})` : "Approve for Session";
case "decline":
return "Decline";
case "cancel":
return "Cancel";
}
}
function extractSessionPrefix(value: unknown): string | undefined {
const record = asRecord(value);
return (
findFirstStringByKeys(record?.proposedExecpolicyAmendment, [
"prefix",
"commandPrefix",
"prefixToApprove",
"allowedPrefix",
"command_prefix",
]) ??
findFirstStringByKeys(record?.sessionApproval, [
"prefix",
"commandPrefix",
"prefixToApprove",
"allowedPrefix",
"command_prefix",
]) ??
findFirstStringByKeys(record?.execPolicyAmendment, [
"prefix",
"commandPrefix",
"prefixToApprove",
"allowedPrefix",
"command_prefix",
])
);
}
function buildApprovalActionsFromDecisions(value: unknown): PendingInputAction[] {
const record = asRecord(value);
const rawDecisions = record?.availableDecisions ?? record?.decisions;
if (!Array.isArray(rawDecisions)) {
return [];
}
const actions: PendingInputAction[] = [];
for (const entry of rawDecisions) {
if (typeof entry === "string") {
const decision = normalizeApprovalDecision(entry);
if (!decision) {
continue;
}
actions.push({
kind: "approval",
decision,
responseDecision: entry,
label: humanizeApprovalDecision(decision),
});
continue;
}
const decisionRecord = asRecord(entry);
const decisionValue =
pickString(decisionRecord, ["decision", "value", "name", "id", "action"]) ?? "";
const decision = normalizeApprovalDecision(decisionValue);
if (!decision) {
continue;
}
const sessionPrefix =
decision === "acceptForSession" ? extractSessionPrefix(decisionRecord) : undefined;
const proposedExecpolicyAmendment =
decision === "acceptForSession"
? (asRecord(decisionRecord?.proposedExecpolicyAmendment) ??
asRecord(decisionRecord?.execPolicyAmendment) ??
undefined)
: undefined;
actions.push({
kind: "approval",
decision,
responseDecision: decisionValue || decision,
...(proposedExecpolicyAmendment ? { proposedExecpolicyAmendment } : {}),
...(sessionPrefix ? { sessionPrefix } : {}),
label:
pickString(decisionRecord, ["label", "title", "text"]) ??
humanizeApprovalDecision(decision, sessionPrefix),
});
}
return actions;
}
function resolveApprovalDecisionFromText(text: string): PendingApprovalDecision | null {
const normalized = text.trim().toLowerCase();
if (!normalized) {
return null;
}
if (normalized.includes("session")) {
return "acceptForSession";
}
if (/cancel|abort|stop/.test(normalized)) {
return "cancel";
}
if (/deny|decline|reject|block|no/.test(normalized)) {
return "decline";
}
if (/approve|allow|accept|yes/.test(normalized)) {
return "accept";
}
return null;
}
function buildApprovalActionsFromOptions(options: string[]): PendingInputAction[] {
const seen = new Set<PendingApprovalDecision>();
const actions: PendingInputAction[] = [];
for (const option of options) {
const decision = resolveApprovalDecisionFromText(option);
if (!decision || seen.has(decision)) {
continue;
}
seen.add(decision);
actions.push({
kind: "approval",
decision,
responseDecision: decision,
label: option.trim() || humanizeApprovalDecision(decision),
});
}
return actions;
}
function buildApprovalActionsFromMethod(
methodLower: string,
requestParams: unknown,
): PendingInputAction[] {
if (isFileChangeApprovalMethod(methodLower)) {
return [
{
kind: "approval",
decision: "accept",
responseDecision: "accept",
label: "Approve File Changes",
},
{
kind: "approval",
decision: "decline",
responseDecision: "decline",
label: "Decline",
},
];
}
if (!isCommandApprovalMethod(methodLower)) {
return [];
}
const sessionPrefix = extractSessionPrefix(requestParams);
const actions: PendingInputAction[] = [
{
kind: "approval",
decision: "accept",
responseDecision: "accept",
label: "Approve Once",
},
];
if (sessionPrefix) {
actions.push({
kind: "approval",
decision: "acceptForSession",
responseDecision: "acceptForSession",
sessionPrefix,
label: humanizeApprovalDecision("acceptForSession", sessionPrefix),
});
}
actions.push(
{
kind: "approval",
decision: "decline",
responseDecision: "decline",
label: "Decline",
},
{
kind: "approval",
decision: "cancel",
responseDecision: "cancel",
label: "Cancel",
},
);
return actions;
}
function extractFilePaths(value: unknown): string[] {
const record = asRecord(value);
if (!record) {
return [];
}
const seen = new Set<string>();
const out: string[] = [];
const pushPath = (pathValue: unknown) => {
if (typeof pathValue !== "string") {
return;
}
const trimmed = pathValue.trim();
if (!trimmed || seen.has(trimmed)) {
return;
}
seen.add(trimmed);
out.push(trimmed);
};
const filePaths = Array.isArray(record.filePaths)
? record.filePaths
: Array.isArray(record.file_paths)
? record.file_paths
: [];
filePaths.forEach((entry) => pushPath(entry));
const changes = Array.isArray(record.changes) ? record.changes : [];
changes.forEach((entry) => pushPath(asRecord(entry)?.path));
return out;
}
export function buildPendingUserInputActions(params: {
method?: string;
requestParams?: unknown;
options?: string[];
}): PendingInputAction[] {
const methodLower = params.method?.trim().toLowerCase() ?? "";
const options = params.options?.map((option) => option.trim()).filter(Boolean) ?? [];
if (methodLower.includes("requestapproval")) {
const approvalActions = buildApprovalActionsFromDecisions(params.requestParams);
const resolvedApprovalActions =
approvalActions.length > 0
? approvalActions
: buildApprovalActionsFromOptions(options).length > 0
? buildApprovalActionsFromOptions(options)
: buildApprovalActionsFromMethod(methodLower, params.requestParams);
return [...resolvedApprovalActions, { kind: "steer", label: "Tell Codex What To Do" }];
}
return options.map((option) => ({
kind: "option",
label: option,
value: option,
}));
}
function dedupeJoinedText(chunks: string[]): string {
const seen = new Set<string>();
const out: string[] = [];
for (const chunk of chunks.map((value) => value.trim()).filter(Boolean)) {
if (seen.has(chunk)) {
continue;
}
seen.add(chunk);
out.push(chunk);
}
return out.join("\n\n").trim();
}
function truncateWithNotice(text: string, maxChars: number, notice: string): string {
const trimmed = text.trim();
if (trimmed.length <= maxChars) {
return trimmed;
}
return `${trimmed.slice(0, Math.max(1, maxChars)).trimEnd()}\n\n${notice}`;
}
function parseQuestionnaireOption(line: string): { key: string; label: string } | null {
const match = line.trim().match(/^[•*-]?\s*([A-Z])[\.\)]?\s+(.+)$/);
if (!match?.[1] || !match[2]) {
return null;
}
return {
key: match[1],
label: match[2].trim(),
};
}
function extractQuestionnaireFromStructuredRequest(
value: unknown,
): PendingQuestionnaireState | undefined {
const record = asRecord(value);
const rawQuestions = Array.isArray(record?.questions) ? record.questions : [];
if (rawQuestions.length === 0) {
return undefined;
}
const questions: PendingQuestionnaireQuestion[] = rawQuestions
.map((entry, index) => {
const question = asRecord(entry);
if (!question) {
return null;
}
const rawOptions = Array.isArray(question.options) ? question.options : [];
const options = rawOptions
.map((option, optionIndex) => {
const optionRecord = asRecord(option);
if (!optionRecord) {
return null;
}
const label = pickString(optionRecord, ["label", "title", "text"]);
if (!label) {
return null;
}
return {
key: String.fromCharCode(65 + optionIndex),
label,
description: pickString(optionRecord, ["description", "details", "summary"]),
recommended: /\(recommended\)/i.test(label),
};
})
.filter(Boolean) as PendingQuestionnaireQuestion["options"];
if (options.length === 0) {
return null;
}
const header = pickString(question, ["header"]);
const prompt = pickString(question, ["question"]) ?? header ?? `Question ${index + 1}`;
return {
index,
id: pickString(question, ["id"]) ?? `q${index + 1}`,
header,
prompt,
options,
guidance: [],
allowFreeform: question.isOther === true || question.is_other === true,
};
})
.filter(Boolean) as PendingQuestionnaireQuestion[];
if (questions.length === 0) {
return undefined;
}
return {
questions,
currentIndex: 0,
answers: questions.map(() => null),
responseMode: "structured",
};
}
export function parsePendingQuestionnaire(text: string): PendingQuestionnaireState | undefined {
const normalized = text.replace(/\r\n/g, "\n").trim();
if (!normalized) {
return undefined;
}
const starts = [...normalized.matchAll(/(?:^|\n)(\d+)\.\s+/g)].map((match) => match.index ?? 0);
if (starts.length < 2) {
return undefined;
}
const questions: PendingQuestionnaireQuestion[] = [];
for (let index = 0; index < starts.length; index += 1) {
const start = starts[index] ?? 0;
const end = starts[index + 1] ?? normalized.length;
const block = normalized
.slice(start, end)
.trim()
.replace(/^\d+\.\s+/, "");
const lines = block.split("\n");
const prompt = lines.shift()?.trim() ?? "";
if (!prompt) {
continue;
}
const options: Array<{ key: string; label: string }> = [];
const guidance: string[] = [];
let inGuidance = false;
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) {
continue;
}
if (/^guidance:?$/i.test(line)) {
inGuidance = true;
continue;
}
const option = parseQuestionnaireOption(line);
if (option && !inGuidance) {
options.push(option);
continue;
}
if (inGuidance) {
guidance.push(line.replace(/^[•*-]\s*/, "").trim());
}
}
if (options.length === 0) {
continue;
}
questions.push({
index: questions.length,
id: `q${questions.length + 1}`,
prompt,
options,
guidance,
});
}
if (questions.length < 2) {
return undefined;
}
return {
questions,
currentIndex: 0,
answers: questions.map(() => null),
responseMode: "compact",
};
}
export function formatPendingQuestionnairePrompt(
questionnaire: PendingQuestionnaireState,
): string {
const question = questionnaire.questions[questionnaire.currentIndex];
if (!question) {
return "Codex needs input.";
}
const heading =
question.header && question.prompt && question.header !== question.prompt
? `${question.header}: ${question.prompt}`
: (question.header ?? question.prompt);
const lines = [
`Codex plan question ${questionnaire.currentIndex + 1} of ${questionnaire.questions.length}`,
"",
heading,
"",
];
for (const option of question.options) {
lines.push(`${option.key}. ${option.label}`);
if (option.description) {
lines.push(` ${option.description}`);
}
}
if (question.guidance.length > 0) {
lines.push("", "Guidance:");
for (const item of question.guidance) {
lines.push(`- ${item}`);
}
}
if (question.allowFreeform) {
lines.push("", "Other: You can reply with free text.");
}
const currentAnswer = questionnaire.answers[questionnaire.currentIndex];
if (currentAnswer) {
lines.push(
"",
`Current answer: ${
currentAnswer.kind === "option"
? `${currentAnswer.optionKey}. ${currentAnswer.optionLabel}`
: currentAnswer.text
}`,
);
} else if (questionnaire.awaitingFreeform) {
lines.push("", "Current answer: waiting for your free-form reply");
}
return lines.join("\n");
}
export function renderPendingQuestionnaireAnswer(answer: PendingQuestionnaireAnswer | null): string {
if (!answer) {
return "";
}
return answer.kind === "option" ? answer.optionLabel.trim() : answer.text.trim();
}
export function buildPendingQuestionnaireResponse(
questionnaire: PendingQuestionnaireState,
): { answers: Record<string, { answers: string[] }> } | string {
if (questionnaire.responseMode === "compact") {
return questionnaire.questions
.map((question, index) => {
const answer = questionnaire.answers[index];
if (!answer) {
return "";
}
return answer.kind === "option"
? `${question.index + 1}${answer.optionKey}`
: `${question.index + 1}: ${answer.text.trim()}`;
})
.filter(Boolean)
.join(" ");
}
return {
answers: Object.fromEntries(
questionnaire.questions.map((question, index) => {
const answer = questionnaire.answers[index];
const rendered = renderPendingQuestionnaireAnswer(answer);
return [question.id, { answers: rendered ? [rendered] : [] }];
}),
),
};
}
export function addQuestionnaireResponseNote(
response: { answers: Record<string, { answers: string[] }> } | string,
note: string,
): { answers: Record<string, { answers: string[] }> } | string {
const trimmed = note.trim();
if (!trimmed || typeof response === "string") {
return response;
}
const entries = Object.entries(response.answers);
if (entries.length === 0) {
return response;
}
const [firstId, firstAnswer] = entries[0];
return {
answers: {
...response.answers,
[firstId]: {
answers: [...firstAnswer.answers, `user_note: ${trimmed}`],
},
},
};
}
export function questionnaireIsComplete(questionnaire: PendingQuestionnaireState): boolean {
return questionnaire.answers.every(
(answer) =>
answer != null &&
(answer.kind === "option" || (answer.kind === "text" && answer.text.trim().length > 0)),
);
}
export function questionnaireCurrentQuestionHasAnswer(
questionnaire: PendingQuestionnaireState,
): boolean {
const answer = questionnaire.answers[questionnaire.currentIndex];
return (
answer != null &&
(answer.kind === "option" || (answer.kind === "text" && answer.text.trim().length > 0))
);
}
function collectText(value: unknown): string[] {
if (typeof value === "string") {
const trimmed = value.trim();
return trimmed ? [trimmed] : [];
}
if (Array.isArray(value)) {
return value.flatMap((entry) => collectText(entry));
}
const record = asRecord(value);
if (!record) {
return [];
}
const directKeys = [
"text",
"delta",
"message",
"prompt",
"question",
"summary",
"title",
"content",
"description",
"reason",
];
const out = directKeys.flatMap((key) => collectText(record[key]));
for (const nestedKey of ["item", "turn", "thread", "response", "result", "data", "questions"]) {
out.push(...collectText(record[nestedKey]));
}
return out;
}
function buildMarkdownCodeBlock(text: string, language = ""): string {
const normalized = text.replace(/\r\n/g, "\n").trim();
if (!normalized) {
return "";
}
const fenceMatches = [...normalized.matchAll(/`{3,}/g)];
const longestFence = fenceMatches.reduce((max, match) => Math.max(max, match[0].length), 2);
const fence = "`".repeat(longestFence + 1);
const languageTag = language.trim();
return `${fence}${languageTag}\n${normalized}\n${fence}`;
}
/**
* Strips common shell launcher wrappers from a command string for display.
* For example: `/bin/zsh -lc 'git status'` → `git status`
*
* Matches upstream Codex Desktop behavior (strip_bash_lc_and_escape in
* codex-rs/tui/src/exec_command.rs). The raw command is preserved for
* approval transport; only the displayed form is simplified.
*/
export function stripShellLauncher(command: string): string {
const match = command.match(
/^(?:\/[/\w]*\/)?(?:bash|zsh|sh|dash|ksh|tcsh|fish)\s+-lc\s+(['"])([\s\S]*)\1\s*$/,
);
if (match) {
return match[2];
}
return command;
}
/**
* Extracts a display command from the app-server's `commandActions` array.
*
* The app-server protocol provides `commandActions` as "best-effort parsed
* command actions for friendly display" (see CommandAction type in
* codex-rs/app-server-protocol). Each action has a `.command` field that is
* already stripped of shell launcher wrappers by the Rust-side parser
* (extract_shell_command → strip_bash_lc_and_escape).
*
* When available, this is more reliable than regex-based stripping because
* the upstream parser uses tree-sitter for proper shell parsing.
*/
export function extractCommandFromActions(requestParams: unknown): string | undefined {
const record = asRecord(requestParams);
if (!record) return undefined;
const actions = record.commandActions;
if (!Array.isArray(actions) || actions.length === 0) return undefined;
const commands = actions
.map((a: unknown) => {
const action = asRecord(a);
if (!action || typeof action.command !== "string") return undefined;
return action.command;
})
.filter((c): c is string => c !== undefined);
if (commands.length === 0) return undefined;
return commands.join(" && ");
}
export function buildPendingPromptText(params: {
method: string;
requestId: string;
options: string[];
actions: PendingInputAction[];
expiresAt: number;
requestParams: unknown;
}): string {
const methodLower = params.method.trim().toLowerCase();
const lines = [
/requestapproval/i.test(params.method)
? isFileChangeApprovalMethod(methodLower)
? `Codex file change approval requested (${params.requestId})`
: isCommandApprovalMethod(methodLower)
? `Codex command approval requested (${params.requestId})`
: `Codex approval requested (${params.requestId})`
: `Codex input requested (${params.requestId})`,
];
const requestText = dedupeJoinedText(collectText(params.requestParams));
if (requestText) {
lines.push(
truncateWithNotice(
requestText,
MAX_PENDING_REQUEST_TEXT_CHARS,
"[Request details truncated. Use steer text if you want to redirect Codex.]",
),
);
}
// Prefer the pre-parsed commandActions from the app-server protocol when
// available — the Rust side already strips shell launchers via tree-sitter.
// Fall back to regex-based stripShellLauncher on the raw command string.
const displayCommand = extractCommandFromActions(params.requestParams);
const rawCommand =
findFirstStringByKeys(params.requestParams, [
"command",
"cmd",
"displayCommand",
"rawCommand",
"shellCommand",
]) ?? "";
const command = displayCommand ?? (rawCommand ? stripShellLauncher(rawCommand) : "");
if (command) {
lines.push("", "Command:", "", buildMarkdownCodeBlock(command, "sh"));
}
const grantRoot = findFirstStringByKeys(params.requestParams, ["grantRoot", "grant_root"]);
if (grantRoot) {
lines.push("", `Requested writable root: \`${grantRoot}\``);
}
if (isFileChangeApprovalMethod(methodLower)) {
const filePaths = extractFilePaths(params.requestParams);
if (filePaths.length > 0) {
lines.push("", "Files:");
for (const filePath of filePaths.slice(0, 12)) {
lines.push(`- \`${filePath}\``);
}
if (filePaths.length > 12) {
lines.push(`- ...and ${filePaths.length - 12} more`);
}
}
}
if (params.actions.length > 0) {
lines.push("", "Choices:");
params.actions
.filter((action) => action.kind !== "steer")
.forEach((action, index) => {
lines.push(`${index + 1}. ${action.label}`);
});
lines.push("", 'Reply with "1", "2", "option 1", etc., or use a button.');
if (/requestapproval/i.test(params.method)) {
lines.push("You can also reply with free text to tell Codex what to do instead.");
}
} else if (params.options.length > 0) {
lines.push("", "Options:");
params.options.forEach((option, index) => {
lines.push(`${index + 1}. ${option}`);
});
} else {
lines.push("Reply with a free-form response.");
}
const seconds = Math.max(1, Math.round((params.expiresAt - Date.now()) / 1_000));
lines.push(`Expires in: ${seconds}s`);
return truncateWithNotice(
lines.join("\n"),
MAX_PENDING_PROMPT_TEXT_CHARS,
"[Prompt truncated for chat delivery. Use the buttons or reply with steer text.]",
);
}
export function createPendingInputState(params: {
method: string;
requestId: string;
requestParams: unknown;
options: string[];
expiresAt: number;
}): PendingInputState {
const actions = buildPendingUserInputActions({
method: params.method,
requestParams: params.requestParams,
options: params.options,
});
const questionnaire =
extractQuestionnaireFromStructuredRequest(params.requestParams) ??
parsePendingQuestionnaire(dedupeJoinedText(collectText(params.requestParams)));
return {
requestId: params.requestId,
options: params.options,
actions,
expiresAt: params.expiresAt,
questionnaire,
promptText: buildPendingPromptText({
method: params.method,
requestId: params.requestId,
options: params.options,
actions,
expiresAt: params.expiresAt,
requestParams: params.requestParams,
}),
method: params.method,
};
}
export function parseCodexUserInput(
text: string,
optionsCount: number,
): { kind: "option"; index: number } | { kind: "text"; text: string } {
const normalized = text.trim();
if (!normalized) {
return { kind: "text", text: "" };
}
const match = normalized.match(/^\s*(?:option\s*)?([1-9]\d*)\s*$/i);
if (!match) {
return { kind: "text", text: normalized };
}
const oneBased = Number.parseInt(match[1] ?? "", 10);
if (Number.isInteger(oneBased) && oneBased >= 1 && oneBased <= optionsCount) {
return { kind: "option", index: oneBased - 1 };
}
return { kind: "text", text: normalized };
}
export function requestToken(requestId: string): string {
return crypto.createHash("sha1").update(requestId).digest("base64url").slice(0, 10);
}