@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
@@ -1,623 +0,0 @@
1
- import type { AgentToolResult } from "@earendil-works/pi-agent-core";
2
- import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
3
- import {
4
- createAgentToolResultMiddlewareRunner,
5
- createCodexAppServerToolResultExtensionRunner,
6
- extractToolResultMediaArtifact,
7
- filterToolResultMediaUrls,
8
- HEARTBEAT_RESPONSE_TOOL_NAME,
9
- type EmbeddedRunAttemptParams,
10
- isToolWrappedWithBeforeToolCallHook,
11
- isMessagingTool,
12
- isMessagingToolSendAction,
13
- normalizeHeartbeatToolResponse,
14
- runAgentHarnessAfterToolCallHook,
15
- setBeforeToolCallDiagnosticsEnabled,
16
- type AnyAgentTool,
17
- type HeartbeatToolResponse,
18
- type MessagingToolSend,
19
- type MessagingToolSourceReplyPayload,
20
- wrapToolWithBeforeToolCallHook,
21
- } from "autobot/plugin-sdk/agent-harness-runtime";
22
- import { normalizeAgentId } from "autobot/plugin-sdk/routing";
23
- import type { CodexDynamicToolsLoading } from "./config.js";
24
- import { invalidInlineImageText, sanitizeInlineImageDataUrl } from "./image-payload-sanitizer.js";
25
- import {
26
- type CodexDynamicToolCallOutputContentItem,
27
- type CodexDynamicToolCallParams,
28
- type CodexDynamicToolCallResponse,
29
- type CodexDynamicToolDiagnosticTerminalType,
30
- type CodexDynamicToolSpec,
31
- type JsonValue,
32
- } from "./protocol.js";
33
-
34
- type CodexDynamicToolHookContext = {
35
- agentId?: string;
36
- config?: EmbeddedRunAttemptParams["config"];
37
- sessionId?: string;
38
- sessionKey?: string;
39
- runId?: string;
40
- channelId?: string;
41
- };
42
-
43
- type CodexToolResultHookContext = Omit<CodexDynamicToolHookContext, "config">;
44
-
45
- export type CodexDynamicToolBridge = {
46
- specs: CodexDynamicToolSpec[];
47
- handleToolCall: (
48
- params: CodexDynamicToolCallParams,
49
- options?: { signal?: AbortSignal },
50
- ) => Promise<CodexDynamicToolCallResponse>;
51
- telemetry: {
52
- didSendViaMessagingTool: boolean;
53
- messagingToolSentTexts: string[];
54
- messagingToolSentMediaUrls: string[];
55
- messagingToolSentTargets: MessagingToolSend[];
56
- messagingToolSourceReplyPayloads: MessagingToolSourceReplyPayload[];
57
- heartbeatToolResponse?: HeartbeatToolResponse;
58
- toolMediaUrls: string[];
59
- toolAudioAsVoice: boolean;
60
- successfulCronAdds?: number;
61
- };
62
- };
63
-
64
- export const CODEX_AUTOBOT_DYNAMIC_TOOL_NAMESPACE = "autobot";
65
-
66
- // Keep AutoBot session spawning searchable in Codex mode so Codex's native
67
- // spawn_agent remains the primary Codex subagent surface.
68
- const ALWAYS_DIRECT_DYNAMIC_TOOL_NAMES = new Set(["sessions_yield"]);
69
- const DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS = 16_000;
70
-
71
- export function createCodexDynamicToolBridge(params: {
72
- tools: AnyAgentTool[];
73
- signal: AbortSignal;
74
- hookContext?: CodexDynamicToolHookContext;
75
- loading?: CodexDynamicToolsLoading;
76
- directToolNames?: Iterable<string>;
77
- }): CodexDynamicToolBridge {
78
- const toolResultHookContext = toToolResultHookContext(params.hookContext);
79
- const toolResultMaxChars = resolveCodexDynamicToolResultMaxChars(params.hookContext);
80
- const tools = params.tools.map((tool) => {
81
- if (isToolWrappedWithBeforeToolCallHook(tool)) {
82
- setBeforeToolCallDiagnosticsEnabled(tool, false);
83
- return tool;
84
- }
85
- return wrapToolWithBeforeToolCallHook(tool, params.hookContext, { emitDiagnostics: false });
86
- });
87
- const toolMap = new Map(tools.map((tool) => [tool.name, tool]));
88
- const telemetry: CodexDynamicToolBridge["telemetry"] = {
89
- didSendViaMessagingTool: false,
90
- messagingToolSentTexts: [],
91
- messagingToolSentMediaUrls: [],
92
- messagingToolSentTargets: [],
93
- messagingToolSourceReplyPayloads: [],
94
- toolMediaUrls: [],
95
- toolAudioAsVoice: false,
96
- };
97
- const middlewareRunner = createAgentToolResultMiddlewareRunner({
98
- runtime: "codex",
99
- ...toolResultHookContext,
100
- });
101
- const legacyExtensionRunner =
102
- createCodexAppServerToolResultExtensionRunner(toolResultHookContext);
103
- const directToolNames = new Set([
104
- ...ALWAYS_DIRECT_DYNAMIC_TOOL_NAMES,
105
- ...(params.directToolNames ?? []),
106
- ]);
107
-
108
- return {
109
- specs: tools.map((tool) =>
110
- createCodexDynamicToolSpec({
111
- tool,
112
- loading: params.loading ?? "searchable",
113
- directToolNames,
114
- }),
115
- ),
116
- telemetry,
117
- handleToolCall: async (call, options) => {
118
- const tool = toolMap.get(call.tool);
119
- if (!tool) {
120
- return {
121
- contentItems: [{ type: "inputText", text: `Unknown AutoBot tool: ${call.tool}` }],
122
- success: false,
123
- };
124
- }
125
- const args = jsonObjectToRecord(call.arguments);
126
- const startedAt = Date.now();
127
- const signal = composeAbortSignals(params.signal, options?.signal);
128
- try {
129
- const preparedArgs = tool.prepareArguments ? tool.prepareArguments(args) : args;
130
- const rawResult = await tool.execute(call.callId, preparedArgs, signal);
131
- const rawIsError = isToolResultError(rawResult);
132
- const middlewareResult = await middlewareRunner.applyToolResultMiddleware({
133
- threadId: call.threadId,
134
- turnId: call.turnId,
135
- toolCallId: call.callId,
136
- toolName: tool.name,
137
- args,
138
- isError: rawIsError,
139
- result: rawResult,
140
- });
141
- const result = await legacyExtensionRunner.applyToolResultExtensions({
142
- threadId: call.threadId,
143
- turnId: call.turnId,
144
- toolCallId: call.callId,
145
- toolName: tool.name,
146
- args,
147
- result: middlewareResult,
148
- });
149
- const resultIsError = rawIsError || isToolResultError(result);
150
- collectToolTelemetry({
151
- toolName: tool.name,
152
- args,
153
- result,
154
- mediaTrustResult: rawResult,
155
- telemetry,
156
- isError: resultIsError,
157
- });
158
- void runAgentHarnessAfterToolCallHook({
159
- toolName: tool.name,
160
- toolCallId: call.callId,
161
- runId: toolResultHookContext.runId,
162
- agentId: toolResultHookContext.agentId,
163
- sessionId: toolResultHookContext.sessionId,
164
- sessionKey: toolResultHookContext.sessionKey,
165
- channelId: toolResultHookContext.channelId,
166
- startArgs: args,
167
- result,
168
- startedAt,
169
- });
170
- return withDiagnosticTerminalType(
171
- {
172
- contentItems: convertToolContents(result.content, toolResultMaxChars),
173
- success: !resultIsError,
174
- },
175
- inferToolResultDiagnosticTerminalType(result, resultIsError),
176
- );
177
- } catch (error) {
178
- collectToolTelemetry({
179
- toolName: tool.name,
180
- args,
181
- result: undefined,
182
- telemetry,
183
- isError: true,
184
- });
185
- void runAgentHarnessAfterToolCallHook({
186
- toolName: tool.name,
187
- toolCallId: call.callId,
188
- runId: toolResultHookContext.runId,
189
- agentId: toolResultHookContext.agentId,
190
- sessionId: toolResultHookContext.sessionId,
191
- sessionKey: toolResultHookContext.sessionKey,
192
- channelId: toolResultHookContext.channelId,
193
- startArgs: args,
194
- error: error instanceof Error ? error.message : String(error),
195
- startedAt,
196
- });
197
- return withDiagnosticTerminalType(
198
- {
199
- contentItems: [
200
- {
201
- type: "inputText",
202
- text: error instanceof Error ? error.message : String(error),
203
- },
204
- ],
205
- success: false,
206
- },
207
- "error",
208
- );
209
- }
210
- },
211
- };
212
- }
213
-
214
- function createCodexDynamicToolSpec(params: {
215
- tool: AnyAgentTool;
216
- loading: CodexDynamicToolsLoading;
217
- directToolNames: ReadonlySet<string>;
218
- }): CodexDynamicToolSpec {
219
- const base = {
220
- name: params.tool.name,
221
- description: params.tool.description,
222
- inputSchema: toJsonValue(params.tool.parameters),
223
- };
224
- if (params.loading === "direct" || params.directToolNames.has(params.tool.name)) {
225
- return base;
226
- }
227
- return {
228
- ...base,
229
- namespace: CODEX_AUTOBOT_DYNAMIC_TOOL_NAMESPACE,
230
- deferLoading: true,
231
- };
232
- }
233
-
234
- function toToolResultHookContext(
235
- ctx: CodexDynamicToolHookContext | undefined,
236
- ): CodexToolResultHookContext {
237
- const { agentId, sessionId, sessionKey, runId, channelId } = ctx ?? {};
238
- return {
239
- ...(agentId && { agentId }),
240
- ...(sessionId && { sessionId }),
241
- ...(sessionKey && { sessionKey }),
242
- ...(runId && { runId }),
243
- ...(channelId && { channelId }),
244
- };
245
- }
246
-
247
- function resolveCodexDynamicToolResultMaxChars(
248
- ctx: CodexDynamicToolHookContext | undefined,
249
- ): number {
250
- const configured = resolveAgentContextLimitValue({
251
- config: ctx?.config,
252
- agentId: ctx?.agentId,
253
- key: "toolResultMaxChars",
254
- });
255
- return configured ?? DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS;
256
- }
257
-
258
- function resolveAgentContextLimitValue(params: {
259
- config: EmbeddedRunAttemptParams["config"] | undefined;
260
- agentId?: string;
261
- key: string;
262
- }): number | undefined {
263
- const agents = readRecord(params.config?.agents);
264
- const defaults = readRecord(readRecord(agents?.defaults)?.contextLimits);
265
- const defaultValue = readPositiveInteger(defaults?.[params.key]);
266
- if (!params.agentId) {
267
- return defaultValue;
268
- }
269
- const list = agents?.list;
270
- if (!Array.isArray(list)) {
271
- return defaultValue;
272
- }
273
- const normalizedAgentId = normalizeAgentId(params.agentId);
274
- const agent = list.find((entry) => {
275
- const entryId = readRecord(entry)?.id;
276
- return typeof entryId === "string" && normalizeAgentId(entryId) === normalizedAgentId;
277
- });
278
- const agentValue = readPositiveInteger(
279
- readRecord(readRecord(agent)?.contextLimits)?.[params.key],
280
- );
281
- return agentValue ?? defaultValue;
282
- }
283
-
284
- function composeAbortSignals(...signals: Array<AbortSignal | undefined>): AbortSignal {
285
- const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
286
- if (activeSignals.length === 0) {
287
- return new AbortController().signal;
288
- }
289
- if (activeSignals.length === 1) {
290
- return activeSignals[0];
291
- }
292
- return AbortSignal.any(activeSignals);
293
- }
294
-
295
- function collectToolTelemetry(params: {
296
- toolName: string;
297
- args: Record<string, unknown>;
298
- result: AgentToolResult<unknown> | undefined;
299
- mediaTrustResult?: AgentToolResult<unknown>;
300
- telemetry: CodexDynamicToolBridge["telemetry"];
301
- isError: boolean;
302
- }): void {
303
- if (params.isError) {
304
- return;
305
- }
306
- if (!params.isError && params.toolName === "cron" && isCronAddAction(params.args)) {
307
- params.telemetry.successfulCronAdds = (params.telemetry.successfulCronAdds ?? 0) + 1;
308
- }
309
- if (!params.isError && params.toolName === HEARTBEAT_RESPONSE_TOOL_NAME) {
310
- const response = normalizeHeartbeatToolResponse(params.result?.details);
311
- if (response) {
312
- params.telemetry.heartbeatToolResponse = response;
313
- }
314
- }
315
- if (!params.isError && params.result) {
316
- const media = extractToolResultMediaArtifact(params.result);
317
- if (media) {
318
- const mediaUrls = filterToolResultMediaUrls(
319
- params.toolName,
320
- media.mediaUrls,
321
- params.mediaTrustResult ?? params.result,
322
- );
323
- const seen = new Set(params.telemetry.toolMediaUrls);
324
- for (const mediaUrl of mediaUrls) {
325
- if (!seen.has(mediaUrl)) {
326
- seen.add(mediaUrl);
327
- params.telemetry.toolMediaUrls.push(mediaUrl);
328
- }
329
- }
330
- if (media.audioAsVoice) {
331
- params.telemetry.toolAudioAsVoice = true;
332
- }
333
- }
334
- }
335
- if (
336
- !isMessagingTool(params.toolName) ||
337
- !isMessagingToolSendAction(params.toolName, params.args)
338
- ) {
339
- return;
340
- }
341
- params.telemetry.didSendViaMessagingTool = true;
342
- const sourceReplyPayload = extractInternalSourceReplyPayload(params.result?.details);
343
- if (sourceReplyPayload) {
344
- params.telemetry.messagingToolSourceReplyPayloads.push(sourceReplyPayload);
345
- return;
346
- }
347
- const text = readFirstString(params.args, ["text", "message", "body", "content"]);
348
- if (text) {
349
- params.telemetry.messagingToolSentTexts.push(text);
350
- }
351
- const mediaUrls = collectMediaUrls(params.args);
352
- params.telemetry.messagingToolSentMediaUrls.push(...mediaUrls);
353
- params.telemetry.messagingToolSentTargets.push({
354
- tool: params.toolName,
355
- provider: readFirstString(params.args, ["provider", "channel"]) ?? params.toolName,
356
- accountId: readFirstString(params.args, ["accountId", "account_id"]),
357
- to: readFirstString(params.args, ["to", "target", "recipient"]),
358
- threadId: readFirstString(params.args, ["threadId", "thread_id", "messageThreadId"]),
359
- ...(text ? { text } : {}),
360
- ...(mediaUrls.length > 0 ? { mediaUrls } : {}),
361
- });
362
- }
363
-
364
- function extractInternalSourceReplyPayload(
365
- details: unknown,
366
- ): MessagingToolSourceReplyPayload | undefined {
367
- if (!isRecord(details) || details.sourceReplySink !== "internal-ui") {
368
- return undefined;
369
- }
370
- const rawPayload = details.sourceReply;
371
- if (!isRecord(rawPayload)) {
372
- return undefined;
373
- }
374
- const text = readFirstString(rawPayload, ["text", "message"]);
375
- const mediaUrls = collectMediaUrls(rawPayload);
376
- const mediaUrl =
377
- typeof rawPayload.mediaUrl === "string" && rawPayload.mediaUrl.trim()
378
- ? rawPayload.mediaUrl.trim()
379
- : mediaUrls[0];
380
- const payload: MessagingToolSourceReplyPayload = {
381
- ...(text ? { text } : {}),
382
- ...(mediaUrl ? { mediaUrl } : {}),
383
- ...(mediaUrls.length > 0 ? { mediaUrls } : {}),
384
- ...(rawPayload.audioAsVoice === true ? { audioAsVoice: true } : {}),
385
- ...(isRecord(rawPayload.presentation)
386
- ? { presentation: rawPayload.presentation as never }
387
- : {}),
388
- ...(isRecord(rawPayload.interactive) ? { interactive: rawPayload.interactive as never } : {}),
389
- ...(isRecord(rawPayload.channelData) ? { channelData: rawPayload.channelData } : {}),
390
- ...(typeof details.idempotencyKey === "string" && details.idempotencyKey.trim()
391
- ? { idempotencyKey: details.idempotencyKey.trim() }
392
- : {}),
393
- };
394
- return text || mediaUrls.length > 0 || payload.presentation || payload.interactive
395
- ? payload
396
- : undefined;
397
- }
398
-
399
- function isRecord(value: unknown): value is Record<string, unknown> {
400
- return value !== null && typeof value === "object" && !Array.isArray(value);
401
- }
402
-
403
- function readRecord(value: unknown): Record<string, unknown> | undefined {
404
- return isRecord(value) ? value : undefined;
405
- }
406
-
407
- function readPositiveInteger(value: unknown): number | undefined {
408
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
409
- return undefined;
410
- }
411
- return Math.floor(value);
412
- }
413
-
414
- function isToolResultError(result: AgentToolResult<unknown>): boolean {
415
- const details = result.details;
416
- if (!isRecord(details)) {
417
- return false;
418
- }
419
- if (details.timedOut === true) {
420
- return true;
421
- }
422
- if (typeof details.exitCode === "number" && details.exitCode !== 0) {
423
- return true;
424
- }
425
- if (typeof details.status !== "string") {
426
- return false;
427
- }
428
- const status = details.status.trim().toLowerCase();
429
- return (
430
- status !== "" &&
431
- status !== "0" &&
432
- status !== "ok" &&
433
- status !== "success" &&
434
- status !== "completed" &&
435
- status !== "recorded" &&
436
- status !== "running"
437
- );
438
- }
439
-
440
- function inferToolResultDiagnosticTerminalType(
441
- result: AgentToolResult<unknown>,
442
- isError: boolean,
443
- ): CodexDynamicToolDiagnosticTerminalType {
444
- const details = result.details;
445
- if (isRecord(details) && typeof details.status === "string") {
446
- const status = details.status.trim().toLowerCase();
447
- if (status === "blocked") {
448
- return "blocked";
449
- }
450
- }
451
- return isError ? "error" : "completed";
452
- }
453
-
454
- function withDiagnosticTerminalType<T extends CodexDynamicToolCallResponse>(
455
- response: T,
456
- terminalType: CodexDynamicToolDiagnosticTerminalType,
457
- ): T {
458
- Object.defineProperty(response, "diagnosticTerminalType", {
459
- configurable: true,
460
- enumerable: false,
461
- value: terminalType,
462
- });
463
- return response;
464
- }
465
-
466
- function normalizeToolResultMaxChars(maxChars: number): number {
467
- return typeof maxChars === "number" && Number.isFinite(maxChars) && maxChars > 0
468
- ? Math.floor(maxChars)
469
- : DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS;
470
- }
471
-
472
- function convertToolContents(
473
- content: Array<TextContent | ImageContent>,
474
- toolResultMaxChars = DEFAULT_CODEX_DYNAMIC_TOOL_RESULT_MAX_CHARS,
475
- ): CodexDynamicToolCallOutputContentItem[] {
476
- const maxChars = normalizeToolResultMaxChars(toolResultMaxChars);
477
- const totalTextChars = content.reduce(
478
- (total, item) => total + (item.type === "text" ? item.text.length : 0),
479
- 0,
480
- );
481
- if (totalTextChars <= maxChars) {
482
- return content.flatMap(convertToolContent);
483
- }
484
-
485
- const noticeText = `...(AutoBot truncated dynamic tool result: original ${totalTextChars} chars, showing ${maxChars}; rerun with narrower args.)`;
486
- const notice = `\n${noticeText}`;
487
- const textBudget = Math.max(0, maxChars - notice.length);
488
- let remainingTextBudget = textBudget;
489
- let appendedNotice = false;
490
- const output: CodexDynamicToolCallOutputContentItem[] = [];
491
-
492
- for (const item of content) {
493
- if (item.type !== "text") {
494
- output.push(...convertToolContent(item));
495
- continue;
496
- }
497
- if (appendedNotice) {
498
- continue;
499
- }
500
- if (notice.length >= maxChars) {
501
- output.push({ type: "inputText", text: noticeText.slice(0, maxChars) });
502
- appendedNotice = true;
503
- continue;
504
- }
505
- const sliceLength = Math.min(item.text.length, remainingTextBudget);
506
- remainingTextBudget -= sliceLength;
507
- const shouldAppendNotice = remainingTextBudget <= 0;
508
- const text = item.text.slice(0, sliceLength);
509
- if (shouldAppendNotice) {
510
- output.push({ type: "inputText", text: `${text.trimEnd()}${notice}`.slice(0, maxChars) });
511
- appendedNotice = true;
512
- } else if (text.length > 0) {
513
- output.push({ type: "inputText", text });
514
- }
515
- }
516
-
517
- if (!appendedNotice) {
518
- output.push({ type: "inputText", text: noticeText.slice(0, maxChars) });
519
- }
520
- return output;
521
- }
522
-
523
- function convertToolContent(
524
- content: TextContent | ImageContent,
525
- ): CodexDynamicToolCallOutputContentItem[] {
526
- if (content.type === "text") {
527
- return [{ type: "inputText", text: content.text }];
528
- }
529
- const imageUrl = sanitizeInlineImageDataUrl(`data:${content.mimeType};base64,${content.data}`);
530
- if (!imageUrl) {
531
- return [{ type: "inputText", text: invalidInlineImageText("codex dynamic tool") }];
532
- }
533
- return [
534
- {
535
- type: "inputImage",
536
- imageUrl,
537
- },
538
- ];
539
- }
540
-
541
- function toJsonValue(value: unknown): JsonValue {
542
- try {
543
- const text = JSON.stringify(value);
544
- if (!text) {
545
- return {};
546
- }
547
- return JSON.parse(text) as JsonValue;
548
- } catch {
549
- return {};
550
- }
551
- }
552
-
553
- function jsonObjectToRecord(value: JsonValue | undefined): Record<string, unknown> {
554
- if (!value || typeof value !== "object" || Array.isArray(value)) {
555
- return {};
556
- }
557
- return value as Record<string, unknown>;
558
- }
559
-
560
- function readFirstString(record: Record<string, unknown>, keys: string[]): string | undefined {
561
- for (const key of keys) {
562
- const value = record[key];
563
- if (typeof value === "string" && value.trim()) {
564
- return value.trim();
565
- }
566
- if (typeof value === "number" && Number.isFinite(value)) {
567
- return String(value);
568
- }
569
- }
570
- return undefined;
571
- }
572
-
573
- function collectMediaUrls(record: Record<string, unknown>): string[] {
574
- const urls: string[] = [];
575
- const pushMediaUrl = (value: unknown) => {
576
- if (typeof value === "string" && value.trim()) {
577
- urls.push(value.trim());
578
- }
579
- };
580
- const pushAttachment = (value: unknown) => {
581
- if (!value || typeof value !== "object" || Array.isArray(value)) {
582
- return;
583
- }
584
- const attachment = value as Record<string, unknown>;
585
- for (const key of ["media", "mediaUrl", "path", "filePath", "fileUrl", "url"]) {
586
- pushMediaUrl(attachment[key]);
587
- }
588
- };
589
- for (const key of [
590
- "media",
591
- "mediaUrl",
592
- "media_url",
593
- "path",
594
- "filePath",
595
- "fileUrl",
596
- "imageUrl",
597
- "image_url",
598
- ]) {
599
- const value = record[key];
600
- pushMediaUrl(value);
601
- }
602
- for (const key of ["mediaUrls", "media_urls", "imageUrls", "image_urls"]) {
603
- const value = record[key];
604
- if (!Array.isArray(value)) {
605
- continue;
606
- }
607
- for (const entry of value) {
608
- pushMediaUrl(entry);
609
- }
610
- }
611
- const attachments = record.attachments;
612
- if (Array.isArray(attachments)) {
613
- for (const attachment of attachments) {
614
- pushAttachment(attachment);
615
- }
616
- }
617
- return urls;
618
- }
619
-
620
- function isCronAddAction(args: Record<string, unknown>): boolean {
621
- const action = args.action;
622
- return typeof action === "string" && action.trim().toLowerCase() === "add";
623
- }