@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,501 +0,0 @@
1
- import path from "node:path";
2
- import {
3
- applyMigrationManualItem,
4
- markMigrationItemConflict,
5
- markMigrationItemError,
6
- markMigrationItemSkipped,
7
- MIGRATION_REASON_TARGET_EXISTS,
8
- summarizeMigrationItems,
9
- writeMigrationConfigPath,
10
- } from "klaw/plugin-sdk/migration";
11
- import {
12
- archiveMigrationItem,
13
- copyMigrationFileItem,
14
- withCachedMigrationConfigRuntime,
15
- writeMigrationReport,
16
- } from "klaw/plugin-sdk/migration-runtime";
17
- import type {
18
- MigrationApplyResult,
19
- MigrationItem,
20
- MigrationPlan,
21
- MigrationProviderContext,
22
- } from "klaw/plugin-sdk/plugin-entry";
23
- import { defaultCodexAppInventoryCache } from "../app-server/app-inventory-cache.js";
24
- import {
25
- resolveCodexAppServerAuthAccountCacheKey,
26
- resolveCodexAppServerAuthProfileIdForAgent,
27
- resolveCodexAppServerEnvApiKeyCacheKey,
28
- } from "../app-server/auth-bridge.js";
29
- import {
30
- CODEX_PLUGINS_MARKETPLACE_NAME,
31
- readCodexPluginConfig,
32
- resolveCodexAppServerRuntimeOptions,
33
- type ResolvedCodexPluginPolicy,
34
- } from "../app-server/config.js";
35
- import {
36
- ensureCodexPluginActivation,
37
- type CodexPluginActivationResult,
38
- } from "../app-server/plugin-activation.js";
39
- import { buildCodexPluginAppCacheKey } from "../app-server/plugin-app-cache-key.js";
40
- import type { v2 } from "../app-server/protocol.js";
41
- import { requestCodexAppServerJson } from "../app-server/request.js";
42
- import {
43
- clearSharedCodexAppServerClientIfCurrentAndWait,
44
- getSharedCodexAppServerClient,
45
- } from "../app-server/shared-client.js";
46
- import { buildCodexMigrationPlan } from "./plan.js";
47
- import {
48
- buildCodexPluginsConfigValue,
49
- CODEX_PLUGIN_CONFIG_ITEM_ID,
50
- CODEX_PLUGIN_CONFIG_PATH,
51
- hasCodexPluginConfigConflict,
52
- readCodexPluginMigrationConfigEntry,
53
- type CodexPluginMigrationConfigEntry,
54
- } from "./plan.js";
55
- import { resolveCodexMigrationTargets } from "./targets.js";
56
-
57
- const CODEX_PLUGIN_AUTH_REQUIRED_REASON = "auth_required";
58
- const CODEX_PLUGIN_NOT_SELECTED_REASON = "not selected for migration";
59
- const CODEX_CONFIG_PATCH_MODE_RETURN = "return";
60
- const CODEX_PLUGIN_LOAD_WARNING =
61
- "Some Codex plugins could not be migrated. Run `klaw migrate codex` after onboarding.";
62
- const TARGET_CODEX_MARKETPLACE_DISCOVERY_POLL_MS = 250;
63
- const TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_MS = 30_000;
64
- const TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_ENV =
65
- "KLAW_CODEX_MIGRATION_PLUGIN_LIST_TIMEOUT_MS";
66
-
67
- export type CodexMigrationTargetAppServerPreparation = {
68
- dispose: () => Promise<void>;
69
- };
70
-
71
- class CodexPluginConfigConflictError extends Error {
72
- constructor(readonly reason: string) {
73
- super(reason);
74
- this.name = "CodexPluginConfigConflictError";
75
- }
76
- }
77
-
78
- function shouldReturnCodexPluginConfigPatch(ctx: MigrationProviderContext): boolean {
79
- return ctx.providerOptions?.configPatchMode === CODEX_CONFIG_PATCH_MODE_RETURN;
80
- }
81
-
82
- export function prepareTargetCodexAppServer(
83
- ctx: MigrationProviderContext,
84
- ): CodexMigrationTargetAppServerPreparation {
85
- const appServer = resolveTargetCodexAppServer(ctx);
86
- const targets = resolveCodexMigrationTargets(ctx);
87
- let warmedClient: Awaited<ReturnType<typeof getSharedCodexAppServerClient>> | undefined;
88
- const ready = getSharedCodexAppServerClient({
89
- startOptions: appServer.start,
90
- timeoutMs: 60_000,
91
- agentDir: targets.agentDir,
92
- config: ctx.config,
93
- }).then(
94
- (client) => {
95
- warmedClient = client;
96
- },
97
- () => undefined,
98
- );
99
- return {
100
- async dispose() {
101
- await ready;
102
- await clearSharedCodexAppServerClientIfCurrentAndWait(warmedClient, {
103
- exitTimeoutMs: 2_000,
104
- forceKillDelayMs: 250,
105
- });
106
- },
107
- };
108
- }
109
-
110
- export async function applyCodexMigrationPlan(params: {
111
- ctx: MigrationProviderContext;
112
- plan?: MigrationPlan;
113
- runtime?: MigrationProviderContext["runtime"];
114
- }): Promise<MigrationApplyResult> {
115
- const plan = params.plan ?? (await buildCodexMigrationPlan(params.ctx));
116
- const reportDir = params.ctx.reportDir ?? path.join(params.ctx.stateDir, "migration", "codex");
117
- const items: MigrationItem[] = [];
118
- const runtime = withCachedMigrationConfigRuntime(
119
- params.ctx.runtime ?? params.runtime,
120
- params.ctx.config,
121
- );
122
- const applyCtx = { ...params.ctx, runtime };
123
- for (const item of plan.items) {
124
- if (item.status !== "planned") {
125
- items.push(item);
126
- continue;
127
- }
128
- if (item.id === CODEX_PLUGIN_CONFIG_ITEM_ID) {
129
- items.push(await applyCodexPluginConfigItem(applyCtx, item, items));
130
- } else if (item.kind === "plugin" && item.action === "install") {
131
- items.push(await applyCodexPluginInstallItem(applyCtx, item));
132
- } else if (item.kind === "manual") {
133
- items.push(applyMigrationManualItem(item));
134
- } else if (item.action === "archive") {
135
- items.push(await archiveMigrationItem(item, reportDir));
136
- } else {
137
- items.push(await copyMigrationFileItem(item, reportDir, { overwrite: params.ctx.overwrite }));
138
- }
139
- }
140
- const result: MigrationApplyResult = {
141
- ...plan,
142
- items,
143
- summary: summarizeMigrationItems(items),
144
- backupPath: params.ctx.backupPath,
145
- reportDir,
146
- };
147
- if (items.some(isCodexPluginLoadWarningItem)) {
148
- result.warnings = [...new Set([...(result.warnings ?? []), CODEX_PLUGIN_LOAD_WARNING])];
149
- result.nextSteps = [...new Set([CODEX_PLUGIN_LOAD_WARNING, ...(result.nextSteps ?? [])])];
150
- }
151
- await writeMigrationReport(result, { title: "Codex Migration Report" });
152
- return result;
153
- }
154
-
155
- async function applyCodexPluginInstallItem(
156
- ctx: MigrationProviderContext,
157
- item: MigrationItem,
158
- ): Promise<MigrationItem> {
159
- const policy = readCodexPluginPolicy(item);
160
- if (!policy) {
161
- return {
162
- ...markMigrationItemError(item, "invalid Codex plugin migration item"),
163
- details: { ...item.details, code: "invalid_plugin_item" },
164
- };
165
- }
166
- try {
167
- const appCacheKey = await buildTargetCodexPluginAppCacheKey(ctx);
168
- const appServer = resolveTargetCodexAppServer(ctx);
169
- const result = await ensureCodexPluginActivation({
170
- identity: policy,
171
- installEvenIfActive: true,
172
- request: async (method, requestParams) =>
173
- await requestTargetCodexAppServerJson({
174
- method,
175
- requestParams,
176
- timeoutMs: 60_000,
177
- startOptions: appServer.start,
178
- agentDir: resolveCodexMigrationTargets(ctx).agentDir,
179
- config: ctx.config,
180
- isolated: false,
181
- }),
182
- appCache: defaultCodexAppInventoryCache,
183
- appCacheKey,
184
- });
185
- const baseDetails = {
186
- ...item.details,
187
- code: result.reason,
188
- activationReason: result.reason,
189
- ...codexPluginActivationReportState(result),
190
- installAttempted: result.installAttempted,
191
- diagnostics: result.diagnostics.map((diagnostic) => diagnostic.message),
192
- };
193
- if (result.ok) {
194
- return {
195
- ...item,
196
- status: "migrated",
197
- ...(result.reason === "already_active" ? { reason: "already active" } : {}),
198
- details: baseDetails,
199
- };
200
- }
201
- if (result.reason === CODEX_PLUGIN_AUTH_REQUIRED_REASON) {
202
- return {
203
- ...item,
204
- status: "skipped",
205
- reason: CODEX_PLUGIN_AUTH_REQUIRED_REASON,
206
- details: {
207
- ...baseDetails,
208
- appsNeedingAuth: sanitizeAppsNeedingAuth(result.installResponse?.appsNeedingAuth ?? []),
209
- },
210
- };
211
- }
212
- if (result.reason === "plugin_missing" || result.reason === "marketplace_missing") {
213
- return {
214
- ...item,
215
- status: "warning",
216
- reason: result.reason,
217
- message: `Codex plugin "${policy.pluginName}" could not be migrated automatically`,
218
- details: {
219
- ...baseDetails,
220
- warningReason: CODEX_PLUGIN_LOAD_WARNING,
221
- },
222
- };
223
- }
224
- return {
225
- ...item,
226
- status: "error",
227
- reason: result.reason,
228
- details: baseDetails,
229
- };
230
- } catch (error) {
231
- if (isCodexPluginInventoryLoadError(error)) {
232
- return {
233
- ...item,
234
- status: "warning",
235
- reason: "plugin_inventory_unavailable",
236
- message: `Codex plugin "${policy.pluginName}" could not be migrated automatically`,
237
- details: {
238
- ...item.details,
239
- code: "plugin_inventory_unavailable",
240
- warningReason: CODEX_PLUGIN_LOAD_WARNING,
241
- diagnostic: formatCodexMigrationError(error),
242
- },
243
- };
244
- }
245
- return {
246
- ...item,
247
- status: "error",
248
- reason: formatCodexMigrationError(error),
249
- details: {
250
- ...item.details,
251
- code: "plugin_install_failed",
252
- },
253
- };
254
- }
255
- }
256
-
257
- function isCodexPluginInventoryLoadError(error: unknown): boolean {
258
- const message = formatCodexMigrationError(error);
259
- return message.includes("codex app-server plugin/list timed out");
260
- }
261
-
262
- function formatCodexMigrationError(error: unknown): string {
263
- return error instanceof Error ? error.message : String(error);
264
- }
265
-
266
- function resolveTargetCodexAppServer(ctx: MigrationProviderContext) {
267
- return resolveCodexAppServerRuntimeOptions({
268
- pluginConfig: readCodexPluginConfig(ctx.config),
269
- });
270
- }
271
-
272
- async function requestTargetCodexAppServerJson(params: {
273
- method: string;
274
- requestParams?: unknown;
275
- timeoutMs: number;
276
- startOptions: ReturnType<typeof resolveTargetCodexAppServer>["start"];
277
- agentDir: string;
278
- config: MigrationProviderContext["config"];
279
- isolated?: boolean;
280
- }): Promise<unknown> {
281
- if (params.method !== "plugin/list") {
282
- return await requestCodexAppServerJson(params);
283
- }
284
-
285
- const deadline = Date.now() + params.timeoutMs;
286
- const discoveryTimeoutMs = targetCodexMarketplaceDiscoveryTimeoutMs();
287
- const discoveryDeadline = Math.min(deadline, Date.now() + discoveryTimeoutMs);
288
- let lastResponse: unknown;
289
- let attempt = 0;
290
- do {
291
- attempt += 1;
292
- const remainingMs = Math.max(1, discoveryDeadline - Date.now());
293
- lastResponse = await requestCodexAppServerJson({
294
- ...params,
295
- timeoutMs: remainingMs,
296
- });
297
- if (hasOpenAiCuratedMarketplace(lastResponse)) {
298
- return lastResponse;
299
- }
300
- if (Date.now() >= discoveryDeadline) {
301
- return lastResponse;
302
- }
303
- const waitMs = Math.min(
304
- TARGET_CODEX_MARKETPLACE_DISCOVERY_POLL_MS,
305
- discoveryDeadline - Date.now(),
306
- );
307
- await sleep(waitMs);
308
- } while (Date.now() < discoveryDeadline);
309
-
310
- return lastResponse;
311
- }
312
-
313
- function hasOpenAiCuratedMarketplace(response: unknown): boolean {
314
- if (!response || typeof response !== "object" || !("marketplaces" in response)) {
315
- return false;
316
- }
317
- const marketplaces = (response as { marketplaces?: unknown }).marketplaces;
318
- return (
319
- Array.isArray(marketplaces) &&
320
- marketplaces.some(
321
- (marketplace) =>
322
- marketplace &&
323
- typeof marketplace === "object" &&
324
- (marketplace as { name?: unknown }).name === CODEX_PLUGINS_MARKETPLACE_NAME,
325
- )
326
- );
327
- }
328
-
329
- function targetCodexMarketplaceDiscoveryTimeoutMs(): number {
330
- const configured = Number(process.env[TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_ENV]);
331
- if (Number.isFinite(configured) && configured >= 0) {
332
- return configured;
333
- }
334
- return TARGET_CODEX_MARKETPLACE_DISCOVERY_TIMEOUT_MS;
335
- }
336
-
337
- function isCodexPluginLoadWarningItem(item: MigrationItem): boolean {
338
- return (
339
- item.kind === "plugin" &&
340
- item.action === "install" &&
341
- item.status === "warning" &&
342
- item.details?.warningReason === CODEX_PLUGIN_LOAD_WARNING
343
- );
344
- }
345
-
346
- async function sleep(ms: number): Promise<void> {
347
- await new Promise((resolve) => setTimeout(resolve, ms));
348
- }
349
-
350
- async function buildTargetCodexPluginAppCacheKey(ctx: MigrationProviderContext): Promise<string> {
351
- const targets = resolveCodexMigrationTargets(ctx);
352
- const appServer = resolveTargetCodexAppServer(ctx);
353
- const authProfileId = resolveCodexAppServerAuthProfileIdForAgent({
354
- agentDir: targets.agentDir,
355
- config: ctx.config,
356
- });
357
- const accountId = await resolveCodexAppServerAuthAccountCacheKey({
358
- authProfileId,
359
- agentDir: targets.agentDir,
360
- config: ctx.config,
361
- });
362
- const envApiKeyFingerprint = authProfileId
363
- ? undefined
364
- : resolveCodexAppServerEnvApiKeyCacheKey({
365
- startOptions: appServer.start,
366
- });
367
- return buildCodexPluginAppCacheKey({
368
- appServer,
369
- agentDir: targets.agentDir,
370
- authProfileId,
371
- accountId,
372
- envApiKeyFingerprint,
373
- });
374
- }
375
-
376
- async function applyCodexPluginConfigItem(
377
- ctx: MigrationProviderContext,
378
- item: MigrationItem,
379
- appliedItems: readonly MigrationItem[],
380
- ): Promise<MigrationItem> {
381
- const entries = appliedItems
382
- .map(readAppliedPluginConfigEntry)
383
- .filter((entry): entry is CodexPluginMigrationConfigEntry => entry !== undefined);
384
- if (entries.length === 0) {
385
- return markMigrationItemSkipped(item, "no selected Codex plugins");
386
- }
387
- const returnPatch = shouldReturnCodexPluginConfigPatch(ctx);
388
- const configApi = ctx.runtime?.config;
389
- const currentConfig = returnPatch
390
- ? ctx.config
391
- : (configApi?.current?.() as MigrationProviderContext["config"] | undefined);
392
- if (!currentConfig) {
393
- return markMigrationItemError(item, "config runtime unavailable");
394
- }
395
- const value = buildCodexPluginsConfigValue(entries, { config: currentConfig });
396
- if (!ctx.overwrite && hasCodexPluginConfigConflict(currentConfig, value)) {
397
- return markMigrationItemConflict(item, MIGRATION_REASON_TARGET_EXISTS);
398
- }
399
- const migratedItem: MigrationItem = {
400
- ...item,
401
- status: "migrated",
402
- details: {
403
- ...item.details,
404
- path: [...CODEX_PLUGIN_CONFIG_PATH],
405
- value,
406
- },
407
- };
408
- if (returnPatch) {
409
- return migratedItem;
410
- }
411
- if (!configApi?.mutateConfigFile) {
412
- return markMigrationItemError(item, "config runtime unavailable");
413
- }
414
- try {
415
- await configApi.mutateConfigFile({
416
- base: "runtime",
417
- afterWrite: { mode: "auto" },
418
- mutate(draft) {
419
- if (!ctx.overwrite && hasCodexPluginConfigConflict(draft, value)) {
420
- throw new CodexPluginConfigConflictError(MIGRATION_REASON_TARGET_EXISTS);
421
- }
422
- writeMigrationConfigPath(draft as Record<string, unknown>, CODEX_PLUGIN_CONFIG_PATH, value);
423
- },
424
- });
425
- return migratedItem;
426
- } catch (error) {
427
- if (error instanceof CodexPluginConfigConflictError) {
428
- return markMigrationItemConflict(item, error.reason);
429
- }
430
- return markMigrationItemError(item, error instanceof Error ? error.message : String(error));
431
- }
432
- }
433
-
434
- function readAppliedPluginConfigEntry(
435
- item: MigrationItem,
436
- ): CodexPluginMigrationConfigEntry | undefined {
437
- if (item.status === "migrated") {
438
- return readCodexPluginMigrationConfigEntry(item, true);
439
- }
440
- if (
441
- item.status === "skipped" &&
442
- item.reason !== CODEX_PLUGIN_NOT_SELECTED_REASON &&
443
- item.reason === CODEX_PLUGIN_AUTH_REQUIRED_REASON
444
- ) {
445
- return readCodexPluginMigrationConfigEntry(item, false);
446
- }
447
- return undefined;
448
- }
449
-
450
- function readCodexPluginPolicy(item: MigrationItem): ResolvedCodexPluginPolicy | undefined {
451
- const configKey = item.details?.configKey;
452
- const marketplaceName = item.details?.marketplaceName;
453
- const pluginName = item.details?.pluginName;
454
- if (
455
- typeof configKey !== "string" ||
456
- marketplaceName !== CODEX_PLUGINS_MARKETPLACE_NAME ||
457
- typeof pluginName !== "string"
458
- ) {
459
- return undefined;
460
- }
461
- return {
462
- configKey,
463
- marketplaceName: CODEX_PLUGINS_MARKETPLACE_NAME,
464
- pluginName,
465
- enabled: true,
466
- allowDestructiveActions: true,
467
- };
468
- }
469
-
470
- function codexPluginActivationReportState(result: CodexPluginActivationResult): {
471
- installed?: boolean;
472
- enabled?: boolean;
473
- } {
474
- switch (result.reason) {
475
- case "already_active":
476
- case "installed":
477
- return { installed: true, enabled: true };
478
- case "auth_required":
479
- return { installed: true, enabled: false };
480
- case "disabled":
481
- case "marketplace_missing":
482
- case "plugin_missing":
483
- return { installed: false, enabled: false };
484
- case "refresh_failed":
485
- return { installed: true, enabled: false };
486
- }
487
- const exhaustiveReason: never = result.reason;
488
- return exhaustiveReason;
489
- }
490
-
491
- function sanitizeAppsNeedingAuth(apps: readonly v2.AppSummary[]): Array<{
492
- id: string;
493
- name: string;
494
- needsAuth: boolean;
495
- }> {
496
- return apps.map((app) => ({
497
- id: app.id,
498
- name: app.name,
499
- needsAuth: app.needsAuth,
500
- }));
501
- }
@@ -1,55 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { readJsonFileWithFallback } from "klaw/plugin-sdk/json-store";
5
- import { pathExists } from "klaw/plugin-sdk/security-runtime";
6
-
7
- export async function exists(filePath: string): Promise<boolean> {
8
- return await pathExists(filePath);
9
- }
10
-
11
- export async function isDirectory(filePath: string | undefined): Promise<boolean> {
12
- if (!filePath) {
13
- return false;
14
- }
15
- try {
16
- return (await fs.stat(filePath)).isDirectory();
17
- } catch {
18
- return false;
19
- }
20
- }
21
-
22
- export function resolveUserHomeDir(): string {
23
- return process.env.HOME?.trim() || os.homedir();
24
- }
25
-
26
- export function resolveHomePath(value: string): string {
27
- if (value === "~") {
28
- return resolveUserHomeDir();
29
- }
30
- if (value.startsWith("~/")) {
31
- return path.join(resolveUserHomeDir(), value.slice(2));
32
- }
33
- return path.resolve(value);
34
- }
35
-
36
- export function sanitizeName(value: string): string {
37
- return value
38
- .trim()
39
- .toLowerCase()
40
- .replaceAll(/[^a-z0-9._-]+/gu, "-")
41
- .replaceAll(/^-+|-+$/gu, "")
42
- .slice(0, 64);
43
- }
44
-
45
- export async function readJsonObject(
46
- filePath: string | undefined,
47
- ): Promise<Record<string, unknown>> {
48
- if (!filePath) {
49
- return {};
50
- }
51
- const { value: parsed } = await readJsonFileWithFallback<unknown>(filePath, {});
52
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
53
- ? (parsed as Record<string, unknown>)
54
- : {};
55
- }