@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,329 @@
1
+ import { c as resolveCodexAppServerRuntimeOptions } from "./config-CLMSw0p2.js";
2
+ import { t as isJsonObject } from "./protocol-C9UWI98H.js";
3
+ import { i as readCodexAppServerBinding, t as clearCodexAppServerBinding } from "./session-binding-e2GFp9VH.js";
4
+ import { t as defaultCodexAppServerClientFactory } from "./client-factory-Bu9OClHJ.js";
5
+ import { compactContextEngineWithSafetyTimeout, embeddedAgentLog, formatErrorMessage, isActiveHarnessContextEngine, resolveCompactionTimeoutMs, resolveContextEngineOwnerPluginId, runHarnessContextEngineMaintenance } from "autobot/plugin-sdk/agent-harness-runtime";
6
+ //#region extensions/codex/src/app-server/compact.ts
7
+ const DEFAULT_CODEX_COMPACTION_WAIT_TIMEOUT_MS = 300 * 1e3;
8
+ const warnedIgnoredCompactionOverrides = /* @__PURE__ */ new Set();
9
+ async function maybeCompactCodexAppServerSession(params, options = {}) {
10
+ const activeContextEngine = isActiveHarnessContextEngine(params.contextEngine) ? params.contextEngine : void 0;
11
+ if (activeContextEngine?.info.ownsCompaction) return await compactOwningContextEngine(params, activeContextEngine);
12
+ warnIfIgnoringAutoBotCompactionOverrides(params);
13
+ const nativeResult = await compactCodexNativeThread(params, options);
14
+ if (activeContextEngine && nativeResult?.ok && nativeResult.compacted) try {
15
+ await runHarnessContextEngineMaintenance({
16
+ contextEngine: activeContextEngine,
17
+ sessionId: params.sessionId,
18
+ sessionKey: params.sessionKey,
19
+ sessionFile: params.sessionFile,
20
+ reason: "compaction",
21
+ runtimeContext: params.contextEngineRuntimeContext,
22
+ config: params.config
23
+ });
24
+ } catch (error) {
25
+ embeddedAgentLog.warn("context engine compaction maintenance failed after Codex compaction", {
26
+ sessionId: params.sessionId,
27
+ engineId: activeContextEngine.info.id,
28
+ error: formatErrorMessage(error)
29
+ });
30
+ }
31
+ return nativeResult;
32
+ }
33
+ async function compactOwningContextEngine(params, contextEngine) {
34
+ embeddedAgentLog.info("starting context-engine-owned Codex app-server compaction", {
35
+ sessionId: params.sessionId,
36
+ sessionKey: params.sessionKey,
37
+ engineId: contextEngine.info.id,
38
+ tokenBudget: params.contextTokenBudget,
39
+ currentTokenCount: params.currentTokenCount,
40
+ trigger: params.trigger,
41
+ compactionTarget: params.trigger === "manual" ? "threshold" : "budget",
42
+ force: params.trigger === "manual"
43
+ });
44
+ let result;
45
+ try {
46
+ result = await compactContextEngineWithSafetyTimeout(contextEngine, {
47
+ sessionId: params.sessionId,
48
+ sessionKey: params.sessionKey,
49
+ sessionFile: params.sessionFile,
50
+ tokenBudget: params.contextTokenBudget,
51
+ currentTokenCount: params.currentTokenCount,
52
+ compactionTarget: params.trigger === "manual" ? "threshold" : "budget",
53
+ customInstructions: params.customInstructions,
54
+ force: params.trigger === "manual",
55
+ runtimeContext: params.contextEngineRuntimeContext
56
+ }, resolveCompactionTimeoutMs(params.config), params.abortSignal);
57
+ } catch (error) {
58
+ embeddedAgentLog.warn("context-engine-owned Codex app-server compaction failed", {
59
+ sessionId: params.sessionId,
60
+ sessionKey: params.sessionKey,
61
+ engineId: contextEngine.info.id,
62
+ error: formatErrorMessage(error)
63
+ });
64
+ return {
65
+ ok: false,
66
+ compacted: false,
67
+ reason: `context engine compaction failed: ${formatErrorMessage(error)}`
68
+ };
69
+ }
70
+ if (result.ok && result.compacted) {
71
+ const compactedSessionId = result.result?.sessionId ?? params.sessionId;
72
+ const compactedSessionFile = result.result?.sessionFile ?? params.sessionFile;
73
+ try {
74
+ await runHarnessContextEngineMaintenance({
75
+ contextEngine,
76
+ sessionId: compactedSessionId,
77
+ sessionKey: params.sessionKey,
78
+ sessionFile: compactedSessionFile,
79
+ reason: "compaction",
80
+ runtimeContext: params.contextEngineRuntimeContext,
81
+ config: params.config
82
+ });
83
+ } catch (error) {
84
+ embeddedAgentLog.warn("context engine compaction maintenance failed", {
85
+ sessionId: compactedSessionId,
86
+ engineId: contextEngine.info.id,
87
+ error: formatErrorMessage(error)
88
+ });
89
+ }
90
+ await clearCodexAppServerBinding(params.sessionFile);
91
+ if (compactedSessionFile !== params.sessionFile) await clearCodexAppServerBinding(compactedSessionFile);
92
+ }
93
+ embeddedAgentLog.info("completed context-engine-owned Codex app-server compaction", {
94
+ sessionId: params.sessionId,
95
+ sessionKey: params.sessionKey,
96
+ engineId: contextEngine.info.id,
97
+ ok: result.ok,
98
+ compacted: result.compacted,
99
+ reason: result.reason,
100
+ codexThreadBindingInvalidated: result.ok && result.compacted
101
+ });
102
+ return {
103
+ ok: result.ok,
104
+ compacted: result.compacted,
105
+ reason: result.reason,
106
+ result: result.result ? {
107
+ ...result.result,
108
+ summary: result.result.summary ?? "",
109
+ firstKeptEntryId: result.result.firstKeptEntryId ?? "",
110
+ details: mergeContextEngineCompactionDetails(result.result.details, { codexThreadBindingInvalidated: result.ok && result.compacted })
111
+ } : result.ok && result.compacted ? {
112
+ summary: "",
113
+ firstKeptEntryId: "",
114
+ tokensBefore: params.currentTokenCount ?? 0,
115
+ details: { codexThreadBindingInvalidated: true }
116
+ } : void 0
117
+ };
118
+ }
119
+ function mergeContextEngineCompactionDetails(details, extra) {
120
+ if (details && typeof details === "object" && !Array.isArray(details)) return {
121
+ ...details,
122
+ ...extra
123
+ };
124
+ return extra;
125
+ }
126
+ function warnIfIgnoringAutoBotCompactionOverrides(params) {
127
+ const ignoredConfig = readIgnoredCompactionOverridePaths(params, isActiveHarnessContextEngine(params.contextEngine) ? params.contextEngine : void 0);
128
+ if (ignoredConfig.length === 0) return;
129
+ const warningKey = ignoredConfig.join("\0");
130
+ if (warnedIgnoredCompactionOverrides.has(warningKey)) return;
131
+ warnedIgnoredCompactionOverrides.add(warningKey);
132
+ embeddedAgentLog.warn("ignoring AutoBot compaction overrides for Codex app-server compaction; Codex uses native server-side compaction", {
133
+ sessionId: params.sessionId,
134
+ sessionKey: params.sessionKey,
135
+ ignoredConfig
136
+ });
137
+ }
138
+ function readIgnoredCompactionOverridePaths(params, activeContextEngine) {
139
+ const ignored = /* @__PURE__ */ new Set();
140
+ const configuredContextEngine = readStringPath(params.config, [
141
+ "plugins",
142
+ "slots",
143
+ "contextEngine"
144
+ ]);
145
+ const runtimeContextEnginePlugin = typeof params.contextEngineRuntimeContext?.contextEnginePluginId === "string" ? params.contextEngineRuntimeContext.contextEnginePluginId.trim() : "";
146
+ const activeContextEnginePlugin = resolveContextEngineOwnerPluginId(activeContextEngine);
147
+ for (const entry of readCompactionOverrideEntries(params)) {
148
+ const localProvider = typeof entry.record.provider === "string" ? entry.record.provider.trim() : "";
149
+ const inheritedProvider = !localProvider && typeof entry.inheritedRecord?.provider === "string" ? entry.inheritedRecord.provider.trim() : "";
150
+ const provider = localProvider || inheritedProvider;
151
+ const providerPath = localProvider ? `${entry.path}.compaction.provider` : inheritedProvider && entry.inheritedPath ? `${entry.inheritedPath}.compaction.provider` : void 0;
152
+ if (provider.toLowerCase() === "lossless-claw" && (activeContextEnginePlugin === "lossless-claw" || runtimeContextEnginePlugin.toLowerCase() === "lossless-claw" || configuredContextEngine?.toLowerCase() === "lossless-claw")) continue;
153
+ if (typeof entry.record.model === "string" && entry.record.model.trim()) ignored.add(`${entry.path}.compaction.model`);
154
+ if (providerPath) ignored.add(providerPath);
155
+ }
156
+ return [...ignored];
157
+ }
158
+ function readCompactionOverrideEntries(params) {
159
+ const entries = [];
160
+ const defaultCompaction = readRecord(readRecord(params.config?.agents)?.defaults)?.compaction;
161
+ const defaultRecord = readRecord(defaultCompaction);
162
+ if (defaultRecord) entries.push({
163
+ path: "agents.defaults",
164
+ record: defaultRecord
165
+ });
166
+ const agentId = readAgentIdFromSessionKey(params.sessionKey ?? params.sandboxSessionKey);
167
+ if (!agentId) return entries;
168
+ const agentCompaction = readRecord((Array.isArray(params.config?.agents?.list) ? params.config.agents.list : []).find((agent) => {
169
+ return (typeof agent?.id === "string" ? agent.id.trim().toLowerCase() : "") === agentId;
170
+ }))?.compaction;
171
+ const agentRecord = readRecord(agentCompaction);
172
+ if (agentRecord) entries.push({
173
+ path: `agents.list.${agentId}`,
174
+ record: agentRecord,
175
+ inheritedRecord: defaultRecord,
176
+ inheritedPath: "agents.defaults"
177
+ });
178
+ return entries;
179
+ }
180
+ function readAgentIdFromSessionKey(sessionKey) {
181
+ const parts = sessionKey?.trim().toLowerCase().split(":").filter(Boolean) ?? [];
182
+ if (parts.length < 3 || parts[0] !== "agent") return;
183
+ return parts[1]?.trim() || void 0;
184
+ }
185
+ function readRecord(value) {
186
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
187
+ }
188
+ function readStringPath(value, path) {
189
+ let current = value;
190
+ for (const segment of path) current = readRecord(current)?.[segment];
191
+ return typeof current === "string" && current.trim() ? current.trim() : void 0;
192
+ }
193
+ async function compactCodexNativeThread(params, options = {}) {
194
+ const appServer = resolveCodexAppServerRuntimeOptions({ pluginConfig: options.pluginConfig });
195
+ const binding = await readCodexAppServerBinding(params.sessionFile, { config: params.config });
196
+ if (!binding?.threadId) return {
197
+ ok: false,
198
+ compacted: false,
199
+ reason: "no codex app-server thread binding"
200
+ };
201
+ const requestedAuthProfileId = params.authProfileId?.trim() || void 0;
202
+ if (requestedAuthProfileId && binding.authProfileId && binding.authProfileId !== requestedAuthProfileId) return {
203
+ ok: false,
204
+ compacted: false,
205
+ reason: "auth profile mismatch for session binding"
206
+ };
207
+ const client = await (options.clientFactory ?? defaultCodexAppServerClientFactory)(appServer.start, requestedAuthProfileId ?? binding.authProfileId, params.agentDir, params.config);
208
+ const waiter = createCodexNativeCompactionWaiter(client, binding.threadId);
209
+ let completion;
210
+ try {
211
+ await client.request("thread/compact/start", { threadId: binding.threadId });
212
+ embeddedAgentLog.info("started codex app-server compaction", {
213
+ sessionId: params.sessionId,
214
+ threadId: binding.threadId
215
+ });
216
+ waiter.startTimeout();
217
+ completion = await waiter.promise;
218
+ } catch (error) {
219
+ waiter.cancel();
220
+ return {
221
+ ok: false,
222
+ compacted: false,
223
+ reason: formatCompactionError(error)
224
+ };
225
+ }
226
+ embeddedAgentLog.info("completed codex app-server compaction", {
227
+ sessionId: params.sessionId,
228
+ threadId: binding.threadId,
229
+ signal: completion.signal,
230
+ turnId: completion.turnId,
231
+ itemId: completion.itemId
232
+ });
233
+ return {
234
+ ok: true,
235
+ compacted: true,
236
+ result: {
237
+ summary: "",
238
+ firstKeptEntryId: "",
239
+ tokensBefore: params.currentTokenCount ?? 0,
240
+ details: {
241
+ backend: "codex-app-server",
242
+ threadId: binding.threadId,
243
+ signal: completion.signal,
244
+ turnId: completion.turnId,
245
+ itemId: completion.itemId
246
+ }
247
+ }
248
+ };
249
+ }
250
+ function createCodexNativeCompactionWaiter(client, threadId) {
251
+ let settled = false;
252
+ let removeHandler = () => {};
253
+ let timeout;
254
+ let failWaiter = () => {};
255
+ return {
256
+ promise: new Promise((resolve, reject) => {
257
+ const cleanup = () => {
258
+ removeHandler();
259
+ if (timeout) clearTimeout(timeout);
260
+ };
261
+ const complete = (completion) => {
262
+ if (settled) return;
263
+ settled = true;
264
+ cleanup();
265
+ resolve(completion);
266
+ };
267
+ const fail = (error) => {
268
+ if (settled) return;
269
+ settled = true;
270
+ cleanup();
271
+ reject(error);
272
+ };
273
+ failWaiter = fail;
274
+ const handler = (notification) => {
275
+ const completion = readNativeCompactionCompletion(notification, threadId);
276
+ if (completion) complete(completion);
277
+ };
278
+ removeHandler = client.addNotificationHandler(handler);
279
+ }),
280
+ startTimeout() {
281
+ if (settled || timeout) return;
282
+ timeout = setTimeout(() => {
283
+ failWaiter(/* @__PURE__ */ new Error(`timed out waiting for codex app-server compaction for ${threadId}`));
284
+ }, resolveCompactionWaitTimeoutMs());
285
+ timeout.unref?.();
286
+ },
287
+ cancel() {
288
+ if (settled) return;
289
+ settled = true;
290
+ removeHandler();
291
+ if (timeout) clearTimeout(timeout);
292
+ }
293
+ };
294
+ }
295
+ function readNativeCompactionCompletion(notification, threadId) {
296
+ const params = notification.params;
297
+ if (!isJsonObject(params) || readString(params, "threadId", "thread_id") !== threadId) return;
298
+ if (notification.method === "thread/compacted") return {
299
+ signal: "thread/compacted",
300
+ turnId: readString(params, "turnId", "turn_id")
301
+ };
302
+ if (notification.method !== "item/completed") return;
303
+ const item = isJsonObject(params.item) ? params.item : void 0;
304
+ if (readString(item, "type") !== "contextCompaction") return;
305
+ return {
306
+ signal: "item/completed",
307
+ turnId: readString(params, "turnId", "turn_id"),
308
+ itemId: readString(item, "id") ?? readString(params, "itemId", "item_id", "id")
309
+ };
310
+ }
311
+ function resolveCompactionWaitTimeoutMs() {
312
+ const raw = process.env.AUTOBOT_CODEX_COMPACTION_WAIT_TIMEOUT_MS?.trim();
313
+ const parsed = raw ? Number.parseInt(raw, 10) : NaN;
314
+ if (Number.isFinite(parsed) && parsed > 0) return parsed;
315
+ return DEFAULT_CODEX_COMPACTION_WAIT_TIMEOUT_MS;
316
+ }
317
+ function readString(params, ...keys) {
318
+ if (!params) return;
319
+ for (const key of keys) {
320
+ const value = params[key];
321
+ if (typeof value === "string") return value;
322
+ }
323
+ }
324
+ function formatCompactionError(error) {
325
+ if (error instanceof Error) return error.message;
326
+ return String(error);
327
+ }
328
+ //#endregion
329
+ export { maybeCompactCodexAppServerSession };
@@ -0,0 +1,367 @@
1
+ import { c as resolveCodexAppServerRuntimeOptions, l as resolveCodexComputerUseConfig } from "./config-CLMSw0p2.js";
2
+ import { i as describeControlFailure, t as requestCodexAppServerJson } from "./request-DbSPeTcV.js";
3
+ import { existsSync } from "node:fs";
4
+ //#region extensions/codex/src/app-server/computer-use.ts
5
+ var CodexComputerUseSetupError = class extends Error {
6
+ constructor(status) {
7
+ super(status.message);
8
+ this.name = "CodexComputerUseSetupError";
9
+ this.status = status;
10
+ }
11
+ };
12
+ const CURATED_MARKETPLACE_POLL_INTERVAL_MS = 2e3;
13
+ const COMPUTER_USE_MARKETPLACE_NAME_PRIORITY = [
14
+ "openai-bundled",
15
+ "openai-curated",
16
+ "local"
17
+ ];
18
+ const DEFAULT_CODEX_BUNDLED_MARKETPLACE_PATH = "/Applications/Codex.app/Contents/Resources/plugins/openai-bundled";
19
+ async function readCodexComputerUseStatus(params = {}) {
20
+ const config = resolveComputerUseConfig(params);
21
+ if (!config.enabled) return disabledStatus(config);
22
+ try {
23
+ return await inspectCodexComputerUse({
24
+ ...params,
25
+ config,
26
+ installPlugin: false
27
+ });
28
+ } catch (error) {
29
+ return unavailableStatus(config, "check_failed", `Computer Use check failed: ${describeControlFailure(error)}`);
30
+ }
31
+ }
32
+ async function ensureCodexComputerUse(params = {}) {
33
+ const config = resolveComputerUseConfig(params);
34
+ if (!config.enabled) return disabledStatus(config);
35
+ const status = await inspectCodexComputerUse({
36
+ ...params,
37
+ config,
38
+ installPlugin: false
39
+ });
40
+ if (status.ready) return status;
41
+ if (config.autoInstall) {
42
+ const blockedAutoInstallStatus = blockUnsafeAutoInstallStatus(config);
43
+ if (blockedAutoInstallStatus) throw new CodexComputerUseSetupError(blockedAutoInstallStatus);
44
+ const installedStatus = await inspectCodexComputerUse({
45
+ ...params,
46
+ config,
47
+ installPlugin: true
48
+ });
49
+ if (!installedStatus.ready) throw new CodexComputerUseSetupError(installedStatus);
50
+ return installedStatus;
51
+ }
52
+ if (!status.ready) throw new CodexComputerUseSetupError(status);
53
+ return status;
54
+ }
55
+ async function installCodexComputerUse(params = {}) {
56
+ const config = resolveComputerUseConfig({
57
+ ...params,
58
+ forceEnable: true,
59
+ overrides: {
60
+ ...params.overrides,
61
+ enabled: true,
62
+ autoInstall: true
63
+ }
64
+ });
65
+ const status = await inspectCodexComputerUse({
66
+ ...params,
67
+ config,
68
+ installPlugin: true
69
+ });
70
+ if (!status.ready) throw new CodexComputerUseSetupError(status);
71
+ return status;
72
+ }
73
+ async function inspectCodexComputerUse(params) {
74
+ const request = createComputerUseRequest(params);
75
+ if (params.installPlugin) await request("experimentalFeature/enablement/set", { enablement: { plugins: true } });
76
+ const marketplace = await resolveMarketplaceRef({
77
+ request,
78
+ config: params.config,
79
+ allowAdd: params.installPlugin,
80
+ signal: params.signal,
81
+ defaultBundledMarketplacePath: params.defaultBundledMarketplacePath
82
+ });
83
+ if (!marketplace.marketplace) return unavailableStatus(params.config, "marketplace_missing", marketplace.message ?? `No Codex marketplace containing ${params.config.pluginName} is registered. Configure computerUse.marketplaceSource or computerUse.marketplacePath, then run /codex computer-use install.`);
84
+ const pluginInspection = await ensureComputerUsePlugin({
85
+ request,
86
+ config: params.config,
87
+ marketplace: marketplace.marketplace,
88
+ installPlugin: params.installPlugin
89
+ });
90
+ if (!pluginInspection.ok) return pluginInspection.status;
91
+ return await readComputerUseTools({
92
+ request,
93
+ config: params.config,
94
+ plugin: pluginInspection.plugin,
95
+ installPlugin: params.installPlugin
96
+ });
97
+ }
98
+ async function ensureComputerUsePlugin(params) {
99
+ let plugin = await readComputerUsePlugin(params.request, params.marketplace, params.config.pluginName);
100
+ if (!plugin.summary.installed || !plugin.summary.enabled) {
101
+ if (!params.installPlugin) return {
102
+ ok: false,
103
+ status: statusFromPlugin({
104
+ config: params.config,
105
+ plugin,
106
+ tools: [],
107
+ reason: pluginSetupReason(plugin, params.marketplace),
108
+ message: pluginSetupMessage(params.config, plugin, params.marketplace)
109
+ })
110
+ };
111
+ if (params.marketplace.kind === "remote") return {
112
+ ok: false,
113
+ status: statusFromPlugin({
114
+ config: params.config,
115
+ plugin,
116
+ tools: [],
117
+ reason: "remote_install_unsupported",
118
+ message: remoteInstallUnsupportedMessage(plugin, params.marketplace)
119
+ })
120
+ };
121
+ await params.request("plugin/install", pluginRequestParams(params.marketplace, params.config.pluginName));
122
+ await reloadMcpServers(params.request);
123
+ plugin = await readComputerUsePlugin(params.request, params.marketplace, params.config.pluginName);
124
+ }
125
+ if (!plugin.summary.installed || !plugin.summary.enabled) return {
126
+ ok: false,
127
+ status: statusFromPlugin({
128
+ config: params.config,
129
+ plugin,
130
+ tools: [],
131
+ reason: pluginSetupReason(plugin, params.marketplace),
132
+ message: pluginSetupMessage(params.config, plugin, params.marketplace)
133
+ })
134
+ };
135
+ return {
136
+ ok: true,
137
+ plugin
138
+ };
139
+ }
140
+ async function readComputerUseTools(params) {
141
+ let server = await readMcpServerStatus(params.request, params.config.mcpServerName);
142
+ if (!server && params.installPlugin) {
143
+ await reloadMcpServers(params.request);
144
+ server = await readMcpServerStatus(params.request, params.config.mcpServerName);
145
+ }
146
+ if (!server) return statusFromPlugin({
147
+ config: params.config,
148
+ plugin: params.plugin,
149
+ tools: [],
150
+ reason: "mcp_missing",
151
+ message: `Computer Use is installed, but the ${params.config.mcpServerName} MCP server is not available.`
152
+ });
153
+ return statusFromPlugin({
154
+ config: params.config,
155
+ plugin: params.plugin,
156
+ tools: Object.keys(server.tools).toSorted(),
157
+ reason: "ready",
158
+ message: "Computer Use is ready."
159
+ });
160
+ }
161
+ async function resolveMarketplaceRef(params) {
162
+ let preferredMarketplaceName = params.config.marketplaceName;
163
+ if (params.config.marketplaceSource && params.allowAdd) {
164
+ const added = await params.request("marketplace/add", { source: params.config.marketplaceSource });
165
+ preferredMarketplaceName ??= added.marketplaceName;
166
+ }
167
+ if (params.config.marketplacePath) return { marketplace: preferredMarketplaceName ? {
168
+ kind: "local",
169
+ name: preferredMarketplaceName,
170
+ path: params.config.marketplacePath
171
+ } : {
172
+ kind: "local",
173
+ path: params.config.marketplacePath
174
+ } };
175
+ let candidates = await listComputerUseMarketplaceCandidates(params.request, params.config);
176
+ if (candidates.length === 0 && shouldAddBundledComputerUseMarketplace(params)) {
177
+ const bundledMarketplacePath = params.defaultBundledMarketplacePath ?? DEFAULT_CODEX_BUNDLED_MARKETPLACE_PATH;
178
+ const added = await params.request("marketplace/add", { source: bundledMarketplacePath });
179
+ preferredMarketplaceName ??= added.marketplaceName;
180
+ candidates = await listComputerUseMarketplaceCandidates(params.request, params.config);
181
+ }
182
+ const waitUntil = marketplaceDiscoveryWaitUntil(params);
183
+ while (candidates.length === 0) {
184
+ if (Date.now() >= waitUntil) break;
185
+ await delay(Math.min(CURATED_MARKETPLACE_POLL_INTERVAL_MS, waitUntil - Date.now()), params.signal);
186
+ candidates = await listComputerUseMarketplaceCandidates(params.request, params.config);
187
+ }
188
+ if (preferredMarketplaceName) {
189
+ const preferred = candidates.find((candidate) => candidate.name === preferredMarketplaceName);
190
+ if (preferred) return { marketplace: preferred };
191
+ return { message: `Configured Codex marketplace ${preferredMarketplaceName} was not found or does not contain ${params.config.pluginName}. Run /codex computer-use install with a source or path to install from a new marketplace.` };
192
+ }
193
+ if (candidates.length > 1) {
194
+ const preferred = chooseKnownComputerUseMarketplace(candidates);
195
+ if (preferred) return { marketplace: preferred };
196
+ return { message: `Multiple Codex marketplaces contain ${params.config.pluginName}. Configure computerUse.marketplaceName or computerUse.marketplacePath to choose one.` };
197
+ }
198
+ if (params.config.marketplaceSource && !params.allowAdd && candidates.length === 0) return { message: "Computer Use marketplace source is configured but has not been registered. Run /codex computer-use install to register it." };
199
+ const marketplace = candidates[0];
200
+ return marketplace ? { marketplace } : {};
201
+ }
202
+ async function listComputerUseMarketplaceCandidates(request, config) {
203
+ return findComputerUseMarketplaces(await request("plugin/list", { cwds: [] }), config.pluginName);
204
+ }
205
+ function blockUnsafeAutoInstallStatus(config) {
206
+ if (!config.marketplaceSource) return;
207
+ return unavailableStatus(config, "auto_install_blocked", "Computer Use auto-install only uses marketplaces Codex app-server has already discovered. Run /codex computer-use install to install from a configured marketplace source.");
208
+ }
209
+ function shouldAddBundledComputerUseMarketplace(params) {
210
+ const bundledMarketplacePath = params.defaultBundledMarketplacePath ?? DEFAULT_CODEX_BUNDLED_MARKETPLACE_PATH;
211
+ return params.allowAdd && !params.config.marketplaceSource && !params.config.marketplacePath && !params.config.marketplaceName && existsSync(bundledMarketplacePath);
212
+ }
213
+ function findComputerUseMarketplaces(listed, pluginName) {
214
+ return listed.marketplaces.filter((marketplace) => marketplace.plugins.some((plugin) => plugin.name === pluginName || plugin.id === pluginName || plugin.id === `${pluginName}@${marketplace.name}`)).map((marketplace) => {
215
+ if (marketplace.path) return {
216
+ kind: "local",
217
+ name: marketplace.name,
218
+ path: marketplace.path
219
+ };
220
+ return {
221
+ kind: "remote",
222
+ name: marketplace.name,
223
+ remoteMarketplaceName: marketplace.name
224
+ };
225
+ });
226
+ }
227
+ function chooseKnownComputerUseMarketplace(candidates) {
228
+ for (const marketplaceName of COMPUTER_USE_MARKETPLACE_NAME_PRIORITY) {
229
+ const candidate = candidates.find((marketplace) => marketplace.name === marketplaceName);
230
+ if (candidate) return candidate;
231
+ }
232
+ }
233
+ function marketplaceDiscoveryWaitUntil(params) {
234
+ if (params.allowAdd && !params.config.marketplaceSource && !params.config.marketplacePath && !params.config.marketplaceName) return Date.now() + params.config.marketplaceDiscoveryTimeoutMs;
235
+ return 0;
236
+ }
237
+ async function delay(ms, signal) {
238
+ if (signal?.aborted) throw abortError(signal);
239
+ await new Promise((resolve, reject) => {
240
+ let timer;
241
+ const onAbort = () => {
242
+ clearTimeout(timer);
243
+ signal?.removeEventListener("abort", onAbort);
244
+ reject(abortError(signal));
245
+ };
246
+ timer = setTimeout(() => {
247
+ signal?.removeEventListener("abort", onAbort);
248
+ resolve();
249
+ }, ms);
250
+ signal?.addEventListener("abort", onAbort, { once: true });
251
+ });
252
+ }
253
+ function abortError(signal) {
254
+ const reason = signal?.reason;
255
+ return reason instanceof Error ? reason : /* @__PURE__ */ new Error("Computer Use setup was aborted.");
256
+ }
257
+ async function readComputerUsePlugin(request, marketplace, pluginName) {
258
+ return (await request("plugin/read", pluginRequestParams(marketplace, pluginName))).plugin;
259
+ }
260
+ async function readMcpServerStatus(request, serverName) {
261
+ let cursor;
262
+ do {
263
+ const response = await request("mcpServerStatus/list", {
264
+ cursor,
265
+ limit: 100,
266
+ detail: "toolsAndAuthOnly"
267
+ });
268
+ const found = response.data.find((server) => server.name === serverName);
269
+ if (found) return found;
270
+ cursor = response.nextCursor;
271
+ } while (cursor);
272
+ }
273
+ async function reloadMcpServers(request) {
274
+ await request("config/mcpServer/reload", void 0);
275
+ }
276
+ function pluginRequestParams(marketplace, pluginName) {
277
+ return {
278
+ ...marketplace.kind === "local" ? { marketplacePath: marketplace.path } : {},
279
+ ...marketplace.kind === "remote" ? { remoteMarketplaceName: marketplace.remoteMarketplaceName } : {},
280
+ pluginName
281
+ };
282
+ }
283
+ function pluginSetupReason(plugin, marketplace) {
284
+ if (marketplace.kind === "remote") return "remote_install_unsupported";
285
+ return plugin.summary.installed ? "plugin_disabled" : "plugin_not_installed";
286
+ }
287
+ function pluginSetupMessage(config, plugin, marketplace) {
288
+ if (marketplace.kind === "remote") return remoteInstallUnsupportedMessage(plugin, marketplace);
289
+ if (!plugin.summary.installed) return "Computer Use is available but not installed. Run /codex computer-use install or enable computerUse.autoInstall.";
290
+ return `Computer Use is installed, but the ${config.pluginName} plugin is disabled. Run /codex computer-use install or enable computerUse.autoInstall to re-enable it.`;
291
+ }
292
+ function remoteInstallUnsupportedMessage(plugin, marketplace) {
293
+ const marketplaceName = marketplace.name ?? plugin.marketplaceName;
294
+ return `Computer Use is ${plugin.summary.installed ? "installed but disabled" : "available"} in remote Codex marketplace ${marketplaceName}, but Codex app-server does not support remote plugin install yet. Configure computerUse.marketplaceSource or computerUse.marketplacePath for a local marketplace, then run /codex computer-use install.`;
295
+ }
296
+ function statusFromPlugin(params) {
297
+ return {
298
+ enabled: true,
299
+ ready: params.plugin.summary.installed && params.plugin.summary.enabled && params.tools.length > 0,
300
+ reason: params.reason,
301
+ installed: params.plugin.summary.installed,
302
+ pluginEnabled: params.plugin.summary.enabled,
303
+ mcpServerAvailable: params.tools.length > 0,
304
+ pluginName: params.config.pluginName,
305
+ mcpServerName: params.config.mcpServerName,
306
+ marketplaceName: params.plugin.marketplaceName,
307
+ ...params.plugin.marketplacePath ? { marketplacePath: params.plugin.marketplacePath } : {},
308
+ tools: params.tools,
309
+ message: params.message
310
+ };
311
+ }
312
+ function disabledStatus(config) {
313
+ return {
314
+ enabled: false,
315
+ ready: false,
316
+ reason: "disabled",
317
+ installed: false,
318
+ pluginEnabled: false,
319
+ mcpServerAvailable: false,
320
+ pluginName: config.pluginName,
321
+ mcpServerName: config.mcpServerName,
322
+ tools: [],
323
+ message: "Computer Use is disabled."
324
+ };
325
+ }
326
+ function unavailableStatus(config, reason, message) {
327
+ return {
328
+ enabled: true,
329
+ ready: false,
330
+ reason,
331
+ installed: false,
332
+ pluginEnabled: false,
333
+ mcpServerAvailable: false,
334
+ pluginName: config.pluginName,
335
+ mcpServerName: config.mcpServerName,
336
+ ...config.marketplaceName ? { marketplaceName: config.marketplaceName } : {},
337
+ ...config.marketplacePath ? { marketplacePath: config.marketplacePath } : {},
338
+ tools: [],
339
+ message
340
+ };
341
+ }
342
+ function createComputerUseRequest(params) {
343
+ if (params.request) return params.request;
344
+ if (params.client) return async (method, requestParams) => await params.client.request(method, requestParams, {
345
+ timeoutMs: params.timeoutMs,
346
+ signal: params.signal
347
+ });
348
+ const runtime = resolveCodexAppServerRuntimeOptions({ pluginConfig: params.pluginConfig });
349
+ return async (method, requestParams) => await requestCodexAppServerJson({
350
+ method,
351
+ requestParams,
352
+ timeoutMs: params.timeoutMs ?? runtime.requestTimeoutMs,
353
+ startOptions: runtime.start
354
+ });
355
+ }
356
+ function resolveComputerUseConfig(params) {
357
+ const overrides = params.forceEnable ? {
358
+ ...params.overrides,
359
+ enabled: true
360
+ } : params.overrides;
361
+ return resolveCodexComputerUseConfig({
362
+ pluginConfig: params.pluginConfig,
363
+ overrides
364
+ });
365
+ }
366
+ //#endregion
367
+ export { installCodexComputerUse as n, readCodexComputerUseStatus as r, ensureCodexComputerUse as t };