@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
@@ -0,0 +1,1533 @@
1
+ import { a as isCodexFastServiceTier, c as resolveCodexAppServerRuntimeOptions } from "./config-CLMSw0p2.js";
2
+ import { n as listCodexAppServerModels, t as listAllCodexAppServerModels } from "./models-jLA2SIvd.js";
3
+ import { t as isJsonObject } from "./protocol-C9UWI98H.js";
4
+ import { i as describeControlFailure, r as CODEX_CONTROL_METHODS, t as requestCodexAppServerJson } from "./request-DbSPeTcV.js";
5
+ import { a as formatComputerUseStatus, c as formatThreads, i as formatCodexStatus, l as readString$1, n as formatAccount, o as formatList, p as summarizeCodexAccountUsage, r as formatCodexDisplayText, s as formatModels, t as buildHelp } from "./command-formatters-BpPOTePl.js";
6
+ import { i as readCodexAppServerBinding, o as writeCodexAppServerBinding, t as clearCodexAppServerBinding } from "./session-binding-e2GFp9VH.js";
7
+ import { _ as steerCodexConversationTurn, b as readCodexConversationBindingData, d as parseCodexFastModeArg, f as parseCodexPermissionsModeArg, g as setCodexConversationPermissions, h as setCodexConversationModel, l as startCodexConversationThread, m as setCodexConversationFastMode, p as readCodexConversationActiveTurn, r as formatCodexCliSessions, u as formatPermissionsMode, v as stopCodexConversationTurn, x as resolveCodexDefaultWorkspaceDir, y as createCodexCliNodeConversationBindingData } from "./node-cli-sessions-BLRDs_US.js";
8
+ import { n as installCodexComputerUse, r as readCodexComputerUseStatus } from "./computer-use-DCZB46Sw.js";
9
+ import { n as rememberCodexRateLimits } from "./rate-limit-cache-9LxQdE0K.js";
10
+ import crypto from "node:crypto";
11
+ import { ensureAuthProfileStore, findNormalizedProviderValue, resolveAgentDir, resolveAuthProfileEligibility, resolveAuthProfileOrder, resolveDefaultAgentDir, resolveProfileUnusableUntilForDisplay, resolveSessionAgentIds } from "autobot/plugin-sdk/agent-runtime";
12
+ //#region extensions/codex/src/command-account.ts
13
+ const OPENAI_PROVIDER_ID = "openai";
14
+ const OPENAI_CODEX_PROVIDER_ID = "openai-codex";
15
+ async function readCodexAccountAuthOverview(params) {
16
+ const config = params.ctx.config;
17
+ const store = ensureAuthProfileStore(resolveDefaultAgentDir(config), {
18
+ allowKeychainPrompt: false,
19
+ config
20
+ });
21
+ const order = resolveDisplayAuthOrder({
22
+ config,
23
+ store
24
+ });
25
+ if (order.length === 0) return;
26
+ const now = Date.now();
27
+ const activeProfileId = resolveActiveProfileId({
28
+ store,
29
+ order,
30
+ config,
31
+ account: params.account,
32
+ limits: params.limits,
33
+ now
34
+ });
35
+ const subscriptionProfileId = order.find((profileId) => isChatGptSubscriptionProfile(store.profiles[profileId]));
36
+ const activeIsSubscription = activeProfileId !== void 0 && isChatGptSubscriptionProfile(store.profiles[activeProfileId]);
37
+ const activeUsage = activeIsSubscription && params.limits.ok ? summarizeCodexAccountUsage(params.limits.value, now) : void 0;
38
+ const subscriptionUsage = subscriptionProfileId && (!activeIsSubscription || subscriptionProfileId !== activeProfileId) ? await readSubscriptionUsage({
39
+ ...params,
40
+ config,
41
+ subscriptionProfileId,
42
+ now
43
+ }) : activeUsage;
44
+ if (!params.account.ok && !params.limits.ok && !subscriptionUsage) return;
45
+ const rows = order.map((profileId, index) => buildProfileRow({
46
+ store,
47
+ config,
48
+ profileId,
49
+ activeProfileId,
50
+ activeIndex: activeProfileId ? order.indexOf(activeProfileId) : -1,
51
+ index,
52
+ now,
53
+ usage: profileId === subscriptionProfileId ? subscriptionUsage : void 0
54
+ }));
55
+ const activeRow = rows.find((row) => row.active);
56
+ if (!activeRow) return {
57
+ currentLine: "OpenAI credentials: no working credential",
58
+ orderTitle: "Auth order",
59
+ rows
60
+ };
61
+ const activeIsApiKey = store.profiles[activeRow.profileId]?.type === "api_key";
62
+ const subscriptionLabel = subscriptionProfileId ? formatProfileLabel(subscriptionProfileId, store.profiles[subscriptionProfileId]) : activeIsSubscription ? activeRow.label : void 0;
63
+ const subscriptionUsageLine = formatSubscriptionUsageLine(subscriptionUsage);
64
+ return {
65
+ ...activeIsApiKey ? { currentLine: buildApiKeyActiveLine(activeRow, subscriptionUsage) } : {},
66
+ ...subscriptionLabel ? { subscriptionLabel } : {},
67
+ ...subscriptionUsageLine ? { subscriptionUsage: subscriptionUsageLine } : {},
68
+ orderTitle: "Auth order",
69
+ rows
70
+ };
71
+ }
72
+ function resolveDisplayAuthOrder(params) {
73
+ const codexOrder = resolveOrder(params.store.order, OPENAI_CODEX_PROVIDER_ID) ?? resolveOrder(params.config?.auth?.order, OPENAI_CODEX_PROVIDER_ID);
74
+ if (codexOrder && codexOrder.length > 0) return dedupe(codexOrder);
75
+ return resolveAuthProfileOrder({
76
+ cfg: params.config,
77
+ store: params.store,
78
+ provider: OPENAI_CODEX_PROVIDER_ID
79
+ });
80
+ }
81
+ function resolveOrder(order, provider) {
82
+ return findNormalizedProviderValue(order, provider);
83
+ }
84
+ function resolveActiveProfileId(params) {
85
+ const liveProfileId = resolveLiveAccountProfileId({
86
+ account: params.account,
87
+ store: params.store,
88
+ order: params.order
89
+ });
90
+ if (liveProfileId) return liveProfileId;
91
+ const lastGood = [params.store.lastGood?.[OPENAI_PROVIDER_ID], params.store.lastGood?.[OPENAI_CODEX_PROVIDER_ID]].find((profileId) => !!profileId && params.order.includes(profileId) && isActiveProfileCandidate(params, profileId));
92
+ if (lastGood) return lastGood;
93
+ const mostRecent = params.order.map((profileId) => ({
94
+ profileId,
95
+ lastUsed: params.store.usageStats?.[profileId]?.lastUsed ?? 0
96
+ })).filter((entry) => entry.lastUsed > 0 && isActiveProfileCandidate(params, entry.profileId)).toSorted((left, right) => right.lastUsed - left.lastUsed)[0]?.profileId;
97
+ if (mostRecent) return mostRecent;
98
+ if (shouldInferApiKeyActiveFromRateLimitProbe(params.limits)) {
99
+ const apiKeyProfile = params.order.find((profileId) => params.store.profiles[profileId]?.type === "api_key");
100
+ if (apiKeyProfile) return apiKeyProfile;
101
+ }
102
+ return resolveAuthProfileOrder({
103
+ cfg: params.config,
104
+ store: params.store,
105
+ provider: OPENAI_CODEX_PROVIDER_ID
106
+ })[0];
107
+ }
108
+ function isActiveProfileCandidate(params, profileId) {
109
+ return !isActiveUntil(resolveProfileUnusableUntilForDisplay(params.store, profileId) ?? void 0, params.now);
110
+ }
111
+ function resolveLiveAccountProfileId(params) {
112
+ if (!params.account.ok || !isJsonObject(params.account.value)) return;
113
+ const account = isJsonObject(params.account.value.account) ? params.account.value.account : params.account.value;
114
+ const type = readString(account, "type")?.toLowerCase();
115
+ if (type === "chatgpt") {
116
+ const email = readString(account, "email")?.toLowerCase();
117
+ const firstSubscription = params.order.find((profileId) => isChatGptSubscriptionProfile(params.store.profiles[profileId]));
118
+ if (!email) return firstSubscription;
119
+ return params.order.find((profileId) => {
120
+ const credential = params.store.profiles[profileId];
121
+ if (!isChatGptSubscriptionProfile(credential)) return false;
122
+ return (credential.email?.trim().toLowerCase() ?? extractEmailFromProfileId(profileId))?.toLowerCase() === email;
123
+ }) ?? firstSubscription;
124
+ }
125
+ if (type === "apikey" || type === "api_key") return params.order.find((profileId) => params.store.profiles[profileId]?.type === "api_key");
126
+ }
127
+ function shouldInferApiKeyActiveFromRateLimitProbe(limits) {
128
+ return !limits.ok && limits.error.toLowerCase().includes("chatgpt authentication required");
129
+ }
130
+ async function readSubscriptionUsage(params) {
131
+ const limits = await params.safeCodexControlRequest(params.pluginConfig, CODEX_CONTROL_METHODS.rateLimits, void 0, {
132
+ config: params.config,
133
+ authProfileId: params.subscriptionProfileId,
134
+ isolated: true
135
+ });
136
+ if (!limits.ok) return;
137
+ rememberCodexRateLimits(limits.value);
138
+ return summarizeCodexAccountUsage(limits.value, params.now);
139
+ }
140
+ function buildProfileRow(params) {
141
+ const credential = params.store.profiles[params.profileId];
142
+ const label = formatProfileLabel(params.profileId, credential);
143
+ const kind = formatProfileKind(credential);
144
+ const active = params.profileId === params.activeProfileId;
145
+ const status = active ? "active now" : params.usage?.blocked ? formatUsageBlockedStatus(params.usage) : describeInactiveProfileStatus({
146
+ store: params.store,
147
+ config: params.config,
148
+ profileId: params.profileId,
149
+ credential,
150
+ now: params.now,
151
+ afterActive: params.activeIndex >= 0 && params.index > params.activeIndex
152
+ });
153
+ return {
154
+ profileId: params.profileId,
155
+ label,
156
+ kind,
157
+ status,
158
+ active,
159
+ ...credential?.type === "api_key" && active ? { billingNote: "billed per token" } : {},
160
+ ...params.usage?.usageLine ? { usage: params.usage.usageLine } : {}
161
+ };
162
+ }
163
+ function formatUsageBlockedStatus(usage) {
164
+ return usage.blocked ? "rate-limited" : "available if needed";
165
+ }
166
+ function describeInactiveProfileStatus(params) {
167
+ const stats = params.store.usageStats?.[params.profileId];
168
+ const blockedUntil = stats?.blockedUntil;
169
+ if (isActiveUntil(blockedUntil, params.now)) return `rate-limited - resets ${formatRelativeReset(blockedUntil, params.now)}`;
170
+ if (isActiveUntil(resolveProfileUnusableUntilForDisplay(params.store, params.profileId) ?? void 0, params.now)) return describeFailureStatus(stats?.disabledReason ?? stats?.cooldownReason, params.credential);
171
+ const eligibility = resolveAuthProfileEligibility({
172
+ cfg: params.config,
173
+ store: params.store,
174
+ provider: OPENAI_CODEX_PROVIDER_ID,
175
+ profileId: params.profileId,
176
+ now: params.now
177
+ });
178
+ if (!eligibility.eligible) return describeEligibilityStatus(eligibility.reasonCode, params.credential);
179
+ return "available if needed";
180
+ }
181
+ function buildApiKeyActiveLine(activeRow, subscriptionUsage) {
182
+ if (subscriptionUsage?.blocked) {
183
+ const switchBack = subscriptionUsage.blockedResetRelative ? ` · switches back ${subscriptionUsage.blockedResetRelative}` : " · switches back automatically";
184
+ return `Now using: ${activeRow.label} - subscription rate-limited${switchBack}`;
185
+ }
186
+ return `Now using: ${activeRow.label} - subscription unavailable · switches back automatically`;
187
+ }
188
+ function formatSubscriptionUsageLine(usage) {
189
+ if (!usage) return;
190
+ const parts = usage.usageLine ? [formatUsageLineForDisplay(usage.usageLine)] : [];
191
+ if (usage.blockedResetRelative) parts.push(`Resets ${usage.blockedResetRelative}`);
192
+ return parts.length > 0 ? parts.join(" · ") : void 0;
193
+ }
194
+ function formatUsageLineForDisplay(value) {
195
+ return value.replace(/^weekly\b/u, "Weekly").replace(/\bshort-term\b/u, "Short-term");
196
+ }
197
+ function readString(record, key) {
198
+ const value = record[key];
199
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
200
+ }
201
+ function isChatGptSubscriptionProfile(credential) {
202
+ return credential?.type === "oauth" || credential?.type === "token";
203
+ }
204
+ function formatProfileKind(credential) {
205
+ if (!credential) return "credential";
206
+ if (isChatGptSubscriptionProfile(credential)) return "ChatGPT subscription";
207
+ if (credential.type === "api_key") return "API key";
208
+ return "credential";
209
+ }
210
+ function formatProfileLabel(profileId, credential) {
211
+ const tail = profileId.includes(":") ? profileId.slice(profileId.indexOf(":") + 1) : profileId;
212
+ const displayName = credential?.displayName?.trim();
213
+ if (displayName) return credential?.type === "api_key" ? simplifyApiKeyDisplayName(displayName, tail) : displayName;
214
+ const email = credential?.email?.trim() ?? extractEmailFromProfileId(profileId);
215
+ if (email) return email;
216
+ if (credential?.type === "api_key") return tail || "API key";
217
+ return humanizeProfileTail(tail);
218
+ }
219
+ function simplifyApiKeyDisplayName(value, tail) {
220
+ const stripped = value.replace(/^OpenAI\s+/iu, "").trim();
221
+ if (tail && stripped.toLowerCase() === humanizeApiKeyProfileTail(tail).toLowerCase()) return tail;
222
+ return stripped || value;
223
+ }
224
+ function humanizeApiKeyProfileTail(tail) {
225
+ const words = splitProfileTail(tail);
226
+ const hasBackup = words.includes("backup");
227
+ return [
228
+ words.filter((word) => word !== "api" && word !== "key" && word !== "backup").map(titleCase).join(" "),
229
+ "API key",
230
+ hasBackup ? "backup" : ""
231
+ ].filter(Boolean).join(" ");
232
+ }
233
+ function humanizeProfileTail(tail) {
234
+ const words = splitProfileTail(tail);
235
+ return words.length > 0 ? words.map(titleCase).join(" ") : tail;
236
+ }
237
+ function splitProfileTail(tail) {
238
+ return tail.replace(/[_\s]+/gu, "-").split("-").map((word) => word.trim().toLowerCase()).filter(Boolean);
239
+ }
240
+ function titleCase(value) {
241
+ return value ? `${value[0]?.toUpperCase() ?? ""}${value.slice(1)}` : value;
242
+ }
243
+ function extractEmailFromProfileId(profileId) {
244
+ const tail = profileId.includes(":") ? profileId.slice(profileId.indexOf(":") + 1) : profileId;
245
+ return /^[^\s@<>()[\]`]+@[^\s@<>()[\]`]+\.[^\s@<>()[\]`]+$/.test(tail) ? tail : void 0;
246
+ }
247
+ function describeFailureStatus(reason, credential) {
248
+ if (reason === "auth" || reason === "auth_permanent" || reason === "session_expired") return credential?.type === "api_key" ? "auth failed - check key" : "sign-in expired";
249
+ if (reason === "billing") return "billing unavailable";
250
+ if (reason === "rate_limit") return "rate-limited";
251
+ return "temporarily unavailable";
252
+ }
253
+ function describeEligibilityStatus(reason, credential) {
254
+ if (reason === "profile_missing" || reason === "missing_credential") return credential?.type === "api_key" ? "not configured" : "sign-in required";
255
+ if (reason === "expired" || reason === "invalid_expires") return "sign-in expired";
256
+ if (reason === "unresolved_ref") return "credential unavailable";
257
+ if (reason === "provider_mismatch") return "wrong provider";
258
+ if (reason === "mode_mismatch") return "wrong credential type";
259
+ return "unavailable";
260
+ }
261
+ function isActiveUntil(value, now) {
262
+ return typeof value === "number" && Number.isFinite(value) && value > now;
263
+ }
264
+ function formatRelativeReset(untilMs, nowMs) {
265
+ const durationMs = Math.max(1e3, untilMs - nowMs);
266
+ const minuteMs = 6e4;
267
+ const hourMs = 60 * minuteMs;
268
+ const dayMs = 24 * hourMs;
269
+ if (durationMs < hourMs) {
270
+ const minutes = Math.ceil(durationMs / minuteMs);
271
+ return `in ${minutes} ${minutes === 1 ? "minute" : "minutes"}`;
272
+ }
273
+ if (durationMs < dayMs) {
274
+ const hours = Math.ceil(durationMs / hourMs);
275
+ return `in ${hours} ${hours === 1 ? "hour" : "hours"}`;
276
+ }
277
+ const days = Math.ceil(durationMs / dayMs);
278
+ return `in ${days} ${days === 1 ? "day" : "days"}`;
279
+ }
280
+ function dedupe(values) {
281
+ const seen = /* @__PURE__ */ new Set();
282
+ const result = [];
283
+ for (const value of values) {
284
+ const trimmed = value.trim();
285
+ if (!trimmed || seen.has(trimmed)) continue;
286
+ seen.add(trimmed);
287
+ result.push(trimmed);
288
+ }
289
+ return result;
290
+ }
291
+ //#endregion
292
+ //#region extensions/codex/src/command-plugins-management.ts
293
+ const POLICY_REFRESH_HINT = "New Codex conversations pick this up automatically. Use /new or /reset to refresh the current one.";
294
+ async function handleCodexPluginsSubcommand(ctx, rest, io) {
295
+ const [verb = "list", ...args] = rest;
296
+ const normalized = verb.toLowerCase();
297
+ if (normalized === "list") {
298
+ if (args.length > 0) return { text: "Usage: /codex plugins list" };
299
+ const current = await io.readConfig();
300
+ return { text: formatPluginList(current.plugins ?? {}, { globalEnabled: current.enabled === true }) };
301
+ }
302
+ const target = args[0];
303
+ if (normalized === "enable" || normalized === "disable") {
304
+ if (!target || args.length > 1) return { text: `Usage: /codex plugins ${normalized} <name>` };
305
+ if (!canMutateCodexPlugins(ctx)) return { text: `Only an owner or operator.admin gateway client can run /codex plugins ${normalized}.` };
306
+ const wantEnabled = normalized === "enable";
307
+ if (!((await io.readConfig()).plugins ?? {})[target]) return { text: `Codex sub-plugin '${formatCodexDisplayText(target)}' is not configured. Run '/codex plugins list' to see configured plugins.` };
308
+ await io.mutate((block) => {
309
+ if (wantEnabled) block.enabled = true;
310
+ block.plugins ??= {};
311
+ block.plugins[target] = {
312
+ ...block.plugins[target],
313
+ enabled: wantEnabled
314
+ };
315
+ });
316
+ return { text: `${formatCodexDisplayText(target)}: ${wantEnabled ? "enabled" : "disabled"} in autobot.json. ${POLICY_REFRESH_HINT}` };
317
+ }
318
+ return { text: `Unknown /codex plugins subcommand: ${formatCodexDisplayText(verb)}\n\n${buildPluginsHelp()}` };
319
+ }
320
+ function canMutateCodexPlugins(ctx) {
321
+ if (ctx.senderIsOwner === true) return true;
322
+ return ctx.gatewayClientScopes?.includes("operator.admin") === true;
323
+ }
324
+ function buildPluginsHelp() {
325
+ return [
326
+ "Codex sub-plugin management (writes only to ~/.autobot/autobot.json, never to ~/.codex/config.toml):",
327
+ "- /codex plugins (alias for list)",
328
+ "- /codex plugins list show all configured Codex sub-plugins",
329
+ "- /codex plugins enable <name> enable a configured sub-plugin",
330
+ "- /codex plugins disable <name> disable a configured sub-plugin"
331
+ ].join("\n");
332
+ }
333
+ function formatPluginList(plugins, options = {}) {
334
+ const globalEnabled = options.globalEnabled === true;
335
+ const keys = Object.keys(plugins).toSorted();
336
+ if (keys.length === 0) return "No Codex sub-plugins configured under plugins.entries.codex.config.codexPlugins.plugins";
337
+ const rows = keys.map((key) => {
338
+ const entry = plugins[key] ?? {};
339
+ const state = globalEnabled && entry.enabled !== false ? "ON " : "OFF";
340
+ return {
341
+ displayKey: formatCodexDisplayText(key),
342
+ state,
343
+ pluginName: formatCodexDisplayText(entry.pluginName ?? key),
344
+ marketplace: formatCodexDisplayText(entry.marketplaceName ?? "?")
345
+ };
346
+ });
347
+ const keyW = Math.max(...rows.map((r) => r.displayKey.length));
348
+ const pluginW = Math.max(...rows.map((r) => r.pluginName.length));
349
+ return [
350
+ "Codex sub-plugins in Autobot config (~/.autobot/autobot.json):",
351
+ "",
352
+ ...rows.map((r) => ` ${r.state} ${r.displayKey.padEnd(keyW)} ${r.pluginName.padEnd(pluginW)} [${r.marketplace}]`),
353
+ "",
354
+ ...globalEnabled ? [] : ["Global codexPlugins.enabled is off; configured sub-plugins are inactive.", ""],
355
+ "New Codex conversations pick up policy changes automatically; /new or /reset to refresh the current one."
356
+ ].join("\n");
357
+ }
358
+ //#endregion
359
+ //#region extensions/codex/src/command-rpc.ts
360
+ function requestOptions(pluginConfig, limit, config) {
361
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
362
+ return {
363
+ limit,
364
+ timeoutMs: runtime.requestTimeoutMs,
365
+ startOptions: runtime.start,
366
+ config
367
+ };
368
+ }
369
+ async function codexControlRequest(pluginConfig, method, requestParams, options = {}) {
370
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
371
+ return await requestCodexAppServerJson({
372
+ method,
373
+ requestParams,
374
+ timeoutMs: runtime.requestTimeoutMs,
375
+ startOptions: runtime.start,
376
+ config: options.config,
377
+ authProfileId: options.authProfileId,
378
+ agentDir: options.agentDir,
379
+ isolated: options.isolated
380
+ });
381
+ }
382
+ async function safeCodexControlRequest(pluginConfig, method, requestParams, options = {}) {
383
+ return await safeValue(async () => await codexControlRequest(pluginConfig, method, requestParams, options));
384
+ }
385
+ async function safeCodexModelList(pluginConfig, limit, config) {
386
+ return await safeValue(async () => await listCodexAppServerModels(requestOptions(pluginConfig, limit, config)));
387
+ }
388
+ async function readCodexStatusProbes(pluginConfig, config) {
389
+ const [models, account, limits, mcps, skills] = await Promise.all([
390
+ safeCodexModelList(pluginConfig, 20, config),
391
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.account, { refreshToken: false }, { config }),
392
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.rateLimits, void 0, { config }),
393
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, { limit: 100 }, { config }),
394
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}, { config })
395
+ ]);
396
+ return {
397
+ models,
398
+ account,
399
+ limits,
400
+ mcps,
401
+ skills
402
+ };
403
+ }
404
+ async function safeValue(read) {
405
+ try {
406
+ return {
407
+ ok: true,
408
+ value: await read()
409
+ };
410
+ } catch (error) {
411
+ return {
412
+ ok: false,
413
+ error: describeControlFailure(error)
414
+ };
415
+ }
416
+ }
417
+ //#endregion
418
+ //#region extensions/codex/src/command-handlers.ts
419
+ const defaultCodexCommandDeps = {
420
+ codexControlRequest,
421
+ listCodexAppServerModels: listAllCodexAppServerModels,
422
+ readCodexStatusProbes,
423
+ readCodexAppServerBinding,
424
+ requestOptions,
425
+ safeCodexControlRequest,
426
+ writeCodexAppServerBinding,
427
+ clearCodexAppServerBinding,
428
+ readCodexComputerUseStatus,
429
+ installCodexComputerUse,
430
+ resolveCodexDefaultWorkspaceDir,
431
+ startCodexConversationThread,
432
+ readCodexConversationActiveTurn,
433
+ setCodexConversationFastMode,
434
+ setCodexConversationModel,
435
+ setCodexConversationPermissions,
436
+ steerCodexConversationTurn,
437
+ stopCodexConversationTurn,
438
+ listCodexCliSessionsOnNode: async () => {
439
+ throw new Error("Codex CLI node sessions require Gateway node runtime.");
440
+ },
441
+ resolveCodexCliSessionForBindingOnNode: async () => {
442
+ throw new Error("Codex CLI node sessions require Gateway node runtime.");
443
+ }
444
+ };
445
+ const CODEX_DIAGNOSTICS_SOURCE = "autobot-diagnostics";
446
+ const CODEX_DIAGNOSTICS_REASON_MAX_CHARS = 2048;
447
+ const CODEX_DIAGNOSTICS_COOLDOWN_MS = 6e4;
448
+ const CODEX_DIAGNOSTICS_ERROR_MAX_CHARS = 500;
449
+ const CODEX_DIAGNOSTICS_COOLDOWN_MAX_THREADS = 100;
450
+ const CODEX_DIAGNOSTICS_COOLDOWN_MAX_SCOPES = 100;
451
+ const CODEX_DIAGNOSTICS_CONFIRMATION_TTL_MS = 5 * 6e4;
452
+ const CODEX_DIAGNOSTICS_CONFIRMATION_MAX_REQUESTS_PER_SCOPE = 100;
453
+ const CODEX_DIAGNOSTICS_CONFIRMATION_MAX_SCOPES = 100;
454
+ const CODEX_DIAGNOSTICS_SCOPE_FIELD_MAX_CHARS = 128;
455
+ const CODEX_RESUME_SAFE_THREAD_ID_PATTERN = /^[A-Za-z0-9._:-]+$/;
456
+ const lastCodexDiagnosticsUploadByThread = /* @__PURE__ */ new Map();
457
+ const lastCodexDiagnosticsUploadByScope = /* @__PURE__ */ new Map();
458
+ const pendingCodexDiagnosticsConfirmations = /* @__PURE__ */ new Map();
459
+ const pendingCodexDiagnosticsConfirmationTokensByScope = /* @__PURE__ */ new Map();
460
+ async function handleCodexSubcommand(ctx, options) {
461
+ const deps = {
462
+ ...defaultCodexCommandDeps,
463
+ ...options.deps
464
+ };
465
+ const [subcommand = "status", ...rest] = splitArgs(ctx.args);
466
+ const normalized = subcommand.toLowerCase();
467
+ if (normalized === "help") return { text: buildHelp() };
468
+ if (normalized === "plugins") {
469
+ if (!deps.codexPluginsManagementIo) return { text: "Codex sub-plugin management is not wired up (codexPluginsManagementIo dep is undefined). Edit ~/.autobot/autobot.json or use `autobot config patch` until the runtime exposes the IO." };
470
+ return await handleCodexPluginsSubcommand(ctx, rest, deps.codexPluginsManagementIo);
471
+ }
472
+ if (normalized === "status") {
473
+ if (rest.length > 0) return { text: "Usage: /codex status" };
474
+ return { text: formatCodexStatus(await deps.readCodexStatusProbes(options.pluginConfig, ctx.config)) };
475
+ }
476
+ if (normalized === "models") {
477
+ if (rest.length > 0) return { text: "Usage: /codex models" };
478
+ return { text: formatModels(await deps.listCodexAppServerModels(deps.requestOptions(options.pluginConfig, 100, ctx.config))) };
479
+ }
480
+ if (normalized === "threads") return { text: await buildThreads(deps, options.pluginConfig, rest.join(" ")) };
481
+ if (normalized === "sessions") return { text: await buildCodexCliSessions(deps, rest) };
482
+ if (normalized === "resume") return { text: await resumeThread(deps, ctx, options.pluginConfig, rest) };
483
+ if (normalized === "bind") return await bindConversation(deps, ctx, options.pluginConfig, rest);
484
+ if (normalized === "detach" || normalized === "unbind") {
485
+ if (rest.length > 0) return { text: "Usage: /codex detach" };
486
+ return { text: await detachConversation(deps, ctx) };
487
+ }
488
+ if (normalized === "binding") {
489
+ if (rest.length > 0) return { text: "Usage: /codex binding" };
490
+ return { text: await describeConversationBinding(deps, ctx) };
491
+ }
492
+ if (normalized === "stop") {
493
+ if (rest.length > 0) return { text: "Usage: /codex stop" };
494
+ return { text: await stopConversationTurn(deps, ctx, options.pluginConfig) };
495
+ }
496
+ if (normalized === "steer") return { text: await steerConversationTurn(deps, ctx, options.pluginConfig, rest.join(" ")) };
497
+ if (normalized === "model") return { text: await setConversationModel(deps, ctx, options.pluginConfig, rest) };
498
+ if (normalized === "fast") return { text: await setConversationFastMode(deps, ctx, options.pluginConfig, rest) };
499
+ if (normalized === "permissions") return { text: await setConversationPermissions(deps, ctx, options.pluginConfig, rest) };
500
+ if (normalized === "compact") return { text: await startThreadAction(deps, ctx, options.pluginConfig, CODEX_CONTROL_METHODS.compact, "compaction", rest) };
501
+ if (normalized === "review") return { text: await startThreadAction(deps, ctx, options.pluginConfig, CODEX_CONTROL_METHODS.review, "review", rest) };
502
+ if (normalized === "diagnostics") return await handleCodexDiagnosticsFeedback(deps, ctx, options.pluginConfig, rest.join(" "), "/codex diagnostics");
503
+ if (normalized === "computer-use" || normalized === "computeruse") return { text: await handleComputerUseCommand(deps, options.pluginConfig, rest) };
504
+ if (normalized === "mcp") {
505
+ if (rest.length > 0) return { text: "Usage: /codex mcp" };
506
+ return { text: formatList(await deps.codexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, { limit: 100 }), "MCP servers") };
507
+ }
508
+ if (normalized === "skills") {
509
+ if (rest.length > 0) return { text: "Usage: /codex skills" };
510
+ return { text: formatList(await deps.codexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}), "Codex skills") };
511
+ }
512
+ if (normalized === "account") {
513
+ if (rest.length > 0) return { text: "Usage: /codex account" };
514
+ const [account, limits] = await Promise.all([deps.safeCodexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.account, { refreshToken: false }), deps.safeCodexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.rateLimits, void 0)]);
515
+ if (limits.ok) rememberCodexRateLimits(limits.value);
516
+ return { text: formatAccount(account, limits, await readCodexAccountAuthOverview({
517
+ ctx,
518
+ pluginConfig: options.pluginConfig,
519
+ safeCodexControlRequest: deps.safeCodexControlRequest,
520
+ account,
521
+ limits
522
+ })) };
523
+ }
524
+ return { text: `Unknown Codex command: ${formatCodexDisplayText(subcommand)}\n\n${buildHelp()}` };
525
+ }
526
+ async function handleComputerUseCommand(deps, pluginConfig, args) {
527
+ const parsed = parseComputerUseArgs(args);
528
+ if (parsed.help) return ["Usage: /codex computer-use [status|install] [--source <marketplace-source>] [--marketplace-path <path>] [--marketplace <name>]", "Checks or installs the configured Codex Computer Use plugin through app-server."].join("\n");
529
+ const params = {
530
+ pluginConfig,
531
+ forceEnable: parsed.action === "install" || parsed.hasOverrides,
532
+ ...Object.keys(parsed.overrides).length > 0 ? { overrides: parsed.overrides } : {}
533
+ };
534
+ if (parsed.action === "install") return formatComputerUseStatus(await deps.installCodexComputerUse(params));
535
+ return formatComputerUseStatus(await deps.readCodexComputerUseStatus(params));
536
+ }
537
+ async function bindConversation(deps, ctx, pluginConfig, args) {
538
+ const parsed = parseBindArgs(args);
539
+ if (parsed.help) return { text: "Usage: /codex bind [thread-id] [--cwd <path>] [--model <model>] [--provider <provider>]" };
540
+ if (!ctx.sessionFile) return { text: "Cannot bind Codex because this command did not include an AutoBot session file." };
541
+ const scope = resolveCodexConversationControlScope(ctx);
542
+ const workspaceDir = parsed.cwd ?? deps.resolveCodexDefaultWorkspaceDir(pluginConfig);
543
+ const authProfileId = (await deps.readCodexAppServerBinding(ctx.sessionFile, {
544
+ agentDir: scope.agentDir,
545
+ config: ctx.config
546
+ }))?.authProfileId;
547
+ const startParams = {
548
+ pluginConfig,
549
+ config: ctx.config,
550
+ sessionFile: ctx.sessionFile,
551
+ workspaceDir,
552
+ agentDir: scope.agentDir,
553
+ threadId: parsed.threadId,
554
+ model: parsed.model,
555
+ modelProvider: parsed.provider
556
+ };
557
+ if (authProfileId) startParams.authProfileId = authProfileId;
558
+ const data = await deps.startCodexConversationThread(startParams);
559
+ const threadId = (await deps.readCodexAppServerBinding(ctx.sessionFile, {
560
+ agentDir: scope.agentDir,
561
+ config: ctx.config
562
+ }))?.threadId ?? parsed.threadId ?? "new thread";
563
+ const summary = `Codex app-server thread ${formatCodexDisplayText(threadId)} in ${formatCodexDisplayText(workspaceDir)}`;
564
+ let request;
565
+ try {
566
+ request = await ctx.requestConversationBinding({
567
+ summary,
568
+ detachHint: "/codex detach",
569
+ data
570
+ });
571
+ } catch (error) {
572
+ await deps.clearCodexAppServerBinding(ctx.sessionFile);
573
+ throw error;
574
+ }
575
+ if (request.status === "bound") return { text: `Bound this conversation to Codex thread ${formatCodexDisplayText(threadId)} in ${formatCodexDisplayText(workspaceDir)}.` };
576
+ if (request.status === "pending") return request.reply;
577
+ await deps.clearCodexAppServerBinding(ctx.sessionFile);
578
+ return { text: formatCodexDisplayText(request.message) };
579
+ }
580
+ async function detachConversation(deps, ctx) {
581
+ const data = readCodexConversationBindingData(await ctx.getCurrentConversationBinding());
582
+ const detached = await ctx.detachConversationBinding();
583
+ if (data?.kind === "codex-app-server-session") await deps.clearCodexAppServerBinding(data.sessionFile);
584
+ else if (ctx.sessionFile) await deps.clearCodexAppServerBinding(ctx.sessionFile);
585
+ return detached.removed ? "Detached this conversation from Codex." : "No Codex conversation binding was attached.";
586
+ }
587
+ async function describeConversationBinding(deps, ctx) {
588
+ const current = await ctx.getCurrentConversationBinding();
589
+ const data = readCodexConversationBindingData(current);
590
+ if (!current || !data) return "No Codex conversation binding is attached.";
591
+ if (data.kind === "codex-cli-node-session") return [
592
+ "Codex conversation binding:",
593
+ "- Mode: Codex CLI node session",
594
+ `- Node: ${formatCodexDisplayText(data.nodeId)}`,
595
+ `- Session: ${formatCodexDisplayText(data.sessionId)}`,
596
+ `- Workspace: ${formatCodexDisplayText(data.cwd ?? "unknown")}`,
597
+ "- Active run: not tracked"
598
+ ].join("\n");
599
+ const threadBinding = await deps.readCodexAppServerBinding(data.sessionFile, {
600
+ agentDir: data.agentDir,
601
+ config: ctx.config
602
+ });
603
+ const active = deps.readCodexConversationActiveTurn(data.sessionFile);
604
+ return [
605
+ "Codex conversation binding:",
606
+ `- Thread: ${formatCodexDisplayText(threadBinding?.threadId ?? "unknown")}`,
607
+ `- Workspace: ${formatCodexDisplayText(data.workspaceDir)}`,
608
+ `- Model: ${formatCodexDisplayText(threadBinding?.model ?? "default")}`,
609
+ `- Fast: ${isCodexFastServiceTier(threadBinding?.serviceTier) ? "on" : "off"}`,
610
+ `- Permissions: ${threadBinding ? formatPermissionsMode(threadBinding) : "default"}`,
611
+ `- Active run: ${formatCodexDisplayText(active ? active.turnId : "none")}`,
612
+ `- Session: ${formatCodexDisplayText(data.sessionFile)}`
613
+ ].join("\n");
614
+ }
615
+ async function buildThreads(deps, pluginConfig, filter) {
616
+ return formatThreads(await deps.codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listThreads, {
617
+ limit: 10,
618
+ ...filter.trim() ? { searchTerm: filter.trim() } : {}
619
+ }));
620
+ }
621
+ async function buildCodexCliSessions(deps, args) {
622
+ const parsed = parseCodexCliSessionsArgs(args);
623
+ if (parsed.help || !parsed.host) return "Usage: /codex sessions --host <node> [filter] [--limit <n>]";
624
+ return formatCodexCliSessions(await deps.listCodexCliSessionsOnNode({
625
+ requestedNode: parsed.host,
626
+ filter: parsed.filter,
627
+ limit: parsed.limit
628
+ }));
629
+ }
630
+ async function resumeThread(deps, ctx, pluginConfig, args) {
631
+ const parsed = parseResumeArgs(args);
632
+ const normalizedThreadId = parsed.threadId?.trim();
633
+ if (parsed.help) return args.includes("--help") || args.includes("-h") || parsed.host ? "Usage: /codex resume <thread-id>\nUsage: /codex resume <session-id> --host <node> --bind here" : "Usage: /codex resume <thread-id>";
634
+ if (parsed.host) return await bindCodexCliNodeSession(deps, ctx, parsed);
635
+ if (!normalizedThreadId || args.length !== 1) return "Usage: /codex resume <thread-id>";
636
+ if (!ctx.sessionFile) return "Cannot attach a Codex thread because this command did not include an AutoBot session file.";
637
+ const response = await deps.codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.resumeThread, {
638
+ threadId: normalizedThreadId,
639
+ persistExtendedHistory: true
640
+ });
641
+ const thread = isJsonObject(response) && isJsonObject(response.thread) ? response.thread : {};
642
+ const effectiveThreadId = readString$1(thread, "id") ?? normalizedThreadId;
643
+ await deps.writeCodexAppServerBinding(ctx.sessionFile, {
644
+ threadId: effectiveThreadId,
645
+ cwd: readString$1(thread, "cwd") ?? "",
646
+ model: isJsonObject(response) ? readString$1(response, "model") : void 0,
647
+ modelProvider: isJsonObject(response) ? readString$1(response, "modelProvider") : void 0
648
+ });
649
+ return `Attached this AutoBot session to Codex thread ${formatCodexDisplayText(effectiveThreadId)}.`;
650
+ }
651
+ async function bindCodexCliNodeSession(deps, ctx, parsed) {
652
+ if (!parsed.threadId || !parsed.host || parsed.bindHere !== true) return "Usage: /codex resume <session-id> --host <node> --bind here";
653
+ const resolved = await deps.resolveCodexCliSessionForBindingOnNode({
654
+ requestedNode: parsed.host,
655
+ sessionId: parsed.threadId
656
+ });
657
+ if (!resolved.session) return `No Codex CLI session ${formatCodexDisplayText(parsed.threadId)} was found on ${formatCodexDisplayText(parsed.host)}.`;
658
+ const nodeId = resolved.node.nodeId;
659
+ if (!nodeId) return "Cannot bind Codex CLI session because the selected node did not include a node id.";
660
+ const data = createCodexCliNodeConversationBindingData({
661
+ nodeId,
662
+ sessionId: parsed.threadId,
663
+ cwd: resolved.session?.cwd
664
+ });
665
+ const summary = `Codex CLI session ${formatCodexDisplayText(parsed.threadId)} on ${formatCodexDisplayText(nodeId)}`;
666
+ const request = await ctx.requestConversationBinding({
667
+ summary,
668
+ detachHint: "/codex detach",
669
+ data
670
+ });
671
+ if (request.status === "bound") return `Bound this conversation to Codex CLI session ${formatCodexDisplayText(parsed.threadId)} on ${formatCodexDisplayText(nodeId)}.`;
672
+ if (request.status === "pending") return request.reply.text ?? "Codex CLI session binding is pending approval.";
673
+ return formatCodexDisplayText(request.message);
674
+ }
675
+ async function stopConversationTurn(deps, ctx, pluginConfig) {
676
+ const target = await resolveControlTarget(ctx);
677
+ if (!target) return "Cannot stop Codex because this command did not include an AutoBot session file.";
678
+ return (await deps.stopCodexConversationTurn({
679
+ sessionFile: target.sessionFile,
680
+ pluginConfig,
681
+ agentDir: target.agentDir,
682
+ config: ctx.config
683
+ })).message;
684
+ }
685
+ async function steerConversationTurn(deps, ctx, pluginConfig, message) {
686
+ const target = await resolveControlTarget(ctx);
687
+ if (!target) return "Cannot steer Codex because this command did not include an AutoBot session file.";
688
+ return (await deps.steerCodexConversationTurn({
689
+ sessionFile: target.sessionFile,
690
+ pluginConfig,
691
+ message,
692
+ agentDir: target.agentDir,
693
+ config: ctx.config
694
+ })).message;
695
+ }
696
+ async function setConversationModel(deps, ctx, pluginConfig, args) {
697
+ if (args.length > 1) return "Usage: /codex model <model>";
698
+ const target = await resolveControlTarget(ctx);
699
+ if (!target) return "Cannot set Codex model because this command did not include an AutoBot session file.";
700
+ const [model = ""] = args;
701
+ const normalized = model.trim();
702
+ if (!normalized) {
703
+ const binding = await deps.readCodexAppServerBinding(target.sessionFile, {
704
+ agentDir: target.agentDir,
705
+ config: ctx.config
706
+ });
707
+ return binding?.model ? `Codex model: ${formatCodexDisplayText(binding.model)}` : "Usage: /codex model <model>";
708
+ }
709
+ return await deps.setCodexConversationModel({
710
+ sessionFile: target.sessionFile,
711
+ pluginConfig,
712
+ model: normalized,
713
+ agentDir: target.agentDir,
714
+ config: ctx.config
715
+ });
716
+ }
717
+ async function setConversationFastMode(deps, ctx, pluginConfig, args) {
718
+ if (args.length > 1) return "Usage: /codex fast [on|off|status]";
719
+ const target = await resolveControlTarget(ctx);
720
+ if (!target) return "Cannot set Codex fast mode because this command did not include an AutoBot session file.";
721
+ const value = args[0];
722
+ const parsed = parseCodexFastModeArg(value);
723
+ if (value && parsed == null && value.trim().toLowerCase() !== "status") return "Usage: /codex fast [on|off|status]";
724
+ return await deps.setCodexConversationFastMode({
725
+ sessionFile: target.sessionFile,
726
+ pluginConfig,
727
+ enabled: parsed,
728
+ agentDir: target.agentDir,
729
+ config: ctx.config
730
+ });
731
+ }
732
+ async function setConversationPermissions(deps, ctx, pluginConfig, args) {
733
+ if (args.length > 1) return "Usage: /codex permissions [default|yolo|status]";
734
+ const target = await resolveControlTarget(ctx);
735
+ if (!target) return "Cannot set Codex permissions because this command did not include an AutoBot session file.";
736
+ const value = args[0];
737
+ const parsed = parseCodexPermissionsModeArg(value);
738
+ if (value && !parsed && value.trim().toLowerCase() !== "status") return "Usage: /codex permissions [default|yolo|status]";
739
+ return await deps.setCodexConversationPermissions({
740
+ sessionFile: target.sessionFile,
741
+ pluginConfig,
742
+ mode: parsed,
743
+ agentDir: target.agentDir,
744
+ config: ctx.config
745
+ });
746
+ }
747
+ async function resolveControlTarget(ctx) {
748
+ const data = readCodexConversationBindingData(await ctx.getCurrentConversationBinding());
749
+ const scope = resolveCodexConversationControlScope(ctx);
750
+ if (data?.kind === "codex-app-server-session") return {
751
+ sessionFile: data.sessionFile,
752
+ agentDir: data.agentDir ?? scope.agentDir
753
+ };
754
+ return ctx.sessionFile ? {
755
+ sessionFile: ctx.sessionFile,
756
+ agentDir: scope.agentDir
757
+ } : void 0;
758
+ }
759
+ async function resolveControlSessionFile(ctx) {
760
+ return (await resolveControlTarget(ctx))?.sessionFile;
761
+ }
762
+ function resolveCodexConversationControlScope(ctx) {
763
+ const { sessionAgentId } = resolveSessionAgentIds({
764
+ sessionKey: ctx.sessionKey,
765
+ config: ctx.config
766
+ });
767
+ return { agentDir: resolveAgentDir(ctx.config, sessionAgentId) };
768
+ }
769
+ async function handleCodexDiagnosticsFeedback(deps, ctx, pluginConfig, args, commandPrefix) {
770
+ if (ctx.senderIsOwner !== true) return { text: "Only an owner can send Codex diagnostics." };
771
+ const parsed = parseDiagnosticsArgs(args);
772
+ if (parsed.action === "usage") return { text: formatDiagnosticsUsage(commandPrefix) };
773
+ if (parsed.action === "confirm") return { text: await confirmCodexDiagnosticsFeedback(deps, ctx, pluginConfig, parsed.token) };
774
+ if (parsed.action === "cancel") return { text: cancelCodexDiagnosticsFeedback(ctx, parsed.token) };
775
+ if (ctx.diagnosticsUploadApproved === true) return { text: await sendCodexDiagnosticsFeedbackForContext(deps, ctx, pluginConfig, parsed.note) };
776
+ if (ctx.diagnosticsPreviewOnly === true) return { text: await previewCodexDiagnosticsFeedbackApproval(deps, ctx, parsed.note) };
777
+ return await requestCodexDiagnosticsFeedbackApproval(deps, ctx, parsed.note, commandPrefix);
778
+ }
779
+ async function requestCodexDiagnosticsFeedbackApproval(deps, ctx, note, commandPrefix) {
780
+ if (!await hasAnyCodexDiagnosticsSessionFile(ctx)) return { text: "Cannot send Codex diagnostics because this command did not include an AutoBot session file." };
781
+ const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
782
+ if (targets.length === 0) return { text: ["No Codex thread is attached to this AutoBot session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n") };
783
+ const now = Date.now();
784
+ const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now);
785
+ if (cooldownMessage) return { text: cooldownMessage };
786
+ if (!ctx.senderId) return { text: "Cannot send Codex diagnostics because this command did not include a sender identity." };
787
+ const reason = normalizeDiagnosticsReason(note);
788
+ const token = createCodexDiagnosticsConfirmation({
789
+ targets,
790
+ note: reason,
791
+ senderId: ctx.senderId,
792
+ channel: ctx.channel,
793
+ scopeKey: readCodexDiagnosticsCooldownScope(ctx),
794
+ privateRouted: ctx.diagnosticsPrivateRouted === true,
795
+ ...readCodexDiagnosticsConfirmationScope(ctx),
796
+ now
797
+ });
798
+ const confirmCommand = `${commandPrefix} confirm ${token}`;
799
+ const cancelCommand = `${commandPrefix} cancel ${token}`;
800
+ const displayReason = reason ? escapeCodexChatText(formatCodexTextForDisplay(reason)) : void 0;
801
+ return {
802
+ text: [
803
+ targets.length === 1 ? "Codex runtime thread detected." : "Codex runtime threads detected.",
804
+ `Codex diagnostics can send ${targets.length === 1 ? "this thread's feedback bundle" : "these threads' feedback bundles"} to OpenAI servers.`,
805
+ "Codex sessions:",
806
+ ...formatCodexDiagnosticsTargetLines(targets),
807
+ ...displayReason ? [`Note: ${displayReason}`] : [],
808
+ "Included: Codex logs and spawned Codex subthreads when available.",
809
+ `To send: ${confirmCommand}`,
810
+ `To cancel: ${cancelCommand}`,
811
+ "This request expires in 5 minutes."
812
+ ].join("\n"),
813
+ interactive: { blocks: [{
814
+ type: "buttons",
815
+ buttons: [{
816
+ label: "Send diagnostics",
817
+ value: confirmCommand,
818
+ style: "danger"
819
+ }, {
820
+ label: "Cancel",
821
+ value: cancelCommand,
822
+ style: "secondary"
823
+ }]
824
+ }] }
825
+ };
826
+ }
827
+ async function previewCodexDiagnosticsFeedbackApproval(deps, ctx, note) {
828
+ if (!await hasAnyCodexDiagnosticsSessionFile(ctx)) return "Cannot send Codex diagnostics because this command did not include an AutoBot session file.";
829
+ const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
830
+ if (targets.length === 0) return ["No Codex thread is attached to this AutoBot session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n");
831
+ const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, Date.now(), { includeThreadId: false });
832
+ if (cooldownMessage) return cooldownMessage;
833
+ const reason = normalizeDiagnosticsReason(note);
834
+ const displayReason = reason ? escapeCodexChatText(formatCodexTextForDisplay(reason)) : void 0;
835
+ return [
836
+ targets.length === 1 ? "Codex runtime thread detected." : "Codex runtime threads detected.",
837
+ `Approving diagnostics will also send ${targets.length === 1 ? "this thread's feedback bundle" : "these threads' feedback bundles"} to OpenAI servers.`,
838
+ "The completed diagnostics reply will list the AutoBot session ids and Codex thread ids that were sent.",
839
+ ...displayReason ? [`Note: ${displayReason}`] : [],
840
+ "Included: Codex logs and spawned Codex subthreads when available."
841
+ ].join("\n");
842
+ }
843
+ async function confirmCodexDiagnosticsFeedback(deps, ctx, pluginConfig, token) {
844
+ const pending = readPendingCodexDiagnosticsConfirmation(token, Date.now());
845
+ if (!pending) return "No pending Codex diagnostics confirmation was found. Run /diagnostics again to create a fresh request.";
846
+ if (!pending.senderId || !ctx.senderId) return "Cannot confirm Codex diagnostics because this command did not include the original sender identity.";
847
+ if (pending.senderId !== ctx.senderId) return "Only the user who requested these Codex diagnostics can confirm the upload.";
848
+ if (pending.channel !== ctx.channel) return "This Codex diagnostics confirmation belongs to a different channel.";
849
+ const scopeMismatch = readCodexDiagnosticsScopeMismatch(pending, ctx);
850
+ if (scopeMismatch) return scopeMismatch.confirmMessage;
851
+ deletePendingCodexDiagnosticsConfirmation(token);
852
+ if (!pending.privateRouted && !await hasAnyCodexDiagnosticsSessionFile(ctx)) return "Cannot send Codex diagnostics because this command did not include an AutoBot session file.";
853
+ const currentTargets = pending.privateRouted ? await resolvePendingCodexDiagnosticsTargets(deps, pending.targets) : await resolveCodexDiagnosticsTargets(deps, ctx);
854
+ if (!codexDiagnosticsTargetsMatch(pending.targets, currentTargets)) return "The Codex diagnostics sessions changed before confirmation. Run /diagnostics again for the current threads.";
855
+ return await sendCodexDiagnosticsFeedbackForTargets(deps, ctx, pluginConfig, pending.note ?? "", pending.targets);
856
+ }
857
+ function cancelCodexDiagnosticsFeedback(ctx, token) {
858
+ const pending = readPendingCodexDiagnosticsConfirmation(token, Date.now());
859
+ if (!pending) return "No pending Codex diagnostics confirmation was found.";
860
+ if (!pending.senderId || !ctx.senderId) return "Cannot cancel Codex diagnostics because this command did not include the original sender identity.";
861
+ if (pending.senderId !== ctx.senderId) return "Only the user who requested these Codex diagnostics can cancel the upload.";
862
+ if (pending.channel !== ctx.channel) return "This Codex diagnostics confirmation belongs to a different channel.";
863
+ const scopeMismatch = readCodexDiagnosticsScopeMismatch(pending, ctx);
864
+ if (scopeMismatch) return scopeMismatch.cancelMessage;
865
+ deletePendingCodexDiagnosticsConfirmation(token);
866
+ return [
867
+ "Codex diagnostics upload canceled.",
868
+ "Codex sessions:",
869
+ ...formatCodexDiagnosticsTargetLines(pending.targets)
870
+ ].join("\n");
871
+ }
872
+ async function sendCodexDiagnosticsFeedbackForContext(deps, ctx, pluginConfig, note) {
873
+ if (!await hasAnyCodexDiagnosticsSessionFile(ctx)) return "Cannot send Codex diagnostics because this command did not include an AutoBot session file.";
874
+ const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
875
+ if (targets.length === 0) return ["No Codex thread is attached to this AutoBot session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n");
876
+ return await sendCodexDiagnosticsFeedbackForTargets(deps, ctx, pluginConfig, note, targets);
877
+ }
878
+ async function sendCodexDiagnosticsFeedbackForTargets(deps, ctx, pluginConfig, note, targets) {
879
+ if (targets.length === 0) return ["No Codex thread is attached to this AutoBot session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n");
880
+ const now = Date.now();
881
+ const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now);
882
+ if (cooldownMessage) return cooldownMessage;
883
+ const reason = normalizeDiagnosticsReason(note);
884
+ const sent = [];
885
+ const failed = [];
886
+ for (const target of targets) {
887
+ const response = await deps.safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.feedback, {
888
+ classification: "bug",
889
+ threadId: target.threadId,
890
+ includeLogs: true,
891
+ tags: buildDiagnosticsTags(ctx),
892
+ ...reason ? { reason } : {}
893
+ });
894
+ if (!response.ok) {
895
+ failed.push({
896
+ target,
897
+ error: response.error
898
+ });
899
+ continue;
900
+ }
901
+ const responseThreadId = isJsonObject(response.value) ? readString$1(response.value, "threadId") : void 0;
902
+ sent.push({
903
+ ...target,
904
+ threadId: responseThreadId ?? target.threadId
905
+ });
906
+ recordCodexDiagnosticsUpload(target.threadId, ctx, now);
907
+ }
908
+ return formatCodexDiagnosticsUploadResult(sent, failed);
909
+ }
910
+ async function hasAnyCodexDiagnosticsSessionFile(ctx) {
911
+ if (await resolveControlSessionFile(ctx)) return true;
912
+ return (ctx.diagnosticsSessions ?? []).some((session) => Boolean(session.sessionFile));
913
+ }
914
+ async function resolveCodexDiagnosticsTargets(deps, ctx) {
915
+ const activeSessionFile = await resolveControlSessionFile(ctx);
916
+ const candidates = [];
917
+ if (activeSessionFile) candidates.push({
918
+ threadId: "",
919
+ sessionFile: activeSessionFile,
920
+ sessionKey: ctx.sessionKey,
921
+ sessionId: ctx.sessionId,
922
+ channel: ctx.channel,
923
+ channelId: ctx.channelId,
924
+ accountId: ctx.accountId,
925
+ messageThreadId: ctx.messageThreadId,
926
+ threadParentId: ctx.threadParentId
927
+ });
928
+ for (const session of ctx.diagnosticsSessions ?? []) {
929
+ if (!session.sessionFile) continue;
930
+ candidates.push({
931
+ threadId: "",
932
+ sessionFile: session.sessionFile,
933
+ sessionKey: session.sessionKey,
934
+ sessionId: session.sessionId,
935
+ channel: session.channel,
936
+ channelId: session.channelId,
937
+ accountId: session.accountId,
938
+ messageThreadId: session.messageThreadId,
939
+ threadParentId: session.threadParentId
940
+ });
941
+ }
942
+ const seenSessionFiles = /* @__PURE__ */ new Set();
943
+ const seenThreadIds = /* @__PURE__ */ new Set();
944
+ const targets = [];
945
+ for (const candidate of candidates) {
946
+ if (seenSessionFiles.has(candidate.sessionFile)) continue;
947
+ seenSessionFiles.add(candidate.sessionFile);
948
+ const binding = await deps.readCodexAppServerBinding(candidate.sessionFile);
949
+ if (!binding?.threadId || seenThreadIds.has(binding.threadId)) continue;
950
+ seenThreadIds.add(binding.threadId);
951
+ targets.push({
952
+ ...candidate,
953
+ threadId: binding.threadId
954
+ });
955
+ }
956
+ return targets;
957
+ }
958
+ async function resolvePendingCodexDiagnosticsTargets(deps, targets) {
959
+ const resolved = [];
960
+ for (const target of targets) {
961
+ const binding = await deps.readCodexAppServerBinding(target.sessionFile);
962
+ if (!binding?.threadId) continue;
963
+ resolved.push({
964
+ ...target,
965
+ threadId: binding.threadId
966
+ });
967
+ }
968
+ return resolved;
969
+ }
970
+ function codexDiagnosticsTargetsMatch(expected, actual) {
971
+ const expectedThreadIds = expected.map((target) => target.threadId).toSorted();
972
+ const actualThreadIds = actual.map((target) => target.threadId).toSorted();
973
+ return expectedThreadIds.length === actualThreadIds.length && expectedThreadIds.every((threadId, index) => threadId === actualThreadIds[index]);
974
+ }
975
+ function formatCodexDiagnosticsUploadResult(sent, failed) {
976
+ const lines = [];
977
+ if (sent.length > 0) {
978
+ lines.push("Codex diagnostics sent to OpenAI servers:");
979
+ lines.push(...formatCodexDiagnosticsTargetLines(sent));
980
+ lines.push("Included Codex logs and spawned Codex subthreads when available.");
981
+ }
982
+ if (failed.length > 0) {
983
+ if (lines.length > 0) lines.push("");
984
+ lines.push("Could not send Codex diagnostics:");
985
+ lines.push(...failed.map(({ target, error }) => `${formatCodexDiagnosticsTargetLine(target)}: ${formatCodexErrorForDisplay(error)}`));
986
+ lines.push("Inspect locally:");
987
+ lines.push(...failed.map(({ target }) => `- ${formatCodexResumeCommandForDisplay(target.threadId)}`));
988
+ }
989
+ return lines.join("\n");
990
+ }
991
+ function formatCodexDiagnosticsTargetLines(targets) {
992
+ return targets.flatMap((target, index) => {
993
+ const lines = formatCodexDiagnosticsTargetBlock(target, index);
994
+ return index < targets.length - 1 ? [...lines, ""] : lines;
995
+ });
996
+ }
997
+ function formatCodexDiagnosticsTargetBlock(target, index) {
998
+ const lines = [`Session ${index + 1}`];
999
+ if (target.channel) lines.push(`Channel: ${formatCodexValueForDisplay(target.channel)}`);
1000
+ if (target.sessionKey) lines.push(`AutoBot session key: ${formatCodexCopyableValueForDisplay(target.sessionKey)}`);
1001
+ if (target.sessionId) lines.push(`AutoBot session id: ${formatCodexCopyableValueForDisplay(target.sessionId)}`);
1002
+ lines.push(`Codex thread id: ${formatCodexCopyableValueForDisplay(target.threadId)}`);
1003
+ lines.push(`Inspect locally: ${formatCodexResumeCommandForDisplay(target.threadId)}`);
1004
+ return lines;
1005
+ }
1006
+ function formatCodexDiagnosticsTargetLine(target) {
1007
+ const parts = [];
1008
+ if (target.channel) parts.push(`channel ${formatCodexValueForDisplay(target.channel)}`);
1009
+ const sessionLabel = target.sessionId || target.sessionKey;
1010
+ if (sessionLabel) parts.push(`AutoBot session ${formatCodexValueForDisplay(sessionLabel)}`);
1011
+ parts.push(`Codex thread ${formatCodexThreadIdForDisplay(target.threadId)}`);
1012
+ return `- ${parts.join(", ")}`;
1013
+ }
1014
+ function normalizeDiagnosticsReason(note) {
1015
+ const normalized = normalizeOptionalString(note);
1016
+ return normalized ? normalized.slice(0, CODEX_DIAGNOSTICS_REASON_MAX_CHARS) : void 0;
1017
+ }
1018
+ function parseDiagnosticsArgs(args) {
1019
+ const [action, token, ...extra] = splitArgs(args);
1020
+ const normalizedAction = action?.toLowerCase();
1021
+ if ((normalizedAction === "confirm" || normalizedAction === "--confirm") && token && extra.length === 0) return {
1022
+ action: "confirm",
1023
+ token
1024
+ };
1025
+ if ((normalizedAction === "cancel" || normalizedAction === "--cancel") && token && extra.length === 0) return {
1026
+ action: "cancel",
1027
+ token
1028
+ };
1029
+ if (normalizedAction === "confirm" || normalizedAction === "--confirm" || normalizedAction === "cancel" || normalizedAction === "--cancel") return { action: "usage" };
1030
+ return {
1031
+ action: "request",
1032
+ note: args
1033
+ };
1034
+ }
1035
+ function formatDiagnosticsUsage(commandPrefix) {
1036
+ return [
1037
+ `Usage: ${commandPrefix} [note]`,
1038
+ `Usage: ${commandPrefix} confirm <token>`,
1039
+ `Usage: ${commandPrefix} cancel <token>`
1040
+ ].join("\n");
1041
+ }
1042
+ function createCodexDiagnosticsConfirmation(params) {
1043
+ prunePendingCodexDiagnosticsConfirmations(params.now);
1044
+ if (!pendingCodexDiagnosticsConfirmationTokensByScope.has(params.scopeKey) && pendingCodexDiagnosticsConfirmationTokensByScope.size >= CODEX_DIAGNOSTICS_CONFIRMATION_MAX_SCOPES) {
1045
+ const oldestScopeKey = pendingCodexDiagnosticsConfirmationTokensByScope.keys().next().value;
1046
+ if (typeof oldestScopeKey === "string") deletePendingCodexDiagnosticsConfirmationScope(oldestScopeKey);
1047
+ }
1048
+ const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(params.scopeKey) ?? [];
1049
+ while (scopeTokens.length >= CODEX_DIAGNOSTICS_CONFIRMATION_MAX_REQUESTS_PER_SCOPE) {
1050
+ const oldestToken = scopeTokens.shift();
1051
+ if (!oldestToken) break;
1052
+ pendingCodexDiagnosticsConfirmations.delete(oldestToken);
1053
+ }
1054
+ const token = crypto.randomBytes(6).toString("hex");
1055
+ scopeTokens.push(token);
1056
+ pendingCodexDiagnosticsConfirmationTokensByScope.set(params.scopeKey, scopeTokens);
1057
+ pendingCodexDiagnosticsConfirmations.set(token, {
1058
+ token,
1059
+ targets: params.targets,
1060
+ note: params.note,
1061
+ senderId: params.senderId,
1062
+ channel: params.channel,
1063
+ accountId: params.accountId,
1064
+ channelId: params.channelId,
1065
+ messageThreadId: params.messageThreadId,
1066
+ threadParentId: params.threadParentId,
1067
+ sessionKey: params.sessionKey,
1068
+ scopeKey: params.scopeKey,
1069
+ ...params.privateRouted === void 0 ? {} : { privateRouted: params.privateRouted },
1070
+ createdAt: params.now
1071
+ });
1072
+ return token;
1073
+ }
1074
+ function readCodexDiagnosticsConfirmationScope(ctx) {
1075
+ return {
1076
+ accountId: normalizeCodexDiagnosticsScopeField(ctx.accountId),
1077
+ channelId: normalizeCodexDiagnosticsScopeField(ctx.channelId),
1078
+ messageThreadId: typeof ctx.messageThreadId === "string" || typeof ctx.messageThreadId === "number" ? normalizeCodexDiagnosticsScopeField(String(ctx.messageThreadId)) : void 0,
1079
+ threadParentId: normalizeCodexDiagnosticsScopeField(ctx.threadParentId),
1080
+ sessionKey: normalizeCodexDiagnosticsScopeField(ctx.sessionKey)
1081
+ };
1082
+ }
1083
+ function readCodexDiagnosticsScopeMismatch(pending, ctx) {
1084
+ const current = readCodexDiagnosticsConfirmationScope(ctx);
1085
+ if (pending.accountId !== current.accountId) return {
1086
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different account.",
1087
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different account."
1088
+ };
1089
+ if (pending.privateRouted) return;
1090
+ if (pending.channelId !== current.channelId) return {
1091
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different channel instance.",
1092
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different channel instance."
1093
+ };
1094
+ if (pending.messageThreadId !== current.messageThreadId) return {
1095
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different thread.",
1096
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different thread."
1097
+ };
1098
+ if (pending.threadParentId !== current.threadParentId) return {
1099
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different parent thread.",
1100
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different parent thread."
1101
+ };
1102
+ if (pending.sessionKey !== current.sessionKey) return {
1103
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different session.",
1104
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different session."
1105
+ };
1106
+ }
1107
+ function readPendingCodexDiagnosticsConfirmation(token, now) {
1108
+ prunePendingCodexDiagnosticsConfirmations(now);
1109
+ return pendingCodexDiagnosticsConfirmations.get(token);
1110
+ }
1111
+ function prunePendingCodexDiagnosticsConfirmations(now) {
1112
+ for (const [token, pending] of pendingCodexDiagnosticsConfirmations) if (now - pending.createdAt >= CODEX_DIAGNOSTICS_CONFIRMATION_TTL_MS) deletePendingCodexDiagnosticsConfirmation(token);
1113
+ }
1114
+ function deletePendingCodexDiagnosticsConfirmation(token) {
1115
+ const pending = pendingCodexDiagnosticsConfirmations.get(token);
1116
+ pendingCodexDiagnosticsConfirmations.delete(token);
1117
+ if (!pending) return;
1118
+ const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(pending.scopeKey);
1119
+ if (!scopeTokens) return;
1120
+ const tokenIndex = scopeTokens.indexOf(token);
1121
+ if (tokenIndex >= 0) scopeTokens.splice(tokenIndex, 1);
1122
+ if (scopeTokens.length === 0) pendingCodexDiagnosticsConfirmationTokensByScope.delete(pending.scopeKey);
1123
+ }
1124
+ function deletePendingCodexDiagnosticsConfirmationScope(scopeKey) {
1125
+ const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(scopeKey) ?? [];
1126
+ for (const token of scopeTokens) pendingCodexDiagnosticsConfirmations.delete(token);
1127
+ pendingCodexDiagnosticsConfirmationTokensByScope.delete(scopeKey);
1128
+ }
1129
+ function buildDiagnosticsTags(ctx) {
1130
+ const tags = { source: CODEX_DIAGNOSTICS_SOURCE };
1131
+ addTag(tags, "channel", ctx.channel);
1132
+ return tags;
1133
+ }
1134
+ function addTag(tags, key, value) {
1135
+ if (typeof value === "string" && value.trim()) tags[key] = value.trim();
1136
+ }
1137
+ function formatCodexThreadIdForDisplay(threadId) {
1138
+ return escapeCodexChatText(formatCodexTextForDisplay(threadId));
1139
+ }
1140
+ function formatCodexValueForDisplay(value) {
1141
+ return escapeCodexChatText(formatCodexTextForDisplay(value));
1142
+ }
1143
+ function formatCodexCopyableValueForDisplay(value) {
1144
+ const safe = formatCodexTextForDisplay(value);
1145
+ if (CODEX_RESUME_SAFE_THREAD_ID_PATTERN.test(safe)) return `\`${safe}\``;
1146
+ return escapeCodexChatText(safe);
1147
+ }
1148
+ function formatCodexTextForDisplay(value) {
1149
+ let safe = "";
1150
+ for (const character of value) {
1151
+ const codePoint = character.codePointAt(0);
1152
+ safe += codePoint != null && isUnsafeDisplayCodePoint(codePoint) ? "?" : character;
1153
+ }
1154
+ safe = safe.trim();
1155
+ return safe || "<unknown>";
1156
+ }
1157
+ function escapeCodexChatText(value) {
1158
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("@", "@").replaceAll("`", "`").replaceAll("[", "[").replaceAll("]", "]").replaceAll("(", "(").replaceAll(")", ")").replaceAll("*", "∗").replaceAll("_", "_").replaceAll("~", "~").replaceAll("|", "|");
1159
+ }
1160
+ function readCodexDiagnosticsCooldownMs(threadId, now) {
1161
+ const lastSentAt = lastCodexDiagnosticsUploadByThread.get(threadId);
1162
+ if (!lastSentAt) return 0;
1163
+ const remainingMs = Math.max(0, CODEX_DIAGNOSTICS_COOLDOWN_MS - (now - lastSentAt));
1164
+ if (remainingMs === 0) lastCodexDiagnosticsUploadByThread.delete(threadId);
1165
+ return remainingMs;
1166
+ }
1167
+ function readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now, options = {}) {
1168
+ for (const target of targets) {
1169
+ const cooldownMs = readCodexDiagnosticsCooldownMs(target.threadId, now);
1170
+ if (cooldownMs > 0) {
1171
+ if (options.includeThreadId === false) return `Codex diagnostics were already sent for one of these Codex threads recently. Try again in ${Math.ceil(cooldownMs / 1e3)}s.`;
1172
+ return `Codex diagnostics were already sent for thread ${formatCodexThreadIdForDisplay(target.threadId)} recently. Try again in ${Math.ceil(cooldownMs / 1e3)}s.`;
1173
+ }
1174
+ }
1175
+ const scopeCooldownMs = readCodexDiagnosticsScopeCooldownMs(readCodexDiagnosticsCooldownScope(ctx), now);
1176
+ if (scopeCooldownMs > 0) return `Codex diagnostics were already sent for this account or channel recently. Try again in ${Math.ceil(scopeCooldownMs / 1e3)}s.`;
1177
+ }
1178
+ function readCodexDiagnosticsScopeCooldownMs(scope, now) {
1179
+ const lastSentAt = lastCodexDiagnosticsUploadByScope.get(scope);
1180
+ if (!lastSentAt) return 0;
1181
+ const remainingMs = Math.max(0, CODEX_DIAGNOSTICS_COOLDOWN_MS - (now - lastSentAt));
1182
+ if (remainingMs === 0) lastCodexDiagnosticsUploadByScope.delete(scope);
1183
+ return remainingMs;
1184
+ }
1185
+ function recordCodexDiagnosticsUpload(threadId, ctx, now) {
1186
+ pruneCodexDiagnosticsCooldowns(now);
1187
+ recordBoundedCodexDiagnosticsCooldown(lastCodexDiagnosticsUploadByScope, readCodexDiagnosticsCooldownScope(ctx), CODEX_DIAGNOSTICS_COOLDOWN_MAX_SCOPES, now);
1188
+ recordBoundedCodexDiagnosticsCooldown(lastCodexDiagnosticsUploadByThread, threadId, CODEX_DIAGNOSTICS_COOLDOWN_MAX_THREADS, now);
1189
+ }
1190
+ function recordBoundedCodexDiagnosticsCooldown(map, key, maxSize, now) {
1191
+ if (!map.has(key)) while (map.size >= maxSize) {
1192
+ const oldestKey = map.keys().next().value;
1193
+ if (typeof oldestKey !== "string") break;
1194
+ map.delete(oldestKey);
1195
+ }
1196
+ map.set(key, now);
1197
+ }
1198
+ function readCodexDiagnosticsCooldownScope(ctx) {
1199
+ const scope = readCodexDiagnosticsConfirmationScope(ctx);
1200
+ const payload = JSON.stringify({
1201
+ accountId: scope.accountId ?? null,
1202
+ channelId: scope.channelId ?? null,
1203
+ sessionKey: scope.sessionKey ?? null,
1204
+ messageThreadId: scope.messageThreadId ?? null,
1205
+ threadParentId: scope.threadParentId ?? null,
1206
+ senderId: normalizeCodexDiagnosticsScopeField(ctx.senderId) ?? null,
1207
+ channel: normalizeCodexDiagnosticsScopeField(ctx.channel) ?? ""
1208
+ });
1209
+ return crypto.createHash("sha256").update(payload).digest("hex");
1210
+ }
1211
+ function pruneCodexDiagnosticsCooldowns(now) {
1212
+ pruneCodexDiagnosticsCooldownMap(lastCodexDiagnosticsUploadByThread, now);
1213
+ pruneCodexDiagnosticsCooldownMap(lastCodexDiagnosticsUploadByScope, now);
1214
+ }
1215
+ function pruneCodexDiagnosticsCooldownMap(map, now) {
1216
+ for (const [key, lastSentAt] of map) if (now - lastSentAt >= CODEX_DIAGNOSTICS_COOLDOWN_MS) map.delete(key);
1217
+ }
1218
+ function formatCodexErrorForDisplay(error) {
1219
+ return escapeCodexChatText(formatCodexTextForDisplay(error).slice(0, CODEX_DIAGNOSTICS_ERROR_MAX_CHARS)) || "unknown error";
1220
+ }
1221
+ function formatCodexResumeCommandForDisplay(threadId) {
1222
+ const safeThreadId = formatCodexTextForDisplay(threadId);
1223
+ if (!CODEX_RESUME_SAFE_THREAD_ID_PATTERN.test(safeThreadId)) return "run codex resume and paste the thread id shown above";
1224
+ return `\`codex resume ${safeThreadId}\``;
1225
+ }
1226
+ function isUnsafeDisplayCodePoint(codePoint) {
1227
+ return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 || codePoint === 173 || codePoint === 1564 || codePoint === 6158 || codePoint >= 8203 && codePoint <= 8207 || codePoint >= 8234 && codePoint <= 8238 || codePoint >= 8288 && codePoint <= 8303 || codePoint === 65279 || codePoint >= 65529 && codePoint <= 65531 || codePoint >= 917504 && codePoint <= 917631;
1228
+ }
1229
+ function normalizeCodexDiagnosticsScopeField(value) {
1230
+ const normalized = normalizeOptionalString(value);
1231
+ if (!normalized) return;
1232
+ if (normalized.length <= CODEX_DIAGNOSTICS_SCOPE_FIELD_MAX_CHARS) return normalized;
1233
+ return `sha256:${crypto.createHash("sha256").update(normalized).digest("hex")}`;
1234
+ }
1235
+ async function startThreadAction(deps, ctx, pluginConfig, method, label, args) {
1236
+ if (args.length > 0) return `Usage: /codex ${label === "compaction" ? "compact" : label}`;
1237
+ const target = await resolveControlTarget(ctx);
1238
+ if (!target) return `Cannot start Codex ${label} because this command did not include an AutoBot session file.`;
1239
+ const binding = await deps.readCodexAppServerBinding(target.sessionFile, {
1240
+ agentDir: target.agentDir,
1241
+ config: ctx.config
1242
+ });
1243
+ if (!binding?.threadId) return `No Codex thread is attached to this AutoBot session yet.`;
1244
+ if (method === CODEX_CONTROL_METHODS.review) await deps.codexControlRequest(pluginConfig, method, {
1245
+ threadId: binding.threadId,
1246
+ target: { type: "uncommittedChanges" }
1247
+ }, {
1248
+ agentDir: target.agentDir,
1249
+ authProfileId: binding.authProfileId,
1250
+ config: ctx.config
1251
+ });
1252
+ else await deps.codexControlRequest(pluginConfig, method, { threadId: binding.threadId }, {
1253
+ agentDir: target.agentDir,
1254
+ authProfileId: binding.authProfileId,
1255
+ config: ctx.config
1256
+ });
1257
+ return `Started Codex ${label} for thread ${formatCodexDisplayText(binding.threadId)}.`;
1258
+ }
1259
+ function splitArgs(value) {
1260
+ const input = value ?? "";
1261
+ const args = [];
1262
+ let current = "";
1263
+ let quote;
1264
+ let escaping = false;
1265
+ let tokenStarted = false;
1266
+ for (const char of input) {
1267
+ if (escaping) {
1268
+ current += char;
1269
+ escaping = false;
1270
+ tokenStarted = true;
1271
+ continue;
1272
+ }
1273
+ if (char === "\\" && quote !== "'") {
1274
+ escaping = true;
1275
+ tokenStarted = true;
1276
+ continue;
1277
+ }
1278
+ if (quote) {
1279
+ if (char === quote) quote = void 0;
1280
+ else current += char;
1281
+ tokenStarted = true;
1282
+ continue;
1283
+ }
1284
+ if (char === "\"" || char === "'") {
1285
+ quote = char;
1286
+ tokenStarted = true;
1287
+ continue;
1288
+ }
1289
+ if (/\s/.test(char)) {
1290
+ if (tokenStarted) {
1291
+ args.push(current);
1292
+ current = "";
1293
+ tokenStarted = false;
1294
+ }
1295
+ continue;
1296
+ }
1297
+ current += char;
1298
+ tokenStarted = true;
1299
+ }
1300
+ if (escaping) current += "\\";
1301
+ if (tokenStarted) args.push(current);
1302
+ return args;
1303
+ }
1304
+ function parseBindArgs(args) {
1305
+ const parsed = {};
1306
+ for (let index = 0; index < args.length; index += 1) {
1307
+ const arg = args[index];
1308
+ if (arg === "--help" || arg === "-h") {
1309
+ parsed.help = true;
1310
+ continue;
1311
+ }
1312
+ if (arg === "--cwd") {
1313
+ const value = readRequiredOptionValue(args, index);
1314
+ if (!value || parsed.cwd !== void 0) {
1315
+ parsed.help = true;
1316
+ continue;
1317
+ }
1318
+ parsed.cwd = value;
1319
+ index += 1;
1320
+ continue;
1321
+ }
1322
+ if (arg === "--model") {
1323
+ const value = readRequiredOptionValue(args, index);
1324
+ if (!value || parsed.model !== void 0) {
1325
+ parsed.help = true;
1326
+ continue;
1327
+ }
1328
+ parsed.model = value;
1329
+ index += 1;
1330
+ continue;
1331
+ }
1332
+ if (arg === "--provider" || arg === "--model-provider") {
1333
+ const value = readRequiredOptionValue(args, index);
1334
+ if (!value || parsed.provider !== void 0) {
1335
+ parsed.help = true;
1336
+ continue;
1337
+ }
1338
+ parsed.provider = value;
1339
+ index += 1;
1340
+ continue;
1341
+ }
1342
+ if (!arg.startsWith("-") && !parsed.threadId) {
1343
+ parsed.threadId = arg;
1344
+ continue;
1345
+ }
1346
+ parsed.help = true;
1347
+ }
1348
+ parsed.threadId = normalizeOptionalString(parsed.threadId);
1349
+ parsed.cwd = normalizeOptionalString(parsed.cwd);
1350
+ parsed.model = normalizeOptionalString(parsed.model);
1351
+ parsed.provider = normalizeOptionalString(parsed.provider);
1352
+ return parsed;
1353
+ }
1354
+ function parseCodexCliSessionsArgs(args) {
1355
+ const parsed = { filter: "" };
1356
+ const filter = [];
1357
+ for (let index = 0; index < args.length; index += 1) {
1358
+ const arg = args[index];
1359
+ if (arg === "--help" || arg === "-h") {
1360
+ parsed.help = true;
1361
+ continue;
1362
+ }
1363
+ if (arg === "--host" || arg === "--node") {
1364
+ const value = readRequiredOptionValue(args, index);
1365
+ if (!value || parsed.host !== void 0) {
1366
+ parsed.help = true;
1367
+ continue;
1368
+ }
1369
+ parsed.host = value;
1370
+ index += 1;
1371
+ continue;
1372
+ }
1373
+ if (arg === "--limit") {
1374
+ const value = readRequiredOptionValue(args, index);
1375
+ const parsedLimit = value ? Number.parseInt(value, 10) : NaN;
1376
+ if (!Number.isFinite(parsedLimit) || parsedLimit <= 0) {
1377
+ parsed.help = true;
1378
+ continue;
1379
+ }
1380
+ parsed.limit = parsedLimit;
1381
+ index += 1;
1382
+ continue;
1383
+ }
1384
+ if (arg.startsWith("-")) {
1385
+ parsed.help = true;
1386
+ continue;
1387
+ }
1388
+ filter.push(arg);
1389
+ }
1390
+ parsed.host = normalizeOptionalString(parsed.host);
1391
+ parsed.filter = filter.join(" ").trim();
1392
+ return parsed;
1393
+ }
1394
+ function parseResumeArgs(args) {
1395
+ const parsed = {};
1396
+ for (let index = 0; index < args.length; index += 1) {
1397
+ const arg = args[index];
1398
+ if (arg === "--help" || arg === "-h") {
1399
+ parsed.help = true;
1400
+ continue;
1401
+ }
1402
+ if (arg === "--host" || arg === "--node") {
1403
+ const value = readRequiredOptionValue(args, index);
1404
+ if (!value || parsed.host !== void 0) {
1405
+ parsed.help = true;
1406
+ continue;
1407
+ }
1408
+ parsed.host = value;
1409
+ index += 1;
1410
+ continue;
1411
+ }
1412
+ if (arg === "--bind") {
1413
+ if (readRequiredOptionValue(args, index) !== "here" || parsed.bindHere !== void 0) {
1414
+ parsed.help = true;
1415
+ continue;
1416
+ }
1417
+ parsed.bindHere = true;
1418
+ index += 1;
1419
+ continue;
1420
+ }
1421
+ if (!arg.startsWith("-") && !parsed.threadId) {
1422
+ parsed.threadId = arg;
1423
+ continue;
1424
+ }
1425
+ parsed.help = true;
1426
+ }
1427
+ parsed.threadId = normalizeOptionalString(parsed.threadId);
1428
+ parsed.host = normalizeOptionalString(parsed.host);
1429
+ return parsed;
1430
+ }
1431
+ function parseComputerUseArgs(args) {
1432
+ const parsed = {
1433
+ action: "status",
1434
+ overrides: {},
1435
+ hasOverrides: false
1436
+ };
1437
+ let sawAction = false;
1438
+ for (let index = 0; index < args.length; index += 1) {
1439
+ const arg = args[index];
1440
+ if (arg === "--help" || arg === "-h") {
1441
+ parsed.help = true;
1442
+ continue;
1443
+ }
1444
+ if (arg === "status" || arg === "install") {
1445
+ if (sawAction) {
1446
+ parsed.help = true;
1447
+ continue;
1448
+ }
1449
+ sawAction = true;
1450
+ parsed.action = arg;
1451
+ continue;
1452
+ }
1453
+ if (arg === "--source" || arg === "--marketplace-source") {
1454
+ const value = readRequiredOptionValue(args, index);
1455
+ if (!value || parsed.overrides.marketplaceSource !== void 0) {
1456
+ parsed.help = true;
1457
+ continue;
1458
+ }
1459
+ parsed.overrides.marketplaceSource = value;
1460
+ index += 1;
1461
+ continue;
1462
+ }
1463
+ if (arg === "--marketplace-path" || arg === "--path") {
1464
+ const value = readRequiredOptionValue(args, index);
1465
+ if (!value || parsed.overrides.marketplacePath !== void 0) {
1466
+ parsed.help = true;
1467
+ continue;
1468
+ }
1469
+ parsed.overrides.marketplacePath = value;
1470
+ index += 1;
1471
+ continue;
1472
+ }
1473
+ if (arg === "--marketplace") {
1474
+ const value = readRequiredOptionValue(args, index);
1475
+ if (!value || parsed.overrides.marketplaceName !== void 0) {
1476
+ parsed.help = true;
1477
+ continue;
1478
+ }
1479
+ parsed.overrides.marketplaceName = value;
1480
+ index += 1;
1481
+ continue;
1482
+ }
1483
+ if (arg === "--plugin") {
1484
+ const value = readRequiredOptionValue(args, index);
1485
+ if (!value || parsed.overrides.pluginName !== void 0) {
1486
+ parsed.help = true;
1487
+ continue;
1488
+ }
1489
+ parsed.overrides.pluginName = value;
1490
+ index += 1;
1491
+ continue;
1492
+ }
1493
+ if (arg === "--server" || arg === "--mcp-server") {
1494
+ const value = readRequiredOptionValue(args, index);
1495
+ if (!value || parsed.overrides.mcpServerName !== void 0) {
1496
+ parsed.help = true;
1497
+ continue;
1498
+ }
1499
+ parsed.overrides.mcpServerName = value;
1500
+ index += 1;
1501
+ continue;
1502
+ }
1503
+ parsed.help = true;
1504
+ }
1505
+ parsed.overrides = normalizeComputerUseStringOverrides(parsed.overrides);
1506
+ parsed.hasOverrides = Object.values(parsed.overrides).some(Boolean);
1507
+ return parsed;
1508
+ }
1509
+ function readRequiredOptionValue(args, index) {
1510
+ const value = args[index + 1];
1511
+ const normalized = value?.trim();
1512
+ if (!normalized || normalized.startsWith("-")) return;
1513
+ return value;
1514
+ }
1515
+ function normalizeComputerUseStringOverrides(overrides) {
1516
+ const normalized = {};
1517
+ const marketplaceSource = normalizeOptionalString(overrides.marketplaceSource);
1518
+ if (marketplaceSource) normalized.marketplaceSource = marketplaceSource;
1519
+ const marketplacePath = normalizeOptionalString(overrides.marketplacePath);
1520
+ if (marketplacePath) normalized.marketplacePath = marketplacePath;
1521
+ const marketplaceName = normalizeOptionalString(overrides.marketplaceName);
1522
+ if (marketplaceName) normalized.marketplaceName = marketplaceName;
1523
+ const pluginName = normalizeOptionalString(overrides.pluginName);
1524
+ if (pluginName) normalized.pluginName = pluginName;
1525
+ const mcpServerName = normalizeOptionalString(overrides.mcpServerName);
1526
+ if (mcpServerName) normalized.mcpServerName = mcpServerName;
1527
+ return normalized;
1528
+ }
1529
+ function normalizeOptionalString(value) {
1530
+ return value?.trim() || void 0;
1531
+ }
1532
+ //#endregion
1533
+ export { handleCodexSubcommand };