@gakr-gakr/codex 0.1.0 → 0.1.1

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.
Files changed (115) hide show
  1. package/dist/client-DNN2uyJW.js +642 -0
  2. package/dist/client-factory-Bu9OClHJ.js +9 -0
  3. package/dist/command-formatters-BpPOTePl.js +520 -0
  4. package/dist/command-handlers-BBs7Vws9.js +1533 -0
  5. package/dist/compact-CDboBy7o.js +329 -0
  6. package/dist/computer-use-DCZB46Sw.js +367 -0
  7. package/dist/config-CLMSw0p2.js +510 -0
  8. package/dist/doctor-contract-api.js +53 -0
  9. package/dist/harness.js +51 -0
  10. package/dist/index.js +1171 -0
  11. package/dist/media-understanding-provider.js +335 -0
  12. package/dist/models-jLA2SIvd.js +110 -0
  13. package/dist/node-cli-sessions-BLRDs_US.js +1216 -0
  14. package/dist/plugin-activation-CEy_oYpx.js +452 -0
  15. package/dist/prompt-overlay.js +12 -0
  16. package/dist/protocol-C9UWI98H.js +9 -0
  17. package/dist/protocol-validators-BGBspNmF.js +5988 -0
  18. package/dist/provider-catalog.js +84 -0
  19. package/dist/provider-discovery.js +33 -0
  20. package/dist/provider.js +150 -0
  21. package/dist/rate-limit-cache-9LxQdE0K.js +24 -0
  22. package/dist/request-DbSPeTcV.js +89 -0
  23. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  24. package/dist/run-attempt-BoEwzQCv.js +5463 -0
  25. package/dist/session-binding-e2GFp9VH.js +222 -0
  26. package/dist/shared-client-D7Vy0glq.js +631 -0
  27. package/dist/side-question-BDLuEzFP.js +668 -0
  28. package/dist/test-api.js +49 -0
  29. package/dist/thread-lifecycle-Clo0EHMk.js +1565 -0
  30. package/dist/vision-tools-Cofrv35p.js +1379 -0
  31. package/package.json +16 -1
  32. package/doctor-contract-api.ts +0 -68
  33. package/harness.ts +0 -72
  34. package/index.ts +0 -124
  35. package/media-understanding-provider.ts +0 -521
  36. package/prompt-overlay.ts +0 -21
  37. package/provider-catalog.ts +0 -83
  38. package/provider-discovery.ts +0 -45
  39. package/provider.ts +0 -243
  40. package/src/app-server/app-inventory-cache.ts +0 -324
  41. package/src/app-server/approval-bridge.ts +0 -1211
  42. package/src/app-server/auth-bridge.ts +0 -614
  43. package/src/app-server/capabilities.ts +0 -27
  44. package/src/app-server/client-factory.ts +0 -24
  45. package/src/app-server/client.ts +0 -715
  46. package/src/app-server/compact.ts +0 -512
  47. package/src/app-server/computer-use.ts +0 -683
  48. package/src/app-server/config.ts +0 -1038
  49. package/src/app-server/context-engine-projection.ts +0 -403
  50. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  51. package/src/app-server/dynamic-tool-profile.ts +0 -70
  52. package/src/app-server/dynamic-tools.ts +0 -623
  53. package/src/app-server/elicitation-bridge.ts +0 -783
  54. package/src/app-server/event-projector.ts +0 -2065
  55. package/src/app-server/image-payload-sanitizer.ts +0 -167
  56. package/src/app-server/local-runtime-attribution.ts +0 -39
  57. package/src/app-server/managed-binary.ts +0 -193
  58. package/src/app-server/models.ts +0 -172
  59. package/src/app-server/native-hook-relay.ts +0 -150
  60. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  61. package/src/app-server/plugin-activation.ts +0 -283
  62. package/src/app-server/plugin-app-cache-key.ts +0 -74
  63. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  64. package/src/app-server/plugin-inventory.ts +0 -357
  65. package/src/app-server/plugin-thread-config.ts +0 -455
  66. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  67. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  68. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  69. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  70. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  71. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  72. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  73. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  74. package/src/app-server/protocol-validators.ts +0 -203
  75. package/src/app-server/protocol.ts +0 -520
  76. package/src/app-server/rate-limit-cache.ts +0 -48
  77. package/src/app-server/rate-limits.ts +0 -583
  78. package/src/app-server/request.ts +0 -73
  79. package/src/app-server/run-attempt.ts +0 -4862
  80. package/src/app-server/session-binding.ts +0 -398
  81. package/src/app-server/session-history.ts +0 -44
  82. package/src/app-server/shared-client.ts +0 -289
  83. package/src/app-server/side-question.ts +0 -1009
  84. package/src/app-server/test-support.ts +0 -48
  85. package/src/app-server/thread-lifecycle.ts +0 -959
  86. package/src/app-server/timeout.ts +0 -9
  87. package/src/app-server/tool-progress-normalization.ts +0 -77
  88. package/src/app-server/trajectory.ts +0 -368
  89. package/src/app-server/transcript-mirror.ts +0 -208
  90. package/src/app-server/transport-stdio.ts +0 -107
  91. package/src/app-server/transport-websocket.ts +0 -90
  92. package/src/app-server/transport.ts +0 -117
  93. package/src/app-server/user-input-bridge.ts +0 -316
  94. package/src/app-server/version.ts +0 -4
  95. package/src/app-server/vision-tools.ts +0 -12
  96. package/src/command-account.ts +0 -544
  97. package/src/command-formatters.ts +0 -426
  98. package/src/command-handlers.ts +0 -2021
  99. package/src/command-plugins-management.ts +0 -137
  100. package/src/command-rpc.ts +0 -142
  101. package/src/commands.ts +0 -65
  102. package/src/conversation-binding-data.ts +0 -124
  103. package/src/conversation-binding.ts +0 -561
  104. package/src/conversation-control.ts +0 -303
  105. package/src/conversation-turn-collector.ts +0 -186
  106. package/src/conversation-turn-input.ts +0 -106
  107. package/src/migration/apply.ts +0 -501
  108. package/src/migration/helpers.ts +0 -55
  109. package/src/migration/plan.ts +0 -461
  110. package/src/migration/provider.ts +0 -41
  111. package/src/migration/source.ts +0 -643
  112. package/src/migration/targets.ts +0 -25
  113. package/src/node-cli-sessions.ts +0 -711
  114. package/test-api.ts +0 -95
  115. package/tsconfig.json +0 -16
