@kodelyth/codex 2026.5.40 → 2026.5.42

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 (178) hide show
  1. package/dist/client-ChMX13_o.js +642 -0
  2. package/dist/client-factory-D3dIsp4Y.js +9 -0
  3. package/dist/command-formatters-BRW7_Nu7.js +519 -0
  4. package/dist/command-handlers-P2IqtXaZ.js +1462 -0
  5. package/dist/compact-baos5flR.js +329 -0
  6. package/dist/computer-use-VfLvTMaa.js +367 -0
  7. package/dist/config-CezENx_E.js +510 -0
  8. package/dist/doctor-contract-api.js +53 -0
  9. package/dist/harness.js +51 -0
  10. package/dist/index.js +1133 -0
  11. package/dist/media-understanding-provider.js +335 -0
  12. package/dist/models-B9DhrIwD.js +110 -0
  13. package/dist/node-cli-sessions-De4_DuFw.js +1216 -0
  14. package/dist/plugin-activation-BlMuJeXz.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-CHuacE27.js +24 -0
  22. package/dist/request-CTQKUxaa.js +89 -0
  23. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  24. package/dist/run-attempt-DqV2OU1R.js +5366 -0
  25. package/dist/session-binding-3PzU7ZTW.js +222 -0
  26. package/dist/shared-client-Cnyr9dyT.js +631 -0
  27. package/dist/side-question-CP5XlA0U.js +667 -0
  28. package/dist/test-api.js +45 -0
  29. package/dist/thread-lifecycle-DBJetBuV.js +1561 -0
  30. package/dist/vision-tools-Cl_5a93K.js +1379 -0
  31. package/doctor-contract-api.test.ts +44 -0
  32. package/doctor-contract-api.ts +68 -0
  33. package/harness.ts +72 -0
  34. package/index.test.ts +230 -0
  35. package/index.ts +66 -0
  36. package/klaw.plugin.json +24 -85
  37. package/media-understanding-provider.test.ts +486 -0
  38. package/media-understanding-provider.ts +521 -0
  39. package/package.json +3 -3
  40. package/prompt-overlay-runtime-contract.test.ts +48 -0
  41. package/prompt-overlay.ts +21 -0
  42. package/provider-catalog.ts +83 -0
  43. package/provider-discovery.ts +45 -0
  44. package/provider.test.ts +384 -0
  45. package/provider.ts +243 -0
  46. package/src/app-server/app-inventory-cache.test.ts +176 -0
  47. package/src/app-server/app-inventory-cache.ts +324 -0
  48. package/src/app-server/approval-bridge.test.ts +1471 -0
  49. package/src/app-server/approval-bridge.ts +1211 -0
  50. package/src/app-server/auth-bridge.test.ts +1449 -0
  51. package/src/app-server/auth-bridge.ts +614 -0
  52. package/src/app-server/auth-profile-runtime-contract.test.ts +239 -0
  53. package/src/app-server/capabilities.ts +27 -0
  54. package/src/app-server/client-factory.ts +24 -0
  55. package/src/app-server/client.test.ts +563 -0
  56. package/src/app-server/client.ts +715 -0
  57. package/src/app-server/compact.test.ts +710 -0
  58. package/src/app-server/compact.ts +500 -0
  59. package/src/app-server/computer-use.test.ts +788 -0
  60. package/src/app-server/computer-use.ts +683 -0
  61. package/src/app-server/config.test.ts +879 -0
  62. package/src/app-server/config.ts +1038 -0
  63. package/src/app-server/context-engine-projection.test.ts +252 -0
  64. package/src/app-server/context-engine-projection.ts +403 -0
  65. package/src/app-server/delivery-no-reply-runtime-contract.test.ts +80 -0
  66. package/src/app-server/dynamic-tool-diagnostics.ts +73 -0
  67. package/src/app-server/dynamic-tool-profile.ts +69 -0
  68. package/src/app-server/dynamic-tools.test.ts +1302 -0
  69. package/src/app-server/dynamic-tools.ts +623 -0
  70. package/src/app-server/elicitation-bridge.test.ts +1056 -0
  71. package/src/app-server/elicitation-bridge.ts +783 -0
  72. package/src/app-server/event-projector.test.ts +2668 -0
  73. package/src/app-server/event-projector.ts +2057 -0
  74. package/src/app-server/image-payload-sanitizer.test.ts +49 -0
  75. package/src/app-server/image-payload-sanitizer.ts +167 -0
  76. package/src/app-server/klaw-owned-tool-runtime-contract.test.ts +456 -0
  77. package/src/app-server/local-runtime-attribution.ts +39 -0
  78. package/src/app-server/managed-binary.test.ts +139 -0
  79. package/src/app-server/managed-binary.ts +193 -0
  80. package/src/app-server/models.test.ts +246 -0
  81. package/src/app-server/models.ts +172 -0
  82. package/src/app-server/native-hook-relay.test.ts +271 -0
  83. package/src/app-server/native-hook-relay.ts +150 -0
  84. package/src/app-server/native-subagent-task-mirror.test.ts +573 -0
  85. package/src/app-server/native-subagent-task-mirror.ts +497 -0
  86. package/src/app-server/outcome-fallback-runtime-contract.test.ts +404 -0
  87. package/src/app-server/plugin-activation.test.ts +336 -0
  88. package/src/app-server/plugin-activation.ts +283 -0
  89. package/src/app-server/plugin-app-cache-key.ts +74 -0
  90. package/src/app-server/plugin-approval-roundtrip.ts +122 -0
  91. package/src/app-server/plugin-inventory.test.ts +355 -0
  92. package/src/app-server/plugin-inventory.ts +357 -0
  93. package/src/app-server/plugin-thread-config.test.ts +865 -0
  94. package/src/app-server/plugin-thread-config.ts +455 -0
  95. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +33 -0
  96. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +199 -0
  97. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +102 -0
  98. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +227 -0
  99. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +2630 -0
  100. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +2630 -0
  101. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +1659 -0
  102. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +1655 -0
  103. package/src/app-server/protocol-validators.test.ts +75 -0
  104. package/src/app-server/protocol-validators.ts +203 -0
  105. package/src/app-server/protocol.ts +520 -0
  106. package/src/app-server/rate-limit-cache.ts +48 -0
  107. package/src/app-server/rate-limits.test.ts +202 -0
  108. package/src/app-server/rate-limits.ts +583 -0
  109. package/src/app-server/request.ts +73 -0
  110. package/src/app-server/run-attempt.context-engine.test.ts +1004 -0
  111. package/src/app-server/run-attempt.test.ts +9477 -0
  112. package/src/app-server/run-attempt.ts +4683 -0
  113. package/src/app-server/run-attempt.vision-tools.test.ts +35 -0
  114. package/src/app-server/schema-normalization-runtime-contract.test.ts +206 -0
  115. package/src/app-server/session-binding.test.ts +303 -0
  116. package/src/app-server/session-binding.ts +398 -0
  117. package/src/app-server/session-history.ts +44 -0
  118. package/src/app-server/shared-client.test.ts +589 -0
  119. package/src/app-server/shared-client.ts +289 -0
  120. package/src/app-server/side-question.test.ts +1175 -0
  121. package/src/app-server/side-question.ts +1007 -0
  122. package/src/app-server/test-support.ts +48 -0
  123. package/src/app-server/thread-lifecycle.test.ts +447 -0
  124. package/src/app-server/thread-lifecycle.ts +939 -0
  125. package/src/app-server/thread-lifecycle.user-mcp-servers.test.ts +442 -0
  126. package/src/app-server/timeout.ts +9 -0
  127. package/src/app-server/tool-progress-normalization.ts +77 -0
  128. package/src/app-server/trajectory.test.ts +205 -0
  129. package/src/app-server/trajectory.ts +365 -0
  130. package/src/app-server/transcript-mirror.test.ts +524 -0
  131. package/src/app-server/transcript-mirror.ts +208 -0
  132. package/src/app-server/transcript-repair-runtime-contract.test.ts +44 -0
  133. package/src/app-server/transport-stdio.test.ts +171 -0
  134. package/src/app-server/transport-stdio.ts +107 -0
  135. package/src/app-server/transport-websocket.test.ts +69 -0
  136. package/src/app-server/transport-websocket.ts +90 -0
  137. package/src/app-server/transport.ts +117 -0
  138. package/src/app-server/user-input-bridge.test.ts +249 -0
  139. package/src/app-server/user-input-bridge.ts +316 -0
  140. package/src/app-server/version.ts +4 -0
  141. package/src/app-server/vision-tools.ts +12 -0
  142. package/src/command-account.ts +544 -0
  143. package/src/command-formatters.ts +425 -0
  144. package/src/command-handlers.ts +2004 -0
  145. package/src/command-rpc.test.ts +16 -0
  146. package/src/command-rpc.ts +142 -0
  147. package/src/commands.test.ts +3312 -0
  148. package/src/commands.ts +65 -0
  149. package/src/conversation-binding-data.ts +124 -0
  150. package/src/conversation-binding.test.ts +599 -0
  151. package/src/conversation-binding.ts +561 -0
  152. package/src/conversation-control.test.ts +126 -0
  153. package/src/conversation-control.ts +303 -0
  154. package/src/conversation-turn-collector.test.ts +191 -0
  155. package/src/conversation-turn-collector.ts +186 -0
  156. package/src/conversation-turn-input.test.ts +141 -0
  157. package/src/conversation-turn-input.ts +106 -0
  158. package/src/manifest.test.ts +20 -0
  159. package/src/migration/apply.ts +501 -0
  160. package/src/migration/helpers.ts +55 -0
  161. package/src/migration/plan.ts +461 -0
  162. package/src/migration/provider.test.ts +1741 -0
  163. package/src/migration/provider.ts +41 -0
  164. package/src/migration/source.ts +643 -0
  165. package/src/migration/targets.ts +25 -0
  166. package/src/node-cli-sessions.test.ts +180 -0
  167. package/src/node-cli-sessions.ts +711 -0
  168. package/test-api.ts +82 -0
  169. package/tsconfig.json +16 -0
  170. package/doctor-contract-api.js +0 -7
  171. package/harness.js +0 -7
  172. package/index.js +0 -7
  173. package/media-understanding-provider.js +0 -7
  174. package/prompt-overlay.js +0 -7
  175. package/provider-catalog.js +0 -7
  176. package/provider-discovery.js +0 -7
  177. package/provider.js +0 -7
  178. package/test-api.js +0 -7
