@gakr-gakr/codex 0.1.0

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 (86) hide show
  1. package/autobot.plugin.json +374 -0
  2. package/doctor-contract-api.ts +68 -0
  3. package/harness.ts +72 -0
  4. package/index.ts +124 -0
  5. package/media-understanding-provider.ts +521 -0
  6. package/package.json +40 -0
  7. package/prompt-overlay.ts +21 -0
  8. package/provider-catalog.ts +83 -0
  9. package/provider-discovery.ts +45 -0
  10. package/provider.ts +243 -0
  11. package/src/app-server/app-inventory-cache.ts +324 -0
  12. package/src/app-server/approval-bridge.ts +1211 -0
  13. package/src/app-server/auth-bridge.ts +614 -0
  14. package/src/app-server/capabilities.ts +27 -0
  15. package/src/app-server/client-factory.ts +24 -0
  16. package/src/app-server/client.ts +715 -0
  17. package/src/app-server/compact.ts +512 -0
  18. package/src/app-server/computer-use.ts +683 -0
  19. package/src/app-server/config.ts +1038 -0
  20. package/src/app-server/context-engine-projection.ts +403 -0
  21. package/src/app-server/dynamic-tool-diagnostics.ts +73 -0
  22. package/src/app-server/dynamic-tool-profile.ts +70 -0
  23. package/src/app-server/dynamic-tools.ts +623 -0
  24. package/src/app-server/elicitation-bridge.ts +783 -0
  25. package/src/app-server/event-projector.ts +2065 -0
  26. package/src/app-server/image-payload-sanitizer.ts +167 -0
  27. package/src/app-server/local-runtime-attribution.ts +39 -0
  28. package/src/app-server/managed-binary.ts +193 -0
  29. package/src/app-server/models.ts +172 -0
  30. package/src/app-server/native-hook-relay.ts +150 -0
  31. package/src/app-server/native-subagent-task-mirror.ts +497 -0
  32. package/src/app-server/plugin-activation.ts +283 -0
  33. package/src/app-server/plugin-app-cache-key.ts +74 -0
  34. package/src/app-server/plugin-approval-roundtrip.ts +122 -0
  35. package/src/app-server/plugin-inventory.ts +357 -0
  36. package/src/app-server/plugin-thread-config.ts +455 -0
  37. package/src/app-server/protocol-generated/json/DynamicToolCallParams.json +33 -0
  38. package/src/app-server/protocol-generated/json/v2/ErrorNotification.json +199 -0
  39. package/src/app-server/protocol-generated/json/v2/GetAccountResponse.json +102 -0
  40. package/src/app-server/protocol-generated/json/v2/ModelListResponse.json +227 -0
  41. package/src/app-server/protocol-generated/json/v2/ThreadResumeResponse.json +2630 -0
  42. package/src/app-server/protocol-generated/json/v2/ThreadStartResponse.json +2630 -0
  43. package/src/app-server/protocol-generated/json/v2/TurnCompletedNotification.json +1659 -0
  44. package/src/app-server/protocol-generated/json/v2/TurnStartResponse.json +1655 -0
  45. package/src/app-server/protocol-validators.ts +203 -0
  46. package/src/app-server/protocol.ts +520 -0
  47. package/src/app-server/rate-limit-cache.ts +48 -0
  48. package/src/app-server/rate-limits.ts +583 -0
  49. package/src/app-server/request.ts +73 -0
  50. package/src/app-server/run-attempt.ts +4862 -0
  51. package/src/app-server/session-binding.ts +398 -0
  52. package/src/app-server/session-history.ts +44 -0
  53. package/src/app-server/shared-client.ts +289 -0
  54. package/src/app-server/side-question.ts +1009 -0
  55. package/src/app-server/test-support.ts +48 -0
  56. package/src/app-server/thread-lifecycle.ts +959 -0
  57. package/src/app-server/timeout.ts +9 -0
  58. package/src/app-server/tool-progress-normalization.ts +77 -0
  59. package/src/app-server/trajectory.ts +368 -0
  60. package/src/app-server/transcript-mirror.ts +208 -0
  61. package/src/app-server/transport-stdio.ts +107 -0
  62. package/src/app-server/transport-websocket.ts +90 -0
  63. package/src/app-server/transport.ts +117 -0
  64. package/src/app-server/user-input-bridge.ts +316 -0
  65. package/src/app-server/version.ts +4 -0
  66. package/src/app-server/vision-tools.ts +12 -0
  67. package/src/command-account.ts +544 -0
  68. package/src/command-formatters.ts +426 -0
  69. package/src/command-handlers.ts +2021 -0
  70. package/src/command-plugins-management.ts +137 -0
  71. package/src/command-rpc.ts +142 -0
  72. package/src/commands.ts +65 -0
  73. package/src/conversation-binding-data.ts +124 -0
  74. package/src/conversation-binding.ts +561 -0
  75. package/src/conversation-control.ts +303 -0
  76. package/src/conversation-turn-collector.ts +186 -0
  77. package/src/conversation-turn-input.ts +106 -0
  78. package/src/migration/apply.ts +501 -0
  79. package/src/migration/helpers.ts +55 -0
  80. package/src/migration/plan.ts +461 -0
  81. package/src/migration/provider.ts +41 -0
  82. package/src/migration/source.ts +643 -0
  83. package/src/migration/targets.ts +25 -0
  84. package/src/node-cli-sessions.ts +711 -0
  85. package/test-api.ts +95 -0
  86. package/tsconfig.json +16 -0