@@ -1,2021 +0,0 @@
1
- import crypto from "node:crypto";
2
- import { resolveAgentDir, resolveSessionAgentIds } from "autobot/plugin-sdk/agent-runtime";
3
- import type { PluginCommandContext, PluginCommandResult } from "autobot/plugin-sdk/plugin-entry";
4
- import { CODEX_CONTROL_METHODS, type CodexControlMethod } from "./app-server/capabilities.js";
5
- import {
6
- installCodexComputerUse,
7
- readCodexComputerUseStatus,
8
- type CodexComputerUseSetupParams,
9
- } from "./app-server/computer-use.js";
10
- import { isCodexFastServiceTier, type CodexComputerUseConfig } from "./app-server/config.js";
11
- import { listAllCodexAppServerModels } from "./app-server/models.js";
12
- import { isJsonObject, type JsonValue } from "./app-server/protocol.js";
13
- import { rememberCodexRateLimits } from "./app-server/rate-limit-cache.js";
14
- import {
15
- clearCodexAppServerBinding,
16
- readCodexAppServerBinding,
17
- writeCodexAppServerBinding,
18
- } from "./app-server/session-binding.js";
19
- import { readCodexAccountAuthOverview } from "./command-account.js";
20
- import {
21
- buildHelp,
22
- formatAccount,
23
- formatComputerUseStatus,
24
- formatCodexDisplayText,
25
- formatCodexStatus,
26
- formatList,
27
- formatModels,
28
- formatThreads,
29
- readString,
30
- } from "./command-formatters.js";
31
- import {
32
- handleCodexPluginsSubcommand,
33
- type CodexPluginsManagementIO,
34
- } from "./command-plugins-management.js";
35
- import {
36
- codexControlRequest,
37
- readCodexStatusProbes,
38
- requestOptions,
39
- safeCodexControlRequest,
40
- type CodexControlRequestOptions,
41
- type SafeValue,
42
- } from "./command-rpc.js";
43
- import {
44
- createCodexCliNodeConversationBindingData,
45
- readCodexConversationBindingData,
46
- resolveCodexDefaultWorkspaceDir,
47
- startCodexConversationThread,
48
- } from "./conversation-binding.js";
49
- import {
50
- formatPermissionsMode,
51
- parseCodexFastModeArg,
52
- parseCodexPermissionsModeArg,
53
- readCodexConversationActiveTurn,
54
- setCodexConversationFastMode,
55
- setCodexConversationModel,
56
- setCodexConversationPermissions,
57
- steerCodexConversationTurn,
58
- stopCodexConversationTurn,
59
- } from "./conversation-control.js";
60
- import {
61
- formatCodexCliSessions,
62
- listCodexCliSessionsOnNode,
63
- resolveCodexCliSessionForBindingOnNode,
64
- } from "./node-cli-sessions.js";
65
-
66
- export type CodexCommandDeps = {
67
- codexControlRequest: CodexControlRequestFn;
68
- listCodexAppServerModels: typeof listAllCodexAppServerModels;
69
- readCodexStatusProbes: typeof readCodexStatusProbes;
70
- readCodexAppServerBinding: typeof readCodexAppServerBinding;
71
- requestOptions: typeof requestOptions;
72
- safeCodexControlRequest: SafeCodexControlRequestFn;
73
- writeCodexAppServerBinding: typeof writeCodexAppServerBinding;
74
- clearCodexAppServerBinding: typeof clearCodexAppServerBinding;
75
- readCodexComputerUseStatus: typeof readCodexComputerUseStatus;
76
- installCodexComputerUse: typeof installCodexComputerUse;
77
- resolveCodexDefaultWorkspaceDir: typeof resolveCodexDefaultWorkspaceDir;
78
- startCodexConversationThread: typeof startCodexConversationThread;
79
- readCodexConversationActiveTurn: typeof readCodexConversationActiveTurn;
80
- setCodexConversationFastMode: typeof setCodexConversationFastMode;
81
- setCodexConversationModel: typeof setCodexConversationModel;
82
- setCodexConversationPermissions: typeof setCodexConversationPermissions;
83
- steerCodexConversationTurn: typeof steerCodexConversationTurn;
84
- stopCodexConversationTurn: typeof stopCodexConversationTurn;
85
- listCodexCliSessionsOnNode: ListCodexCliSessionsOnNodeFn;
86
- resolveCodexCliSessionForBindingOnNode: ResolveCodexCliSessionForBindingOnNodeFn;
87
- codexPluginsManagementIo?: CodexPluginsManagementIO;
88
- };
89
-
90
- type CodexControlRequestFn = (
91
- pluginConfig: unknown,
92
- method: CodexControlMethod,
93
- requestParams: JsonValue | undefined,
94
- options?: CodexControlRequestOptions,
95
- ) => Promise<JsonValue | undefined>;
96
-
97
- type SafeCodexControlRequestFn = (
98
- pluginConfig: unknown,
99
- method: CodexControlMethod,
100
- requestParams: JsonValue | undefined,
101
- options?: CodexControlRequestOptions,
102
- ) => Promise<SafeValue<JsonValue | undefined>>;
103
-
104
- type ListCodexCliSessionsOnNodeFn = (
105
- params: Omit<Parameters<typeof listCodexCliSessionsOnNode>[0], "runtime">,
106
- ) => ReturnType<typeof listCodexCliSessionsOnNode>;
107
-
108
- type ResolveCodexCliSessionForBindingOnNodeFn = (
109
- params: Omit<Parameters<typeof resolveCodexCliSessionForBindingOnNode>[0], "runtime">,
110
- ) => ReturnType<typeof resolveCodexCliSessionForBindingOnNode>;
111
-
112
- const defaultCodexCommandDeps: CodexCommandDeps = {
113
- codexControlRequest,
114
- listCodexAppServerModels: listAllCodexAppServerModels,
115
- readCodexStatusProbes,
116
- readCodexAppServerBinding,
117
- requestOptions,
118
- safeCodexControlRequest,
119
- writeCodexAppServerBinding,
120
- clearCodexAppServerBinding,
121
- readCodexComputerUseStatus,
122
- installCodexComputerUse,
123
- resolveCodexDefaultWorkspaceDir,
124
- startCodexConversationThread,
125
- readCodexConversationActiveTurn,
126
- setCodexConversationFastMode,
127
- setCodexConversationModel,
128
- setCodexConversationPermissions,
129
- steerCodexConversationTurn,
130
- stopCodexConversationTurn,
131
- listCodexCliSessionsOnNode: async () => {
132
- throw new Error("Codex CLI node sessions require Gateway node runtime.");
133
- },
134
- resolveCodexCliSessionForBindingOnNode: async () => {
135
- throw new Error("Codex CLI node sessions require Gateway node runtime.");
136
- },
137
- };
138
-
139
- type ParsedBindArgs = {
140
- threadId?: string;
141
- cwd?: string;
142
- model?: string;
143
- provider?: string;
144
- help?: boolean;
145
- };
146
-
147
- type ParsedComputerUseArgs = {
148
- action: "status" | "install";
149
- overrides: Partial<CodexComputerUseConfig>;
150
- hasOverrides: boolean;
151
- help?: boolean;
152
- };
153
-
154
- type ParsedCodexCliSessionsArgs = {
155
- host?: string;
156
- filter: string;
157
- limit?: number;
158
- help?: boolean;
159
- };
160
-
161
- type ParsedResumeArgs = {
162
- threadId?: string;
163
- host?: string;
164
- bindHere?: boolean;
165
- help?: boolean;
166
- };
167
-
168
- type ParsedDiagnosticsArgs =
169
- | { action: "request"; note: string }
170
- | { action: "confirm"; token: string }
171
- | { action: "cancel"; token: string }
172
- | { action: "usage" };
173
-
174
- type CodexDiagnosticsTarget = {
175
- threadId: string;
176
- sessionFile: string;
177
- sessionKey?: string;
178
- sessionId?: string;
179
- channel?: string;
180
- channelId?: string;
181
- accountId?: string;
182
- messageThreadId?: string | number;
183
- threadParentId?: string;
184
- };
185
-
186
- type PendingCodexDiagnosticsConfirmation = {
187
- token: string;
188
- targets: CodexDiagnosticsTarget[];
189
- note?: string;
190
- senderId: string;
191
- channel: string;
192
- accountId?: string;
193
- channelId?: string;
194
- messageThreadId?: string;
195
- threadParentId?: string;
196
- sessionKey?: string;
197
- scopeKey: string;
198
- privateRouted?: boolean;
199
- createdAt: number;
200
- };
201
-
202
- const CODEX_DIAGNOSTICS_SOURCE = "autobot-diagnostics";
203
- const CODEX_DIAGNOSTICS_REASON_MAX_CHARS = 2048;
204
- const CODEX_DIAGNOSTICS_COOLDOWN_MS = 60_000;
205
- const CODEX_DIAGNOSTICS_ERROR_MAX_CHARS = 500;
206
- const CODEX_DIAGNOSTICS_COOLDOWN_MAX_THREADS = 100;
207
- const CODEX_DIAGNOSTICS_COOLDOWN_MAX_SCOPES = 100;
208
- const CODEX_DIAGNOSTICS_CONFIRMATION_TTL_MS = 5 * 60_000;
209
- const CODEX_DIAGNOSTICS_CONFIRMATION_MAX_REQUESTS_PER_SCOPE = 100;
210
- const CODEX_DIAGNOSTICS_CONFIRMATION_MAX_SCOPES = 100;
211
- const CODEX_DIAGNOSTICS_SCOPE_FIELD_MAX_CHARS = 128;
212
- const CODEX_RESUME_SAFE_THREAD_ID_PATTERN = /^[A-Za-z0-9._:-]+$/;
213
-
214
- const lastCodexDiagnosticsUploadByThread = new Map<string, number>();
215
- const lastCodexDiagnosticsUploadByScope = new Map<string, number>();
216
- const pendingCodexDiagnosticsConfirmations = new Map<string, PendingCodexDiagnosticsConfirmation>();
217
- const pendingCodexDiagnosticsConfirmationTokensByScope = new Map<string, string[]>();
218
-
219
- export function resetCodexDiagnosticsFeedbackStateForTests(): void {
220
- lastCodexDiagnosticsUploadByThread.clear();
221
- lastCodexDiagnosticsUploadByScope.clear();
222
- pendingCodexDiagnosticsConfirmations.clear();
223
- pendingCodexDiagnosticsConfirmationTokensByScope.clear();
224
- }
225
-
226
- export async function handleCodexSubcommand(
227
- ctx: PluginCommandContext,
228
- options: { pluginConfig?: unknown; deps?: Partial<CodexCommandDeps> },
229
- ): Promise<PluginCommandResult> {
230
- const deps: CodexCommandDeps = { ...defaultCodexCommandDeps, ...options.deps };
231
- const [subcommand = "status", ...rest] = splitArgs(ctx.args);
232
- const normalized = subcommand.toLowerCase();
233
- if (normalized === "help") {
234
- return { text: buildHelp() };
235
- }
236
- if (normalized === "plugins") {
237
- if (!deps.codexPluginsManagementIo) {
238
- return {
239
- text:
240
- "Codex sub-plugin management is not wired up (codexPluginsManagementIo dep is undefined). " +
241
- "Edit ~/.autobot/autobot.json or use `autobot config patch` until the runtime exposes the IO.",
242
- };
243
- }
244
- return await handleCodexPluginsSubcommand(ctx, rest, deps.codexPluginsManagementIo);
245
- }
246
- if (normalized === "status") {
247
- if (rest.length > 0) {
248
- return { text: "Usage: /codex status" };
249
- }
250
- return {
251
- text: formatCodexStatus(await deps.readCodexStatusProbes(options.pluginConfig, ctx.config)),
252
- };
253
- }
254
- if (normalized === "models") {
255
- if (rest.length > 0) {
256
- return { text: "Usage: /codex models" };
257
- }
258
- return {
259
- text: formatModels(
260
- await deps.listCodexAppServerModels(
261
- deps.requestOptions(options.pluginConfig, 100, ctx.config),
262
- ),
263
- ),
264
- };
265
- }
266
- if (normalized === "threads") {
267
- return { text: await buildThreads(deps, options.pluginConfig, rest.join(" ")) };
268
- }
269
- if (normalized === "sessions") {
270
- return { text: await buildCodexCliSessions(deps, rest) };
271
- }
272
- if (normalized === "resume") {
273
- return { text: await resumeThread(deps, ctx, options.pluginConfig, rest) };
274
- }
275
- if (normalized === "bind") {
276
- return await bindConversation(deps, ctx, options.pluginConfig, rest);
277
- }
278
- if (normalized === "detach" || normalized === "unbind") {
279
- if (rest.length > 0) {
280
- return { text: "Usage: /codex detach" };
281
- }
282
- return { text: await detachConversation(deps, ctx) };
283
- }
284
- if (normalized === "binding") {
285
- if (rest.length > 0) {
286
- return { text: "Usage: /codex binding" };
287
- }
288
- return { text: await describeConversationBinding(deps, ctx) };
289
- }
290
- if (normalized === "stop") {
291
- if (rest.length > 0) {
292
- return { text: "Usage: /codex stop" };
293
- }
294
- return { text: await stopConversationTurn(deps, ctx, options.pluginConfig) };
295
- }
296
- if (normalized === "steer") {
297
- return { text: await steerConversationTurn(deps, ctx, options.pluginConfig, rest.join(" ")) };
298
- }
299
- if (normalized === "model") {
300
- return { text: await setConversationModel(deps, ctx, options.pluginConfig, rest) };
301
- }
302
- if (normalized === "fast") {
303
- return { text: await setConversationFastMode(deps, ctx, options.pluginConfig, rest) };
304
- }
305
- if (normalized === "permissions") {
306
- return { text: await setConversationPermissions(deps, ctx, options.pluginConfig, rest) };
307
- }
308
- if (normalized === "compact") {
309
- return {
310
- text: await startThreadAction(
311
- deps,
312
- ctx,
313
- options.pluginConfig,
314
- CODEX_CONTROL_METHODS.compact,
315
- "compaction",
316
- rest,
317
- ),
318
- };
319
- }
320
- if (normalized === "review") {
321
- return {
322
- text: await startThreadAction(
323
- deps,
324
- ctx,
325
- options.pluginConfig,
326
- CODEX_CONTROL_METHODS.review,
327
- "review",
328
- rest,
329
- ),
330
- };
331
- }
332
- if (normalized === "diagnostics") {
333
- return await handleCodexDiagnosticsFeedback(
334
- deps,
335
- ctx,
336
- options.pluginConfig,
337
- rest.join(" "),
338
- "/codex diagnostics",
339
- );
340
- }
341
- if (normalized === "computer-use" || normalized === "computeruse") {
342
- return {
343
- text: await handleComputerUseCommand(deps, options.pluginConfig, rest),
344
- };
345
- }
346
- if (normalized === "mcp") {
347
- if (rest.length > 0) {
348
- return { text: "Usage: /codex mcp" };
349
- }
350
- return {
351
- text: formatList(
352
- await deps.codexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, {
353
- limit: 100,
354
- }),
355
- "MCP servers",
356
- ),
357
- };
358
- }
359
- if (normalized === "skills") {
360
- if (rest.length > 0) {
361
- return { text: "Usage: /codex skills" };
362
- }
363
- return {
364
- text: formatList(
365
- await deps.codexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}),
366
- "Codex skills",
367
- ),
368
- };
369
- }
370
- if (normalized === "account") {
371
- if (rest.length > 0) {
372
- return { text: "Usage: /codex account" };
373
- }
374
- const [account, limits] = await Promise.all([
375
- deps.safeCodexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.account, {
376
- refreshToken: false,
377
- }),
378
- deps.safeCodexControlRequest(
379
- options.pluginConfig,
380
- CODEX_CONTROL_METHODS.rateLimits,
381
- undefined,
382
- ),
383
- ]);
384
- if (limits.ok) {
385
- rememberCodexRateLimits(limits.value);
386
- }
387
- return {
388
- text: formatAccount(
389
- account,
390
- limits,
391
- await readCodexAccountAuthOverview({
392
- ctx,
393
- pluginConfig: options.pluginConfig,
394
- safeCodexControlRequest: deps.safeCodexControlRequest,
395
- account,
396
- limits,
397
- }),
398
- ),
399
- };
400
- }
401
- return { text: `Unknown Codex command: ${formatCodexDisplayText(subcommand)}\n\n${buildHelp()}` };
402
- }
403
-
404
- async function handleComputerUseCommand(
405
- deps: CodexCommandDeps,
406
- pluginConfig: unknown,
407
- args: string[],
408
- ): Promise<string> {
409
- const parsed = parseComputerUseArgs(args);
410
- if (parsed.help) {
411
- return [
412
- "Usage: /codex computer-use [status|install] [--source <marketplace-source>] [--marketplace-path <path>] [--marketplace <name>]",
413
- "Checks or installs the configured Codex Computer Use plugin through app-server.",
414
- ].join("\n");
415
- }
416
- const params: CodexComputerUseSetupParams = {
417
- pluginConfig,
418
- forceEnable: parsed.action === "install" || parsed.hasOverrides,
419
- ...(Object.keys(parsed.overrides).length > 0 ? { overrides: parsed.overrides } : {}),
420
- };
421
- if (parsed.action === "install") {
422
- return formatComputerUseStatus(await deps.installCodexComputerUse(params));
423
- }
424
- return formatComputerUseStatus(await deps.readCodexComputerUseStatus(params));
425
- }
426
-
427
- async function bindConversation(
428
- deps: CodexCommandDeps,
429
- ctx: PluginCommandContext,
430
- pluginConfig: unknown,
431
- args: string[],
432
- ): Promise<PluginCommandResult> {
433
- const parsed = parseBindArgs(args);
434
- if (parsed.help) {
435
- return {
436
- text: "Usage: /codex bind [thread-id] [--cwd <path>] [--model <model>] [--provider <provider>]",
437
- };
438
- }
439
- if (!ctx.sessionFile) {
440
- return {
441
- text: "Cannot bind Codex because this command did not include an AutoBot session file.",
442
- };
443
- }
444
- const scope = resolveCodexConversationControlScope(ctx);
445
- const workspaceDir = parsed.cwd ?? deps.resolveCodexDefaultWorkspaceDir(pluginConfig);
446
- const existingBinding = await deps.readCodexAppServerBinding(ctx.sessionFile, {
447
- agentDir: scope.agentDir,
448
- config: ctx.config,
449
- });
450
- const authProfileId = existingBinding?.authProfileId;
451
- const startParams: Parameters<CodexCommandDeps["startCodexConversationThread"]>[0] = {
452
- pluginConfig,
453
- config: ctx.config,
454
- sessionFile: ctx.sessionFile,
455
- workspaceDir,
456
- agentDir: scope.agentDir,
457
- threadId: parsed.threadId,
458
- model: parsed.model,
459
- modelProvider: parsed.provider,
460
- };
461
- if (authProfileId) {
462
- startParams.authProfileId = authProfileId;
463
- }
464
- const data = await deps.startCodexConversationThread(startParams);
465
- const binding = await deps.readCodexAppServerBinding(ctx.sessionFile, {
466
- agentDir: scope.agentDir,
467
- config: ctx.config,
468
- });
469
- const threadId = binding?.threadId ?? parsed.threadId ?? "new thread";
470
- const summary = `Codex app-server thread ${formatCodexDisplayText(threadId)} in ${formatCodexDisplayText(workspaceDir)}`;
471
- let request: Awaited<ReturnType<PluginCommandContext["requestConversationBinding"]>>;
472
- try {
473
- request = await ctx.requestConversationBinding({
474
- summary,
475
- detachHint: "/codex detach",
476
- data,
477
- });
478
- } catch (error) {
479
- await deps.clearCodexAppServerBinding(ctx.sessionFile);
480
- throw error;
481
- }
482
- if (request.status === "bound") {
483
- return {
484
- text: `Bound this conversation to Codex thread ${formatCodexDisplayText(
485
- threadId,
486
- )} in ${formatCodexDisplayText(workspaceDir)}.`,
487
- };
488
- }
489
- if (request.status === "pending") {
490
- return request.reply;
491
- }
492
- await deps.clearCodexAppServerBinding(ctx.sessionFile);
493
- return { text: formatCodexDisplayText(request.message) };
494
- }
495
-
496
- async function detachConversation(
497
- deps: CodexCommandDeps,
498
- ctx: PluginCommandContext,
499
- ): Promise<string> {
500
- const current = await ctx.getCurrentConversationBinding();
501
- const data = readCodexConversationBindingData(current);
502
- const detached = await ctx.detachConversationBinding();
503
- if (data?.kind === "codex-app-server-session") {
504
- await deps.clearCodexAppServerBinding(data.sessionFile);
505
- } else if (ctx.sessionFile) {
506
- await deps.clearCodexAppServerBinding(ctx.sessionFile);
507
- }
508
- return detached.removed
509
- ? "Detached this conversation from Codex."
510
- : "No Codex conversation binding was attached.";
511
- }
512
-
513
- async function describeConversationBinding(
514
- deps: CodexCommandDeps,
515
- ctx: PluginCommandContext,
516
- ): Promise<string> {
517
- const current = await ctx.getCurrentConversationBinding();
518
- const data = readCodexConversationBindingData(current);
519
- if (!current || !data) {
520
- return "No Codex conversation binding is attached.";
521
- }
522
- if (data.kind === "codex-cli-node-session") {
523
- return [
524
- "Codex conversation binding:",
525
- "- Mode: Codex CLI node session",
526
- `- Node: ${formatCodexDisplayText(data.nodeId)}`,
527
- `- Session: ${formatCodexDisplayText(data.sessionId)}`,
528
- `- Workspace: ${formatCodexDisplayText(data.cwd ?? "unknown")}`,
529
- "- Active run: not tracked",
530
- ].join("\n");
531
- }
532
- const threadBinding = await deps.readCodexAppServerBinding(data.sessionFile, {
533
- agentDir: data.agentDir,
534
- config: ctx.config,
535
- });
536
- const active = deps.readCodexConversationActiveTurn(data.sessionFile);
537
- return [
538
- "Codex conversation binding:",
539
- `- Thread: ${formatCodexDisplayText(threadBinding?.threadId ?? "unknown")}`,
540
- `- Workspace: ${formatCodexDisplayText(data.workspaceDir)}`,
541
- `- Model: ${formatCodexDisplayText(threadBinding?.model ?? "default")}`,
542
- `- Fast: ${isCodexFastServiceTier(threadBinding?.serviceTier) ? "on" : "off"}`,
543
- `- Permissions: ${threadBinding ? formatPermissionsMode(threadBinding) : "default"}`,
544
- `- Active run: ${formatCodexDisplayText(active ? active.turnId : "none")}`,
545
- `- Session: ${formatCodexDisplayText(data.sessionFile)}`,
546
- ].join("\n");
547
- }
548
-
549
- async function buildThreads(
550
- deps: CodexCommandDeps,
551
- pluginConfig: unknown,
552
- filter: string,
553
- ): Promise<string> {
554
- const response = await deps.codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listThreads, {
555
- limit: 10,
556
- ...(filter.trim() ? { searchTerm: filter.trim() } : {}),
557
- });
558
- return formatThreads(response);
559
- }
560
-
561
- async function buildCodexCliSessions(deps: CodexCommandDeps, args: string[]): Promise<string> {
562
- const parsed = parseCodexCliSessionsArgs(args);
563
- if (parsed.help || !parsed.host) {
564
- return "Usage: /codex sessions --host <node> [filter] [--limit <n>]";
565
- }
566
- return formatCodexCliSessions(
567
- await deps.listCodexCliSessionsOnNode({
568
- requestedNode: parsed.host,
569
- filter: parsed.filter,
570
- limit: parsed.limit,
571
- }),
572
- );
573
- }
574
-
575
- async function resumeThread(
576
- deps: CodexCommandDeps,
577
- ctx: PluginCommandContext,
578
- pluginConfig: unknown,
579
- args: string[],
580
- ): Promise<string> {
581
- const parsed = parseResumeArgs(args);
582
- const normalizedThreadId = parsed.threadId?.trim();
583
- if (parsed.help) {
584
- return args.includes("--help") || args.includes("-h") || parsed.host
585
- ? "Usage: /codex resume <thread-id>\nUsage: /codex resume <session-id> --host <node> --bind here"
586
- : "Usage: /codex resume <thread-id>";
587
- }
588
- if (parsed.host) {
589
- return await bindCodexCliNodeSession(deps, ctx, parsed);
590
- }
591
- if (!normalizedThreadId || args.length !== 1) {
592
- return "Usage: /codex resume <thread-id>";
593
- }
594
- if (!ctx.sessionFile) {
595
- return "Cannot attach a Codex thread because this command did not include an AutoBot session file.";
596
- }
597
- const response = await deps.codexControlRequest(
598
- pluginConfig,
599
- CODEX_CONTROL_METHODS.resumeThread,
600
- {
601
- threadId: normalizedThreadId,
602
- persistExtendedHistory: true,
603
- },
604
- );
605
- const thread = isJsonObject(response) && isJsonObject(response.thread) ? response.thread : {};
606
- const effectiveThreadId = readString(thread, "id") ?? normalizedThreadId;
607
- await deps.writeCodexAppServerBinding(ctx.sessionFile, {
608
- threadId: effectiveThreadId,
609
- cwd: readString(thread, "cwd") ?? "",
610
- model: isJsonObject(response) ? readString(response, "model") : undefined,
611
- modelProvider: isJsonObject(response) ? readString(response, "modelProvider") : undefined,
612
- });
613
- return `Attached this AutoBot session to Codex thread ${formatCodexDisplayText(
614
- effectiveThreadId,
615
- )}.`;
616
- }
617
-
618
- async function bindCodexCliNodeSession(
619
- deps: CodexCommandDeps,
620
- ctx: PluginCommandContext,
621
- parsed: ParsedResumeArgs,
622
- ): Promise<string> {
623
- if (!parsed.threadId || !parsed.host || parsed.bindHere !== true) {
624
- return "Usage: /codex resume <session-id> --host <node> --bind here";
625
- }
626
- const resolved = await deps.resolveCodexCliSessionForBindingOnNode({
627
- requestedNode: parsed.host,
628
- sessionId: parsed.threadId,
629
- });
630
- if (!resolved.session) {
631
- return `No Codex CLI session ${formatCodexDisplayText(parsed.threadId)} was found on ${formatCodexDisplayText(parsed.host)}.`;
632
- }
633
- const nodeId = resolved.node.nodeId;
634
- if (!nodeId) {
635
- return "Cannot bind Codex CLI session because the selected node did not include a node id.";
636
- }
637
- const data = createCodexCliNodeConversationBindingData({
638
- nodeId,
639
- sessionId: parsed.threadId,
640
- cwd: resolved.session?.cwd,
641
- });
642
- const summary = `Codex CLI session ${formatCodexDisplayText(parsed.threadId)} on ${formatCodexDisplayText(nodeId)}`;
643
- const request = await ctx.requestConversationBinding({
644
- summary,
645
- detachHint: "/codex detach",
646
- data,
647
- });
648
- if (request.status === "bound") {
649
- return `Bound this conversation to Codex CLI session ${formatCodexDisplayText(
650
- parsed.threadId,
651
- )} on ${formatCodexDisplayText(nodeId)}.`;
652
- }
653
- if (request.status === "pending") {
654
- return request.reply.text ?? "Codex CLI session binding is pending approval.";
655
- }
656
- return formatCodexDisplayText(request.message);
657
- }
658
-
659
- async function stopConversationTurn(
660
- deps: CodexCommandDeps,
661
- ctx: PluginCommandContext,
662
- pluginConfig: unknown,
663
- ): Promise<string> {
664
- const target = await resolveControlTarget(ctx);
665
- if (!target) {
666
- return "Cannot stop Codex because this command did not include an AutoBot session file.";
667
- }
668
- return (
669
- await deps.stopCodexConversationTurn({
670
- sessionFile: target.sessionFile,
671
- pluginConfig,
672
- agentDir: target.agentDir,
673
- config: ctx.config,
674
- })
675
- ).message;
676
- }
677
-
678
- async function steerConversationTurn(
679
- deps: CodexCommandDeps,
680
- ctx: PluginCommandContext,
681
- pluginConfig: unknown,
682
- message: string,
683
- ): Promise<string> {
684
- const target = await resolveControlTarget(ctx);
685
- if (!target) {
686
- return "Cannot steer Codex because this command did not include an AutoBot session file.";
687
- }
688
- return (
689
- await deps.steerCodexConversationTurn({
690
- sessionFile: target.sessionFile,
691
- pluginConfig,
692
- message,
693
- agentDir: target.agentDir,
694
- config: ctx.config,
695
- })
696
- ).message;
697
- }
698
-
699
- async function setConversationModel(
700
- deps: CodexCommandDeps,
701
- ctx: PluginCommandContext,
702
- pluginConfig: unknown,
703
- args: string[],
704
- ): Promise<string> {
705
- if (args.length > 1) {
706
- return "Usage: /codex model <model>";
707
- }
708
- const target = await resolveControlTarget(ctx);
709
- if (!target) {
710
- return "Cannot set Codex model because this command did not include an AutoBot session file.";
711
- }
712
- const [model = ""] = args;
713
- const normalized = model.trim();
714
- if (!normalized) {
715
- const binding = await deps.readCodexAppServerBinding(target.sessionFile, {
716
- agentDir: target.agentDir,
717
- config: ctx.config,
718
- });
719
- return binding?.model
720
- ? `Codex model: ${formatCodexDisplayText(binding.model)}`
721
- : "Usage: /codex model <model>";
722
- }
723
- return await deps.setCodexConversationModel({
724
- sessionFile: target.sessionFile,
725
- pluginConfig,
726
- model: normalized,
727
- agentDir: target.agentDir,
728
- config: ctx.config,
729
- });
730
- }
731
-
732
- async function setConversationFastMode(
733
- deps: CodexCommandDeps,
734
- ctx: PluginCommandContext,
735
- pluginConfig: unknown,
736
- args: string[],
737
- ): Promise<string> {
738
- if (args.length > 1) {
739
- return "Usage: /codex fast [on|off|status]";
740
- }
741
- const target = await resolveControlTarget(ctx);
742
- if (!target) {
743
- return "Cannot set Codex fast mode because this command did not include an AutoBot session file.";
744
- }
745
- const value = args[0];
746
- const parsed = parseCodexFastModeArg(value);
747
- if (value && parsed == null && value.trim().toLowerCase() !== "status") {
748
- return "Usage: /codex fast [on|off|status]";
749
- }
750
- return await deps.setCodexConversationFastMode({
751
- sessionFile: target.sessionFile,
752
- pluginConfig,
753
- enabled: parsed,
754
- agentDir: target.agentDir,
755
- config: ctx.config,
756
- });
757
- }
758
-
759
- async function setConversationPermissions(
760
- deps: CodexCommandDeps,
761
- ctx: PluginCommandContext,
762
- pluginConfig: unknown,
763
- args: string[],
764
- ): Promise<string> {
765
- if (args.length > 1) {
766
- return "Usage: /codex permissions [default|yolo|status]";
767
- }
768
- const target = await resolveControlTarget(ctx);
769
- if (!target) {
770
- return "Cannot set Codex permissions because this command did not include an AutoBot session file.";
771
- }
772
- const value = args[0];
773
- const parsed = parseCodexPermissionsModeArg(value);
774
- if (value && !parsed && value.trim().toLowerCase() !== "status") {
775
- return "Usage: /codex permissions [default|yolo|status]";
776
- }
777
- return await deps.setCodexConversationPermissions({
778
- sessionFile: target.sessionFile,
779
- pluginConfig,
780
- mode: parsed,
781
- agentDir: target.agentDir,
782
- config: ctx.config,
783
- });
784
- }
785
-
786
- type CodexConversationControlTarget = {
787
- sessionFile: string;
788
- agentDir: string;
789
- };
790
-
791
- async function resolveControlTarget(
792
- ctx: PluginCommandContext,
793
- ): Promise<CodexConversationControlTarget | undefined> {
794
- const binding = await ctx.getCurrentConversationBinding();
795
- const data = readCodexConversationBindingData(binding);
796
- const scope = resolveCodexConversationControlScope(ctx);
797
- if (data?.kind === "codex-app-server-session") {
798
- return {
799
- sessionFile: data.sessionFile,
800
- agentDir: data.agentDir ?? scope.agentDir,
801
- };
802
- }
803
- return ctx.sessionFile ? { sessionFile: ctx.sessionFile, agentDir: scope.agentDir } : undefined;
804
- }
805
-
806
- async function resolveControlSessionFile(ctx: PluginCommandContext): Promise<string | undefined> {
807
- return (await resolveControlTarget(ctx))?.sessionFile;
808
- }
809
-
810
- function resolveCodexConversationControlScope(ctx: PluginCommandContext): { agentDir: string } {
811
- const { sessionAgentId } = resolveSessionAgentIds({
812
- sessionKey: ctx.sessionKey,
813
- config: ctx.config,
814
- });
815
- return {
816
- agentDir: resolveAgentDir(ctx.config, sessionAgentId),
817
- };
818
- }
819
-
820
- async function handleCodexDiagnosticsFeedback(
821
- deps: CodexCommandDeps,
822
- ctx: PluginCommandContext,
823
- pluginConfig: unknown,
824
- args: string,
825
- commandPrefix: string,
826
- ): Promise<PluginCommandResult> {
827
- if (ctx.senderIsOwner !== true) {
828
- return { text: "Only an owner can send Codex diagnostics." };
829
- }
830
- const parsed = parseDiagnosticsArgs(args);
831
- if (parsed.action === "usage") {
832
- return { text: formatDiagnosticsUsage(commandPrefix) };
833
- }
834
- if (parsed.action === "confirm") {
835
- return {
836
- text: await confirmCodexDiagnosticsFeedback(deps, ctx, pluginConfig, parsed.token),
837
- };
838
- }
839
- if (parsed.action === "cancel") {
840
- return { text: cancelCodexDiagnosticsFeedback(ctx, parsed.token) };
841
- }
842
- if (ctx.diagnosticsUploadApproved === true) {
843
- return {
844
- text: await sendCodexDiagnosticsFeedbackForContext(deps, ctx, pluginConfig, parsed.note),
845
- };
846
- }
847
- if (ctx.diagnosticsPreviewOnly === true) {
848
- return {
849
- text: await previewCodexDiagnosticsFeedbackApproval(deps, ctx, parsed.note),
850
- };
851
- }
852
- return await requestCodexDiagnosticsFeedbackApproval(deps, ctx, parsed.note, commandPrefix);
853
- }
854
-
855
- async function requestCodexDiagnosticsFeedbackApproval(
856
- deps: CodexCommandDeps,
857
- ctx: PluginCommandContext,
858
- note: string,
859
- commandPrefix: string,
860
- ): Promise<PluginCommandResult> {
861
- if (!(await hasAnyCodexDiagnosticsSessionFile(ctx))) {
862
- return {
863
- text: "Cannot send Codex diagnostics because this command did not include an AutoBot session file.",
864
- };
865
- }
866
- const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
867
- if (targets.length === 0) {
868
- return {
869
- text: [
870
- "No Codex thread is attached to this AutoBot session yet.",
871
- "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics.",
872
- ].join("\n"),
873
- };
874
- }
875
- const now = Date.now();
876
- const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now);
877
- if (cooldownMessage) {
878
- return { text: cooldownMessage };
879
- }
880
- if (!ctx.senderId) {
881
- return {
882
- text: "Cannot send Codex diagnostics because this command did not include a sender identity.",
883
- };
884
- }
885
- const reason = normalizeDiagnosticsReason(note);
886
- const token = createCodexDiagnosticsConfirmation({
887
- targets,
888
- note: reason,
889
- senderId: ctx.senderId,
890
- channel: ctx.channel,
891
- scopeKey: readCodexDiagnosticsCooldownScope(ctx),
892
- privateRouted: ctx.diagnosticsPrivateRouted === true,
893
- ...readCodexDiagnosticsConfirmationScope(ctx),
894
- now,
895
- });
896
- const confirmCommand = `${commandPrefix} confirm ${token}`;
897
- const cancelCommand = `${commandPrefix} cancel ${token}`;
898
- const displayReason = reason ? escapeCodexChatText(formatCodexTextForDisplay(reason)) : undefined;
899
- const lines = [
900
- targets.length === 1 ? "Codex runtime thread detected." : "Codex runtime threads detected.",
901
- `Codex diagnostics can send ${targets.length === 1 ? "this thread's feedback bundle" : "these threads' feedback bundles"} to OpenAI servers.`,
902
- "Codex sessions:",
903
- ...formatCodexDiagnosticsTargetLines(targets),
904
- ...(displayReason ? [`Note: ${displayReason}`] : []),
905
- "Included: Codex logs and spawned Codex subthreads when available.",
906
- `To send: ${confirmCommand}`,
907
- `To cancel: ${cancelCommand}`,
908
- "This request expires in 5 minutes.",
909
- ];
910
- return {
911
- text: lines.join("\n"),
912
- interactive: {
913
- blocks: [
914
- {
915
- type: "buttons",
916
- buttons: [
917
- { label: "Send diagnostics", value: confirmCommand, style: "danger" },
918
- { label: "Cancel", value: cancelCommand, style: "secondary" },
919
- ],
920
- },
921
- ],
922
- },
923
- };
924
- }
925
-
926
- async function previewCodexDiagnosticsFeedbackApproval(
927
- deps: CodexCommandDeps,
928
- ctx: PluginCommandContext,
929
- note: string,
930
- ): Promise<string> {
931
- if (!(await hasAnyCodexDiagnosticsSessionFile(ctx))) {
932
- return "Cannot send Codex diagnostics because this command did not include an AutoBot session file.";
933
- }
934
- const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
935
- if (targets.length === 0) {
936
- return [
937
- "No Codex thread is attached to this AutoBot session yet.",
938
- "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics.",
939
- ].join("\n");
940
- }
941
- const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, Date.now(), {
942
- includeThreadId: false,
943
- });
944
- if (cooldownMessage) {
945
- return cooldownMessage;
946
- }
947
- const reason = normalizeDiagnosticsReason(note);
948
- const displayReason = reason ? escapeCodexChatText(formatCodexTextForDisplay(reason)) : undefined;
949
- return [
950
- targets.length === 1 ? "Codex runtime thread detected." : "Codex runtime threads detected.",
951
- `Approving diagnostics will also send ${targets.length === 1 ? "this thread's feedback bundle" : "these threads' feedback bundles"} to OpenAI servers.`,
952
- "The completed diagnostics reply will list the AutoBot session ids and Codex thread ids that were sent.",
953
- ...(displayReason ? [`Note: ${displayReason}`] : []),
954
- "Included: Codex logs and spawned Codex subthreads when available.",
955
- ].join("\n");
956
- }
957
-
958
- async function confirmCodexDiagnosticsFeedback(
959
- deps: CodexCommandDeps,
960
- ctx: PluginCommandContext,
961
- pluginConfig: unknown,
962
- token: string,
963
- ): Promise<string> {
964
- const pending = readPendingCodexDiagnosticsConfirmation(token, Date.now());
965
- if (!pending) {
966
- return "No pending Codex diagnostics confirmation was found. Run /diagnostics again to create a fresh request.";
967
- }
968
- if (!pending.senderId || !ctx.senderId) {
969
- return "Cannot confirm Codex diagnostics because this command did not include the original sender identity.";
970
- }
971
- if (pending.senderId !== ctx.senderId) {
972
- return "Only the user who requested these Codex diagnostics can confirm the upload.";
973
- }
974
- if (pending.channel !== ctx.channel) {
975
- return "This Codex diagnostics confirmation belongs to a different channel.";
976
- }
977
- const scopeMismatch = readCodexDiagnosticsScopeMismatch(pending, ctx);
978
- if (scopeMismatch) {
979
- return scopeMismatch.confirmMessage;
980
- }
981
- deletePendingCodexDiagnosticsConfirmation(token);
982
- if (!pending.privateRouted && !(await hasAnyCodexDiagnosticsSessionFile(ctx))) {
983
- return "Cannot send Codex diagnostics because this command did not include an AutoBot session file.";
984
- }
985
- const currentTargets = pending.privateRouted
986
- ? await resolvePendingCodexDiagnosticsTargets(deps, pending.targets)
987
- : await resolveCodexDiagnosticsTargets(deps, ctx);
988
- if (!codexDiagnosticsTargetsMatch(pending.targets, currentTargets)) {
989
- return "The Codex diagnostics sessions changed before confirmation. Run /diagnostics again for the current threads.";
990
- }
991
- return await sendCodexDiagnosticsFeedbackForTargets(
992
- deps,
993
- ctx,
994
- pluginConfig,
995
- pending.note ?? "",
996
- pending.targets,
997
- );
998
- }
999
-
1000
- function cancelCodexDiagnosticsFeedback(ctx: PluginCommandContext, token: string): string {
1001
- const pending = readPendingCodexDiagnosticsConfirmation(token, Date.now());
1002
- if (!pending) {
1003
- return "No pending Codex diagnostics confirmation was found.";
1004
- }
1005
- if (!pending.senderId || !ctx.senderId) {
1006
- return "Cannot cancel Codex diagnostics because this command did not include the original sender identity.";
1007
- }
1008
- if (pending.senderId !== ctx.senderId) {
1009
- return "Only the user who requested these Codex diagnostics can cancel the upload.";
1010
- }
1011
- if (pending.channel !== ctx.channel) {
1012
- return "This Codex diagnostics confirmation belongs to a different channel.";
1013
- }
1014
- const scopeMismatch = readCodexDiagnosticsScopeMismatch(pending, ctx);
1015
- if (scopeMismatch) {
1016
- return scopeMismatch.cancelMessage;
1017
- }
1018
- deletePendingCodexDiagnosticsConfirmation(token);
1019
- return [
1020
- "Codex diagnostics upload canceled.",
1021
- "Codex sessions:",
1022
- ...formatCodexDiagnosticsTargetLines(pending.targets),
1023
- ].join("\n");
1024
- }
1025
-
1026
- async function sendCodexDiagnosticsFeedbackForContext(
1027
- deps: CodexCommandDeps,
1028
- ctx: PluginCommandContext,
1029
- pluginConfig: unknown,
1030
- note: string,
1031
- ): Promise<string> {
1032
- if (!(await hasAnyCodexDiagnosticsSessionFile(ctx))) {
1033
- return "Cannot send Codex diagnostics because this command did not include an AutoBot session file.";
1034
- }
1035
- const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
1036
- if (targets.length === 0) {
1037
- return [
1038
- "No Codex thread is attached to this AutoBot session yet.",
1039
- "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics.",
1040
- ].join("\n");
1041
- }
1042
- return await sendCodexDiagnosticsFeedbackForTargets(deps, ctx, pluginConfig, note, targets);
1043
- }
1044
-
1045
- async function sendCodexDiagnosticsFeedbackForTargets(
1046
- deps: CodexCommandDeps,
1047
- ctx: PluginCommandContext,
1048
- pluginConfig: unknown,
1049
- note: string,
1050
- targets: CodexDiagnosticsTarget[],
1051
- ): Promise<string> {
1052
- if (targets.length === 0) {
1053
- return [
1054
- "No Codex thread is attached to this AutoBot session yet.",
1055
- "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics.",
1056
- ].join("\n");
1057
- }
1058
- const now = Date.now();
1059
- const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now);
1060
- if (cooldownMessage) {
1061
- return cooldownMessage;
1062
- }
1063
- const reason = normalizeDiagnosticsReason(note);
1064
- const sent: CodexDiagnosticsTarget[] = [];
1065
- const failed: Array<{ target: CodexDiagnosticsTarget; error: string }> = [];
1066
- for (const target of targets) {
1067
- const response = await deps.safeCodexControlRequest(
1068
- pluginConfig,
1069
- CODEX_CONTROL_METHODS.feedback,
1070
- {
1071
- classification: "bug",
1072
- threadId: target.threadId,
1073
- includeLogs: true,
1074
- tags: buildDiagnosticsTags(ctx),
1075
- ...(reason ? { reason } : {}),
1076
- },
1077
- );
1078
- if (!response.ok) {
1079
- failed.push({ target, error: response.error });
1080
- continue;
1081
- }
1082
- const responseThreadId = isJsonObject(response.value)
1083
- ? readString(response.value, "threadId")
1084
- : undefined;
1085
- sent.push({ ...target, threadId: responseThreadId ?? target.threadId });
1086
- recordCodexDiagnosticsUpload(target.threadId, ctx, now);
1087
- }
1088
- return formatCodexDiagnosticsUploadResult(sent, failed);
1089
- }
1090
-
1091
- async function hasAnyCodexDiagnosticsSessionFile(ctx: PluginCommandContext): Promise<boolean> {
1092
- if (await resolveControlSessionFile(ctx)) {
1093
- return true;
1094
- }
1095
- return (ctx.diagnosticsSessions ?? []).some((session) => Boolean(session.sessionFile));
1096
- }
1097
-
1098
- async function resolveCodexDiagnosticsTargets(
1099
- deps: CodexCommandDeps,
1100
- ctx: PluginCommandContext,
1101
- ): Promise<CodexDiagnosticsTarget[]> {
1102
- const activeSessionFile = await resolveControlSessionFile(ctx);
1103
- const candidates: CodexDiagnosticsTarget[] = [];
1104
- if (activeSessionFile) {
1105
- candidates.push({
1106
- threadId: "",
1107
- sessionFile: activeSessionFile,
1108
- sessionKey: ctx.sessionKey,
1109
- sessionId: ctx.sessionId,
1110
- channel: ctx.channel,
1111
- channelId: ctx.channelId,
1112
- accountId: ctx.accountId,
1113
- messageThreadId: ctx.messageThreadId,
1114
- threadParentId: ctx.threadParentId,
1115
- });
1116
- }
1117
- for (const session of ctx.diagnosticsSessions ?? []) {
1118
- if (!session.sessionFile) {
1119
- continue;
1120
- }
1121
- candidates.push({
1122
- threadId: "",
1123
- sessionFile: session.sessionFile,
1124
- sessionKey: session.sessionKey,
1125
- sessionId: session.sessionId,
1126
- channel: session.channel,
1127
- channelId: session.channelId,
1128
- accountId: session.accountId,
1129
- messageThreadId: session.messageThreadId,
1130
- threadParentId: session.threadParentId,
1131
- });
1132
- }
1133
- const seenSessionFiles = new Set<string>();
1134
- const seenThreadIds = new Set<string>();
1135
- const targets: CodexDiagnosticsTarget[] = [];
1136
- for (const candidate of candidates) {
1137
- if (seenSessionFiles.has(candidate.sessionFile)) {
1138
- continue;
1139
- }
1140
- seenSessionFiles.add(candidate.sessionFile);
1141
- const binding = await deps.readCodexAppServerBinding(candidate.sessionFile);
1142
- if (!binding?.threadId || seenThreadIds.has(binding.threadId)) {
1143
- continue;
1144
- }
1145
- seenThreadIds.add(binding.threadId);
1146
- targets.push({ ...candidate, threadId: binding.threadId });
1147
- }
1148
- return targets;
1149
- }
1150
-
1151
- async function resolvePendingCodexDiagnosticsTargets(
1152
- deps: CodexCommandDeps,
1153
- targets: readonly CodexDiagnosticsTarget[],
1154
- ): Promise<CodexDiagnosticsTarget[]> {
1155
- const resolved: CodexDiagnosticsTarget[] = [];
1156
- for (const target of targets) {
1157
- const binding = await deps.readCodexAppServerBinding(target.sessionFile);
1158
- if (!binding?.threadId) {
1159
- continue;
1160
- }
1161
- resolved.push({ ...target, threadId: binding.threadId });
1162
- }
1163
- return resolved;
1164
- }
1165
-
1166
- function codexDiagnosticsTargetsMatch(
1167
- expected: readonly CodexDiagnosticsTarget[],
1168
- actual: readonly CodexDiagnosticsTarget[],
1169
- ): boolean {
1170
- const expectedThreadIds = expected.map((target) => target.threadId).toSorted();
1171
- const actualThreadIds = actual.map((target) => target.threadId).toSorted();
1172
- return (
1173
- expectedThreadIds.length === actualThreadIds.length &&
1174
- expectedThreadIds.every((threadId, index) => threadId === actualThreadIds[index])
1175
- );
1176
- }
1177
-
1178
- function formatCodexDiagnosticsUploadResult(
1179
- sent: readonly CodexDiagnosticsTarget[],
1180
- failed: ReadonlyArray<{ target: CodexDiagnosticsTarget; error: string }>,
1181
- ): string {
1182
- const lines: string[] = [];
1183
- if (sent.length > 0) {
1184
- lines.push("Codex diagnostics sent to OpenAI servers:");
1185
- lines.push(...formatCodexDiagnosticsTargetLines(sent));
1186
- lines.push("Included Codex logs and spawned Codex subthreads when available.");
1187
- }
1188
- if (failed.length > 0) {
1189
- if (lines.length > 0) {
1190
- lines.push("");
1191
- }
1192
- lines.push("Could not send Codex diagnostics:");
1193
- lines.push(
1194
- ...failed.map(
1195
- ({ target, error }) =>
1196
- `${formatCodexDiagnosticsTargetLine(target)}: ${formatCodexErrorForDisplay(error)}`,
1197
- ),
1198
- );
1199
- lines.push("Inspect locally:");
1200
- lines.push(
1201
- ...failed.map(({ target }) => `- ${formatCodexResumeCommandForDisplay(target.threadId)}`),
1202
- );
1203
- }
1204
- return lines.join("\n");
1205
- }
1206
-
1207
- function formatCodexDiagnosticsTargetLines(targets: readonly CodexDiagnosticsTarget[]): string[] {
1208
- return targets.flatMap((target, index) => {
1209
- const lines = formatCodexDiagnosticsTargetBlock(target, index);
1210
- return index < targets.length - 1 ? [...lines, ""] : lines;
1211
- });
1212
- }
1213
-
1214
- function formatCodexDiagnosticsTargetBlock(
1215
- target: CodexDiagnosticsTarget,
1216
- index: number,
1217
- ): string[] {
1218
- const lines = [`Session ${index + 1}`];
1219
- if (target.channel) {
1220
- lines.push(`Channel: ${formatCodexValueForDisplay(target.channel)}`);
1221
- }
1222
- if (target.sessionKey) {
1223
- lines.push(`AutoBot session key: ${formatCodexCopyableValueForDisplay(target.sessionKey)}`);
1224
- }
1225
- if (target.sessionId) {
1226
- lines.push(`AutoBot session id: ${formatCodexCopyableValueForDisplay(target.sessionId)}`);
1227
- }
1228
- lines.push(`Codex thread id: ${formatCodexCopyableValueForDisplay(target.threadId)}`);
1229
- lines.push(`Inspect locally: ${formatCodexResumeCommandForDisplay(target.threadId)}`);
1230
- return lines;
1231
- }
1232
-
1233
- function formatCodexDiagnosticsTargetLine(target: CodexDiagnosticsTarget): string {
1234
- const parts: string[] = [];
1235
- if (target.channel) {
1236
- parts.push(`channel ${formatCodexValueForDisplay(target.channel)}`);
1237
- }
1238
- const sessionLabel = target.sessionId || target.sessionKey;
1239
- if (sessionLabel) {
1240
- parts.push(`AutoBot session ${formatCodexValueForDisplay(sessionLabel)}`);
1241
- }
1242
- parts.push(`Codex thread ${formatCodexThreadIdForDisplay(target.threadId)}`);
1243
- return `- ${parts.join(", ")}`;
1244
- }
1245
-
1246
- function normalizeDiagnosticsReason(note: string): string | undefined {
1247
- const normalized = normalizeOptionalString(note);
1248
- return normalized ? normalized.slice(0, CODEX_DIAGNOSTICS_REASON_MAX_CHARS) : undefined;
1249
- }
1250
-
1251
- function parseDiagnosticsArgs(args: string): ParsedDiagnosticsArgs {
1252
- const [action, token, ...extra] = splitArgs(args);
1253
- const normalizedAction = action?.toLowerCase();
1254
- if (
1255
- (normalizedAction === "confirm" || normalizedAction === "--confirm") &&
1256
- token &&
1257
- extra.length === 0
1258
- ) {
1259
- return { action: "confirm", token };
1260
- }
1261
- if (
1262
- (normalizedAction === "cancel" || normalizedAction === "--cancel") &&
1263
- token &&
1264
- extra.length === 0
1265
- ) {
1266
- return { action: "cancel", token };
1267
- }
1268
- if (
1269
- normalizedAction === "confirm" ||
1270
- normalizedAction === "--confirm" ||
1271
- normalizedAction === "cancel" ||
1272
- normalizedAction === "--cancel"
1273
- ) {
1274
- return { action: "usage" };
1275
- }
1276
- return { action: "request", note: args };
1277
- }
1278
-
1279
- function formatDiagnosticsUsage(commandPrefix: string): string {
1280
- return [
1281
- `Usage: ${commandPrefix} [note]`,
1282
- `Usage: ${commandPrefix} confirm <token>`,
1283
- `Usage: ${commandPrefix} cancel <token>`,
1284
- ].join("\n");
1285
- }
1286
-
1287
- function createCodexDiagnosticsConfirmation(params: {
1288
- targets: CodexDiagnosticsTarget[];
1289
- note?: string;
1290
- senderId: string;
1291
- channel: string;
1292
- accountId?: string;
1293
- channelId?: string;
1294
- messageThreadId?: string;
1295
- threadParentId?: string;
1296
- sessionKey?: string;
1297
- scopeKey: string;
1298
- privateRouted?: boolean;
1299
- now: number;
1300
- }): string {
1301
- prunePendingCodexDiagnosticsConfirmations(params.now);
1302
- if (
1303
- !pendingCodexDiagnosticsConfirmationTokensByScope.has(params.scopeKey) &&
1304
- pendingCodexDiagnosticsConfirmationTokensByScope.size >=
1305
- CODEX_DIAGNOSTICS_CONFIRMATION_MAX_SCOPES
1306
- ) {
1307
- const oldestScopeKey = pendingCodexDiagnosticsConfirmationTokensByScope.keys().next().value;
1308
- if (typeof oldestScopeKey === "string") {
1309
- deletePendingCodexDiagnosticsConfirmationScope(oldestScopeKey);
1310
- }
1311
- }
1312
- const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(params.scopeKey) ?? [];
1313
- while (scopeTokens.length >= CODEX_DIAGNOSTICS_CONFIRMATION_MAX_REQUESTS_PER_SCOPE) {
1314
- const oldestToken = scopeTokens.shift();
1315
- if (!oldestToken) {
1316
- break;
1317
- }
1318
- pendingCodexDiagnosticsConfirmations.delete(oldestToken);
1319
- }
1320
- const token = crypto.randomBytes(6).toString("hex");
1321
- scopeTokens.push(token);
1322
- pendingCodexDiagnosticsConfirmationTokensByScope.set(params.scopeKey, scopeTokens);
1323
- pendingCodexDiagnosticsConfirmations.set(token, {
1324
- token,
1325
- targets: params.targets,
1326
- note: params.note,
1327
- senderId: params.senderId,
1328
- channel: params.channel,
1329
- accountId: params.accountId,
1330
- channelId: params.channelId,
1331
- messageThreadId: params.messageThreadId,
1332
- threadParentId: params.threadParentId,
1333
- sessionKey: params.sessionKey,
1334
- scopeKey: params.scopeKey,
1335
- ...(params.privateRouted === undefined ? {} : { privateRouted: params.privateRouted }),
1336
- createdAt: params.now,
1337
- });
1338
- return token;
1339
- }
1340
-
1341
- function readCodexDiagnosticsConfirmationScope(ctx: PluginCommandContext): {
1342
- accountId?: string;
1343
- channelId?: string;
1344
- messageThreadId?: string;
1345
- threadParentId?: string;
1346
- sessionKey?: string;
1347
- } {
1348
- return {
1349
- accountId: normalizeCodexDiagnosticsScopeField(ctx.accountId),
1350
- channelId: normalizeCodexDiagnosticsScopeField(ctx.channelId),
1351
- messageThreadId:
1352
- typeof ctx.messageThreadId === "string" || typeof ctx.messageThreadId === "number"
1353
- ? normalizeCodexDiagnosticsScopeField(String(ctx.messageThreadId))
1354
- : undefined,
1355
- threadParentId: normalizeCodexDiagnosticsScopeField(ctx.threadParentId),
1356
- sessionKey: normalizeCodexDiagnosticsScopeField(ctx.sessionKey),
1357
- };
1358
- }
1359
-
1360
- function readCodexDiagnosticsScopeMismatch(
1361
- pending: PendingCodexDiagnosticsConfirmation,
1362
- ctx: PluginCommandContext,
1363
- ):
1364
- | {
1365
- confirmMessage: string;
1366
- cancelMessage: string;
1367
- }
1368
- | undefined {
1369
- const current = readCodexDiagnosticsConfirmationScope(ctx);
1370
- if (pending.accountId !== current.accountId) {
1371
- return {
1372
- confirmMessage: "This Codex diagnostics confirmation belongs to a different account.",
1373
- cancelMessage: "This Codex diagnostics confirmation belongs to a different account.",
1374
- };
1375
- }
1376
- if (pending.privateRouted) {
1377
- return undefined;
1378
- }
1379
- if (pending.channelId !== current.channelId) {
1380
- return {
1381
- confirmMessage:
1382
- "This Codex diagnostics confirmation belongs to a different channel instance.",
1383
- cancelMessage: "This Codex diagnostics confirmation belongs to a different channel instance.",
1384
- };
1385
- }
1386
- if (pending.messageThreadId !== current.messageThreadId) {
1387
- return {
1388
- confirmMessage: "This Codex diagnostics confirmation belongs to a different thread.",
1389
- cancelMessage: "This Codex diagnostics confirmation belongs to a different thread.",
1390
- };
1391
- }
1392
- if (pending.threadParentId !== current.threadParentId) {
1393
- return {
1394
- confirmMessage: "This Codex diagnostics confirmation belongs to a different parent thread.",
1395
- cancelMessage: "This Codex diagnostics confirmation belongs to a different parent thread.",
1396
- };
1397
- }
1398
- if (pending.sessionKey !== current.sessionKey) {
1399
- return {
1400
- confirmMessage: "This Codex diagnostics confirmation belongs to a different session.",
1401
- cancelMessage: "This Codex diagnostics confirmation belongs to a different session.",
1402
- };
1403
- }
1404
- return undefined;
1405
- }
1406
-
1407
- function readPendingCodexDiagnosticsConfirmation(
1408
- token: string,
1409
- now: number,
1410
- ): PendingCodexDiagnosticsConfirmation | undefined {
1411
- prunePendingCodexDiagnosticsConfirmations(now);
1412
- return pendingCodexDiagnosticsConfirmations.get(token);
1413
- }
1414
-
1415
- function prunePendingCodexDiagnosticsConfirmations(now: number): void {
1416
- for (const [token, pending] of pendingCodexDiagnosticsConfirmations) {
1417
- if (now - pending.createdAt >= CODEX_DIAGNOSTICS_CONFIRMATION_TTL_MS) {
1418
- deletePendingCodexDiagnosticsConfirmation(token);
1419
- }
1420
- }
1421
- }
1422
-
1423
- function deletePendingCodexDiagnosticsConfirmation(token: string): void {
1424
- const pending = pendingCodexDiagnosticsConfirmations.get(token);
1425
- pendingCodexDiagnosticsConfirmations.delete(token);
1426
- if (!pending) {
1427
- return;
1428
- }
1429
- const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(pending.scopeKey);
1430
- if (!scopeTokens) {
1431
- return;
1432
- }
1433
- const tokenIndex = scopeTokens.indexOf(token);
1434
- if (tokenIndex >= 0) {
1435
- scopeTokens.splice(tokenIndex, 1);
1436
- }
1437
- if (scopeTokens.length === 0) {
1438
- pendingCodexDiagnosticsConfirmationTokensByScope.delete(pending.scopeKey);
1439
- }
1440
- }
1441
-
1442
- function deletePendingCodexDiagnosticsConfirmationScope(scopeKey: string): void {
1443
- const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(scopeKey) ?? [];
1444
- for (const token of scopeTokens) {
1445
- pendingCodexDiagnosticsConfirmations.delete(token);
1446
- }
1447
- pendingCodexDiagnosticsConfirmationTokensByScope.delete(scopeKey);
1448
- }
1449
-
1450
- function buildDiagnosticsTags(ctx: PluginCommandContext): Record<string, string> {
1451
- const tags: Record<string, string> = {
1452
- source: CODEX_DIAGNOSTICS_SOURCE,
1453
- };
1454
- addTag(tags, "channel", ctx.channel);
1455
- return tags;
1456
- }
1457
-
1458
- function addTag(tags: Record<string, string>, key: string, value: unknown): void {
1459
- if (typeof value === "string" && value.trim()) {
1460
- tags[key] = value.trim();
1461
- }
1462
- }
1463
-
1464
- function formatCodexThreadIdForDisplay(threadId: string): string {
1465
- return escapeCodexChatText(formatCodexTextForDisplay(threadId));
1466
- }
1467
-
1468
- function formatCodexValueForDisplay(value: string): string {
1469
- return escapeCodexChatText(formatCodexTextForDisplay(value));
1470
- }
1471
-
1472
- function formatCodexCopyableValueForDisplay(value: string): string {
1473
- const safe = formatCodexTextForDisplay(value);
1474
- if (CODEX_RESUME_SAFE_THREAD_ID_PATTERN.test(safe)) {
1475
- return `\`${safe}\``;
1476
- }
1477
- return escapeCodexChatText(safe);
1478
- }
1479
-
1480
- function formatCodexTextForDisplay(value: string): string {
1481
- let safe = "";
1482
- for (const character of value) {
1483
- const codePoint = character.codePointAt(0);
1484
- safe += codePoint != null && isUnsafeDisplayCodePoint(codePoint) ? "?" : character;
1485
- }
1486
- safe = safe.trim();
1487
- return safe || "<unknown>";
1488
- }
1489
-
1490
- function escapeCodexChatText(value: string): string {
1491
- return value
1492
- .replaceAll("&", "&amp;")
1493
- .replaceAll("<", "&lt;")
1494
- .replaceAll(">", "&gt;")
1495
- .replaceAll("@", "\uff20")
1496
- .replaceAll("`", "\uff40")
1497
- .replaceAll("[", "\uff3b")
1498
- .replaceAll("]", "\uff3d")
1499
- .replaceAll("(", "\uff08")
1500
- .replaceAll(")", "\uff09")
1501
- .replaceAll("*", "\u2217")
1502
- .replaceAll("_", "\uff3f")
1503
- .replaceAll("~", "\uff5e")
1504
- .replaceAll("|", "\uff5c");
1505
- }
1506
-
1507
- function readCodexDiagnosticsCooldownMs(threadId: string, now: number): number {
1508
- const lastSentAt = lastCodexDiagnosticsUploadByThread.get(threadId);
1509
- if (!lastSentAt) {
1510
- return 0;
1511
- }
1512
- const remainingMs = Math.max(0, CODEX_DIAGNOSTICS_COOLDOWN_MS - (now - lastSentAt));
1513
- if (remainingMs === 0) {
1514
- lastCodexDiagnosticsUploadByThread.delete(threadId);
1515
- }
1516
- return remainingMs;
1517
- }
1518
-
1519
- function readCodexDiagnosticsTargetsCooldownMessage(
1520
- targets: readonly CodexDiagnosticsTarget[],
1521
- ctx: PluginCommandContext,
1522
- now: number,
1523
- options: { includeThreadId?: boolean } = {},
1524
- ): string | undefined {
1525
- for (const target of targets) {
1526
- const cooldownMs = readCodexDiagnosticsCooldownMs(target.threadId, now);
1527
- if (cooldownMs > 0) {
1528
- if (options.includeThreadId === false) {
1529
- return `Codex diagnostics were already sent for one of these Codex threads recently. Try again in ${Math.ceil(
1530
- cooldownMs / 1000,
1531
- )}s.`;
1532
- }
1533
- const displayThreadId = formatCodexThreadIdForDisplay(target.threadId);
1534
- return `Codex diagnostics were already sent for thread ${displayThreadId} recently. Try again in ${Math.ceil(
1535
- cooldownMs / 1000,
1536
- )}s.`;
1537
- }
1538
- }
1539
- const scopeCooldownMs = readCodexDiagnosticsScopeCooldownMs(
1540
- readCodexDiagnosticsCooldownScope(ctx),
1541
- now,
1542
- );
1543
- if (scopeCooldownMs > 0) {
1544
- return `Codex diagnostics were already sent for this account or channel recently. Try again in ${Math.ceil(
1545
- scopeCooldownMs / 1000,
1546
- )}s.`;
1547
- }
1548
- return undefined;
1549
- }
1550
-
1551
- function readCodexDiagnosticsScopeCooldownMs(scope: string, now: number): number {
1552
- const lastSentAt = lastCodexDiagnosticsUploadByScope.get(scope);
1553
- if (!lastSentAt) {
1554
- return 0;
1555
- }
1556
- const remainingMs = Math.max(0, CODEX_DIAGNOSTICS_COOLDOWN_MS - (now - lastSentAt));
1557
- if (remainingMs === 0) {
1558
- lastCodexDiagnosticsUploadByScope.delete(scope);
1559
- }
1560
- return remainingMs;
1561
- }
1562
-
1563
- function recordCodexDiagnosticsUpload(
1564
- threadId: string,
1565
- ctx: PluginCommandContext,
1566
- now: number,
1567
- ): void {
1568
- pruneCodexDiagnosticsCooldowns(now);
1569
- recordBoundedCodexDiagnosticsCooldown(
1570
- lastCodexDiagnosticsUploadByScope,
1571
- readCodexDiagnosticsCooldownScope(ctx),
1572
- CODEX_DIAGNOSTICS_COOLDOWN_MAX_SCOPES,
1573
- now,
1574
- );
1575
- recordBoundedCodexDiagnosticsCooldown(
1576
- lastCodexDiagnosticsUploadByThread,
1577
- threadId,
1578
- CODEX_DIAGNOSTICS_COOLDOWN_MAX_THREADS,
1579
- now,
1580
- );
1581
- }
1582
-
1583
- function recordBoundedCodexDiagnosticsCooldown(
1584
- map: Map<string, number>,
1585
- key: string,
1586
- maxSize: number,
1587
- now: number,
1588
- ): void {
1589
- if (!map.has(key)) {
1590
- while (map.size >= maxSize) {
1591
- const oldestKey = map.keys().next().value;
1592
- if (typeof oldestKey !== "string") {
1593
- break;
1594
- }
1595
- map.delete(oldestKey);
1596
- }
1597
- }
1598
- map.set(key, now);
1599
- }
1600
-
1601
- function readCodexDiagnosticsCooldownScope(ctx: PluginCommandContext): string {
1602
- const scope = readCodexDiagnosticsConfirmationScope(ctx);
1603
- const payload = JSON.stringify({
1604
- accountId: scope.accountId ?? null,
1605
- channelId: scope.channelId ?? null,
1606
- sessionKey: scope.sessionKey ?? null,
1607
- messageThreadId: scope.messageThreadId ?? null,
1608
- threadParentId: scope.threadParentId ?? null,
1609
- senderId: normalizeCodexDiagnosticsScopeField(ctx.senderId) ?? null,
1610
- channel: normalizeCodexDiagnosticsScopeField(ctx.channel) ?? "",
1611
- });
1612
- return crypto.createHash("sha256").update(payload).digest("hex");
1613
- }
1614
-
1615
- function pruneCodexDiagnosticsCooldowns(now: number): void {
1616
- pruneCodexDiagnosticsCooldownMap(lastCodexDiagnosticsUploadByThread, now);
1617
- pruneCodexDiagnosticsCooldownMap(lastCodexDiagnosticsUploadByScope, now);
1618
- }
1619
-
1620
- function pruneCodexDiagnosticsCooldownMap(map: Map<string, number>, now: number): void {
1621
- for (const [key, lastSentAt] of map) {
1622
- if (now - lastSentAt >= CODEX_DIAGNOSTICS_COOLDOWN_MS) {
1623
- map.delete(key);
1624
- }
1625
- }
1626
- }
1627
-
1628
- function formatCodexErrorForDisplay(error: string): string {
1629
- const safe = formatCodexTextForDisplay(error).slice(0, CODEX_DIAGNOSTICS_ERROR_MAX_CHARS);
1630
- return escapeCodexChatText(safe) || "unknown error";
1631
- }
1632
-
1633
- function formatCodexResumeCommandForDisplay(threadId: string): string {
1634
- const safeThreadId = formatCodexTextForDisplay(threadId);
1635
- if (!CODEX_RESUME_SAFE_THREAD_ID_PATTERN.test(safeThreadId)) {
1636
- return "run codex resume and paste the thread id shown above";
1637
- }
1638
- return `\`codex resume ${safeThreadId}\``;
1639
- }
1640
-
1641
- function isUnsafeDisplayCodePoint(codePoint: number): boolean {
1642
- return (
1643
- codePoint <= 0x001f ||
1644
- (codePoint >= 0x007f && codePoint <= 0x009f) ||
1645
- codePoint === 0x00ad ||
1646
- codePoint === 0x061c ||
1647
- codePoint === 0x180e ||
1648
- (codePoint >= 0x200b && codePoint <= 0x200f) ||
1649
- (codePoint >= 0x202a && codePoint <= 0x202e) ||
1650
- (codePoint >= 0x2060 && codePoint <= 0x206f) ||
1651
- codePoint === 0xfeff ||
1652
- (codePoint >= 0xfff9 && codePoint <= 0xfffb) ||
1653
- (codePoint >= 0xe0000 && codePoint <= 0xe007f)
1654
- );
1655
- }
1656
-
1657
- function normalizeCodexDiagnosticsScopeField(value: string | undefined): string | undefined {
1658
- const normalized = normalizeOptionalString(value);
1659
- if (!normalized) {
1660
- return undefined;
1661
- }
1662
- if (normalized.length <= CODEX_DIAGNOSTICS_SCOPE_FIELD_MAX_CHARS) {
1663
- return normalized;
1664
- }
1665
- return `sha256:${crypto.createHash("sha256").update(normalized).digest("hex")}`;
1666
- }
1667
-
1668
- async function startThreadAction(
1669
- deps: CodexCommandDeps,
1670
- ctx: PluginCommandContext,
1671
- pluginConfig: unknown,
1672
- method: typeof CODEX_CONTROL_METHODS.compact | typeof CODEX_CONTROL_METHODS.review,
1673
- label: string,
1674
- args: string[],
1675
- ): Promise<string> {
1676
- if (args.length > 0) {
1677
- return `Usage: /codex ${label === "compaction" ? "compact" : label}`;
1678
- }
1679
- const target = await resolveControlTarget(ctx);
1680
- if (!target) {
1681
- return `Cannot start Codex ${label} because this command did not include an AutoBot session file.`;
1682
- }
1683
- const binding = await deps.readCodexAppServerBinding(target.sessionFile, {
1684
- agentDir: target.agentDir,
1685
- config: ctx.config,
1686
- });
1687
- if (!binding?.threadId) {
1688
- return `No Codex thread is attached to this AutoBot session yet.`;
1689
- }
1690
- if (method === CODEX_CONTROL_METHODS.review) {
1691
- await deps.codexControlRequest(
1692
- pluginConfig,
1693
- method,
1694
- {
1695
- threadId: binding.threadId,
1696
- target: { type: "uncommittedChanges" },
1697
- },
1698
- {
1699
- agentDir: target.agentDir,
1700
- authProfileId: binding.authProfileId,
1701
- config: ctx.config,
1702
- },
1703
- );
1704
- } else {
1705
- await deps.codexControlRequest(
1706
- pluginConfig,
1707
- method,
1708
- { threadId: binding.threadId },
1709
- {
1710
- agentDir: target.agentDir,
1711
- authProfileId: binding.authProfileId,
1712
- config: ctx.config,
1713
- },
1714
- );
1715
- }
1716
- return `Started Codex ${label} for thread ${formatCodexDisplayText(binding.threadId)}.`;
1717
- }
1718
-
1719
- function splitArgs(value: string | undefined): string[] {
1720
- const input = value ?? "";
1721
- const args: string[] = [];
1722
- let current = "";
1723
- let quote: '"' | "'" | undefined;
1724
- let escaping = false;
1725
- let tokenStarted = false;
1726
- for (const char of input) {
1727
- if (escaping) {
1728
- current += char;
1729
- escaping = false;
1730
- tokenStarted = true;
1731
- continue;
1732
- }
1733
- if (char === "\\" && quote !== "'") {
1734
- escaping = true;
1735
- tokenStarted = true;
1736
- continue;
1737
- }
1738
- if (quote) {
1739
- if (char === quote) {
1740
- quote = undefined;
1741
- } else {
1742
- current += char;
1743
- }
1744
- tokenStarted = true;
1745
- continue;
1746
- }
1747
- if (char === '"' || char === "'") {
1748
- quote = char;
1749
- tokenStarted = true;
1750
- continue;
1751
- }
1752
- if (/\s/.test(char)) {
1753
- if (tokenStarted) {
1754
- args.push(current);
1755
- current = "";
1756
- tokenStarted = false;
1757
- }
1758
- continue;
1759
- }
1760
- current += char;
1761
- tokenStarted = true;
1762
- }
1763
- if (escaping) {
1764
- current += "\\";
1765
- }
1766
- if (tokenStarted) {
1767
- args.push(current);
1768
- }
1769
- return args;
1770
- }
1771
-
1772
- function parseBindArgs(args: string[]): ParsedBindArgs {
1773
- const parsed: ParsedBindArgs = {};
1774
- for (let index = 0; index < args.length; index += 1) {
1775
- const arg = args[index];
1776
- if (arg === "--help" || arg === "-h") {
1777
- parsed.help = true;
1778
- continue;
1779
- }
1780
- if (arg === "--cwd") {
1781
- const value = readRequiredOptionValue(args, index);
1782
- if (!value || parsed.cwd !== undefined) {
1783
- parsed.help = true;
1784
- continue;
1785
- }
1786
- parsed.cwd = value;
1787
- index += 1;
1788
- continue;
1789
- }
1790
- if (arg === "--model") {
1791
- const value = readRequiredOptionValue(args, index);
1792
- if (!value || parsed.model !== undefined) {
1793
- parsed.help = true;
1794
- continue;
1795
- }
1796
- parsed.model = value;
1797
- index += 1;
1798
- continue;
1799
- }
1800
- if (arg === "--provider" || arg === "--model-provider") {
1801
- const value = readRequiredOptionValue(args, index);
1802
- if (!value || parsed.provider !== undefined) {
1803
- parsed.help = true;
1804
- continue;
1805
- }
1806
- parsed.provider = value;
1807
- index += 1;
1808
- continue;
1809
- }
1810
- if (!arg.startsWith("-") && !parsed.threadId) {
1811
- parsed.threadId = arg;
1812
- continue;
1813
- }
1814
- parsed.help = true;
1815
- }
1816
- parsed.threadId = normalizeOptionalString(parsed.threadId);
1817
- parsed.cwd = normalizeOptionalString(parsed.cwd);
1818
- parsed.model = normalizeOptionalString(parsed.model);
1819
- parsed.provider = normalizeOptionalString(parsed.provider);
1820
- return parsed;
1821
- }
1822
-
1823
- function parseCodexCliSessionsArgs(args: string[]): ParsedCodexCliSessionsArgs {
1824
- const parsed: ParsedCodexCliSessionsArgs = { filter: "" };
1825
- const filter: string[] = [];
1826
- for (let index = 0; index < args.length; index += 1) {
1827
- const arg = args[index];
1828
- if (arg === "--help" || arg === "-h") {
1829
- parsed.help = true;
1830
- continue;
1831
- }
1832
- if (arg === "--host" || arg === "--node") {
1833
- const value = readRequiredOptionValue(args, index);
1834
- if (!value || parsed.host !== undefined) {
1835
- parsed.help = true;
1836
- continue;
1837
- }
1838
- parsed.host = value;
1839
- index += 1;
1840
- continue;
1841
- }
1842
- if (arg === "--limit") {
1843
- const value = readRequiredOptionValue(args, index);
1844
- const parsedLimit = value ? Number.parseInt(value, 10) : Number.NaN;
1845
- if (!Number.isFinite(parsedLimit) || parsedLimit <= 0) {
1846
- parsed.help = true;
1847
- continue;
1848
- }
1849
- parsed.limit = parsedLimit;
1850
- index += 1;
1851
- continue;
1852
- }
1853
- if (arg.startsWith("-")) {
1854
- parsed.help = true;
1855
- continue;
1856
- }
1857
- filter.push(arg);
1858
- }
1859
- parsed.host = normalizeOptionalString(parsed.host);
1860
- parsed.filter = filter.join(" ").trim();
1861
- return parsed;
1862
- }
1863
-
1864
- function parseResumeArgs(args: string[]): ParsedResumeArgs {
1865
- const parsed: ParsedResumeArgs = {};
1866
- for (let index = 0; index < args.length; index += 1) {
1867
- const arg = args[index];
1868
- if (arg === "--help" || arg === "-h") {
1869
- parsed.help = true;
1870
- continue;
1871
- }
1872
- if (arg === "--host" || arg === "--node") {
1873
- const value = readRequiredOptionValue(args, index);
1874
- if (!value || parsed.host !== undefined) {
1875
- parsed.help = true;
1876
- continue;
1877
- }
1878
- parsed.host = value;
1879
- index += 1;
1880
- continue;
1881
- }
1882
- if (arg === "--bind") {
1883
- const value = readRequiredOptionValue(args, index);
1884
- if (value !== "here" || parsed.bindHere !== undefined) {
1885
- parsed.help = true;
1886
- continue;
1887
- }
1888
- parsed.bindHere = true;
1889
- index += 1;
1890
- continue;
1891
- }
1892
- if (!arg.startsWith("-") && !parsed.threadId) {
1893
- parsed.threadId = arg;
1894
- continue;
1895
- }
1896
- parsed.help = true;
1897
- }
1898
- parsed.threadId = normalizeOptionalString(parsed.threadId);
1899
- parsed.host = normalizeOptionalString(parsed.host);
1900
- return parsed;
1901
- }
1902
-
1903
- function parseComputerUseArgs(args: string[]): ParsedComputerUseArgs {
1904
- const parsed: ParsedComputerUseArgs = {
1905
- action: "status",
1906
- overrides: {},
1907
- hasOverrides: false,
1908
- };
1909
- let sawAction = false;
1910
- for (let index = 0; index < args.length; index += 1) {
1911
- const arg = args[index];
1912
- if (arg === "--help" || arg === "-h") {
1913
- parsed.help = true;
1914
- continue;
1915
- }
1916
- if (arg === "status" || arg === "install") {
1917
- if (sawAction) {
1918
- parsed.help = true;
1919
- continue;
1920
- }
1921
- sawAction = true;
1922
- parsed.action = arg;
1923
- continue;
1924
- }
1925
- if (arg === "--source" || arg === "--marketplace-source") {
1926
- const value = readRequiredOptionValue(args, index);
1927
- if (!value || parsed.overrides.marketplaceSource !== undefined) {
1928
- parsed.help = true;
1929
- continue;
1930
- }
1931
- parsed.overrides.marketplaceSource = value;
1932
- index += 1;
1933
- continue;
1934
- }
1935
- if (arg === "--marketplace-path" || arg === "--path") {
1936
- const value = readRequiredOptionValue(args, index);
1937
- if (!value || parsed.overrides.marketplacePath !== undefined) {
1938
- parsed.help = true;
1939
- continue;
1940
- }
1941
- parsed.overrides.marketplacePath = value;
1942
- index += 1;
1943
- continue;
1944
- }
1945
- if (arg === "--marketplace") {
1946
- const value = readRequiredOptionValue(args, index);
1947
- if (!value || parsed.overrides.marketplaceName !== undefined) {
1948
- parsed.help = true;
1949
- continue;
1950
- }
1951
- parsed.overrides.marketplaceName = value;
1952
- index += 1;
1953
- continue;
1954
- }
1955
- if (arg === "--plugin") {
1956
- const value = readRequiredOptionValue(args, index);
1957
- if (!value || parsed.overrides.pluginName !== undefined) {
1958
- parsed.help = true;
1959
- continue;
1960
- }
1961
- parsed.overrides.pluginName = value;
1962
- index += 1;
1963
- continue;
1964
- }
1965
- if (arg === "--server" || arg === "--mcp-server") {
1966
- const value = readRequiredOptionValue(args, index);
1967
- if (!value || parsed.overrides.mcpServerName !== undefined) {
1968
- parsed.help = true;
1969
- continue;
1970
- }
1971
- parsed.overrides.mcpServerName = value;
1972
- index += 1;
1973
- continue;
1974
- }
1975
- parsed.help = true;
1976
- }
1977
- parsed.overrides = normalizeComputerUseStringOverrides(parsed.overrides);
1978
- parsed.hasOverrides = Object.values(parsed.overrides).some(Boolean);
1979
- return parsed;
1980
- }
1981
-
1982
- function readRequiredOptionValue(args: string[], index: number): string | undefined {
1983
- const value = args[index + 1];
1984
- const normalized = value?.trim();
1985
- if (!normalized || normalized.startsWith("-")) {
1986
- return undefined;
1987
- }
1988
- return value;
1989
- }
1990
-
1991
- function normalizeComputerUseStringOverrides(
1992
- overrides: Partial<CodexComputerUseConfig>,
1993
- ): Partial<CodexComputerUseConfig> {
1994
- const normalized: Partial<CodexComputerUseConfig> = {};
1995
- const marketplaceSource = normalizeOptionalString(overrides.marketplaceSource);
1996
- if (marketplaceSource) {
1997
- normalized.marketplaceSource = marketplaceSource;
1998
- }
1999
- const marketplacePath = normalizeOptionalString(overrides.marketplacePath);
2000
- if (marketplacePath) {
2001
- normalized.marketplacePath = marketplacePath;
2002
- }
2003
- const marketplaceName = normalizeOptionalString(overrides.marketplaceName);
2004
- if (marketplaceName) {
2005
- normalized.marketplaceName = marketplaceName;
2006
- }
2007
- const pluginName = normalizeOptionalString(overrides.pluginName);
2008
- if (pluginName) {
2009
- normalized.pluginName = pluginName;
2010
- }
2011
- const mcpServerName = normalizeOptionalString(overrides.mcpServerName);
2012
- if (mcpServerName) {
2013
- normalized.mcpServerName = mcpServerName;
2014
- }
2015
- return normalized;
2016
- }
2017
-
2018
- function normalizeOptionalString(value: string | undefined): string | undefined {
2019
- const trimmed = value?.trim();
2020
- return trimmed || undefined;
2021
- }