@traceai/codex-sdk 0.0.0-stage → 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 (107) hide show
  1. package/README.md +172 -2
  2. package/dist/esm/attributes.d.ts +101 -0
  3. package/dist/esm/attributes.d.ts.map +1 -0
  4. package/dist/esm/attributes.js +104 -0
  5. package/dist/esm/attributes.js.map +1 -0
  6. package/dist/esm/codexWrapper.d.ts +5 -0
  7. package/dist/esm/codexWrapper.d.ts.map +1 -0
  8. package/dist/esm/codexWrapper.js +63 -0
  9. package/dist/esm/codexWrapper.js.map +1 -0
  10. package/dist/esm/index.d.ts +8 -0
  11. package/dist/esm/index.d.ts.map +1 -0
  12. package/dist/esm/index.js +5 -0
  13. package/dist/esm/index.js.map +1 -0
  14. package/dist/esm/instrumentation.d.ts +85 -0
  15. package/dist/esm/instrumentation.d.ts.map +1 -0
  16. package/dist/esm/instrumentation.js +195 -0
  17. package/dist/esm/instrumentation.js.map +1 -0
  18. package/dist/esm/package.json +1 -0
  19. package/dist/esm/spans.d.ts +152 -0
  20. package/dist/esm/spans.d.ts.map +1 -0
  21. package/dist/esm/spans.js +678 -0
  22. package/dist/esm/spans.js.map +1 -0
  23. package/dist/esm/threadWrapper.d.ts +35 -0
  24. package/dist/esm/threadWrapper.d.ts.map +1 -0
  25. package/dist/esm/threadWrapper.js +208 -0
  26. package/dist/esm/threadWrapper.js.map +1 -0
  27. package/dist/esm/types.d.ts +123 -0
  28. package/dist/esm/types.d.ts.map +1 -0
  29. package/dist/esm/types.js +10 -0
  30. package/dist/esm/types.js.map +1 -0
  31. package/dist/esm/version.d.ts +2 -0
  32. package/dist/esm/version.d.ts.map +1 -0
  33. package/dist/esm/version.js +2 -0
  34. package/dist/esm/version.js.map +1 -0
  35. package/dist/esnext/attributes.d.ts +101 -0
  36. package/dist/esnext/attributes.d.ts.map +1 -0
  37. package/dist/esnext/attributes.js +104 -0
  38. package/dist/esnext/attributes.js.map +1 -0
  39. package/dist/esnext/codexWrapper.d.ts +5 -0
  40. package/dist/esnext/codexWrapper.d.ts.map +1 -0
  41. package/dist/esnext/codexWrapper.js +65 -0
  42. package/dist/esnext/codexWrapper.js.map +1 -0
  43. package/dist/esnext/index.d.ts +8 -0
  44. package/dist/esnext/index.d.ts.map +1 -0
  45. package/dist/esnext/index.js +5 -0
  46. package/dist/esnext/index.js.map +1 -0
  47. package/dist/esnext/instrumentation.d.ts +85 -0
  48. package/dist/esnext/instrumentation.d.ts.map +1 -0
  49. package/dist/esnext/instrumentation.js +200 -0
  50. package/dist/esnext/instrumentation.js.map +1 -0
  51. package/dist/esnext/spans.d.ts +152 -0
  52. package/dist/esnext/spans.d.ts.map +1 -0
  53. package/dist/esnext/spans.js +688 -0
  54. package/dist/esnext/spans.js.map +1 -0
  55. package/dist/esnext/threadWrapper.d.ts +35 -0
  56. package/dist/esnext/threadWrapper.d.ts.map +1 -0
  57. package/dist/esnext/threadWrapper.js +206 -0
  58. package/dist/esnext/threadWrapper.js.map +1 -0
  59. package/dist/esnext/types.d.ts +123 -0
  60. package/dist/esnext/types.d.ts.map +1 -0
  61. package/dist/esnext/types.js +10 -0
  62. package/dist/esnext/types.js.map +1 -0
  63. package/dist/esnext/version.d.ts +2 -0
  64. package/dist/esnext/version.d.ts.map +1 -0
  65. package/dist/esnext/version.js +2 -0
  66. package/dist/esnext/version.js.map +1 -0
  67. package/dist/src/attributes.d.ts +101 -0
  68. package/dist/src/attributes.d.ts.map +1 -0
  69. package/dist/src/attributes.js +107 -0
  70. package/dist/src/attributes.js.map +1 -0
  71. package/dist/src/codexWrapper.d.ts +5 -0
  72. package/dist/src/codexWrapper.d.ts.map +1 -0
  73. package/dist/src/codexWrapper.js +68 -0
  74. package/dist/src/codexWrapper.js.map +1 -0
  75. package/dist/src/index.d.ts +8 -0
  76. package/dist/src/index.d.ts.map +1 -0
  77. package/dist/src/index.js +21 -0
  78. package/dist/src/index.js.map +1 -0
  79. package/dist/src/instrumentation.d.ts +85 -0
  80. package/dist/src/instrumentation.d.ts.map +1 -0
  81. package/dist/src/instrumentation.js +222 -0
  82. package/dist/src/instrumentation.js.map +1 -0
  83. package/dist/src/spans.d.ts +152 -0
  84. package/dist/src/spans.d.ts.map +1 -0
  85. package/dist/src/spans.js +698 -0
  86. package/dist/src/spans.js.map +1 -0
  87. package/dist/src/threadWrapper.d.ts +35 -0
  88. package/dist/src/threadWrapper.d.ts.map +1 -0
  89. package/dist/src/threadWrapper.js +229 -0
  90. package/dist/src/threadWrapper.js.map +1 -0
  91. package/dist/src/types.d.ts +123 -0
  92. package/dist/src/types.d.ts.map +1 -0
  93. package/dist/src/types.js +11 -0
  94. package/dist/src/types.js.map +1 -0
  95. package/dist/src/version.d.ts +2 -0
  96. package/dist/src/version.d.ts.map +1 -0
  97. package/dist/src/version.js +5 -0
  98. package/dist/src/version.js.map +1 -0
  99. package/package.json +76 -3
  100. package/src/attributes.ts +113 -0
  101. package/src/codexWrapper.ts +71 -0
  102. package/src/index.ts +27 -0
  103. package/src/instrumentation.ts +227 -0
  104. package/src/spans.ts +729 -0
  105. package/src/threadWrapper.ts +221 -0
  106. package/src/types.ts +113 -0
  107. package/src/version.ts +1 -0
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Span names and attribute keys for Codex SDK spans.
3
+ *
4
+ * Standard keys (`fi.span.kind`, `session.id`, `input.value`, token counts...)
5
+ * come from `@traceai/fi-semantic-conventions` so the Future AGI collector
6
+ * promotes them. `codex.*` keys carry the SDK's own structural fields.
7
+ */
8
+ import { FISpanKind, SemanticConventions } from "@traceai/fi-semantic-conventions";
9
+
10
+ export const SpanNames = {
11
+ TURN: "codex.turn",
12
+ AGENT_MESSAGE: "codex.agent_message",
13
+ REASONING: "codex.reasoning",
14
+ COMMAND_EXECUTION: "codex.command_execution",
15
+ FILE_CHANGE: "codex.file_change",
16
+ MCP_TOOL_CALL: "codex.mcp_tool_call",
17
+ WEB_SEARCH: "codex.web_search",
18
+ TODO_LIST: "codex.todo_list",
19
+ ERROR: "codex.error",
20
+ } as const;
21
+
22
+ /** SDK item type -> span name and Future AGI span kind. */
23
+ export const ITEM_SPANS: Record<string, { name: string; kind: FISpanKind; tool: boolean }> = {
24
+ agent_message: { name: SpanNames.AGENT_MESSAGE, kind: FISpanKind.LLM, tool: false },
25
+ reasoning: { name: SpanNames.REASONING, kind: FISpanKind.CHAIN, tool: false },
26
+ command_execution: { name: SpanNames.COMMAND_EXECUTION, kind: FISpanKind.TOOL, tool: true },
27
+ file_change: { name: SpanNames.FILE_CHANGE, kind: FISpanKind.TOOL, tool: true },
28
+ mcp_tool_call: { name: SpanNames.MCP_TOOL_CALL, kind: FISpanKind.TOOL, tool: true },
29
+ web_search: { name: SpanNames.WEB_SEARCH, kind: FISpanKind.TOOL, tool: true },
30
+ todo_list: { name: SpanNames.TODO_LIST, kind: FISpanKind.CHAIN, tool: false },
31
+ // Non-fatal: status UNSET with codex.warning=true.
32
+ error: { name: SpanNames.ERROR, kind: FISpanKind.CHAIN, tool: false },
33
+ };
34
+
35
+ /** Fallback for an item type a newer SDK adds. */
36
+ export const UNKNOWN_ITEM_SPAN = { kind: FISpanKind.CHAIN, tool: false };
37
+
38
+ export const CodexAttributes = {
39
+ THREAD_ID: "codex.thread.id",
40
+ THREAD_RESUMED: "codex.thread.resumed",
41
+ SANDBOX_MODE: "codex.sandbox_mode",
42
+ APPROVAL_POLICY: "codex.approval_policy",
43
+ REASONING_EFFORT: "codex.model_reasoning_effort",
44
+ WEB_SEARCH_MODE: "codex.web_search_mode",
45
+ INPUT_IMAGE_COUNT: "codex.input.image_count",
46
+ INPUT_LENGTH: "codex.input.length",
47
+
48
+ ITEM_ID: "codex.item.id",
49
+ ITEM_TYPE: "codex.item.type",
50
+ ITEM_STATUS: "codex.item.status",
51
+ /** false when the SDK sent only `item.completed`; the span then starts at the previous event. */
52
+ ITEM_STARTED_EVENT: "codex.item.started_event",
53
+ ITEM_INCOMPLETE: "codex.item.incomplete",
54
+
55
+ COMMAND_EXIT_CODE: "codex.command.exit_code",
56
+ COMMAND_OUTPUT_LENGTH: "codex.command.output_length",
57
+ FILE_CHANGE_COUNT: "codex.file_change.count",
58
+ FILE_CHANGE_KINDS: "codex.file_change.kinds",
59
+ MCP_SERVER: "codex.mcp.server",
60
+ MCP_TOOL: "codex.mcp.tool",
61
+ TODO_COUNT: "codex.todo.count",
62
+ TODO_COMPLETED: "codex.todo.completed",
63
+ TEXT_LENGTH: "codex.text.length",
64
+
65
+ USAGE_CACHED_INPUT_TOKENS: "codex.usage.cached_input_tokens",
66
+ USAGE_CACHE_WRITE_INPUT_TOKENS: "codex.usage.cache_write_input_tokens",
67
+ USAGE_REASONING_OUTPUT_TOKENS: "codex.usage.reasoning_output_tokens",
68
+ /** A resumed thread's first turn in this process: no earlier total, so nothing promoted. */
69
+ USAGE_BASELINE_UNKNOWN: "codex.usage.baseline_unknown",
70
+ /** The running total went down; the reported value was promoted as is. */
71
+ USAGE_NON_MONOTONIC: "codex.usage.non_monotonic",
72
+ /** Prefix for the thread's running totals, e.g. `codex.cumulative.input_tokens`. */
73
+ CUMULATIVE_PREFIX: "codex.cumulative.",
74
+
75
+ /** Fixed summary unless outputs are visible; see README "Privacy". */
76
+ ERROR_MESSAGE: "codex.error.message",
77
+ /** Error class name of a thrown error, e.g. `Error`, `TypeError`. */
78
+ ERROR_TYPE: "codex.error.type",
79
+ /** `error` events in the turn. Codex sends them for errors it retries; the turn can still complete. */
80
+ STREAM_ERROR_COUNT: "codex.stream_error.count",
81
+ /** On `codex.error` spans: a non-fatal error item (warning, deprecation, model reroute). */
82
+ WARNING: "codex.warning",
83
+ CANCELLED: "codex.cancelled",
84
+ } as const;
85
+
86
+ /** Standard keys used by this package, resolved from fi-semantic-conventions. */
87
+ export const StandardAttributes = {
88
+ FI_SPAN_KIND: SemanticConventions.FI_SPAN_KIND,
89
+ /** Same value as `fi.span.kind`; the Python fi_instrumentation key the collector also reads. */
90
+ GEN_AI_SPAN_KIND: "gen_ai.span.kind",
91
+ SESSION_ID: SemanticConventions.SESSION_ID,
92
+ CONVERSATION_ID: SemanticConventions.GEN_AI_CONVERSATION_ID,
93
+ INPUT_VALUE: SemanticConventions.INPUT_VALUE,
94
+ INPUT_MIME_TYPE: SemanticConventions.INPUT_MIME_TYPE,
95
+ OUTPUT_VALUE: SemanticConventions.OUTPUT_VALUE,
96
+ OUTPUT_MIME_TYPE: SemanticConventions.OUTPUT_MIME_TYPE,
97
+ MODEL_NAME: SemanticConventions.LLM_MODEL_NAME,
98
+ PROVIDER: SemanticConventions.LLM_PROVIDER,
99
+ TOOL_NAME: SemanticConventions.TOOL_NAME,
100
+ GEN_AI_TOOL_NAME: "gen_ai.tool.name",
101
+ TOOL_CALL_ID: "gen_ai.tool.call.id",
102
+ AGENT_NAME: "gen_ai.agent.name",
103
+ INPUT_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT,
104
+ OUTPUT_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_COMPLETION,
105
+ TOTAL_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_TOTAL,
106
+ CACHE_READ_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ,
107
+ CACHE_WRITE_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE,
108
+ REASONING_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING,
109
+ } as const;
110
+
111
+ export const AGENT_NAME = "codex";
112
+ /** Codex talks to the OpenAI Responses API (or an OpenAI-compatible proxy). */
113
+ export const PROVIDER_NAME = "openai";
@@ -0,0 +1,71 @@
1
+ import { diag } from "@opentelemetry/api";
2
+
3
+ const PATCH_RECORD = Symbol.for("@traceai/codex-sdk/client-patch-record");
4
+ const METHODS = ["startThread", "resumeThread"] as const;
5
+ type Client = Record<string | symbol, unknown>;
6
+
7
+ interface Owner {
8
+ active: boolean;
9
+ }
10
+
11
+ interface FactoryPatch {
12
+ method: typeof METHODS[number];
13
+ originalDescriptor: PropertyDescriptor | undefined;
14
+ wrapper: (...args: unknown[]) => object;
15
+ }
16
+
17
+ interface ClientPatch {
18
+ owner: Owner;
19
+ factories: FactoryPatch[];
20
+ }
21
+
22
+ /** Retain neither the client nor a possibly bound original factory in this closure. */
23
+ function weakUndo(ref: WeakRef<Client>, owner: Owner): () => void {
24
+ return () => {
25
+ // Saved wrappers must remain inert even if the instrumentor is enabled again.
26
+ owner.active = false;
27
+ const target = ref.deref();
28
+ if (!target) return;
29
+ const record = Object.getOwnPropertyDescriptor(target, PATCH_RECORD)?.value as ClientPatch | undefined;
30
+ if (record?.owner !== owner) return;
31
+ for (const { method, originalDescriptor, wrapper } of record.factories) {
32
+ try {
33
+ // Inspect the descriptor, not the value: application accessors must not run.
34
+ if (Object.getOwnPropertyDescriptor(target, method)?.value !== wrapper) continue;
35
+ if (originalDescriptor) Object.defineProperty(target, method, originalDescriptor);
36
+ else delete target[method];
37
+ } catch (error) {
38
+ diag.debug(`@traceai/codex-sdk: factory unpatch failed: ${error}`);
39
+ }
40
+ }
41
+ delete target[PATCH_RECORD];
42
+ };
43
+ }
44
+
45
+ /** A client has one active owner, just like a Thread; duplicate owners do not stack. */
46
+ export function patchCodex(target: Client, wrapThread: (thread: object) => object): (() => void) | undefined {
47
+ if ((target[PATCH_RECORD] as ClientPatch | undefined)?.owner.active) return undefined;
48
+ const owner: Owner = { active: true };
49
+ const record: ClientPatch = { owner, factories: [] };
50
+ const undo = weakUndo(new WeakRef(target), owner);
51
+ Object.defineProperty(target, PATCH_RECORD, { value: record, configurable: true });
52
+ try {
53
+ for (const method of METHODS) {
54
+ const original = target[method];
55
+ if (typeof original !== "function") continue;
56
+ const originalDescriptor = Object.getOwnPropertyDescriptor(target, method);
57
+ const wrapper = function tracedThreadFactory(this: unknown, ...args: unknown[]): object {
58
+ const thread = original.apply(this, args);
59
+ return owner.active ? wrapThread(thread) : thread;
60
+ };
61
+ Object.defineProperty(target, method, { value: wrapper, writable: true, configurable: true });
62
+ record.factories.push({ method, originalDescriptor, wrapper });
63
+ }
64
+ } catch (error) {
65
+ undo();
66
+ throw error;
67
+ }
68
+ if (record.factories.length) return undo;
69
+ undo();
70
+ return undefined;
71
+ }
package/src/index.ts ADDED
@@ -0,0 +1,27 @@
1
+ export {
2
+ CodexSDKInstrumentation,
3
+ INSTRUMENTATION_NAME,
4
+ instrumentCodexSDK,
5
+ resolveContentPolicy,
6
+ shutdown,
7
+ } from "./instrumentation";
8
+ export type { CodexSDKInstrumentationConfig } from "./instrumentation";
9
+ export { isPatched } from "./threadWrapper";
10
+ export type { ContentPolicy } from "./spans";
11
+ export {
12
+ AGENT_NAME,
13
+ CodexAttributes,
14
+ ITEM_SPANS,
15
+ PROVIDER_NAME,
16
+ SpanNames,
17
+ StandardAttributes,
18
+ } from "./attributes";
19
+ export type {
20
+ CodexModuleLike,
21
+ ThreadEventLike,
22
+ ThreadItemLike,
23
+ ThreadLike,
24
+ ThreadOptionsLike,
25
+ UsageLike,
26
+ } from "./types";
27
+ export { VERSION } from "./version";
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Public entry points: an instrumentation object that patches the SDK's
3
+ * `Thread` class (or single `Codex` / `Thread` instances), and a `shutdown()`
4
+ * that flushes the tracer provider before a short script exits.
5
+ */
6
+ import { TracerProvider, diag, trace } from "@opentelemetry/api";
7
+ import { FITracer, TraceConfigOptions } from "@traceai/fi-core";
8
+ import { patchCodex } from "./codexWrapper";
9
+ import { ContentPolicy } from "./spans";
10
+ import { TurnTracingContext, patchThread } from "./threadWrapper";
11
+ import { CodexModuleLike, ThreadLike } from "./types";
12
+ import { VERSION } from "./version";
13
+
14
+ export const INSTRUMENTATION_NAME = "@traceai/codex-sdk";
15
+
16
+ /**
17
+ * fi-core env keys. Read fail-closed, unlike fi-core (`value.toLowerCase() ===
18
+ * "true"`): only an explicit `false` (trimmed, any case) opts in to content.
19
+ */
20
+ const FI_HIDE_INPUTS = "FI_HIDE_INPUTS";
21
+ const FI_HIDE_OUTPUTS = "FI_HIDE_OUTPUTS";
22
+ const FI_HIDE_ERROR_DETAILS = "FI_HIDE_ERROR_DETAILS";
23
+
24
+ export interface CodexSDKInstrumentationConfig {
25
+ /** Provider to create spans with. Defaults to the global provider at call time. */
26
+ tracerProvider?: TracerProvider;
27
+ /**
28
+ * fi-core trace config. Unlike fi-core, `hideInputs` and `hideOutputs`
29
+ * default to `true` here: prompts, shell commands, command output, file
30
+ * paths and MCP arguments can contain source code or secrets. Opt in with
31
+ * `false`, or with `FI_HIDE_INPUTS=false` / `FI_HIDE_OUTPUTS=false`.
32
+ */
33
+ traceConfig?: TraceConfigOptions;
34
+ }
35
+
36
+ /** `false` only for an explicit `false`; any other value (or none) keeps content hidden. */
37
+ function envHide(key: string): boolean {
38
+ const value = typeof process !== "undefined" ? process.env?.[key] : undefined;
39
+ return !(typeof value === "string" && value.trim().toLowerCase() === "false");
40
+ }
41
+
42
+ /** Precedence: explicit option > fi-core env var > this package's default (hidden). */
43
+ export function resolveContentPolicy(traceConfig?: TraceConfigOptions): ContentPolicy {
44
+ return {
45
+ hideInputs: traceConfig?.hideInputs ?? envHide(FI_HIDE_INPUTS),
46
+ hideOutputs: traceConfig?.hideOutputs ?? envHide(FI_HIDE_OUTPUTS),
47
+ hideErrorDetails: traceConfig?.hideErrorDetails ?? envHide(FI_HIDE_ERROR_DETAILS),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Traces `@openai/codex-sdk` turns.
53
+ *
54
+ * ```ts
55
+ * import * as CodexSDK from "@openai/codex-sdk";
56
+ * const instrumentation = new CodexSDKInstrumentation({ tracerProvider });
57
+ * instrumentation.manuallyInstrument(CodexSDK);
58
+ * const thread = new CodexSDK.Codex().startThread();
59
+ * await thread.run("..."); // one codex.turn trace
60
+ * ```
61
+ *
62
+ * The SDK is ESM-only, so its module namespace cannot be patched; its `Thread`
63
+ * class prototype can. `wrapCodex()` / `wrapThread()` patch single instances
64
+ * instead, for apps that prefer not to touch the shared class.
65
+ *
66
+ * This is not an OpenTelemetry `InstrumentationBase`: there is no module to
67
+ * hook on `require`/`import`, so it cannot be passed to
68
+ * `registerInstrumentations()`. Call `manuallyInstrument()` or the wrap methods.
69
+ */
70
+ export class CodexSDKInstrumentation {
71
+ private tracerProvider?: TracerProvider;
72
+ private readonly traceConfig?: TraceConfigOptions;
73
+ /** Undo functions for class patches. */
74
+ private readonly undo: Array<() => void> = [];
75
+ /** Client undo functions hold only WeakRefs; collected clients release their bookkeeping. */
76
+ private readonly clientUndo = new Set<() => void>();
77
+ private readonly clientFinalizer = new FinalizationRegistry<() => void>((undo) => {
78
+ // Deactivate the owner too: saved factories must remain inert after collection.
79
+ undo();
80
+ this.clientUndo.delete(undo);
81
+ });
82
+ /** Thread undo functions hold only WeakRefs; collected threads release their bookkeeping. */
83
+ private readonly threadUndo = new Set<() => void>();
84
+ private readonly threadFinalizer = new FinalizationRegistry<() => void>((undo) => {
85
+ this.threadUndo.delete(undo);
86
+ });
87
+ private enabled = true;
88
+
89
+ constructor(config: CodexSDKInstrumentationConfig = {}) {
90
+ this.traceConfig = config.traceConfig;
91
+ this.tracerProvider = config.tracerProvider;
92
+ }
93
+
94
+ setTracerProvider(tracerProvider: TracerProvider): void {
95
+ this.tracerProvider = tracerProvider;
96
+ }
97
+
98
+ /** The content policy this instrumentation applies. */
99
+ get contentPolicy(): ContentPolicy {
100
+ return resolveContentPolicy(this.traceConfig);
101
+ }
102
+
103
+ /**
104
+ * Patch `module.Thread.prototype`. Pass the SDK module namespace
105
+ * (`import * as CodexSDK from "@openai/codex-sdk"`) or `{ Thread }`.
106
+ * Returns `true` when the class was patched by this call.
107
+ */
108
+ manuallyInstrument(module: CodexModuleLike): boolean {
109
+ const proto = (module?.Thread as { prototype?: ThreadLike } | undefined)?.prototype;
110
+ if (!proto) {
111
+ diag.warn(`${INSTRUMENTATION_NAME}: manuallyInstrument() expects the @openai/codex-sdk module (no Thread export found)`);
112
+ return false;
113
+ }
114
+ this.enabled = true;
115
+ const undo = patchThread(proto, () => this.tracingContext());
116
+ if (undo) this.undo.push(undo);
117
+ return !!undo;
118
+ }
119
+
120
+ /**
121
+ * Patch one Thread instance. Returns the same instance. Only a weak reference
122
+ * is kept, so `unpatch()` can restore live threads without retaining dropped ones.
123
+ */
124
+ wrapThread<T extends object>(thread: T): T {
125
+ this.enabled = true;
126
+ const undo = patchThread(thread as ThreadLike, () => this.tracingContext());
127
+ if (undo) {
128
+ this.threadUndo.add(undo);
129
+ this.threadFinalizer.register(thread, undo, undo);
130
+ }
131
+ return thread;
132
+ }
133
+
134
+ /** Patch one Codex instance so every thread it starts or resumes is traced. Returns the same instance. */
135
+ wrapCodex<T extends object>(codex: T): T {
136
+ if (!codex || typeof codex !== "object") return codex;
137
+ this.enabled = true;
138
+ const undo = patchCodex(codex as Record<string | symbol, unknown>, (thread) => this.wrapThread(thread));
139
+ if (undo) {
140
+ this.clientUndo.add(undo);
141
+ this.clientFinalizer.register(codex, undo, undo);
142
+ }
143
+ return codex;
144
+ }
145
+
146
+ /** Remove every patch this instrumentation applied. */
147
+ unpatch(): void {
148
+ this.enabled = false;
149
+ for (const undo of this.threadUndo) {
150
+ this.threadFinalizer.unregister(undo);
151
+ undo();
152
+ }
153
+ this.threadUndo.clear();
154
+ for (const undo of this.clientUndo) {
155
+ this.clientFinalizer.unregister(undo);
156
+ try {
157
+ undo();
158
+ } catch (error) {
159
+ diag.debug(`${INSTRUMENTATION_NAME}: unpatch failed: ${error}`);
160
+ }
161
+ }
162
+ this.clientUndo.clear();
163
+ while (this.undo.length) {
164
+ const fn = this.undo.pop();
165
+ try {
166
+ fn?.();
167
+ } catch (error) {
168
+ diag.debug(`${INSTRUMENTATION_NAME}: unpatch failed: ${error}`);
169
+ }
170
+ }
171
+ }
172
+
173
+ /** Flush the provider's span processors. Does not shut the provider down. */
174
+ async forceFlush(): Promise<void> {
175
+ await flushProvider(this.tracerProvider ?? trace.getTracerProvider());
176
+ }
177
+
178
+ private tracingContext(): TurnTracingContext | undefined {
179
+ if (!this.enabled) return undefined;
180
+ const policy = this.contentPolicy;
181
+ const provider = this.tracerProvider ?? trace.getTracerProvider();
182
+ const tracer = new FITracer({
183
+ tracer: provider.getTracer(INSTRUMENTATION_NAME, VERSION),
184
+ traceConfig: { ...this.traceConfig, hideInputs: policy.hideInputs, hideOutputs: policy.hideOutputs, hideErrorDetails: policy.hideErrorDetails },
185
+ });
186
+ return { tracer, policy };
187
+ }
188
+ }
189
+
190
+ /** Python-style convenience constructor. */
191
+ export function instrumentCodexSDK(
192
+ module: CodexModuleLike,
193
+ config: CodexSDKInstrumentationConfig = {},
194
+ ): CodexSDKInstrumentation {
195
+ const instrumentation = new CodexSDKInstrumentation(config);
196
+ instrumentation.manuallyInstrument(module);
197
+ return instrumentation;
198
+ }
199
+
200
+ /**
201
+ * Flush spans before a short script exits. Export errors are logged, never
202
+ * thrown: export failure does not fail the agent.
203
+ */
204
+ export async function shutdown(tracerProvider?: TracerProvider): Promise<void> {
205
+ await flushProvider(tracerProvider ?? trace.getTracerProvider());
206
+ }
207
+
208
+ function resolveDelegate(provider: TracerProvider): TracerProvider {
209
+ const maybeProxy = provider as TracerProvider & {
210
+ getDelegate?: () => TracerProvider;
211
+ forceFlush?: () => Promise<void>;
212
+ };
213
+ if (typeof maybeProxy.forceFlush !== "function" && typeof maybeProxy.getDelegate === "function") {
214
+ return maybeProxy.getDelegate();
215
+ }
216
+ return provider;
217
+ }
218
+
219
+ async function flushProvider(provider: TracerProvider): Promise<void> {
220
+ const target = resolveDelegate(provider) as TracerProvider & { forceFlush?: () => Promise<void> };
221
+ if (typeof target.forceFlush !== "function") return;
222
+ try {
223
+ await target.forceFlush();
224
+ } catch (error) {
225
+ diag.warn(`${INSTRUMENTATION_NAME}: forceFlush failed: ${error}`);
226
+ }
227
+ }