@@ -0,0 +1,283 @@
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
+ }
@@ -0,0 +1,74 @@
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("autobot: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
+ }
@@ -0,0 +1,122 @@
1
+ import {
2
+ callGatewayTool,
3
+ type EmbeddedRunAttemptParams,
4
+ } from "autobot/plugin-sdk/agent-harness-runtime";
5
+
6
+ const DEFAULT_CODEX_APPROVAL_TIMEOUT_MS = 120_000;
7
+ const MAX_PLUGIN_APPROVAL_TITLE_LENGTH = 80;
8
+ const MAX_PLUGIN_APPROVAL_DESCRIPTION_LENGTH = 256;
9
+
10
+ type ExecApprovalDecision = "allow-once" | "allow-always" | "deny";
11
+
12
+ export type AppServerApprovalOutcome =
13
+ | "approved-once"
14
+ | "approved-session"
15
+ | "denied"
16
+ | "unavailable"
17
+ | "cancelled";
18
+
19
+ type ApprovalRequestResult = {
20
+ id?: string;
21
+ decision?: ExecApprovalDecision | null;
22
+ };
23
+
24
+ type ApprovalWaitResult = {
25
+ id?: string;
26
+ decision?: ExecApprovalDecision | null;
27
+ };
28
+
29
+ export async function requestPluginApproval(params: {
30
+ paramsForRun: EmbeddedRunAttemptParams;
31
+ title: string;
32
+ description: string;
33
+ severity: "info" | "warning";
34
+ toolName: string;
35
+ toolCallId?: string;
36
+ }): Promise<ApprovalRequestResult | undefined> {
37
+ const timeoutMs = DEFAULT_CODEX_APPROVAL_TIMEOUT_MS;
38
+ return callGatewayTool(
39
+ "plugin.approval.request",
40
+ { timeoutMs: timeoutMs + 10_000 },
41
+ {
42
+ pluginId: "autobot-codex-app-server",
43
+ title: truncateForGateway(params.title, MAX_PLUGIN_APPROVAL_TITLE_LENGTH),
44
+ description: truncateForGateway(params.description, MAX_PLUGIN_APPROVAL_DESCRIPTION_LENGTH),
45
+ severity: params.severity,
46
+ toolName: params.toolName,
47
+ toolCallId: params.toolCallId,
48
+ agentId: params.paramsForRun.agentId,
49
+ sessionKey: params.paramsForRun.sessionKey,
50
+ turnSourceChannel: params.paramsForRun.messageChannel ?? params.paramsForRun.messageProvider,
51
+ turnSourceTo: params.paramsForRun.currentChannelId,
52
+ turnSourceAccountId: params.paramsForRun.agentAccountId,
53
+ turnSourceThreadId: params.paramsForRun.currentThreadTs,
54
+ timeoutMs,
55
+ twoPhase: true,
56
+ },
57
+ { expectFinal: false },
58
+ ) as Promise<ApprovalRequestResult | undefined>;
59
+ }
60
+
61
+ export function approvalRequestExplicitlyUnavailable(result: unknown): boolean {
62
+ if (result === null || result === undefined || typeof result !== "object") {
63
+ return false;
64
+ }
65
+ let descriptor: PropertyDescriptor | undefined;
66
+ try {
67
+ descriptor = Object.getOwnPropertyDescriptor(result, "decision");
68
+ } catch {
69
+ return false;
70
+ }
71
+ return descriptor !== undefined && "value" in descriptor && descriptor.value === null;
72
+ }
73
+
74
+ export async function waitForPluginApprovalDecision(params: {
75
+ approvalId: string;
76
+ signal?: AbortSignal;
77
+ }): Promise<ExecApprovalDecision | null | undefined> {
78
+ const timeoutMs = DEFAULT_CODEX_APPROVAL_TIMEOUT_MS;
79
+ const waitPromise: Promise<ApprovalWaitResult | undefined> = callGatewayTool(
80
+ "plugin.approval.waitDecision",
81
+ { timeoutMs: timeoutMs + 10_000 },
82
+ { id: params.approvalId },
83
+ );
84
+ if (!params.signal) {
85
+ return (await waitPromise)?.decision;
86
+ }
87
+ let onAbort: (() => void) | undefined;
88
+ const abortPromise = new Promise<never>((_, reject) => {
89
+ if (params.signal!.aborted) {
90
+ reject(params.signal!.reason);
91
+ return;
92
+ }
93
+ onAbort = () => reject(params.signal!.reason);
94
+ params.signal!.addEventListener("abort", onAbort, { once: true });
95
+ });
96
+ try {
97
+ return (await Promise.race([waitPromise, abortPromise]))?.decision;
98
+ } finally {
99
+ if (onAbort) {
100
+ params.signal.removeEventListener("abort", onAbort);
101
+ }
102
+ }
103
+ }
104
+
105
+ export function mapExecDecisionToOutcome(
106
+ decision: ExecApprovalDecision | null | undefined,
107
+ ): AppServerApprovalOutcome {
108
+ if (decision === "allow-once") {
109
+ return "approved-once";
110
+ }
111
+ if (decision === "allow-always") {
112
+ return "approved-session";
113
+ }
114
+ if (decision === null || decision === undefined) {
115
+ return "unavailable";
116
+ }
117
+ return "denied";
118
+ }
119
+
120
+ function truncateForGateway(value: string, maxLength: number): string {
121
+ return value.length <= maxLength ? value : `${value.slice(0, Math.max(0, maxLength - 3))}...`;
122
+ }