@@ -0,0 +1,1462 @@
1
+ import { a as isCodexFastServiceTier, c as resolveCodexAppServerRuntimeOptions } from "./config-CezENx_E.js";
2
+ import { n as listCodexAppServerModels, t as listAllCodexAppServerModels } from "./models-B9DhrIwD.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-CTQKUxaa.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-BRW7_Nu7.js";
6
+ import { i as readCodexAppServerBinding, o as writeCodexAppServerBinding, t as clearCodexAppServerBinding } from "./session-binding-3PzU7ZTW.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-De4_DuFw.js";
8
+ import { n as installCodexComputerUse, r as readCodexComputerUseStatus } from "./computer-use-VfLvTMaa.js";
9
+ import { n as rememberCodexRateLimits } from "./rate-limit-cache-CHuacE27.js";
10
+ import crypto from "node:crypto";
11
+ import { ensureAuthProfileStore, findNormalizedProviderValue, resolveAgentDir, resolveAuthProfileEligibility, resolveAuthProfileOrder, resolveDefaultAgentDir, resolveProfileUnusableUntilForDisplay, resolveSessionAgentIds } from "klaw/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-rpc.ts
293
+ function requestOptions(pluginConfig, limit, config) {
294
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
295
+ return {
296
+ limit,
297
+ timeoutMs: runtime.requestTimeoutMs,
298
+ startOptions: runtime.start,
299
+ config
300
+ };
301
+ }
302
+ async function codexControlRequest(pluginConfig, method, requestParams, options = {}) {
303
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig });
304
+ return await requestCodexAppServerJson({
305
+ method,
306
+ requestParams,
307
+ timeoutMs: runtime.requestTimeoutMs,
308
+ startOptions: runtime.start,
309
+ config: options.config,
310
+ authProfileId: options.authProfileId,
311
+ agentDir: options.agentDir,
312
+ isolated: options.isolated
313
+ });
314
+ }
315
+ async function safeCodexControlRequest(pluginConfig, method, requestParams, options = {}) {
316
+ return await safeValue(async () => await codexControlRequest(pluginConfig, method, requestParams, options));
317
+ }
318
+ async function safeCodexModelList(pluginConfig, limit, config) {
319
+ return await safeValue(async () => await listCodexAppServerModels(requestOptions(pluginConfig, limit, config)));
320
+ }
321
+ async function readCodexStatusProbes(pluginConfig, config) {
322
+ const [models, account, limits, mcps, skills] = await Promise.all([
323
+ safeCodexModelList(pluginConfig, 20, config),
324
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.account, { refreshToken: false }, { config }),
325
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.rateLimits, void 0, { config }),
326
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, { limit: 100 }, { config }),
327
+ safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}, { config })
328
+ ]);
329
+ return {
330
+ models,
331
+ account,
332
+ limits,
333
+ mcps,
334
+ skills
335
+ };
336
+ }
337
+ async function safeValue(read) {
338
+ try {
339
+ return {
340
+ ok: true,
341
+ value: await read()
342
+ };
343
+ } catch (error) {
344
+ return {
345
+ ok: false,
346
+ error: describeControlFailure(error)
347
+ };
348
+ }
349
+ }
350
+ //#endregion
351
+ //#region extensions/codex/src/command-handlers.ts
352
+ const defaultCodexCommandDeps = {
353
+ codexControlRequest,
354
+ listCodexAppServerModels: listAllCodexAppServerModels,
355
+ readCodexStatusProbes,
356
+ readCodexAppServerBinding,
357
+ requestOptions,
358
+ safeCodexControlRequest,
359
+ writeCodexAppServerBinding,
360
+ clearCodexAppServerBinding,
361
+ readCodexComputerUseStatus,
362
+ installCodexComputerUse,
363
+ resolveCodexDefaultWorkspaceDir,
364
+ startCodexConversationThread,
365
+ readCodexConversationActiveTurn,
366
+ setCodexConversationFastMode,
367
+ setCodexConversationModel,
368
+ setCodexConversationPermissions,
369
+ steerCodexConversationTurn,
370
+ stopCodexConversationTurn,
371
+ listCodexCliSessionsOnNode: async () => {
372
+ throw new Error("Codex CLI node sessions require Gateway node runtime.");
373
+ },
374
+ resolveCodexCliSessionForBindingOnNode: async () => {
375
+ throw new Error("Codex CLI node sessions require Gateway node runtime.");
376
+ }
377
+ };
378
+ const CODEX_DIAGNOSTICS_SOURCE = "klaw-diagnostics";
379
+ const CODEX_DIAGNOSTICS_REASON_MAX_CHARS = 2048;
380
+ const CODEX_DIAGNOSTICS_COOLDOWN_MS = 6e4;
381
+ const CODEX_DIAGNOSTICS_ERROR_MAX_CHARS = 500;
382
+ const CODEX_DIAGNOSTICS_COOLDOWN_MAX_THREADS = 100;
383
+ const CODEX_DIAGNOSTICS_COOLDOWN_MAX_SCOPES = 100;
384
+ const CODEX_DIAGNOSTICS_CONFIRMATION_TTL_MS = 5 * 6e4;
385
+ const CODEX_DIAGNOSTICS_CONFIRMATION_MAX_REQUESTS_PER_SCOPE = 100;
386
+ const CODEX_DIAGNOSTICS_CONFIRMATION_MAX_SCOPES = 100;
387
+ const CODEX_DIAGNOSTICS_SCOPE_FIELD_MAX_CHARS = 128;
388
+ const CODEX_RESUME_SAFE_THREAD_ID_PATTERN = /^[A-Za-z0-9._:-]+$/;
389
+ const lastCodexDiagnosticsUploadByThread = /* @__PURE__ */ new Map();
390
+ const lastCodexDiagnosticsUploadByScope = /* @__PURE__ */ new Map();
391
+ const pendingCodexDiagnosticsConfirmations = /* @__PURE__ */ new Map();
392
+ const pendingCodexDiagnosticsConfirmationTokensByScope = /* @__PURE__ */ new Map();
393
+ async function handleCodexSubcommand(ctx, options) {
394
+ const deps = {
395
+ ...defaultCodexCommandDeps,
396
+ ...options.deps
397
+ };
398
+ const [subcommand = "status", ...rest] = splitArgs(ctx.args);
399
+ const normalized = subcommand.toLowerCase();
400
+ if (normalized === "help") return { text: buildHelp() };
401
+ if (normalized === "status") {
402
+ if (rest.length > 0) return { text: "Usage: /codex status" };
403
+ return { text: formatCodexStatus(await deps.readCodexStatusProbes(options.pluginConfig, ctx.config)) };
404
+ }
405
+ if (normalized === "models") {
406
+ if (rest.length > 0) return { text: "Usage: /codex models" };
407
+ return { text: formatModels(await deps.listCodexAppServerModels(deps.requestOptions(options.pluginConfig, 100, ctx.config))) };
408
+ }
409
+ if (normalized === "threads") return { text: await buildThreads(deps, options.pluginConfig, rest.join(" ")) };
410
+ if (normalized === "sessions") return { text: await buildCodexCliSessions(deps, rest) };
411
+ if (normalized === "resume") return { text: await resumeThread(deps, ctx, options.pluginConfig, rest) };
412
+ if (normalized === "bind") return await bindConversation(deps, ctx, options.pluginConfig, rest);
413
+ if (normalized === "detach" || normalized === "unbind") {
414
+ if (rest.length > 0) return { text: "Usage: /codex detach" };
415
+ return { text: await detachConversation(deps, ctx) };
416
+ }
417
+ if (normalized === "binding") {
418
+ if (rest.length > 0) return { text: "Usage: /codex binding" };
419
+ return { text: await describeConversationBinding(deps, ctx) };
420
+ }
421
+ if (normalized === "stop") {
422
+ if (rest.length > 0) return { text: "Usage: /codex stop" };
423
+ return { text: await stopConversationTurn(deps, ctx, options.pluginConfig) };
424
+ }
425
+ if (normalized === "steer") return { text: await steerConversationTurn(deps, ctx, options.pluginConfig, rest.join(" ")) };
426
+ if (normalized === "model") return { text: await setConversationModel(deps, ctx, options.pluginConfig, rest) };
427
+ if (normalized === "fast") return { text: await setConversationFastMode(deps, ctx, options.pluginConfig, rest) };
428
+ if (normalized === "permissions") return { text: await setConversationPermissions(deps, ctx, options.pluginConfig, rest) };
429
+ if (normalized === "compact") return { text: await startThreadAction(deps, ctx, options.pluginConfig, CODEX_CONTROL_METHODS.compact, "compaction", rest) };
430
+ if (normalized === "review") return { text: await startThreadAction(deps, ctx, options.pluginConfig, CODEX_CONTROL_METHODS.review, "review", rest) };
431
+ if (normalized === "diagnostics") return await handleCodexDiagnosticsFeedback(deps, ctx, options.pluginConfig, rest.join(" "), "/codex diagnostics");
432
+ if (normalized === "computer-use" || normalized === "computeruse") return { text: await handleComputerUseCommand(deps, options.pluginConfig, rest) };
433
+ if (normalized === "mcp") {
434
+ if (rest.length > 0) return { text: "Usage: /codex mcp" };
435
+ return { text: formatList(await deps.codexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.listMcpServers, { limit: 100 }), "MCP servers") };
436
+ }
437
+ if (normalized === "skills") {
438
+ if (rest.length > 0) return { text: "Usage: /codex skills" };
439
+ return { text: formatList(await deps.codexControlRequest(options.pluginConfig, CODEX_CONTROL_METHODS.listSkills, {}), "Codex skills") };
440
+ }
441
+ if (normalized === "account") {
442
+ if (rest.length > 0) return { text: "Usage: /codex account" };
443
+ 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)]);
444
+ if (limits.ok) rememberCodexRateLimits(limits.value);
445
+ return { text: formatAccount(account, limits, await readCodexAccountAuthOverview({
446
+ ctx,
447
+ pluginConfig: options.pluginConfig,
448
+ safeCodexControlRequest: deps.safeCodexControlRequest,
449
+ account,
450
+ limits
451
+ })) };
452
+ }
453
+ return { text: `Unknown Codex command: ${formatCodexDisplayText(subcommand)}\n\n${buildHelp()}` };
454
+ }
455
+ async function handleComputerUseCommand(deps, pluginConfig, args) {
456
+ const parsed = parseComputerUseArgs(args);
457
+ 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");
458
+ const params = {
459
+ pluginConfig,
460
+ forceEnable: parsed.action === "install" || parsed.hasOverrides,
461
+ ...Object.keys(parsed.overrides).length > 0 ? { overrides: parsed.overrides } : {}
462
+ };
463
+ if (parsed.action === "install") return formatComputerUseStatus(await deps.installCodexComputerUse(params));
464
+ return formatComputerUseStatus(await deps.readCodexComputerUseStatus(params));
465
+ }
466
+ async function bindConversation(deps, ctx, pluginConfig, args) {
467
+ const parsed = parseBindArgs(args);
468
+ if (parsed.help) return { text: "Usage: /codex bind [thread-id] [--cwd <path>] [--model <model>] [--provider <provider>]" };
469
+ if (!ctx.sessionFile) return { text: "Cannot bind Codex because this command did not include an Klaw session file." };
470
+ const scope = resolveCodexConversationControlScope(ctx);
471
+ const workspaceDir = parsed.cwd ?? deps.resolveCodexDefaultWorkspaceDir(pluginConfig);
472
+ const authProfileId = (await deps.readCodexAppServerBinding(ctx.sessionFile, {
473
+ agentDir: scope.agentDir,
474
+ config: ctx.config
475
+ }))?.authProfileId;
476
+ const startParams = {
477
+ pluginConfig,
478
+ config: ctx.config,
479
+ sessionFile: ctx.sessionFile,
480
+ workspaceDir,
481
+ agentDir: scope.agentDir,
482
+ threadId: parsed.threadId,
483
+ model: parsed.model,
484
+ modelProvider: parsed.provider
485
+ };
486
+ if (authProfileId) startParams.authProfileId = authProfileId;
487
+ const data = await deps.startCodexConversationThread(startParams);
488
+ const threadId = (await deps.readCodexAppServerBinding(ctx.sessionFile, {
489
+ agentDir: scope.agentDir,
490
+ config: ctx.config
491
+ }))?.threadId ?? parsed.threadId ?? "new thread";
492
+ const summary = `Codex app-server thread ${formatCodexDisplayText(threadId)} in ${formatCodexDisplayText(workspaceDir)}`;
493
+ let request;
494
+ try {
495
+ request = await ctx.requestConversationBinding({
496
+ summary,
497
+ detachHint: "/codex detach",
498
+ data
499
+ });
500
+ } catch (error) {
501
+ await deps.clearCodexAppServerBinding(ctx.sessionFile);
502
+ throw error;
503
+ }
504
+ if (request.status === "bound") return { text: `Bound this conversation to Codex thread ${formatCodexDisplayText(threadId)} in ${formatCodexDisplayText(workspaceDir)}.` };
505
+ if (request.status === "pending") return request.reply;
506
+ await deps.clearCodexAppServerBinding(ctx.sessionFile);
507
+ return { text: formatCodexDisplayText(request.message) };
508
+ }
509
+ async function detachConversation(deps, ctx) {
510
+ const data = readCodexConversationBindingData(await ctx.getCurrentConversationBinding());
511
+ const detached = await ctx.detachConversationBinding();
512
+ if (data?.kind === "codex-app-server-session") await deps.clearCodexAppServerBinding(data.sessionFile);
513
+ else if (ctx.sessionFile) await deps.clearCodexAppServerBinding(ctx.sessionFile);
514
+ return detached.removed ? "Detached this conversation from Codex." : "No Codex conversation binding was attached.";
515
+ }
516
+ async function describeConversationBinding(deps, ctx) {
517
+ const current = await ctx.getCurrentConversationBinding();
518
+ const data = readCodexConversationBindingData(current);
519
+ if (!current || !data) return "No Codex conversation binding is attached.";
520
+ if (data.kind === "codex-cli-node-session") return [
521
+ "Codex conversation binding:",
522
+ "- Mode: Codex CLI node session",
523
+ `- Node: ${formatCodexDisplayText(data.nodeId)}`,
524
+ `- Session: ${formatCodexDisplayText(data.sessionId)}`,
525
+ `- Workspace: ${formatCodexDisplayText(data.cwd ?? "unknown")}`,
526
+ "- Active run: not tracked"
527
+ ].join("\n");
528
+ const threadBinding = await deps.readCodexAppServerBinding(data.sessionFile, {
529
+ agentDir: data.agentDir,
530
+ config: ctx.config
531
+ });
532
+ const active = deps.readCodexConversationActiveTurn(data.sessionFile);
533
+ return [
534
+ "Codex conversation binding:",
535
+ `- Thread: ${formatCodexDisplayText(threadBinding?.threadId ?? "unknown")}`,
536
+ `- Workspace: ${formatCodexDisplayText(data.workspaceDir)}`,
537
+ `- Model: ${formatCodexDisplayText(threadBinding?.model ?? "default")}`,
538
+ `- Fast: ${isCodexFastServiceTier(threadBinding?.serviceTier) ? "on" : "off"}`,
539
+ `- Permissions: ${threadBinding ? formatPermissionsMode(threadBinding) : "default"}`,
540
+ `- Active run: ${formatCodexDisplayText(active ? active.turnId : "none")}`,
541
+ `- Session: ${formatCodexDisplayText(data.sessionFile)}`
542
+ ].join("\n");
543
+ }
544
+ async function buildThreads(deps, pluginConfig, filter) {
545
+ return formatThreads(await deps.codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.listThreads, {
546
+ limit: 10,
547
+ ...filter.trim() ? { searchTerm: filter.trim() } : {}
548
+ }));
549
+ }
550
+ async function buildCodexCliSessions(deps, args) {
551
+ const parsed = parseCodexCliSessionsArgs(args);
552
+ if (parsed.help || !parsed.host) return "Usage: /codex sessions --host <node> [filter] [--limit <n>]";
553
+ return formatCodexCliSessions(await deps.listCodexCliSessionsOnNode({
554
+ requestedNode: parsed.host,
555
+ filter: parsed.filter,
556
+ limit: parsed.limit
557
+ }));
558
+ }
559
+ async function resumeThread(deps, ctx, pluginConfig, args) {
560
+ const parsed = parseResumeArgs(args);
561
+ const normalizedThreadId = parsed.threadId?.trim();
562
+ 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>";
563
+ if (parsed.host) return await bindCodexCliNodeSession(deps, ctx, parsed);
564
+ if (!normalizedThreadId || args.length !== 1) return "Usage: /codex resume <thread-id>";
565
+ if (!ctx.sessionFile) return "Cannot attach a Codex thread because this command did not include an Klaw session file.";
566
+ const response = await deps.codexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.resumeThread, {
567
+ threadId: normalizedThreadId,
568
+ persistExtendedHistory: true
569
+ });
570
+ const thread = isJsonObject(response) && isJsonObject(response.thread) ? response.thread : {};
571
+ const effectiveThreadId = readString$1(thread, "id") ?? normalizedThreadId;
572
+ await deps.writeCodexAppServerBinding(ctx.sessionFile, {
573
+ threadId: effectiveThreadId,
574
+ cwd: readString$1(thread, "cwd") ?? "",
575
+ model: isJsonObject(response) ? readString$1(response, "model") : void 0,
576
+ modelProvider: isJsonObject(response) ? readString$1(response, "modelProvider") : void 0
577
+ });
578
+ return `Attached this Klaw session to Codex thread ${formatCodexDisplayText(effectiveThreadId)}.`;
579
+ }
580
+ async function bindCodexCliNodeSession(deps, ctx, parsed) {
581
+ if (!parsed.threadId || !parsed.host || parsed.bindHere !== true) return "Usage: /codex resume <session-id> --host <node> --bind here";
582
+ const resolved = await deps.resolveCodexCliSessionForBindingOnNode({
583
+ requestedNode: parsed.host,
584
+ sessionId: parsed.threadId
585
+ });
586
+ if (!resolved.session) return `No Codex CLI session ${formatCodexDisplayText(parsed.threadId)} was found on ${formatCodexDisplayText(parsed.host)}.`;
587
+ const nodeId = resolved.node.nodeId;
588
+ if (!nodeId) return "Cannot bind Codex CLI session because the selected node did not include a node id.";
589
+ const data = createCodexCliNodeConversationBindingData({
590
+ nodeId,
591
+ sessionId: parsed.threadId,
592
+ cwd: resolved.session?.cwd
593
+ });
594
+ const summary = `Codex CLI session ${formatCodexDisplayText(parsed.threadId)} on ${formatCodexDisplayText(nodeId)}`;
595
+ const request = await ctx.requestConversationBinding({
596
+ summary,
597
+ detachHint: "/codex detach",
598
+ data
599
+ });
600
+ if (request.status === "bound") return `Bound this conversation to Codex CLI session ${formatCodexDisplayText(parsed.threadId)} on ${formatCodexDisplayText(nodeId)}.`;
601
+ if (request.status === "pending") return request.reply.text ?? "Codex CLI session binding is pending approval.";
602
+ return formatCodexDisplayText(request.message);
603
+ }
604
+ async function stopConversationTurn(deps, ctx, pluginConfig) {
605
+ const target = await resolveControlTarget(ctx);
606
+ if (!target) return "Cannot stop Codex because this command did not include an Klaw session file.";
607
+ return (await deps.stopCodexConversationTurn({
608
+ sessionFile: target.sessionFile,
609
+ pluginConfig,
610
+ agentDir: target.agentDir,
611
+ config: ctx.config
612
+ })).message;
613
+ }
614
+ async function steerConversationTurn(deps, ctx, pluginConfig, message) {
615
+ const target = await resolveControlTarget(ctx);
616
+ if (!target) return "Cannot steer Codex because this command did not include an Klaw session file.";
617
+ return (await deps.steerCodexConversationTurn({
618
+ sessionFile: target.sessionFile,
619
+ pluginConfig,
620
+ message,
621
+ agentDir: target.agentDir,
622
+ config: ctx.config
623
+ })).message;
624
+ }
625
+ async function setConversationModel(deps, ctx, pluginConfig, args) {
626
+ if (args.length > 1) return "Usage: /codex model <model>";
627
+ const target = await resolveControlTarget(ctx);
628
+ if (!target) return "Cannot set Codex model because this command did not include an Klaw session file.";
629
+ const [model = ""] = args;
630
+ const normalized = model.trim();
631
+ if (!normalized) {
632
+ const binding = await deps.readCodexAppServerBinding(target.sessionFile, {
633
+ agentDir: target.agentDir,
634
+ config: ctx.config
635
+ });
636
+ return binding?.model ? `Codex model: ${formatCodexDisplayText(binding.model)}` : "Usage: /codex model <model>";
637
+ }
638
+ return await deps.setCodexConversationModel({
639
+ sessionFile: target.sessionFile,
640
+ pluginConfig,
641
+ model: normalized,
642
+ agentDir: target.agentDir,
643
+ config: ctx.config
644
+ });
645
+ }
646
+ async function setConversationFastMode(deps, ctx, pluginConfig, args) {
647
+ if (args.length > 1) return "Usage: /codex fast [on|off|status]";
648
+ const target = await resolveControlTarget(ctx);
649
+ if (!target) return "Cannot set Codex fast mode because this command did not include an Klaw session file.";
650
+ const value = args[0];
651
+ const parsed = parseCodexFastModeArg(value);
652
+ if (value && parsed == null && value.trim().toLowerCase() !== "status") return "Usage: /codex fast [on|off|status]";
653
+ return await deps.setCodexConversationFastMode({
654
+ sessionFile: target.sessionFile,
655
+ pluginConfig,
656
+ enabled: parsed,
657
+ agentDir: target.agentDir,
658
+ config: ctx.config
659
+ });
660
+ }
661
+ async function setConversationPermissions(deps, ctx, pluginConfig, args) {
662
+ if (args.length > 1) return "Usage: /codex permissions [default|yolo|status]";
663
+ const target = await resolveControlTarget(ctx);
664
+ if (!target) return "Cannot set Codex permissions because this command did not include an Klaw session file.";
665
+ const value = args[0];
666
+ const parsed = parseCodexPermissionsModeArg(value);
667
+ if (value && !parsed && value.trim().toLowerCase() !== "status") return "Usage: /codex permissions [default|yolo|status]";
668
+ return await deps.setCodexConversationPermissions({
669
+ sessionFile: target.sessionFile,
670
+ pluginConfig,
671
+ mode: parsed,
672
+ agentDir: target.agentDir,
673
+ config: ctx.config
674
+ });
675
+ }
676
+ async function resolveControlTarget(ctx) {
677
+ const data = readCodexConversationBindingData(await ctx.getCurrentConversationBinding());
678
+ const scope = resolveCodexConversationControlScope(ctx);
679
+ if (data?.kind === "codex-app-server-session") return {
680
+ sessionFile: data.sessionFile,
681
+ agentDir: data.agentDir ?? scope.agentDir
682
+ };
683
+ return ctx.sessionFile ? {
684
+ sessionFile: ctx.sessionFile,
685
+ agentDir: scope.agentDir
686
+ } : void 0;
687
+ }
688
+ async function resolveControlSessionFile(ctx) {
689
+ return (await resolveControlTarget(ctx))?.sessionFile;
690
+ }
691
+ function resolveCodexConversationControlScope(ctx) {
692
+ const { sessionAgentId } = resolveSessionAgentIds({
693
+ sessionKey: ctx.sessionKey,
694
+ config: ctx.config
695
+ });
696
+ return { agentDir: resolveAgentDir(ctx.config, sessionAgentId) };
697
+ }
698
+ async function handleCodexDiagnosticsFeedback(deps, ctx, pluginConfig, args, commandPrefix) {
699
+ if (ctx.senderIsOwner !== true) return { text: "Only an owner can send Codex diagnostics." };
700
+ const parsed = parseDiagnosticsArgs(args);
701
+ if (parsed.action === "usage") return { text: formatDiagnosticsUsage(commandPrefix) };
702
+ if (parsed.action === "confirm") return { text: await confirmCodexDiagnosticsFeedback(deps, ctx, pluginConfig, parsed.token) };
703
+ if (parsed.action === "cancel") return { text: cancelCodexDiagnosticsFeedback(ctx, parsed.token) };
704
+ if (ctx.diagnosticsUploadApproved === true) return { text: await sendCodexDiagnosticsFeedbackForContext(deps, ctx, pluginConfig, parsed.note) };
705
+ if (ctx.diagnosticsPreviewOnly === true) return { text: await previewCodexDiagnosticsFeedbackApproval(deps, ctx, parsed.note) };
706
+ return await requestCodexDiagnosticsFeedbackApproval(deps, ctx, parsed.note, commandPrefix);
707
+ }
708
+ async function requestCodexDiagnosticsFeedbackApproval(deps, ctx, note, commandPrefix) {
709
+ if (!await hasAnyCodexDiagnosticsSessionFile(ctx)) return { text: "Cannot send Codex diagnostics because this command did not include an Klaw session file." };
710
+ const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
711
+ if (targets.length === 0) return { text: ["No Codex thread is attached to this Klaw session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n") };
712
+ const now = Date.now();
713
+ const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now);
714
+ if (cooldownMessage) return { text: cooldownMessage };
715
+ if (!ctx.senderId) return { text: "Cannot send Codex diagnostics because this command did not include a sender identity." };
716
+ const reason = normalizeDiagnosticsReason(note);
717
+ const token = createCodexDiagnosticsConfirmation({
718
+ targets,
719
+ note: reason,
720
+ senderId: ctx.senderId,
721
+ channel: ctx.channel,
722
+ scopeKey: readCodexDiagnosticsCooldownScope(ctx),
723
+ privateRouted: ctx.diagnosticsPrivateRouted === true,
724
+ ...readCodexDiagnosticsConfirmationScope(ctx),
725
+ now
726
+ });
727
+ const confirmCommand = `${commandPrefix} confirm ${token}`;
728
+ const cancelCommand = `${commandPrefix} cancel ${token}`;
729
+ const displayReason = reason ? escapeCodexChatText(formatCodexTextForDisplay(reason)) : void 0;
730
+ return {
731
+ text: [
732
+ targets.length === 1 ? "Codex runtime thread detected." : "Codex runtime threads detected.",
733
+ `Codex diagnostics can send ${targets.length === 1 ? "this thread's feedback bundle" : "these threads' feedback bundles"} to OpenAI servers.`,
734
+ "Codex sessions:",
735
+ ...formatCodexDiagnosticsTargetLines(targets),
736
+ ...displayReason ? [`Note: ${displayReason}`] : [],
737
+ "Included: Codex logs and spawned Codex subthreads when available.",
738
+ `To send: ${confirmCommand}`,
739
+ `To cancel: ${cancelCommand}`,
740
+ "This request expires in 5 minutes."
741
+ ].join("\n"),
742
+ interactive: { blocks: [{
743
+ type: "buttons",
744
+ buttons: [{
745
+ label: "Send diagnostics",
746
+ value: confirmCommand,
747
+ style: "danger"
748
+ }, {
749
+ label: "Cancel",
750
+ value: cancelCommand,
751
+ style: "secondary"
752
+ }]
753
+ }] }
754
+ };
755
+ }
756
+ async function previewCodexDiagnosticsFeedbackApproval(deps, ctx, note) {
757
+ if (!await hasAnyCodexDiagnosticsSessionFile(ctx)) return "Cannot send Codex diagnostics because this command did not include an Klaw session file.";
758
+ const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
759
+ if (targets.length === 0) return ["No Codex thread is attached to this Klaw session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n");
760
+ const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, Date.now(), { includeThreadId: false });
761
+ if (cooldownMessage) return cooldownMessage;
762
+ const reason = normalizeDiagnosticsReason(note);
763
+ const displayReason = reason ? escapeCodexChatText(formatCodexTextForDisplay(reason)) : void 0;
764
+ return [
765
+ targets.length === 1 ? "Codex runtime thread detected." : "Codex runtime threads detected.",
766
+ `Approving diagnostics will also send ${targets.length === 1 ? "this thread's feedback bundle" : "these threads' feedback bundles"} to OpenAI servers.`,
767
+ "The completed diagnostics reply will list the Klaw session ids and Codex thread ids that were sent.",
768
+ ...displayReason ? [`Note: ${displayReason}`] : [],
769
+ "Included: Codex logs and spawned Codex subthreads when available."
770
+ ].join("\n");
771
+ }
772
+ async function confirmCodexDiagnosticsFeedback(deps, ctx, pluginConfig, token) {
773
+ const pending = readPendingCodexDiagnosticsConfirmation(token, Date.now());
774
+ if (!pending) return "No pending Codex diagnostics confirmation was found. Run /diagnostics again to create a fresh request.";
775
+ if (!pending.senderId || !ctx.senderId) return "Cannot confirm Codex diagnostics because this command did not include the original sender identity.";
776
+ if (pending.senderId !== ctx.senderId) return "Only the user who requested these Codex diagnostics can confirm the upload.";
777
+ if (pending.channel !== ctx.channel) return "This Codex diagnostics confirmation belongs to a different channel.";
778
+ const scopeMismatch = readCodexDiagnosticsScopeMismatch(pending, ctx);
779
+ if (scopeMismatch) return scopeMismatch.confirmMessage;
780
+ deletePendingCodexDiagnosticsConfirmation(token);
781
+ if (!pending.privateRouted && !await hasAnyCodexDiagnosticsSessionFile(ctx)) return "Cannot send Codex diagnostics because this command did not include an Klaw session file.";
782
+ const currentTargets = pending.privateRouted ? await resolvePendingCodexDiagnosticsTargets(deps, pending.targets) : await resolveCodexDiagnosticsTargets(deps, ctx);
783
+ if (!codexDiagnosticsTargetsMatch(pending.targets, currentTargets)) return "The Codex diagnostics sessions changed before confirmation. Run /diagnostics again for the current threads.";
784
+ return await sendCodexDiagnosticsFeedbackForTargets(deps, ctx, pluginConfig, pending.note ?? "", pending.targets);
785
+ }
786
+ function cancelCodexDiagnosticsFeedback(ctx, token) {
787
+ const pending = readPendingCodexDiagnosticsConfirmation(token, Date.now());
788
+ if (!pending) return "No pending Codex diagnostics confirmation was found.";
789
+ if (!pending.senderId || !ctx.senderId) return "Cannot cancel Codex diagnostics because this command did not include the original sender identity.";
790
+ if (pending.senderId !== ctx.senderId) return "Only the user who requested these Codex diagnostics can cancel the upload.";
791
+ if (pending.channel !== ctx.channel) return "This Codex diagnostics confirmation belongs to a different channel.";
792
+ const scopeMismatch = readCodexDiagnosticsScopeMismatch(pending, ctx);
793
+ if (scopeMismatch) return scopeMismatch.cancelMessage;
794
+ deletePendingCodexDiagnosticsConfirmation(token);
795
+ return [
796
+ "Codex diagnostics upload canceled.",
797
+ "Codex sessions:",
798
+ ...formatCodexDiagnosticsTargetLines(pending.targets)
799
+ ].join("\n");
800
+ }
801
+ async function sendCodexDiagnosticsFeedbackForContext(deps, ctx, pluginConfig, note) {
802
+ if (!await hasAnyCodexDiagnosticsSessionFile(ctx)) return "Cannot send Codex diagnostics because this command did not include an Klaw session file.";
803
+ const targets = await resolveCodexDiagnosticsTargets(deps, ctx);
804
+ if (targets.length === 0) return ["No Codex thread is attached to this Klaw session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n");
805
+ return await sendCodexDiagnosticsFeedbackForTargets(deps, ctx, pluginConfig, note, targets);
806
+ }
807
+ async function sendCodexDiagnosticsFeedbackForTargets(deps, ctx, pluginConfig, note, targets) {
808
+ if (targets.length === 0) return ["No Codex thread is attached to this Klaw session yet.", "Use /codex threads to find a thread, then /codex resume <thread-id> before sending diagnostics."].join("\n");
809
+ const now = Date.now();
810
+ const cooldownMessage = readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now);
811
+ if (cooldownMessage) return cooldownMessage;
812
+ const reason = normalizeDiagnosticsReason(note);
813
+ const sent = [];
814
+ const failed = [];
815
+ for (const target of targets) {
816
+ const response = await deps.safeCodexControlRequest(pluginConfig, CODEX_CONTROL_METHODS.feedback, {
817
+ classification: "bug",
818
+ threadId: target.threadId,
819
+ includeLogs: true,
820
+ tags: buildDiagnosticsTags(ctx),
821
+ ...reason ? { reason } : {}
822
+ });
823
+ if (!response.ok) {
824
+ failed.push({
825
+ target,
826
+ error: response.error
827
+ });
828
+ continue;
829
+ }
830
+ const responseThreadId = isJsonObject(response.value) ? readString$1(response.value, "threadId") : void 0;
831
+ sent.push({
832
+ ...target,
833
+ threadId: responseThreadId ?? target.threadId
834
+ });
835
+ recordCodexDiagnosticsUpload(target.threadId, ctx, now);
836
+ }
837
+ return formatCodexDiagnosticsUploadResult(sent, failed);
838
+ }
839
+ async function hasAnyCodexDiagnosticsSessionFile(ctx) {
840
+ if (await resolveControlSessionFile(ctx)) return true;
841
+ return (ctx.diagnosticsSessions ?? []).some((session) => Boolean(session.sessionFile));
842
+ }
843
+ async function resolveCodexDiagnosticsTargets(deps, ctx) {
844
+ const activeSessionFile = await resolveControlSessionFile(ctx);
845
+ const candidates = [];
846
+ if (activeSessionFile) candidates.push({
847
+ threadId: "",
848
+ sessionFile: activeSessionFile,
849
+ sessionKey: ctx.sessionKey,
850
+ sessionId: ctx.sessionId,
851
+ channel: ctx.channel,
852
+ channelId: ctx.channelId,
853
+ accountId: ctx.accountId,
854
+ messageThreadId: ctx.messageThreadId,
855
+ threadParentId: ctx.threadParentId
856
+ });
857
+ for (const session of ctx.diagnosticsSessions ?? []) {
858
+ if (!session.sessionFile) continue;
859
+ candidates.push({
860
+ threadId: "",
861
+ sessionFile: session.sessionFile,
862
+ sessionKey: session.sessionKey,
863
+ sessionId: session.sessionId,
864
+ channel: session.channel,
865
+ channelId: session.channelId,
866
+ accountId: session.accountId,
867
+ messageThreadId: session.messageThreadId,
868
+ threadParentId: session.threadParentId
869
+ });
870
+ }
871
+ const seenSessionFiles = /* @__PURE__ */ new Set();
872
+ const seenThreadIds = /* @__PURE__ */ new Set();
873
+ const targets = [];
874
+ for (const candidate of candidates) {
875
+ if (seenSessionFiles.has(candidate.sessionFile)) continue;
876
+ seenSessionFiles.add(candidate.sessionFile);
877
+ const binding = await deps.readCodexAppServerBinding(candidate.sessionFile);
878
+ if (!binding?.threadId || seenThreadIds.has(binding.threadId)) continue;
879
+ seenThreadIds.add(binding.threadId);
880
+ targets.push({
881
+ ...candidate,
882
+ threadId: binding.threadId
883
+ });
884
+ }
885
+ return targets;
886
+ }
887
+ async function resolvePendingCodexDiagnosticsTargets(deps, targets) {
888
+ const resolved = [];
889
+ for (const target of targets) {
890
+ const binding = await deps.readCodexAppServerBinding(target.sessionFile);
891
+ if (!binding?.threadId) continue;
892
+ resolved.push({
893
+ ...target,
894
+ threadId: binding.threadId
895
+ });
896
+ }
897
+ return resolved;
898
+ }
899
+ function codexDiagnosticsTargetsMatch(expected, actual) {
900
+ const expectedThreadIds = expected.map((target) => target.threadId).toSorted();
901
+ const actualThreadIds = actual.map((target) => target.threadId).toSorted();
902
+ return expectedThreadIds.length === actualThreadIds.length && expectedThreadIds.every((threadId, index) => threadId === actualThreadIds[index]);
903
+ }
904
+ function formatCodexDiagnosticsUploadResult(sent, failed) {
905
+ const lines = [];
906
+ if (sent.length > 0) {
907
+ lines.push("Codex diagnostics sent to OpenAI servers:");
908
+ lines.push(...formatCodexDiagnosticsTargetLines(sent));
909
+ lines.push("Included Codex logs and spawned Codex subthreads when available.");
910
+ }
911
+ if (failed.length > 0) {
912
+ if (lines.length > 0) lines.push("");
913
+ lines.push("Could not send Codex diagnostics:");
914
+ lines.push(...failed.map(({ target, error }) => `${formatCodexDiagnosticsTargetLine(target)}: ${formatCodexErrorForDisplay(error)}`));
915
+ lines.push("Inspect locally:");
916
+ lines.push(...failed.map(({ target }) => `- ${formatCodexResumeCommandForDisplay(target.threadId)}`));
917
+ }
918
+ return lines.join("\n");
919
+ }
920
+ function formatCodexDiagnosticsTargetLines(targets) {
921
+ return targets.flatMap((target, index) => {
922
+ const lines = formatCodexDiagnosticsTargetBlock(target, index);
923
+ return index < targets.length - 1 ? [...lines, ""] : lines;
924
+ });
925
+ }
926
+ function formatCodexDiagnosticsTargetBlock(target, index) {
927
+ const lines = [`Session ${index + 1}`];
928
+ if (target.channel) lines.push(`Channel: ${formatCodexValueForDisplay(target.channel)}`);
929
+ if (target.sessionKey) lines.push(`Klaw session key: ${formatCodexCopyableValueForDisplay(target.sessionKey)}`);
930
+ if (target.sessionId) lines.push(`Klaw session id: ${formatCodexCopyableValueForDisplay(target.sessionId)}`);
931
+ lines.push(`Codex thread id: ${formatCodexCopyableValueForDisplay(target.threadId)}`);
932
+ lines.push(`Inspect locally: ${formatCodexResumeCommandForDisplay(target.threadId)}`);
933
+ return lines;
934
+ }
935
+ function formatCodexDiagnosticsTargetLine(target) {
936
+ const parts = [];
937
+ if (target.channel) parts.push(`channel ${formatCodexValueForDisplay(target.channel)}`);
938
+ const sessionLabel = target.sessionId || target.sessionKey;
939
+ if (sessionLabel) parts.push(`Klaw session ${formatCodexValueForDisplay(sessionLabel)}`);
940
+ parts.push(`Codex thread ${formatCodexThreadIdForDisplay(target.threadId)}`);
941
+ return `- ${parts.join(", ")}`;
942
+ }
943
+ function normalizeDiagnosticsReason(note) {
944
+ const normalized = normalizeOptionalString(note);
945
+ return normalized ? normalized.slice(0, CODEX_DIAGNOSTICS_REASON_MAX_CHARS) : void 0;
946
+ }
947
+ function parseDiagnosticsArgs(args) {
948
+ const [action, token, ...extra] = splitArgs(args);
949
+ const normalizedAction = action?.toLowerCase();
950
+ if ((normalizedAction === "confirm" || normalizedAction === "--confirm") && token && extra.length === 0) return {
951
+ action: "confirm",
952
+ token
953
+ };
954
+ if ((normalizedAction === "cancel" || normalizedAction === "--cancel") && token && extra.length === 0) return {
955
+ action: "cancel",
956
+ token
957
+ };
958
+ if (normalizedAction === "confirm" || normalizedAction === "--confirm" || normalizedAction === "cancel" || normalizedAction === "--cancel") return { action: "usage" };
959
+ return {
960
+ action: "request",
961
+ note: args
962
+ };
963
+ }
964
+ function formatDiagnosticsUsage(commandPrefix) {
965
+ return [
966
+ `Usage: ${commandPrefix} [note]`,
967
+ `Usage: ${commandPrefix} confirm <token>`,
968
+ `Usage: ${commandPrefix} cancel <token>`
969
+ ].join("\n");
970
+ }
971
+ function createCodexDiagnosticsConfirmation(params) {
972
+ prunePendingCodexDiagnosticsConfirmations(params.now);
973
+ if (!pendingCodexDiagnosticsConfirmationTokensByScope.has(params.scopeKey) && pendingCodexDiagnosticsConfirmationTokensByScope.size >= CODEX_DIAGNOSTICS_CONFIRMATION_MAX_SCOPES) {
974
+ const oldestScopeKey = pendingCodexDiagnosticsConfirmationTokensByScope.keys().next().value;
975
+ if (typeof oldestScopeKey === "string") deletePendingCodexDiagnosticsConfirmationScope(oldestScopeKey);
976
+ }
977
+ const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(params.scopeKey) ?? [];
978
+ while (scopeTokens.length >= CODEX_DIAGNOSTICS_CONFIRMATION_MAX_REQUESTS_PER_SCOPE) {
979
+ const oldestToken = scopeTokens.shift();
980
+ if (!oldestToken) break;
981
+ pendingCodexDiagnosticsConfirmations.delete(oldestToken);
982
+ }
983
+ const token = crypto.randomBytes(6).toString("hex");
984
+ scopeTokens.push(token);
985
+ pendingCodexDiagnosticsConfirmationTokensByScope.set(params.scopeKey, scopeTokens);
986
+ pendingCodexDiagnosticsConfirmations.set(token, {
987
+ token,
988
+ targets: params.targets,
989
+ note: params.note,
990
+ senderId: params.senderId,
991
+ channel: params.channel,
992
+ accountId: params.accountId,
993
+ channelId: params.channelId,
994
+ messageThreadId: params.messageThreadId,
995
+ threadParentId: params.threadParentId,
996
+ sessionKey: params.sessionKey,
997
+ scopeKey: params.scopeKey,
998
+ ...params.privateRouted === void 0 ? {} : { privateRouted: params.privateRouted },
999
+ createdAt: params.now
1000
+ });
1001
+ return token;
1002
+ }
1003
+ function readCodexDiagnosticsConfirmationScope(ctx) {
1004
+ return {
1005
+ accountId: normalizeCodexDiagnosticsScopeField(ctx.accountId),
1006
+ channelId: normalizeCodexDiagnosticsScopeField(ctx.channelId),
1007
+ messageThreadId: typeof ctx.messageThreadId === "string" || typeof ctx.messageThreadId === "number" ? normalizeCodexDiagnosticsScopeField(String(ctx.messageThreadId)) : void 0,
1008
+ threadParentId: normalizeCodexDiagnosticsScopeField(ctx.threadParentId),
1009
+ sessionKey: normalizeCodexDiagnosticsScopeField(ctx.sessionKey)
1010
+ };
1011
+ }
1012
+ function readCodexDiagnosticsScopeMismatch(pending, ctx) {
1013
+ const current = readCodexDiagnosticsConfirmationScope(ctx);
1014
+ if (pending.accountId !== current.accountId) return {
1015
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different account.",
1016
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different account."
1017
+ };
1018
+ if (pending.privateRouted) return;
1019
+ if (pending.channelId !== current.channelId) return {
1020
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different channel instance.",
1021
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different channel instance."
1022
+ };
1023
+ if (pending.messageThreadId !== current.messageThreadId) return {
1024
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different thread.",
1025
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different thread."
1026
+ };
1027
+ if (pending.threadParentId !== current.threadParentId) return {
1028
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different parent thread.",
1029
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different parent thread."
1030
+ };
1031
+ if (pending.sessionKey !== current.sessionKey) return {
1032
+ confirmMessage: "This Codex diagnostics confirmation belongs to a different session.",
1033
+ cancelMessage: "This Codex diagnostics confirmation belongs to a different session."
1034
+ };
1035
+ }
1036
+ function readPendingCodexDiagnosticsConfirmation(token, now) {
1037
+ prunePendingCodexDiagnosticsConfirmations(now);
1038
+ return pendingCodexDiagnosticsConfirmations.get(token);
1039
+ }
1040
+ function prunePendingCodexDiagnosticsConfirmations(now) {
1041
+ for (const [token, pending] of pendingCodexDiagnosticsConfirmations) if (now - pending.createdAt >= CODEX_DIAGNOSTICS_CONFIRMATION_TTL_MS) deletePendingCodexDiagnosticsConfirmation(token);
1042
+ }
1043
+ function deletePendingCodexDiagnosticsConfirmation(token) {
1044
+ const pending = pendingCodexDiagnosticsConfirmations.get(token);
1045
+ pendingCodexDiagnosticsConfirmations.delete(token);
1046
+ if (!pending) return;
1047
+ const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(pending.scopeKey);
1048
+ if (!scopeTokens) return;
1049
+ const tokenIndex = scopeTokens.indexOf(token);
1050
+ if (tokenIndex >= 0) scopeTokens.splice(tokenIndex, 1);
1051
+ if (scopeTokens.length === 0) pendingCodexDiagnosticsConfirmationTokensByScope.delete(pending.scopeKey);
1052
+ }
1053
+ function deletePendingCodexDiagnosticsConfirmationScope(scopeKey) {
1054
+ const scopeTokens = pendingCodexDiagnosticsConfirmationTokensByScope.get(scopeKey) ?? [];
1055
+ for (const token of scopeTokens) pendingCodexDiagnosticsConfirmations.delete(token);
1056
+ pendingCodexDiagnosticsConfirmationTokensByScope.delete(scopeKey);
1057
+ }
1058
+ function buildDiagnosticsTags(ctx) {
1059
+ const tags = { source: CODEX_DIAGNOSTICS_SOURCE };
1060
+ addTag(tags, "channel", ctx.channel);
1061
+ return tags;
1062
+ }
1063
+ function addTag(tags, key, value) {
1064
+ if (typeof value === "string" && value.trim()) tags[key] = value.trim();
1065
+ }
1066
+ function formatCodexThreadIdForDisplay(threadId) {
1067
+ return escapeCodexChatText(formatCodexTextForDisplay(threadId));
1068
+ }
1069
+ function formatCodexValueForDisplay(value) {
1070
+ return escapeCodexChatText(formatCodexTextForDisplay(value));
1071
+ }
1072
+ function formatCodexCopyableValueForDisplay(value) {
1073
+ const safe = formatCodexTextForDisplay(value);
1074
+ if (CODEX_RESUME_SAFE_THREAD_ID_PATTERN.test(safe)) return `\`${safe}\``;
1075
+ return escapeCodexChatText(safe);
1076
+ }
1077
+ function formatCodexTextForDisplay(value) {
1078
+ let safe = "";
1079
+ for (const character of value) {
1080
+ const codePoint = character.codePointAt(0);
1081
+ safe += codePoint != null && isUnsafeDisplayCodePoint(codePoint) ? "?" : character;
1082
+ }
1083
+ safe = safe.trim();
1084
+ return safe || "<unknown>";
1085
+ }
1086
+ function escapeCodexChatText(value) {
1087
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("@", "@").replaceAll("`", "`").replaceAll("[", "[").replaceAll("]", "]").replaceAll("(", "(").replaceAll(")", ")").replaceAll("*", "∗").replaceAll("_", "_").replaceAll("~", "~").replaceAll("|", "|");
1088
+ }
1089
+ function readCodexDiagnosticsCooldownMs(threadId, now) {
1090
+ const lastSentAt = lastCodexDiagnosticsUploadByThread.get(threadId);
1091
+ if (!lastSentAt) return 0;
1092
+ const remainingMs = Math.max(0, CODEX_DIAGNOSTICS_COOLDOWN_MS - (now - lastSentAt));
1093
+ if (remainingMs === 0) lastCodexDiagnosticsUploadByThread.delete(threadId);
1094
+ return remainingMs;
1095
+ }
1096
+ function readCodexDiagnosticsTargetsCooldownMessage(targets, ctx, now, options = {}) {
1097
+ for (const target of targets) {
1098
+ const cooldownMs = readCodexDiagnosticsCooldownMs(target.threadId, now);
1099
+ if (cooldownMs > 0) {
1100
+ 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.`;
1101
+ return `Codex diagnostics were already sent for thread ${formatCodexThreadIdForDisplay(target.threadId)} recently. Try again in ${Math.ceil(cooldownMs / 1e3)}s.`;
1102
+ }
1103
+ }
1104
+ const scopeCooldownMs = readCodexDiagnosticsScopeCooldownMs(readCodexDiagnosticsCooldownScope(ctx), now);
1105
+ if (scopeCooldownMs > 0) return `Codex diagnostics were already sent for this account or channel recently. Try again in ${Math.ceil(scopeCooldownMs / 1e3)}s.`;
1106
+ }
1107
+ function readCodexDiagnosticsScopeCooldownMs(scope, now) {
1108
+ const lastSentAt = lastCodexDiagnosticsUploadByScope.get(scope);
1109
+ if (!lastSentAt) return 0;
1110
+ const remainingMs = Math.max(0, CODEX_DIAGNOSTICS_COOLDOWN_MS - (now - lastSentAt));
1111
+ if (remainingMs === 0) lastCodexDiagnosticsUploadByScope.delete(scope);
1112
+ return remainingMs;
1113
+ }
1114
+ function recordCodexDiagnosticsUpload(threadId, ctx, now) {
1115
+ pruneCodexDiagnosticsCooldowns(now);
1116
+ recordBoundedCodexDiagnosticsCooldown(lastCodexDiagnosticsUploadByScope, readCodexDiagnosticsCooldownScope(ctx), CODEX_DIAGNOSTICS_COOLDOWN_MAX_SCOPES, now);
1117
+ recordBoundedCodexDiagnosticsCooldown(lastCodexDiagnosticsUploadByThread, threadId, CODEX_DIAGNOSTICS_COOLDOWN_MAX_THREADS, now);
1118
+ }
1119
+ function recordBoundedCodexDiagnosticsCooldown(map, key, maxSize, now) {
1120
+ if (!map.has(key)) while (map.size >= maxSize) {
1121
+ const oldestKey = map.keys().next().value;
1122
+ if (typeof oldestKey !== "string") break;
1123
+ map.delete(oldestKey);
1124
+ }
1125
+ map.set(key, now);
1126
+ }
1127
+ function readCodexDiagnosticsCooldownScope(ctx) {
1128
+ const scope = readCodexDiagnosticsConfirmationScope(ctx);
1129
+ const payload = JSON.stringify({
1130
+ accountId: scope.accountId ?? null,
1131
+ channelId: scope.channelId ?? null,
1132
+ sessionKey: scope.sessionKey ?? null,
1133
+ messageThreadId: scope.messageThreadId ?? null,
1134
+ threadParentId: scope.threadParentId ?? null,
1135
+ senderId: normalizeCodexDiagnosticsScopeField(ctx.senderId) ?? null,
1136
+ channel: normalizeCodexDiagnosticsScopeField(ctx.channel) ?? ""
1137
+ });
1138
+ return crypto.createHash("sha256").update(payload).digest("hex");
1139
+ }
1140
+ function pruneCodexDiagnosticsCooldowns(now) {
1141
+ pruneCodexDiagnosticsCooldownMap(lastCodexDiagnosticsUploadByThread, now);
1142
+ pruneCodexDiagnosticsCooldownMap(lastCodexDiagnosticsUploadByScope, now);
1143
+ }
1144
+ function pruneCodexDiagnosticsCooldownMap(map, now) {
1145
+ for (const [key, lastSentAt] of map) if (now - lastSentAt >= CODEX_DIAGNOSTICS_COOLDOWN_MS) map.delete(key);
1146
+ }
1147
+ function formatCodexErrorForDisplay(error) {
1148
+ return escapeCodexChatText(formatCodexTextForDisplay(error).slice(0, CODEX_DIAGNOSTICS_ERROR_MAX_CHARS)) || "unknown error";
1149
+ }
1150
+ function formatCodexResumeCommandForDisplay(threadId) {
1151
+ const safeThreadId = formatCodexTextForDisplay(threadId);
1152
+ if (!CODEX_RESUME_SAFE_THREAD_ID_PATTERN.test(safeThreadId)) return "run codex resume and paste the thread id shown above";
1153
+ return `\`codex resume ${safeThreadId}\``;
1154
+ }
1155
+ function isUnsafeDisplayCodePoint(codePoint) {
1156
+ 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;
1157
+ }
1158
+ function normalizeCodexDiagnosticsScopeField(value) {
1159
+ const normalized = normalizeOptionalString(value);
1160
+ if (!normalized) return;
1161
+ if (normalized.length <= CODEX_DIAGNOSTICS_SCOPE_FIELD_MAX_CHARS) return normalized;
1162
+ return `sha256:${crypto.createHash("sha256").update(normalized).digest("hex")}`;
1163
+ }
1164
+ async function startThreadAction(deps, ctx, pluginConfig, method, label, args) {
1165
+ if (args.length > 0) return `Usage: /codex ${label === "compaction" ? "compact" : label}`;
1166
+ const target = await resolveControlTarget(ctx);
1167
+ if (!target) return `Cannot start Codex ${label} because this command did not include an Klaw session file.`;
1168
+ const binding = await deps.readCodexAppServerBinding(target.sessionFile, {
1169
+ agentDir: target.agentDir,
1170
+ config: ctx.config
1171
+ });
1172
+ if (!binding?.threadId) return `No Codex thread is attached to this Klaw session yet.`;
1173
+ if (method === CODEX_CONTROL_METHODS.review) await deps.codexControlRequest(pluginConfig, method, {
1174
+ threadId: binding.threadId,
1175
+ target: { type: "uncommittedChanges" }
1176
+ }, {
1177
+ agentDir: target.agentDir,
1178
+ authProfileId: binding.authProfileId,
1179
+ config: ctx.config
1180
+ });
1181
+ else await deps.codexControlRequest(pluginConfig, method, { threadId: binding.threadId }, {
1182
+ agentDir: target.agentDir,
1183
+ authProfileId: binding.authProfileId,
1184
+ config: ctx.config
1185
+ });
1186
+ return `Started Codex ${label} for thread ${formatCodexDisplayText(binding.threadId)}.`;
1187
+ }
1188
+ function splitArgs(value) {
1189
+ const input = value ?? "";
1190
+ const args = [];
1191
+ let current = "";
1192
+ let quote;
1193
+ let escaping = false;
1194
+ let tokenStarted = false;
1195
+ for (const char of input) {
1196
+ if (escaping) {
1197
+ current += char;
1198
+ escaping = false;
1199
+ tokenStarted = true;
1200
+ continue;
1201
+ }
1202
+ if (char === "\\" && quote !== "'") {
1203
+ escaping = true;
1204
+ tokenStarted = true;
1205
+ continue;
1206
+ }
1207
+ if (quote) {
1208
+ if (char === quote) quote = void 0;
1209
+ else current += char;
1210
+ tokenStarted = true;
1211
+ continue;
1212
+ }
1213
+ if (char === "\"" || char === "'") {
1214
+ quote = char;
1215
+ tokenStarted = true;
1216
+ continue;
1217
+ }
1218
+ if (/\s/.test(char)) {
1219
+ if (tokenStarted) {
1220
+ args.push(current);
1221
+ current = "";
1222
+ tokenStarted = false;
1223
+ }
1224
+ continue;
1225
+ }
1226
+ current += char;
1227
+ tokenStarted = true;
1228
+ }
1229
+ if (escaping) current += "\\";
1230
+ if (tokenStarted) args.push(current);
1231
+ return args;
1232
+ }
1233
+ function parseBindArgs(args) {
1234
+ const parsed = {};
1235
+ for (let index = 0; index < args.length; index += 1) {
1236
+ const arg = args[index];
1237
+ if (arg === "--help" || arg === "-h") {
1238
+ parsed.help = true;
1239
+ continue;
1240
+ }
1241
+ if (arg === "--cwd") {
1242
+ const value = readRequiredOptionValue(args, index);
1243
+ if (!value || parsed.cwd !== void 0) {
1244
+ parsed.help = true;
1245
+ continue;
1246
+ }
1247
+ parsed.cwd = value;
1248
+ index += 1;
1249
+ continue;
1250
+ }
1251
+ if (arg === "--model") {
1252
+ const value = readRequiredOptionValue(args, index);
1253
+ if (!value || parsed.model !== void 0) {
1254
+ parsed.help = true;
1255
+ continue;
1256
+ }
1257
+ parsed.model = value;
1258
+ index += 1;
1259
+ continue;
1260
+ }
1261
+ if (arg === "--provider" || arg === "--model-provider") {
1262
+ const value = readRequiredOptionValue(args, index);
1263
+ if (!value || parsed.provider !== void 0) {
1264
+ parsed.help = true;
1265
+ continue;
1266
+ }
1267
+ parsed.provider = value;
1268
+ index += 1;
1269
+ continue;
1270
+ }
1271
+ if (!arg.startsWith("-") && !parsed.threadId) {
1272
+ parsed.threadId = arg;
1273
+ continue;
1274
+ }
1275
+ parsed.help = true;
1276
+ }
1277
+ parsed.threadId = normalizeOptionalString(parsed.threadId);
1278
+ parsed.cwd = normalizeOptionalString(parsed.cwd);
1279
+ parsed.model = normalizeOptionalString(parsed.model);
1280
+ parsed.provider = normalizeOptionalString(parsed.provider);
1281
+ return parsed;
1282
+ }
1283
+ function parseCodexCliSessionsArgs(args) {
1284
+ const parsed = { filter: "" };
1285
+ const filter = [];
1286
+ for (let index = 0; index < args.length; index += 1) {
1287
+ const arg = args[index];
1288
+ if (arg === "--help" || arg === "-h") {
1289
+ parsed.help = true;
1290
+ continue;
1291
+ }
1292
+ if (arg === "--host" || arg === "--node") {
1293
+ const value = readRequiredOptionValue(args, index);
1294
+ if (!value || parsed.host !== void 0) {
1295
+ parsed.help = true;
1296
+ continue;
1297
+ }
1298
+ parsed.host = value;
1299
+ index += 1;
1300
+ continue;
1301
+ }
1302
+ if (arg === "--limit") {
1303
+ const value = readRequiredOptionValue(args, index);
1304
+ const parsedLimit = value ? Number.parseInt(value, 10) : NaN;
1305
+ if (!Number.isFinite(parsedLimit) || parsedLimit <= 0) {
1306
+ parsed.help = true;
1307
+ continue;
1308
+ }
1309
+ parsed.limit = parsedLimit;
1310
+ index += 1;
1311
+ continue;
1312
+ }
1313
+ if (arg.startsWith("-")) {
1314
+ parsed.help = true;
1315
+ continue;
1316
+ }
1317
+ filter.push(arg);
1318
+ }
1319
+ parsed.host = normalizeOptionalString(parsed.host);
1320
+ parsed.filter = filter.join(" ").trim();
1321
+ return parsed;
1322
+ }
1323
+ function parseResumeArgs(args) {
1324
+ const parsed = {};
1325
+ for (let index = 0; index < args.length; index += 1) {
1326
+ const arg = args[index];
1327
+ if (arg === "--help" || arg === "-h") {
1328
+ parsed.help = true;
1329
+ continue;
1330
+ }
1331
+ if (arg === "--host" || arg === "--node") {
1332
+ const value = readRequiredOptionValue(args, index);
1333
+ if (!value || parsed.host !== void 0) {
1334
+ parsed.help = true;
1335
+ continue;
1336
+ }
1337
+ parsed.host = value;
1338
+ index += 1;
1339
+ continue;
1340
+ }
1341
+ if (arg === "--bind") {
1342
+ if (readRequiredOptionValue(args, index) !== "here" || parsed.bindHere !== void 0) {
1343
+ parsed.help = true;
1344
+ continue;
1345
+ }
1346
+ parsed.bindHere = true;
1347
+ index += 1;
1348
+ continue;
1349
+ }
1350
+ if (!arg.startsWith("-") && !parsed.threadId) {
1351
+ parsed.threadId = arg;
1352
+ continue;
1353
+ }
1354
+ parsed.help = true;
1355
+ }
1356
+ parsed.threadId = normalizeOptionalString(parsed.threadId);
1357
+ parsed.host = normalizeOptionalString(parsed.host);
1358
+ return parsed;
1359
+ }
1360
+ function parseComputerUseArgs(args) {
1361
+ const parsed = {
1362
+ action: "status",
1363
+ overrides: {},
1364
+ hasOverrides: false
1365
+ };
1366
+ let sawAction = false;
1367
+ for (let index = 0; index < args.length; index += 1) {
1368
+ const arg = args[index];
1369
+ if (arg === "--help" || arg === "-h") {
1370
+ parsed.help = true;
1371
+ continue;
1372
+ }
1373
+ if (arg === "status" || arg === "install") {
1374
+ if (sawAction) {
1375
+ parsed.help = true;
1376
+ continue;
1377
+ }
1378
+ sawAction = true;
1379
+ parsed.action = arg;
1380
+ continue;
1381
+ }
1382
+ if (arg === "--source" || arg === "--marketplace-source") {
1383
+ const value = readRequiredOptionValue(args, index);
1384
+ if (!value || parsed.overrides.marketplaceSource !== void 0) {
1385
+ parsed.help = true;
1386
+ continue;
1387
+ }
1388
+ parsed.overrides.marketplaceSource = value;
1389
+ index += 1;
1390
+ continue;
1391
+ }
1392
+ if (arg === "--marketplace-path" || arg === "--path") {
1393
+ const value = readRequiredOptionValue(args, index);
1394
+ if (!value || parsed.overrides.marketplacePath !== void 0) {
1395
+ parsed.help = true;
1396
+ continue;
1397
+ }
1398
+ parsed.overrides.marketplacePath = value;
1399
+ index += 1;
1400
+ continue;
1401
+ }
1402
+ if (arg === "--marketplace") {
1403
+ const value = readRequiredOptionValue(args, index);
1404
+ if (!value || parsed.overrides.marketplaceName !== void 0) {
1405
+ parsed.help = true;
1406
+ continue;
1407
+ }
1408
+ parsed.overrides.marketplaceName = value;
1409
+ index += 1;
1410
+ continue;
1411
+ }
1412
+ if (arg === "--plugin") {
1413
+ const value = readRequiredOptionValue(args, index);
1414
+ if (!value || parsed.overrides.pluginName !== void 0) {
1415
+ parsed.help = true;
1416
+ continue;
1417
+ }
1418
+ parsed.overrides.pluginName = value;
1419
+ index += 1;
1420
+ continue;
1421
+ }
1422
+ if (arg === "--server" || arg === "--mcp-server") {
1423
+ const value = readRequiredOptionValue(args, index);
1424
+ if (!value || parsed.overrides.mcpServerName !== void 0) {
1425
+ parsed.help = true;
1426
+ continue;
1427
+ }
1428
+ parsed.overrides.mcpServerName = value;
1429
+ index += 1;
1430
+ continue;
1431
+ }
1432
+ parsed.help = true;
1433
+ }
1434
+ parsed.overrides = normalizeComputerUseStringOverrides(parsed.overrides);
1435
+ parsed.hasOverrides = Object.values(parsed.overrides).some(Boolean);
1436
+ return parsed;
1437
+ }
1438
+ function readRequiredOptionValue(args, index) {
1439
+ const value = args[index + 1];
1440
+ const normalized = value?.trim();
1441
+ if (!normalized || normalized.startsWith("-")) return;
1442
+ return value;
1443
+ }
1444
+ function normalizeComputerUseStringOverrides(overrides) {
1445
+ const normalized = {};
1446
+ const marketplaceSource = normalizeOptionalString(overrides.marketplaceSource);
1447
+ if (marketplaceSource) normalized.marketplaceSource = marketplaceSource;
1448
+ const marketplacePath = normalizeOptionalString(overrides.marketplacePath);
1449
+ if (marketplacePath) normalized.marketplacePath = marketplacePath;
1450
+ const marketplaceName = normalizeOptionalString(overrides.marketplaceName);
1451
+ if (marketplaceName) normalized.marketplaceName = marketplaceName;
1452
+ const pluginName = normalizeOptionalString(overrides.pluginName);
1453
+ if (pluginName) normalized.pluginName = pluginName;
1454
+ const mcpServerName = normalizeOptionalString(overrides.mcpServerName);
1455
+ if (mcpServerName) normalized.mcpServerName = mcpServerName;
1456
+ return normalized;
1457
+ }
1458
+ function normalizeOptionalString(value) {
1459
+ return value?.trim() || void 0;
1460
+ }
1461
+ //#endregion
1462
+ export { handleCodexSubcommand };