@kodelyth/codex 2026.5.42 → 2026.6.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 (138) hide show
  1. package/package.json +16 -1
  2. package/doctor-contract-api.test.ts +0 -44
  3. package/doctor-contract-api.ts +0 -68
  4. package/harness.ts +0 -72
  5. package/index.test.ts +0 -230
  6. package/index.ts +0 -66
  7. package/media-understanding-provider.test.ts +0 -486
  8. package/media-understanding-provider.ts +0 -521
  9. package/prompt-overlay-runtime-contract.test.ts +0 -48
  10. package/prompt-overlay.ts +0 -21
  11. package/provider-catalog.ts +0 -83
  12. package/provider-discovery.ts +0 -45
  13. package/provider.test.ts +0 -384
  14. package/provider.ts +0 -243
  15. package/src/app-server/app-inventory-cache.test.ts +0 -176
  16. package/src/app-server/app-inventory-cache.ts +0 -324
  17. package/src/app-server/approval-bridge.test.ts +0 -1471
  18. package/src/app-server/approval-bridge.ts +0 -1211
  19. package/src/app-server/auth-bridge.test.ts +0 -1449
  20. package/src/app-server/auth-bridge.ts +0 -614
  21. package/src/app-server/auth-profile-runtime-contract.test.ts +0 -239
  22. package/src/app-server/capabilities.ts +0 -27
  23. package/src/app-server/client-factory.ts +0 -24
  24. package/src/app-server/client.test.ts +0 -563
  25. package/src/app-server/client.ts +0 -715
  26. package/src/app-server/compact.test.ts +0 -710
  27. package/src/app-server/compact.ts +0 -500
  28. package/src/app-server/computer-use.test.ts +0 -788
  29. package/src/app-server/computer-use.ts +0 -683
  30. package/src/app-server/config.test.ts +0 -879
  31. package/src/app-server/config.ts +0 -1038
  32. package/src/app-server/context-engine-projection.test.ts +0 -252
  33. package/src/app-server/context-engine-projection.ts +0 -403
  34. package/src/app-server/delivery-no-reply-runtime-contract.test.ts +0 -80
  35. package/src/app-server/dynamic-tool-diagnostics.ts +0 -73
  36. package/src/app-server/dynamic-tool-profile.ts +0 -69
  37. package/src/app-server/dynamic-tools.test.ts +0 -1302
  38. package/src/app-server/dynamic-tools.ts +0 -623
  39. package/src/app-server/elicitation-bridge.test.ts +0 -1056
  40. package/src/app-server/elicitation-bridge.ts +0 -783
  41. package/src/app-server/event-projector.test.ts +0 -2668
  42. package/src/app-server/event-projector.ts +0 -2057
  43. package/src/app-server/image-payload-sanitizer.test.ts +0 -49
  44. package/src/app-server/image-payload-sanitizer.ts +0 -167
  45. package/src/app-server/klaw-owned-tool-runtime-contract.test.ts +0 -456
  46. package/src/app-server/local-runtime-attribution.ts +0 -39
  47. package/src/app-server/managed-binary.test.ts +0 -139
  48. package/src/app-server/managed-binary.ts +0 -193
  49. package/src/app-server/models.test.ts +0 -246
  50. package/src/app-server/models.ts +0 -172
  51. package/src/app-server/native-hook-relay.test.ts +0 -271
  52. package/src/app-server/native-hook-relay.ts +0 -150
  53. package/src/app-server/native-subagent-task-mirror.test.ts +0 -573
  54. package/src/app-server/native-subagent-task-mirror.ts +0 -497
  55. package/src/app-server/outcome-fallback-runtime-contract.test.ts +0 -404
  56. package/src/app-server/plugin-activation.test.ts +0 -336
  57. package/src/app-server/plugin-activation.ts +0 -283
  58. package/src/app-server/plugin-app-cache-key.ts +0 -74
  59. package/src/app-server/plugin-approval-roundtrip.ts +0 -122
  60. package/src/app-server/plugin-inventory.test.ts +0 -355
  61. package/src/app-server/plugin-inventory.ts +0 -357
  62. package/src/app-server/plugin-thread-config.test.ts +0 -865
  63. package/src/app-server/plugin-thread-config.ts +0 -455
  64. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +0 -33
  65. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +0 -199
  66. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +0 -102
  67. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +0 -227
  68. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +0 -2630
  69. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +0 -2630
  70. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +0 -1659
  71. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +0 -1655
  72. package/src/app-server/protocol-validators.test.ts +0 -75
  73. package/src/app-server/protocol-validators.ts +0 -203
  74. package/src/app-server/protocol.ts +0 -520
  75. package/src/app-server/rate-limit-cache.ts +0 -48
  76. package/src/app-server/rate-limits.test.ts +0 -202
  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.context-engine.test.ts +0 -1004
  80. package/src/app-server/run-attempt.test.ts +0 -9477
  81. package/src/app-server/run-attempt.ts +0 -4683
  82. package/src/app-server/run-attempt.vision-tools.test.ts +0 -35
  83. package/src/app-server/schema-normalization-runtime-contract.test.ts +0 -206
  84. package/src/app-server/session-binding.test.ts +0 -303
  85. package/src/app-server/session-binding.ts +0 -398
  86. package/src/app-server/session-history.ts +0 -44
  87. package/src/app-server/shared-client.test.ts +0 -589
  88. package/src/app-server/shared-client.ts +0 -289
  89. package/src/app-server/side-question.test.ts +0 -1175
  90. package/src/app-server/side-question.ts +0 -1007
  91. package/src/app-server/test-support.ts +0 -48
  92. package/src/app-server/thread-lifecycle.test.ts +0 -447
  93. package/src/app-server/thread-lifecycle.ts +0 -939
  94. package/src/app-server/thread-lifecycle.user-mcp-servers.test.ts +0 -442
  95. package/src/app-server/timeout.ts +0 -9
  96. package/src/app-server/tool-progress-normalization.ts +0 -77
  97. package/src/app-server/trajectory.test.ts +0 -205
  98. package/src/app-server/trajectory.ts +0 -365
  99. package/src/app-server/transcript-mirror.test.ts +0 -524
  100. package/src/app-server/transcript-mirror.ts +0 -208
  101. package/src/app-server/transcript-repair-runtime-contract.test.ts +0 -44
  102. package/src/app-server/transport-stdio.test.ts +0 -171
  103. package/src/app-server/transport-stdio.ts +0 -107
  104. package/src/app-server/transport-websocket.test.ts +0 -69
  105. package/src/app-server/transport-websocket.ts +0 -90
  106. package/src/app-server/transport.ts +0 -117
  107. package/src/app-server/user-input-bridge.test.ts +0 -249
  108. package/src/app-server/user-input-bridge.ts +0 -316
  109. package/src/app-server/version.ts +0 -4
  110. package/src/app-server/vision-tools.ts +0 -12
  111. package/src/command-account.ts +0 -544
  112. package/src/command-formatters.ts +0 -425
  113. package/src/command-handlers.ts +0 -2004
  114. package/src/command-rpc.test.ts +0 -16
  115. package/src/command-rpc.ts +0 -142
  116. package/src/commands.test.ts +0 -3312
  117. package/src/commands.ts +0 -65
  118. package/src/conversation-binding-data.ts +0 -124
  119. package/src/conversation-binding.test.ts +0 -599
  120. package/src/conversation-binding.ts +0 -561
  121. package/src/conversation-control.test.ts +0 -126
  122. package/src/conversation-control.ts +0 -303
  123. package/src/conversation-turn-collector.test.ts +0 -191
  124. package/src/conversation-turn-collector.ts +0 -186
  125. package/src/conversation-turn-input.test.ts +0 -141
  126. package/src/conversation-turn-input.ts +0 -106
  127. package/src/manifest.test.ts +0 -20
  128. package/src/migration/apply.ts +0 -501
  129. package/src/migration/helpers.ts +0 -55
  130. package/src/migration/plan.ts +0 -461
  131. package/src/migration/provider.test.ts +0 -1741
  132. package/src/migration/provider.ts +0 -41
  133. package/src/migration/source.ts +0 -643
  134. package/src/migration/targets.ts +0 -25
  135. package/src/node-cli-sessions.test.ts +0 -180
  136. package/src/node-cli-sessions.ts +0 -711
  137. package/test-api.ts +0 -82
  138. package/tsconfig.json +0 -16
@@ -1,336 +0,0 @@
1
- import { describe, expect, it, vi } from "vitest";
2
- import { CodexAppInventoryCache } from "./app-inventory-cache.js";
3
- import { CODEX_PLUGINS_MARKETPLACE_NAME, type ResolvedCodexPluginPolicy } from "./config.js";
4
- import {
5
- ensureCodexAppsSubstrateConfig,
6
- ensureCodexPluginActivation,
7
- upsertTomlBoolean,
8
- } from "./plugin-activation.js";
9
- import type { v2 } from "./protocol.js";
10
-
11
- describe("Codex plugin activation", () => {
12
- function expectActivationResult(
13
- result: Awaited<ReturnType<typeof ensureCodexPluginActivation>>,
14
- expected: { ok: boolean; reason: string; installAttempted: boolean },
15
- ) {
16
- expect(result.ok).toBe(expected.ok);
17
- expect(result.reason).toBe(expected.reason);
18
- expect(result.installAttempted).toBe(expected.installAttempted);
19
- }
20
-
21
- function expectBooleanParam(params: unknown, key: string, expected: boolean) {
22
- expect((params as Record<string, unknown> | undefined)?.[key]).toBe(expected);
23
- }
24
-
25
- it("skips plugin/install when the migrated plugin is already active", async () => {
26
- const calls: string[] = [];
27
- const result = await ensureCodexPluginActivation({
28
- identity: identity("google-calendar"),
29
- request: async (method) => {
30
- calls.push(method);
31
- if (method === "plugin/list") {
32
- return pluginList([pluginSummary("google-calendar", { installed: true, enabled: true })]);
33
- }
34
- throw new Error(`unexpected request ${method}`);
35
- },
36
- });
37
-
38
- expectActivationResult(result, {
39
- ok: true,
40
- reason: "already_active",
41
- installAttempted: false,
42
- });
43
- expect(calls).toEqual(["plugin/list"]);
44
- });
45
-
46
- it("can reinstall an already active plugin when migration explicitly applies it", async () => {
47
- const calls: string[] = [];
48
- const result = await ensureCodexPluginActivation({
49
- identity: identity("google-calendar"),
50
- installEvenIfActive: true,
51
- request: async (method, params) => {
52
- calls.push(method);
53
- if (method === "plugin/list") {
54
- return pluginList([pluginSummary("google-calendar", { installed: true, enabled: true })]);
55
- }
56
- if (method === "plugin/install") {
57
- expect(params).toEqual({
58
- marketplacePath: "/marketplaces/openai-curated",
59
- pluginName: "google-calendar",
60
- });
61
- return { authPolicy: "ON_USE", appsNeedingAuth: [] } satisfies v2.PluginInstallResponse;
62
- }
63
- if (method === "skills/list") {
64
- return { data: [] } satisfies v2.SkillsListResponse;
65
- }
66
- if (method === "hooks/list") {
67
- return { data: [] } satisfies v2.HooksListResponse;
68
- }
69
- if (method === "config/mcpServer/reload") {
70
- return {};
71
- }
72
- throw new Error(`unexpected request ${method}`);
73
- },
74
- });
75
-
76
- expectActivationResult(result, {
77
- ok: true,
78
- reason: "already_active",
79
- installAttempted: true,
80
- });
81
- expect(calls).toEqual([
82
- "plugin/list",
83
- "plugin/install",
84
- "plugin/list",
85
- "skills/list",
86
- "hooks/list",
87
- "config/mcpServer/reload",
88
- ]);
89
- });
90
-
91
- it("installs a migration-authorized local curated plugin and refreshes runtime state", async () => {
92
- const calls: Array<{ method: string; params: unknown }> = [];
93
- const appCache = new CodexAppInventoryCache();
94
- const result = await ensureCodexPluginActivation({
95
- identity: identity("google-calendar"),
96
- appCache,
97
- appCacheKey: "runtime",
98
- request: async (method, params) => {
99
- calls.push({ method, params });
100
- if (method === "plugin/list") {
101
- return pluginList([
102
- pluginSummary("google-calendar", { installed: false, enabled: false }),
103
- ]);
104
- }
105
- if (method === "plugin/install") {
106
- expect(params).toEqual({
107
- marketplacePath: "/marketplaces/openai-curated",
108
- pluginName: "google-calendar",
109
- });
110
- return { authPolicy: "ON_USE", appsNeedingAuth: [] } satisfies v2.PluginInstallResponse;
111
- }
112
- if (method === "skills/list") {
113
- expectBooleanParam(params, "forceReload", true);
114
- return { data: [] } satisfies v2.SkillsListResponse;
115
- }
116
- if (method === "hooks/list") {
117
- return { data: [] } satisfies v2.HooksListResponse;
118
- }
119
- if (method === "config/mcpServer/reload") {
120
- return {};
121
- }
122
- if (method === "app/list") {
123
- expectBooleanParam(params, "forceRefetch", true);
124
- return { data: [], nextCursor: null } satisfies v2.AppsListResponse;
125
- }
126
- throw new Error(`unexpected request ${method}`);
127
- },
128
- });
129
-
130
- expectActivationResult(result, {
131
- ok: true,
132
- reason: "installed",
133
- installAttempted: true,
134
- });
135
- expect(calls.map((call) => call.method)).toEqual([
136
- "plugin/list",
137
- "plugin/install",
138
- "plugin/list",
139
- "skills/list",
140
- "hooks/list",
141
- "config/mcpServer/reload",
142
- "app/list",
143
- ]);
144
- expect(appCache.getRevision()).toBeGreaterThan(0);
145
- });
146
-
147
- it("keeps activation fail-closed when post-install app inventory refresh fails", async () => {
148
- const appCache = new CodexAppInventoryCache();
149
- const result = await ensureCodexPluginActivation({
150
- identity: identity("google-calendar"),
151
- appCache,
152
- appCacheKey: "runtime",
153
- request: async (method) => {
154
- if (method === "plugin/list") {
155
- return pluginList([
156
- pluginSummary("google-calendar", { installed: false, enabled: false }),
157
- ]);
158
- }
159
- if (method === "plugin/install") {
160
- return { authPolicy: "ON_USE", appsNeedingAuth: [] } satisfies v2.PluginInstallResponse;
161
- }
162
- if (method === "skills/list") {
163
- return { data: [] } satisfies v2.SkillsListResponse;
164
- }
165
- if (method === "hooks/list") {
166
- return { data: [] } satisfies v2.HooksListResponse;
167
- }
168
- if (method === "config/mcpServer/reload") {
169
- return {};
170
- }
171
- if (method === "app/list") {
172
- throw new Error("app/list unavailable");
173
- }
174
- throw new Error(`unexpected request ${method}`);
175
- },
176
- });
177
-
178
- expectActivationResult(result, {
179
- ok: true,
180
- reason: "installed",
181
- installAttempted: true,
182
- });
183
- expect(result.diagnostics).toEqual([
184
- {
185
- message: "Codex app inventory refresh skipped: app/list unavailable",
186
- },
187
- ]);
188
- expect(appCache.getRevision()).toBeGreaterThan(0);
189
- });
190
-
191
- it("reports post-install runtime refresh failures without hiding the install attempt", async () => {
192
- const result = await ensureCodexPluginActivation({
193
- identity: identity("google-calendar"),
194
- request: async (method) => {
195
- if (method === "plugin/list") {
196
- return pluginList([
197
- pluginSummary("google-calendar", { installed: false, enabled: false }),
198
- ]);
199
- }
200
- if (method === "plugin/install") {
201
- return { authPolicy: "ON_USE", appsNeedingAuth: [] } satisfies v2.PluginInstallResponse;
202
- }
203
- if (method === "skills/list") {
204
- throw new Error("skills/list unavailable");
205
- }
206
- throw new Error(`unexpected request ${method}`);
207
- },
208
- });
209
-
210
- expectActivationResult(result, {
211
- ok: false,
212
- reason: "refresh_failed",
213
- installAttempted: true,
214
- });
215
- expect(result.diagnostics).toEqual([
216
- {
217
- message: "Codex plugin runtime refresh failed after install: skills/list unavailable",
218
- },
219
- ]);
220
- });
221
-
222
- it("installs from a remote curated marketplace when no local marketplace path is present", async () => {
223
- const calls: Array<{ method: string; params: unknown }> = [];
224
- const result = await ensureCodexPluginActivation({
225
- identity: identity("google-calendar"),
226
- request: async (method, params) => {
227
- calls.push({ method, params });
228
- if (method === "plugin/list") {
229
- return {
230
- ...pluginList([pluginSummary("google-calendar", { installed: false, enabled: false })]),
231
- marketplaces: [
232
- {
233
- name: CODEX_PLUGINS_MARKETPLACE_NAME,
234
- path: null,
235
- interface: null,
236
- plugins: [pluginSummary("google-calendar", { installed: false, enabled: false })],
237
- },
238
- ],
239
- } satisfies v2.PluginListResponse;
240
- }
241
- if (method === "plugin/install") {
242
- expect(params).toEqual({
243
- remoteMarketplaceName: CODEX_PLUGINS_MARKETPLACE_NAME,
244
- pluginName: "google-calendar",
245
- });
246
- return { authPolicy: "ON_USE", appsNeedingAuth: [] } satisfies v2.PluginInstallResponse;
247
- }
248
- if (method === "skills/list") {
249
- return { data: [] } satisfies v2.SkillsListResponse;
250
- }
251
- if (method === "hooks/list") {
252
- return { data: [] } satisfies v2.HooksListResponse;
253
- }
254
- if (method === "config/mcpServer/reload") {
255
- return {};
256
- }
257
- throw new Error(`unexpected request ${method}`);
258
- },
259
- });
260
-
261
- expectActivationResult(result, {
262
- ok: true,
263
- reason: "installed",
264
- installAttempted: true,
265
- });
266
- expect(calls.map((call) => call.method)).toEqual([
267
- "plugin/list",
268
- "plugin/install",
269
- "plugin/list",
270
- "skills/list",
271
- "hooks/list",
272
- "config/mcpServer/reload",
273
- ]);
274
- });
275
-
276
- it("upserts native apps substrate config without clobbering other toml", async () => {
277
- const existing = 'model = "gpt-5.5"\n\n[features]\nother = true\n';
278
- expect(upsertTomlBoolean(existing, "features", "apps", true)).toBe(
279
- 'model = "gpt-5.5"\n\n[features]\nother = true\napps = true\n',
280
- );
281
-
282
- const writes: Array<{ path: string; content: string }> = [];
283
- const result = await ensureCodexAppsSubstrateConfig({
284
- codexHome: "/codex-home",
285
- readFile: vi.fn(async () => existing),
286
- mkdir: vi.fn(async () => undefined),
287
- writeFile: vi.fn(async (filePath, content) => {
288
- writes.push({ path: String(filePath), content: String(content) });
289
- }),
290
- });
291
-
292
- expect(result).toEqual({ changed: true, configPath: "/codex-home/config.toml" });
293
- expect(writes[0]?.content).toContain("[features]\nother = true\napps = true");
294
- expect(writes[0]?.content).toContain("[apps._default]\nenabled = true");
295
- });
296
- });
297
-
298
- function identity(pluginName: string): ResolvedCodexPluginPolicy {
299
- return {
300
- configKey: pluginName,
301
- marketplaceName: CODEX_PLUGINS_MARKETPLACE_NAME,
302
- pluginName,
303
- enabled: true,
304
- allowDestructiveActions: false,
305
- };
306
- }
307
-
308
- function pluginList(plugins: v2.PluginSummary[]): v2.PluginListResponse {
309
- return {
310
- marketplaces: [
311
- {
312
- name: CODEX_PLUGINS_MARKETPLACE_NAME,
313
- path: "/marketplaces/openai-curated",
314
- interface: null,
315
- plugins,
316
- },
317
- ],
318
- marketplaceLoadErrors: [],
319
- featuredPluginIds: [],
320
- };
321
- }
322
-
323
- function pluginSummary(id: string, overrides: Partial<v2.PluginSummary> = {}): v2.PluginSummary {
324
- return {
325
- id,
326
- name: id,
327
- source: { type: "remote" },
328
- installed: false,
329
- enabled: false,
330
- installPolicy: "AVAILABLE",
331
- authPolicy: "ON_USE",
332
- availability: "AVAILABLE",
333
- interface: null,
334
- ...overrides,
335
- };
336
- }
@@ -1,283 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import {
4
- type CodexAppInventoryCache,
5
- type CodexAppInventoryRequest,
6
- } from "./app-inventory-cache.js";
7
- import { CODEX_PLUGINS_MARKETPLACE_NAME, type ResolvedCodexPluginPolicy } from "./config.js";
8
- import {
9
- findOpenAiCuratedPluginSummary,
10
- pluginReadParams,
11
- type CodexPluginMarketplaceRef,
12
- type CodexPluginRuntimeRequest,
13
- } from "./plugin-inventory.js";
14
- import type { v2 } from "./protocol.js";
15
-
16
- export type CodexPluginActivationReason =
17
- | "already_active"
18
- | "installed"
19
- | "disabled"
20
- | "marketplace_missing"
21
- | "plugin_missing"
22
- | "auth_required"
23
- | "refresh_failed";
24
-
25
- export type CodexPluginActivationDiagnostic = {
26
- message: string;
27
- };
28
-
29
- export type CodexPluginActivationResult = {
30
- identity: ResolvedCodexPluginPolicy;
31
- ok: boolean;
32
- reason: CodexPluginActivationReason;
33
- installAttempted: boolean;
34
- marketplace?: CodexPluginMarketplaceRef;
35
- installResponse?: v2.PluginInstallResponse;
36
- diagnostics: CodexPluginActivationDiagnostic[];
37
- };
38
-
39
- export type EnsureCodexPluginActivationParams = {
40
- identity: ResolvedCodexPluginPolicy;
41
- request: CodexPluginRuntimeRequest;
42
- appCache?: CodexAppInventoryCache;
43
- appCacheKey?: string;
44
- installEvenIfActive?: boolean;
45
- };
46
-
47
- export type CodexPluginRuntimeRefreshResult = {
48
- diagnostics: CodexPluginActivationDiagnostic[];
49
- };
50
-
51
- export async function ensureCodexPluginActivation(
52
- params: EnsureCodexPluginActivationParams,
53
- ): Promise<CodexPluginActivationResult> {
54
- if (params.identity.marketplaceName !== CODEX_PLUGINS_MARKETPLACE_NAME) {
55
- return activationFailure(params.identity, "marketplace_missing", {
56
- message: "Only " + CODEX_PLUGINS_MARKETPLACE_NAME + " plugins can be activated.",
57
- });
58
- }
59
-
60
- const listed = (await params.request("plugin/list", {
61
- cwds: [],
62
- } satisfies v2.PluginListParams)) as v2.PluginListResponse;
63
- const resolved = findOpenAiCuratedPluginSummary(listed, params.identity.pluginName);
64
- if (!resolved) {
65
- const hasCuratedMarketplace = listed.marketplaces.some(
66
- (marketplace) => marketplace.name === CODEX_PLUGINS_MARKETPLACE_NAME,
67
- );
68
- if (!hasCuratedMarketplace) {
69
- return activationFailure(params.identity, "marketplace_missing", {
70
- message: `Codex marketplace ${CODEX_PLUGINS_MARKETPLACE_NAME} was not found.`,
71
- });
72
- }
73
- return activationFailure(params.identity, "plugin_missing", {
74
- message: `${params.identity.pluginName} was not found in ${CODEX_PLUGINS_MARKETPLACE_NAME}.`,
75
- });
76
- }
77
-
78
- if (resolved.summary.installed && resolved.summary.enabled && !params.installEvenIfActive) {
79
- return {
80
- identity: params.identity,
81
- ok: true,
82
- reason: "already_active",
83
- installAttempted: false,
84
- marketplace: resolved.marketplace,
85
- diagnostics: [],
86
- };
87
- }
88
-
89
- const installResponse = (await params.request(
90
- "plugin/install",
91
- pluginReadParams(
92
- resolved.marketplace,
93
- params.identity.pluginName,
94
- ) satisfies v2.PluginInstallParams,
95
- )) as v2.PluginInstallResponse;
96
- const refreshDiagnostics: CodexPluginActivationDiagnostic[] = [];
97
- let refreshFailed = false;
98
- try {
99
- const refreshResult = await refreshCodexPluginRuntimeState({
100
- request: params.request,
101
- appCache: params.appCache,
102
- appCacheKey: params.appCacheKey,
103
- });
104
- refreshDiagnostics.push(...refreshResult.diagnostics);
105
- } catch (error) {
106
- refreshFailed = true;
107
- refreshDiagnostics.push({
108
- message: `Codex plugin runtime refresh failed after install: ${
109
- error instanceof Error ? error.message : String(error)
110
- }`,
111
- });
112
- }
113
- const authRequired = installResponse.appsNeedingAuth.length > 0;
114
- return {
115
- identity: params.identity,
116
- ok: !authRequired && !refreshFailed,
117
- reason: refreshFailed
118
- ? "refresh_failed"
119
- : authRequired
120
- ? "auth_required"
121
- : resolved.summary.installed && resolved.summary.enabled
122
- ? "already_active"
123
- : "installed",
124
- installAttempted: true,
125
- marketplace: resolved.marketplace,
126
- installResponse,
127
- diagnostics: [
128
- ...refreshDiagnostics,
129
- ...installResponse.appsNeedingAuth.map((app) => ({
130
- message: `${app.name} requires app authentication before plugin tools are exposed.`,
131
- })),
132
- ],
133
- };
134
- }
135
-
136
- export async function refreshCodexPluginRuntimeState(params: {
137
- request: CodexPluginRuntimeRequest;
138
- appCache?: CodexAppInventoryCache;
139
- appCacheKey?: string;
140
- }): Promise<CodexPluginRuntimeRefreshResult> {
141
- const diagnostics: CodexPluginActivationDiagnostic[] = [];
142
- await params.request("plugin/list", {
143
- cwds: [],
144
- } satisfies v2.PluginListParams);
145
- await params.request("skills/list", {
146
- cwds: [],
147
- forceReload: true,
148
- } satisfies v2.SkillsListParams);
149
- try {
150
- await params.request("hooks/list", {
151
- cwds: [],
152
- } satisfies v2.HooksListParams);
153
- } catch (error) {
154
- diagnostics.push({
155
- message: `Codex hooks refresh skipped: ${error instanceof Error ? error.message : String(error)}`,
156
- });
157
- }
158
- await params.request("config/mcpServer/reload", undefined);
159
-
160
- if (params.appCache && params.appCacheKey) {
161
- params.appCache.invalidate(params.appCacheKey, "Codex plugin activation changed app inventory");
162
- const request: CodexAppInventoryRequest = async (method, requestParams) =>
163
- (await params.request(method, requestParams)) as v2.AppsListResponse;
164
- try {
165
- await params.appCache.refreshNow({
166
- key: params.appCacheKey,
167
- request,
168
- forceRefetch: true,
169
- });
170
- } catch (error) {
171
- diagnostics.push({
172
- message: `Codex app inventory refresh skipped: ${
173
- error instanceof Error ? error.message : String(error)
174
- }`,
175
- });
176
- }
177
- }
178
-
179
- return { diagnostics };
180
- }
181
-
182
- export async function ensureCodexAppsSubstrateConfig(params: {
183
- codexHome: string;
184
- readFile?: (filePath: string, encoding: "utf8") => Promise<string>;
185
- writeFile?: (filePath: string, content: string, encoding: "utf8") => Promise<void>;
186
- mkdir?: (dirPath: string, options: { recursive: true }) => Promise<unknown>;
187
- }): Promise<{ changed: boolean; configPath: string }> {
188
- const readFile = params.readFile ?? ((filePath, encoding) => fs.readFile(filePath, encoding));
189
- const writeFile =
190
- params.writeFile ??
191
- ((filePath, content, encoding) => fs.writeFile(filePath, content, encoding));
192
- const mkdir = params.mkdir ?? ((dirPath, options) => fs.mkdir(dirPath, options));
193
- const configPath = path.join(params.codexHome, "config.toml");
194
- let current = "";
195
- try {
196
- current = await readFile(configPath, "utf8");
197
- } catch (error) {
198
- if (!isEnoent(error)) {
199
- throw error;
200
- }
201
- }
202
-
203
- const next = upsertTomlBoolean(
204
- upsertTomlBoolean(current, "features", "apps", true),
205
- "apps._default",
206
- "enabled",
207
- true,
208
- );
209
- if (next === current) {
210
- return { changed: false, configPath };
211
- }
212
- await mkdir(path.dirname(configPath), { recursive: true });
213
- await writeFile(configPath, next, "utf8");
214
- return { changed: true, configPath };
215
- }
216
-
217
- export function upsertTomlBoolean(
218
- source: string,
219
- section: string,
220
- key: string,
221
- value: boolean,
222
- ): string {
223
- const lines = source.replace(/\r\n/g, "\n").split("\n");
224
- if (lines.length > 0 && lines.at(-1) === "") {
225
- lines.pop();
226
- }
227
- const sectionHeaderPattern = new RegExp(`^\\s*\\[${escapeRegExp(section)}\\]\\s*(?:#.*)?$`);
228
- const anySectionPattern = /^\s*\[[^\]]+\]\s*(?:#.*)?$/;
229
- const keyPattern = new RegExp(`^\\s*${escapeRegExp(key)}\\s*=`);
230
- const desiredLine = `${key} = ${value ? "true" : "false"}`;
231
- const sectionStart = lines.findIndex((line) => sectionHeaderPattern.test(line));
232
- if (sectionStart === -1) {
233
- const nextLines = [...lines];
234
- if (nextLines.length > 0 && nextLines.at(-1)?.trim()) {
235
- nextLines.push("");
236
- }
237
- nextLines.push(`[${section}]`, desiredLine);
238
- return `${nextLines.join("\n")}\n`;
239
- }
240
-
241
- let sectionEnd = lines.length;
242
- for (let index = sectionStart + 1; index < lines.length; index += 1) {
243
- if (anySectionPattern.test(lines[index] ?? "")) {
244
- sectionEnd = index;
245
- break;
246
- }
247
- }
248
- for (let index = sectionStart + 1; index < sectionEnd; index += 1) {
249
- if (keyPattern.test(lines[index] ?? "")) {
250
- if (lines[index] === desiredLine) {
251
- return `${lines.join("\n")}\n`;
252
- }
253
- const nextLines = [...lines];
254
- nextLines[index] = desiredLine;
255
- return `${nextLines.join("\n")}\n`;
256
- }
257
- }
258
- const nextLines = [...lines];
259
- nextLines.splice(sectionEnd, 0, desiredLine);
260
- return `${nextLines.join("\n")}\n`;
261
- }
262
-
263
- function activationFailure(
264
- identity: ResolvedCodexPluginPolicy,
265
- reason: CodexPluginActivationReason,
266
- diagnostic: CodexPluginActivationDiagnostic,
267
- ): CodexPluginActivationResult {
268
- return {
269
- identity,
270
- ok: false,
271
- reason,
272
- installAttempted: false,
273
- diagnostics: [diagnostic],
274
- };
275
- }
276
-
277
- function isEnoent(error: unknown): boolean {
278
- return Boolean(error && typeof error === "object" && "code" in error && error.code === "ENOENT");
279
- }
280
-
281
- function escapeRegExp(value: string): string {
282
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
283
- }
@@ -1,74 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import {
3
- buildCodexAppInventoryCacheKey,
4
- type CodexAppInventoryCacheKeyInput,
5
- } from "./app-inventory-cache.js";
6
- import { resolveCodexAppServerHomeDir } from "./auth-bridge.js";
7
- import type { CodexAppServerRuntimeOptions, CodexAppServerStartOptions } from "./config.js";
8
-
9
- export type CodexPluginAppCacheKeyParams = Omit<
10
- CodexAppInventoryCacheKeyInput,
11
- "codexHome" | "endpoint"
12
- > & {
13
- appServer: Pick<CodexAppServerRuntimeOptions, "start">;
14
- agentDir?: string;
15
- };
16
-
17
- export function buildCodexPluginAppCacheKey(params: CodexPluginAppCacheKeyParams): string {
18
- return buildCodexAppInventoryCacheKey({
19
- codexHome: resolveCodexPluginAppCacheCodexHome(params.appServer, params.agentDir),
20
- endpoint: resolveCodexPluginAppCacheEndpoint(params.appServer),
21
- authProfileId: params.authProfileId,
22
- accountId: params.accountId,
23
- envApiKeyFingerprint: params.envApiKeyFingerprint,
24
- appServerVersion: params.appServerVersion,
25
- });
26
- }
27
-
28
- export function resolveCodexPluginAppCacheEndpoint(
29
- appServer: Pick<CodexAppServerRuntimeOptions, "start">,
30
- ): string {
31
- return JSON.stringify({
32
- transport: appServer.start.transport,
33
- command: appServer.start.command,
34
- args: appServer.start.args,
35
- url: appServer.start.url ?? null,
36
- credentialFingerprint: fingerprintCodexPluginAppCacheCredentials(appServer.start),
37
- });
38
- }
39
-
40
- export function resolveCodexPluginAppCacheCodexHome(
41
- appServer: Pick<CodexAppServerRuntimeOptions, "start">,
42
- agentDir?: string,
43
- ): string | undefined {
44
- const configuredCodexHome = appServer.start.env?.CODEX_HOME?.trim();
45
- if (configuredCodexHome) {
46
- return configuredCodexHome;
47
- }
48
- return appServer.start.transport === "stdio" && agentDir
49
- ? resolveCodexAppServerHomeDir(agentDir)
50
- : undefined;
51
- }
52
-
53
- function fingerprintCodexPluginAppCacheCredentials(
54
- startOptions: CodexAppServerStartOptions,
55
- ): string | null {
56
- const authToken = startOptions.authToken ?? "";
57
- const headers = Object.entries(startOptions.headers)
58
- .map(([key, value]) => [key.toLowerCase(), value] as const)
59
- .toSorted(([left], [right]) => left.localeCompare(right));
60
- if (!authToken && headers.length === 0) {
61
- return null;
62
- }
63
- const hash = createHash("sha256");
64
- hash.update("klaw:codex:plugin-app-cache-credentials:v1");
65
- hash.update("\0");
66
- hash.update(authToken);
67
- for (const [key, value] of headers) {
68
- hash.update("\0");
69
- hash.update(key);
70
- hash.update("\0");
71
- hash.update(value);
72
- }
73
- return `sha256:${hash.digest("hex")}`;
74
- }