@traceai/codex-sdk 0.0.0-stage → 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 (94) hide show
  1. package/README.md +164 -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/index.d.ts +8 -0
  7. package/dist/esm/index.d.ts.map +1 -0
  8. package/dist/esm/index.js +5 -0
  9. package/dist/esm/index.js.map +1 -0
  10. package/dist/esm/instrumentation.d.ts +81 -0
  11. package/dist/esm/instrumentation.d.ts.map +1 -0
  12. package/dist/esm/instrumentation.js +186 -0
  13. package/dist/esm/instrumentation.js.map +1 -0
  14. package/dist/esm/package.json +1 -0
  15. package/dist/esm/spans.d.ts +152 -0
  16. package/dist/esm/spans.d.ts.map +1 -0
  17. package/dist/esm/spans.js +678 -0
  18. package/dist/esm/spans.js.map +1 -0
  19. package/dist/esm/threadWrapper.d.ts +35 -0
  20. package/dist/esm/threadWrapper.d.ts.map +1 -0
  21. package/dist/esm/threadWrapper.js +186 -0
  22. package/dist/esm/threadWrapper.js.map +1 -0
  23. package/dist/esm/types.d.ts +123 -0
  24. package/dist/esm/types.d.ts.map +1 -0
  25. package/dist/esm/types.js +10 -0
  26. package/dist/esm/types.js.map +1 -0
  27. package/dist/esm/version.d.ts +2 -0
  28. package/dist/esm/version.d.ts.map +1 -0
  29. package/dist/esm/version.js +2 -0
  30. package/dist/esm/version.js.map +1 -0
  31. package/dist/esnext/attributes.d.ts +101 -0
  32. package/dist/esnext/attributes.d.ts.map +1 -0
  33. package/dist/esnext/attributes.js +104 -0
  34. package/dist/esnext/attributes.js.map +1 -0
  35. package/dist/esnext/index.d.ts +8 -0
  36. package/dist/esnext/index.d.ts.map +1 -0
  37. package/dist/esnext/index.js +5 -0
  38. package/dist/esnext/index.js.map +1 -0
  39. package/dist/esnext/instrumentation.d.ts +81 -0
  40. package/dist/esnext/instrumentation.d.ts.map +1 -0
  41. package/dist/esnext/instrumentation.js +191 -0
  42. package/dist/esnext/instrumentation.js.map +1 -0
  43. package/dist/esnext/spans.d.ts +152 -0
  44. package/dist/esnext/spans.d.ts.map +1 -0
  45. package/dist/esnext/spans.js +688 -0
  46. package/dist/esnext/spans.js.map +1 -0
  47. package/dist/esnext/threadWrapper.d.ts +35 -0
  48. package/dist/esnext/threadWrapper.d.ts.map +1 -0
  49. package/dist/esnext/threadWrapper.js +183 -0
  50. package/dist/esnext/threadWrapper.js.map +1 -0
  51. package/dist/esnext/types.d.ts +123 -0
  52. package/dist/esnext/types.d.ts.map +1 -0
  53. package/dist/esnext/types.js +10 -0
  54. package/dist/esnext/types.js.map +1 -0
  55. package/dist/esnext/version.d.ts +2 -0
  56. package/dist/esnext/version.d.ts.map +1 -0
  57. package/dist/esnext/version.js +2 -0
  58. package/dist/esnext/version.js.map +1 -0
  59. package/dist/src/attributes.d.ts +101 -0
  60. package/dist/src/attributes.d.ts.map +1 -0
  61. package/dist/src/attributes.js +107 -0
  62. package/dist/src/attributes.js.map +1 -0
  63. package/dist/src/index.d.ts +8 -0
  64. package/dist/src/index.d.ts.map +1 -0
  65. package/dist/src/index.js +21 -0
  66. package/dist/src/index.js.map +1 -0
  67. package/dist/src/instrumentation.d.ts +81 -0
  68. package/dist/src/instrumentation.d.ts.map +1 -0
  69. package/dist/src/instrumentation.js +213 -0
  70. package/dist/src/instrumentation.js.map +1 -0
  71. package/dist/src/spans.d.ts +152 -0
  72. package/dist/src/spans.d.ts.map +1 -0
  73. package/dist/src/spans.js +698 -0
  74. package/dist/src/spans.js.map +1 -0
  75. package/dist/src/threadWrapper.d.ts +35 -0
  76. package/dist/src/threadWrapper.d.ts.map +1 -0
  77. package/dist/src/threadWrapper.js +206 -0
  78. package/dist/src/threadWrapper.js.map +1 -0
  79. package/dist/src/types.d.ts +123 -0
  80. package/dist/src/types.d.ts.map +1 -0
  81. package/dist/src/types.js +11 -0
  82. package/dist/src/types.js.map +1 -0
  83. package/dist/src/version.d.ts +2 -0
  84. package/dist/src/version.d.ts.map +1 -0
  85. package/dist/src/version.js +5 -0
  86. package/dist/src/version.js.map +1 -0
  87. package/package.json +75 -3
  88. package/src/attributes.ts +113 -0
  89. package/src/index.ts +27 -0
  90. package/src/instrumentation.ts +215 -0
  91. package/src/spans.ts +729 -0
  92. package/src/threadWrapper.ts +200 -0
  93. package/src/types.ts +113 -0
  94. package/src/version.ts +1 -0
@@ -0,0 +1,104 @@
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
+ export const SpanNames = {
10
+ TURN: "codex.turn",
11
+ AGENT_MESSAGE: "codex.agent_message",
12
+ REASONING: "codex.reasoning",
13
+ COMMAND_EXECUTION: "codex.command_execution",
14
+ FILE_CHANGE: "codex.file_change",
15
+ MCP_TOOL_CALL: "codex.mcp_tool_call",
16
+ WEB_SEARCH: "codex.web_search",
17
+ TODO_LIST: "codex.todo_list",
18
+ ERROR: "codex.error",
19
+ };
20
+ /** SDK item type -> span name and Future AGI span kind. */
21
+ export const ITEM_SPANS = {
22
+ agent_message: { name: SpanNames.AGENT_MESSAGE, kind: FISpanKind.LLM, tool: false },
23
+ reasoning: { name: SpanNames.REASONING, kind: FISpanKind.CHAIN, tool: false },
24
+ command_execution: { name: SpanNames.COMMAND_EXECUTION, kind: FISpanKind.TOOL, tool: true },
25
+ file_change: { name: SpanNames.FILE_CHANGE, kind: FISpanKind.TOOL, tool: true },
26
+ mcp_tool_call: { name: SpanNames.MCP_TOOL_CALL, kind: FISpanKind.TOOL, tool: true },
27
+ web_search: { name: SpanNames.WEB_SEARCH, kind: FISpanKind.TOOL, tool: true },
28
+ todo_list: { name: SpanNames.TODO_LIST, kind: FISpanKind.CHAIN, tool: false },
29
+ // Non-fatal: status UNSET with codex.warning=true.
30
+ error: { name: SpanNames.ERROR, kind: FISpanKind.CHAIN, tool: false },
31
+ };
32
+ /** Fallback for an item type a newer SDK adds. */
33
+ export const UNKNOWN_ITEM_SPAN = { kind: FISpanKind.CHAIN, tool: false };
34
+ export const CodexAttributes = {
35
+ THREAD_ID: "codex.thread.id",
36
+ THREAD_RESUMED: "codex.thread.resumed",
37
+ SANDBOX_MODE: "codex.sandbox_mode",
38
+ APPROVAL_POLICY: "codex.approval_policy",
39
+ REASONING_EFFORT: "codex.model_reasoning_effort",
40
+ WEB_SEARCH_MODE: "codex.web_search_mode",
41
+ INPUT_IMAGE_COUNT: "codex.input.image_count",
42
+ INPUT_LENGTH: "codex.input.length",
43
+ ITEM_ID: "codex.item.id",
44
+ ITEM_TYPE: "codex.item.type",
45
+ ITEM_STATUS: "codex.item.status",
46
+ /** false when the SDK sent only `item.completed`; the span then starts at the previous event. */
47
+ ITEM_STARTED_EVENT: "codex.item.started_event",
48
+ ITEM_INCOMPLETE: "codex.item.incomplete",
49
+ COMMAND_EXIT_CODE: "codex.command.exit_code",
50
+ COMMAND_OUTPUT_LENGTH: "codex.command.output_length",
51
+ FILE_CHANGE_COUNT: "codex.file_change.count",
52
+ FILE_CHANGE_KINDS: "codex.file_change.kinds",
53
+ MCP_SERVER: "codex.mcp.server",
54
+ MCP_TOOL: "codex.mcp.tool",
55
+ TODO_COUNT: "codex.todo.count",
56
+ TODO_COMPLETED: "codex.todo.completed",
57
+ TEXT_LENGTH: "codex.text.length",
58
+ USAGE_CACHED_INPUT_TOKENS: "codex.usage.cached_input_tokens",
59
+ USAGE_CACHE_WRITE_INPUT_TOKENS: "codex.usage.cache_write_input_tokens",
60
+ USAGE_REASONING_OUTPUT_TOKENS: "codex.usage.reasoning_output_tokens",
61
+ /** A resumed thread's first turn in this process: no earlier total, so nothing promoted. */
62
+ USAGE_BASELINE_UNKNOWN: "codex.usage.baseline_unknown",
63
+ /** The running total went down; the reported value was promoted as is. */
64
+ USAGE_NON_MONOTONIC: "codex.usage.non_monotonic",
65
+ /** Prefix for the thread's running totals, e.g. `codex.cumulative.input_tokens`. */
66
+ CUMULATIVE_PREFIX: "codex.cumulative.",
67
+ /** Fixed summary unless outputs are visible; see README "Privacy". */
68
+ ERROR_MESSAGE: "codex.error.message",
69
+ /** Error class name of a thrown error, e.g. `Error`, `TypeError`. */
70
+ ERROR_TYPE: "codex.error.type",
71
+ /** `error` events in the turn. Codex sends them for errors it retries; the turn can still complete. */
72
+ STREAM_ERROR_COUNT: "codex.stream_error.count",
73
+ /** On `codex.error` spans: a non-fatal error item (warning, deprecation, model reroute). */
74
+ WARNING: "codex.warning",
75
+ CANCELLED: "codex.cancelled",
76
+ };
77
+ /** Standard keys used by this package, resolved from fi-semantic-conventions. */
78
+ export const StandardAttributes = {
79
+ FI_SPAN_KIND: SemanticConventions.FI_SPAN_KIND,
80
+ /** Same value as `fi.span.kind`; the Python fi_instrumentation key the collector also reads. */
81
+ GEN_AI_SPAN_KIND: "gen_ai.span.kind",
82
+ SESSION_ID: SemanticConventions.SESSION_ID,
83
+ CONVERSATION_ID: SemanticConventions.GEN_AI_CONVERSATION_ID,
84
+ INPUT_VALUE: SemanticConventions.INPUT_VALUE,
85
+ INPUT_MIME_TYPE: SemanticConventions.INPUT_MIME_TYPE,
86
+ OUTPUT_VALUE: SemanticConventions.OUTPUT_VALUE,
87
+ OUTPUT_MIME_TYPE: SemanticConventions.OUTPUT_MIME_TYPE,
88
+ MODEL_NAME: SemanticConventions.LLM_MODEL_NAME,
89
+ PROVIDER: SemanticConventions.LLM_PROVIDER,
90
+ TOOL_NAME: SemanticConventions.TOOL_NAME,
91
+ GEN_AI_TOOL_NAME: "gen_ai.tool.name",
92
+ TOOL_CALL_ID: "gen_ai.tool.call.id",
93
+ AGENT_NAME: "gen_ai.agent.name",
94
+ INPUT_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT,
95
+ OUTPUT_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_COMPLETION,
96
+ TOTAL_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_TOTAL,
97
+ CACHE_READ_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_READ,
98
+ CACHE_WRITE_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_PROMPT_DETAILS_CACHE_WRITE,
99
+ REASONING_TOKENS: SemanticConventions.LLM_TOKEN_COUNT_COMPLETION_DETAILS_REASONING,
100
+ };
101
+ export const AGENT_NAME = "codex";
102
+ /** Codex talks to the OpenAI Responses API (or an OpenAI-compatible proxy). */
103
+ export const PROVIDER_NAME = "openai";
104
+ //# sourceMappingURL=attributes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attributes.js","sourceRoot":"","sources":["../../src/attributes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAEnF,MAAM,CAAC,MAAM,SAAS,GAAG;IACvB,IAAI,EAAE,YAAY;IAClB,aAAa,EAAE,qBAAqB;IACpC,SAAS,EAAE,iBAAiB;IAC5B,iBAAiB,EAAE,yBAAyB;IAC5C,WAAW,EAAE,mBAAmB;IAChC,aAAa,EAAE,qBAAqB;IACpC,UAAU,EAAE,kBAAkB;IAC9B,SAAS,EAAE,iBAAiB;IAC5B,KAAK,EAAE,aAAa;CACZ,CAAC;AAEX,2DAA2D;AAC3D,MAAM,CAAC,MAAM,UAAU,GAAsE;IAC3F,aAAa,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,aAAa,EAAE,IAAI,EAAE,UAAU,CAAC,GAAG,EAAE,IAAI,EAAE,KAAK,EAAE;IACnF,SAAS,EAAE,EAAE,IAAI,EAAE,SAAS,CAAC,SAAS,EAAE,IAAI,EAAE,UAAU,CA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AC,YAAY;IAC1C,SAAS,EAAE,mBAAmB,CAAC,SAAS;IACxC,gBAAgB,EAAE,kBAAkB;IACpC,YAAY,EAAE,qBAAqB;IACnC,UAAU,EAAE,mBAAmB;IAC/B,YAAY,EAAE,mBAAmB,CAAC,sBAAsB;IACxD,aAAa,EAAE,mBAAmB,CAAC,0BAA0B;IAC7D,YAAY,EAAE,mBAAmB,CAAC,qBAAqB;IACvD,iBAAiB,EAAE,mBAAmB,CAAC,yCAAyC;IAChF,kBAAkB,EAAE,mBAAmB,CAAC,0CAA0C;IAClF,gBAAgB,EAAE,mBAAmB,CAAC,4CAA4C;CAC1E,CAAC;AAEX,MAAM,CAAC,MAAM,UAAU,GAAG,OAAO,CAAC;AAClC,+EAA+E;AAC/E,MAAM,CAAC,MAAM,aAAa,GAAG,QAAQ,CAAC"}
@@ -0,0 +1,8 @@
1
+ export { CodexSDKInstrumentation, INSTRUMENTATION_NAME, instrumentCodexSDK, resolveContentPolicy, shutdown, } from "./instrumentation";
2
+ export type { CodexSDKInstrumentationConfig } from "./instrumentation";
3
+ export { isPatched } from "./threadWrapper";
4
+ export type { ContentPolicy } from "./spans";
5
+ export { AGENT_NAME, CodexAttributes, ITEM_SPANS, PROVIDER_NAME, SpanNames, StandardAttributes, } from "./attributes";
6
+ export type { CodexModuleLike, ThreadEventLike, ThreadItemLike, ThreadLike, ThreadOptionsLike, UsageLike, } from "./types";
7
+ export { VERSION } from "./version";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,kBAAkB,EAClB,oBAAoB,EACpB,QAAQ,GACT,MAAM,mBAAmB,CAAC;AAC3B,YAAY,EAAE,6BAA6B,EAAE,MAAM,mBAAmB,CAAC;AACvE,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EACL,UAAU,EACV,eAAe,EACf,UAAU,EACV,aAAa,EACb,SAAS,EACT,kBAAkB,GACnB,MAAM,cAAc,CAAC;AACtB,YAAY,EACV,eAAe,EACf,eAAe,EACf,cAAc,EACd,UAAU,EACV,iBAAiB,EACjB,SAAS,GACV,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,5 @@
1
+ export { CodexSDKInstrumentation, INSTRUMENTATION_NAME, instrumentCodexSDK, resolveContentPolicy, shutdown, } from "./instrumentation";
2
+ export { isPatched } from "./threadWrapper";
3
+ export { AGENT_NAME, CodexAttributes, ITEM_SPANS, PROVIDER_NAME, SpanNames, StandardAttributes, } from "./attributes";
4
+ export { VERSION } from "./version";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,kBAAkB,EAClB,oBAAoB,EACpB,QAAQ,GACT,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,EACL,UAAU,EACV,eAAe,EACf,UAAU,EACV,aAAa,EACb,SAAS,EACT,kBAAkB,GACnB,MAAM,cAAc,CAAC;AAStB,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,81 @@
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 } from "@opentelemetry/api";
7
+ import { TraceConfigOptions } from "@traceai/fi-core";
8
+ import { ContentPolicy } from "./spans";
9
+ import { CodexModuleLike } from "./types";
10
+ export declare const INSTRUMENTATION_NAME = "@traceai/codex-sdk";
11
+ export interface CodexSDKInstrumentationConfig {
12
+ /** Provider to create spans with. Defaults to the global provider at call time. */
13
+ tracerProvider?: TracerProvider;
14
+ /**
15
+ * fi-core trace config. Unlike fi-core, `hideInputs` and `hideOutputs`
16
+ * default to `true` here: prompts, shell commands, command output, file
17
+ * paths and MCP arguments can contain source code or secrets. Opt in with
18
+ * `false`, or with `FI_HIDE_INPUTS=false` / `FI_HIDE_OUTPUTS=false`.
19
+ */
20
+ traceConfig?: TraceConfigOptions;
21
+ }
22
+ /** Precedence: explicit option > fi-core env var > this package's default (hidden). */
23
+ export declare function resolveContentPolicy(traceConfig?: TraceConfigOptions): ContentPolicy;
24
+ /**
25
+ * Traces `@openai/codex-sdk` turns.
26
+ *
27
+ * ```ts
28
+ * import * as CodexSDK from "@openai/codex-sdk";
29
+ * const instrumentation = new CodexSDKInstrumentation({ tracerProvider });
30
+ * instrumentation.manuallyInstrument(CodexSDK);
31
+ * const thread = new CodexSDK.Codex().startThread();
32
+ * await thread.run("..."); // one codex.turn trace
33
+ * ```
34
+ *
35
+ * The SDK is ESM-only, so its module namespace cannot be patched; its `Thread`
36
+ * class prototype can. `wrapCodex()` / `wrapThread()` patch single instances
37
+ * instead, for apps that prefer not to touch the shared class.
38
+ *
39
+ * This is not an OpenTelemetry `InstrumentationBase`: there is no module to
40
+ * hook on `require`/`import`, so it cannot be passed to
41
+ * `registerInstrumentations()`. Call `manuallyInstrument()` or the wrap methods.
42
+ */
43
+ export declare class CodexSDKInstrumentation {
44
+ private tracerProvider?;
45
+ private readonly traceConfig?;
46
+ /** Undo functions for the class patch and wrapCodex() factories (never one per thread). */
47
+ private readonly undo;
48
+ /** False after unpatch(): instance patches stay in place but pass events through untraced. */
49
+ private enabled;
50
+ constructor(config?: CodexSDKInstrumentationConfig);
51
+ setTracerProvider(tracerProvider: TracerProvider): void;
52
+ /** The content policy this instrumentation applies. */
53
+ get contentPolicy(): ContentPolicy;
54
+ /**
55
+ * Patch `module.Thread.prototype`. Pass the SDK module namespace
56
+ * (`import * as CodexSDK from "@openai/codex-sdk"`) or `{ Thread }`.
57
+ * Returns `true` when the class was patched by this call.
58
+ */
59
+ manuallyInstrument(module: CodexModuleLike): boolean;
60
+ /**
61
+ * Patch one Thread instance. Returns the same instance. No reference to the
62
+ * thread is kept: after `unpatch()` the patched method passes events through
63
+ * untraced instead of being removed.
64
+ */
65
+ wrapThread<T extends object>(thread: T): T;
66
+ /** Patch one Codex instance so every thread it starts or resumes is traced. Returns the same instance. */
67
+ wrapCodex<T extends object>(codex: T): T;
68
+ /** Remove every patch this instrumentation applied. */
69
+ unpatch(): void;
70
+ /** Flush the provider's span processors. Does not shut the provider down. */
71
+ forceFlush(): Promise<void>;
72
+ private tracingContext;
73
+ }
74
+ /** Python-style convenience constructor. */
75
+ export declare function instrumentCodexSDK(module: CodexModuleLike, config?: CodexSDKInstrumentationConfig): CodexSDKInstrumentation;
76
+ /**
77
+ * Flush spans before a short script exits. Export errors are logged, never
78
+ * thrown: export failure does not fail the agent.
79
+ */
80
+ export declare function shutdown(tracerProvider?: TracerProvider): Promise<void>;
81
+ //# sourceMappingURL=instrumentation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentation.d.ts","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,cAAc,EAAe,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAY,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAChE,OAAO,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAExC,OAAO,EAAE,eAAe,EAAc,MAAM,SAAS,CAAC;AAGtD,eAAO,MAAM,oBAAoB,uBAAuB,CAAC;AAUzD,MAAM,WAAW,6BAA6B;IAC5C,mFAAmF;IACnF,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;;;;OAKG;IACH,WAAW,CAAC,EAAE,kBAAkB,CAAC;CAClC;AAQD,uFAAuF;AACvF,wBAAgB,oBAAoB,CAAC,WAAW,CAAC,EAAE,kBAAkB,GAAG,aAAa,CAMpF;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,qBAAa,uBAAuB;IAClC,OAAO,CAAC,cAAc,CAAC,CAAiB;IACxC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAqB;IAClD,2FAA2F;IAC3F,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAyB;IAC9C,8FAA8F;IAC9F,OAAO,CAAC,OAAO,CAAQ;gBAEX,MAAM,GAAE,6BAAkC;IAKtD,iBAAiB,CAAC,cAAc,EAAE,cAAc,GAAG,IAAI;IAIvD,uDAAuD;IACvD,IAAI,aAAa,IAAI,aAAa,CAEjC;IAED;;;;OAIG;IACH,kBAAkB,CAAC,MAAM,EAAE,eAAe,GAAG,OAAO;IAYpD;;;;OAIG;IACH,UAAU,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC;IAM1C,0GAA0G;IAC1G,SAAS,CAAC,CAAC,SAAS,MAAM,EAAE,KAAK,EAAE,CAAC,GAAG,CAAC;IA4BxC,uDAAuD;IACvD,OAAO,IAAI,IAAI;IAYf,6EAA6E;IACvE,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAIjC,OAAO,CAAC,cAAc;CAUvB;AAED,4CAA4C;AAC5C,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,eAAe,EACvB,MAAM,GAAE,6BAAkC,GACzC,uBAAuB,CAIzB;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,cAAc,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAE7E"}
@@ -0,0 +1,191 @@
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 { diag, trace } from "@opentelemetry/api";
7
+ import { FITracer } from "@traceai/fi-core";
8
+ import { patchThread } from "./threadWrapper";
9
+ import { VERSION } from "./version";
10
+ export const INSTRUMENTATION_NAME = "@traceai/codex-sdk";
11
+ /**
12
+ * fi-core env keys. Read fail-closed, unlike fi-core (`value.toLowerCase() ===
13
+ * "true"`): only an explicit `false` (trimmed, any case) opts in to content.
14
+ */
15
+ const FI_HIDE_INPUTS = "FI_HIDE_INPUTS";
16
+ const FI_HIDE_OUTPUTS = "FI_HIDE_OUTPUTS";
17
+ const FI_HIDE_ERROR_DETAILS = "FI_HIDE_ERROR_DETAILS";
18
+ /** `false` only for an explicit `false`; any other value (or none) keeps content hidden. */
19
+ function envHide(key) {
20
+ var _a;
21
+ const value = typeof process !== "undefined" ? (_a = process.env) === null || _a === void 0 ? void 0 : _a[key] : undefined;
22
+ return !(typeof value === "string" && value.trim().toLowerCase() === "false");
23
+ }
24
+ /** Precedence: explicit option > fi-core env var > this package's default (hidden). */
25
+ export function resolveContentPolicy(traceConfig) {
26
+ var _a, _b, _c;
27
+ return {
28
+ hideInputs: (_a = traceConfig === null || traceConfig === void 0 ? void 0 : traceConfig.hideInputs) !== null && _a !== void 0 ? _a : envHide(FI_HIDE_INPUTS),
29
+ hideOutputs: (_b = traceConfig === null || traceConfig === void 0 ? void 0 : traceConfig.hideOutputs) !== null && _b !== void 0 ? _b : envHide(FI_HIDE_OUTPUTS),
30
+ hideErrorDetails: (_c = traceConfig === null || traceConfig === void 0 ? void 0 : traceConfig.hideErrorDetails) !== null && _c !== void 0 ? _c : envHide(FI_HIDE_ERROR_DETAILS),
31
+ };
32
+ }
33
+ /**
34
+ * Traces `@openai/codex-sdk` turns.
35
+ *
36
+ * ```ts
37
+ * import * as CodexSDK from "@openai/codex-sdk";
38
+ * const instrumentation = new CodexSDKInstrumentation({ tracerProvider });
39
+ * instrumentation.manuallyInstrument(CodexSDK);
40
+ * const thread = new CodexSDK.Codex().startThread();
41
+ * await thread.run("..."); // one codex.turn trace
42
+ * ```
43
+ *
44
+ * The SDK is ESM-only, so its module namespace cannot be patched; its `Thread`
45
+ * class prototype can. `wrapCodex()` / `wrapThread()` patch single instances
46
+ * instead, for apps that prefer not to touch the shared class.
47
+ *
48
+ * This is not an OpenTelemetry `InstrumentationBase`: there is no module to
49
+ * hook on `require`/`import`, so it cannot be passed to
50
+ * `registerInstrumentations()`. Call `manuallyInstrument()` or the wrap methods.
51
+ */
52
+ export class CodexSDKInstrumentation {
53
+ constructor(config = {}) {
54
+ /** Undo functions for the class patch and wrapCodex() factories (never one per thread). */
55
+ this.undo = [];
56
+ /** False after unpatch(): instance patches stay in place but pass events through untraced. */
57
+ this.enabled = true;
58
+ this.traceConfig = config.traceConfig;
59
+ this.tracerProvider = config.tracerProvider;
60
+ }
61
+ setTracerProvider(tracerProvider) {
62
+ this.tracerProvider = tracerProvider;
63
+ }
64
+ /** The content policy this instrumentation applies. */
65
+ get contentPolicy() {
66
+ return resolveContentPolicy(this.traceConfig);
67
+ }
68
+ /**
69
+ * Patch `module.Thread.prototype`. Pass the SDK module namespace
70
+ * (`import * as CodexSDK from "@openai/codex-sdk"`) or `{ Thread }`.
71
+ * Returns `true` when the class was patched by this call.
72
+ */
73
+ manuallyInstrument(module) {
74
+ var _a;
75
+ const proto = (_a = module === null || module === void 0 ? void 0 : module.Thread) === null || _a === void 0 ? void 0 : _a.prototype;
76
+ if (!proto) {
77
+ diag.warn(`${INSTRUMENTATION_NAME}: manuallyInstrument() expects the @openai/codex-sdk module (no Thread export found)`);
78
+ return false;
79
+ }
80
+ this.enabled = true;
81
+ const undo = patchThread(proto, () => this.tracingContext());
82
+ if (undo)
83
+ this.undo.push(undo);
84
+ return !!undo;
85
+ }
86
+ /**
87
+ * Patch one Thread instance. Returns the same instance. No reference to the
88
+ * thread is kept: after `unpatch()` the patched method passes events through
89
+ * untraced instead of being removed.
90
+ */
91
+ wrapThread(thread) {
92
+ this.enabled = true;
93
+ patchThread(thread, () => this.tracingContext());
94
+ return thread;
95
+ }
96
+ /** Patch one Codex instance so every thread it starts or resumes is traced. Returns the same instance. */
97
+ wrapCodex(codex) {
98
+ if (!codex || typeof codex !== "object")
99
+ return codex;
100
+ this.enabled = true;
101
+ const target = codex;
102
+ // Held weakly: a wrapped client the app drops can be collected before unpatch().
103
+ const ref = new WeakRef(target);
104
+ for (const method of ["startThread", "resumeThread"]) {
105
+ const original = target[method];
106
+ if (typeof original !== "function")
107
+ continue;
108
+ const hadOwn = Object.prototype.hasOwnProperty.call(codex, method);
109
+ const self = this;
110
+ Object.defineProperty(codex, method, {
111
+ value: function tracedThreadFactory(...args) {
112
+ return self.wrapThread(original.apply(this, args));
113
+ },
114
+ writable: true,
115
+ configurable: true,
116
+ });
117
+ this.undo.push(() => {
118
+ const live = ref.deref();
119
+ if (!live)
120
+ return;
121
+ if (hadOwn)
122
+ Object.defineProperty(live, method, { value: original, writable: true, configurable: true });
123
+ else
124
+ delete live[method];
125
+ });
126
+ }
127
+ return codex;
128
+ }
129
+ /** Remove every patch this instrumentation applied. */
130
+ unpatch() {
131
+ this.enabled = false;
132
+ while (this.undo.length) {
133
+ const fn = this.undo.pop();
134
+ try {
135
+ fn === null || fn === void 0 ? void 0 : fn();
136
+ }
137
+ catch (error) {
138
+ diag.debug(`${INSTRUMENTATION_NAME}: unpatch failed: ${error}`);
139
+ }
140
+ }
141
+ }
142
+ /** Flush the provider's span processors. Does not shut the provider down. */
143
+ async forceFlush() {
144
+ var _a;
145
+ await flushProvider((_a = this.tracerProvider) !== null && _a !== void 0 ? _a : trace.getTracerProvider());
146
+ }
147
+ tracingContext() {
148
+ var _a;
149
+ if (!this.enabled)
150
+ return undefined;
151
+ const policy = this.contentPolicy;
152
+ const provider = (_a = this.tracerProvider) !== null && _a !== void 0 ? _a : trace.getTracerProvider();
153
+ const tracer = new FITracer({
154
+ tracer: provider.getTracer(INSTRUMENTATION_NAME, VERSION),
155
+ traceConfig: Object.assign(Object.assign({}, this.traceConfig), { hideInputs: policy.hideInputs, hideOutputs: policy.hideOutputs, hideErrorDetails: policy.hideErrorDetails }),
156
+ });
157
+ return { tracer, policy };
158
+ }
159
+ }
160
+ /** Python-style convenience constructor. */
161
+ export function instrumentCodexSDK(module, config = {}) {
162
+ const instrumentation = new CodexSDKInstrumentation(config);
163
+ instrumentation.manuallyInstrument(module);
164
+ return instrumentation;
165
+ }
166
+ /**
167
+ * Flush spans before a short script exits. Export errors are logged, never
168
+ * thrown: export failure does not fail the agent.
169
+ */
170
+ export async function shutdown(tracerProvider) {
171
+ await flushProvider(tracerProvider !== null && tracerProvider !== void 0 ? tracerProvider : trace.getTracerProvider());
172
+ }
173
+ function resolveDelegate(provider) {
174
+ const maybeProxy = provider;
175
+ if (typeof maybeProxy.forceFlush !== "function" && typeof maybeProxy.getDelegate === "function") {
176
+ return maybeProxy.getDelegate();
177
+ }
178
+ return provider;
179
+ }
180
+ async function flushProvider(provider) {
181
+ const target = resolveDelegate(provider);
182
+ if (typeof target.forceFlush !== "function")
183
+ return;
184
+ try {
185
+ await target.forceFlush();
186
+ }
187
+ catch (error) {
188
+ diag.warn(`${INSTRUMENTATION_NAME}: forceFlush failed: ${error}`);
189
+ }
190
+ }
191
+ //# sourceMappingURL=instrumentation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAkB,IAAI,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACjE,OAAO,EAAE,QAAQ,EAAsB,MAAM,kBAAkB,CAAC;AAEhE,OAAO,EAAsB,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAElE,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC,MAAM,CAAC,MAAM,oBAAoB,GAAG,oBAAoB,CAAC;AAEzD;;;GAGG;AACH,MAAM,cAAc,GAAG,gBAAgB,CAAC;AACxC,MAAM,eAAe,GAAG,iBAAiB,CAAC;AAC1C,MAAM,qBAAqB,GAAG,uBAAuB,CAAC;AActD,4FAA4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ChG,OAAO,UAAU,CAAC,WAAW,EAAE,CAAC;IAClC,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,KAAK,UAAU,aAAa,CAAC,QAAwB;IACnD,MAAM,MAAM,GAAG,eAAe,CAAC,QAAQ,CAA0D,CAAC;IAClG,IAAI,OAAO,MAAM,CAAC,UAAU,KAAK,UAAU;QAAE,OAAO;IACpD,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,UAAU,EAAE,CAAC;IAC5B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,IAAI,CAAC,GAAG,oBAAoB,wBAAwB,KAAK,EAAE,CAAC,CAAC;IACpE,CAAC;AACH,CAAC"}
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Span model for one Codex turn (one `Thread.run()` or `Thread.runStreamed()`).
3
+ *
4
+ * The SDK yields `ThreadEvent`s, not spans. `TurnTracer` turns them into:
5
+ *
6
+ * codex.turn (AGENT) session.id = thread id, usage
7
+ * ├─ codex.reasoning (CHAIN)
8
+ * ├─ codex.command_execution (TOOL)
9
+ * ├─ codex.file_change (TOOL)
10
+ * ├─ codex.mcp_tool_call (TOOL)
11
+ * ├─ codex.web_search (TOOL)
12
+ * ├─ codex.todo_list (CHAIN)
13
+ * ├─ codex.agent_message (LLM)
14
+ * └─ codex.error (CHAIN, codex.warning=true) non-fatal error item
15
+ *
16
+ * Every public method swallows its own errors: tracing never fails the agent.
17
+ */
18
+ import { Context, HrTime, Tracer } from "@opentelemetry/api";
19
+ import { InputLike, ThreadOptionsLike, TurnOptionsLike } from "./types";
20
+ /** Which content the wrapper may copy onto spans. Both default to hidden. */
21
+ export interface ContentPolicy {
22
+ hideInputs: boolean;
23
+ hideOutputs: boolean;
24
+ /** Error details remain hidden even when ordinary outputs are visible. */
25
+ hideErrorDetails: boolean;
26
+ }
27
+ /** How the wrapped event stream stopped. */
28
+ export type FinishOutcome = {
29
+ kind: "completed";
30
+ } | {
31
+ kind: "returned";
32
+ } | {
33
+ kind: "error";
34
+ error: unknown;
35
+ };
36
+ /**
37
+ * One clock for every start and end time the wrapper sets. OTel falls back to
38
+ * millisecond `Date.now()` for the end of a span whose start time was given,
39
+ * so mixing explicit and implicit times can order a child after its parent.
40
+ */
41
+ export declare function clockMs(): number;
42
+ export declare function toHrTime(ms: number): HrTime;
43
+ export declare function truncate(value: string, max: number): string;
44
+ export declare function safeJson(value: unknown, max?: number): string;
45
+ /** Same normalization as the SDK's `normalizeInput`: text parts joined by a blank line. */
46
+ export declare function normalizeInput(input: InputLike | undefined): {
47
+ prompt: string;
48
+ images: number;
49
+ };
50
+ /**
51
+ * The SDK builds its thrown messages from raw data: `Codex Exec exited with
52
+ * code 1: <the binary's stderr>` and `Failed to parse item: <the raw line>`
53
+ * (dist/index.js of 0.162.1). Stderr can hold config lines, local paths and
54
+ * the user name; the raw line can hold the prompt or command output. With
55
+ * outputs hidden only this fixed summary is exported.
56
+ */
57
+ export declare function errorSummary(error: unknown): string;
58
+ type UsageTotals = {
59
+ input_tokens?: number;
60
+ cached_input_tokens?: number;
61
+ cache_write_input_tokens?: number;
62
+ output_tokens?: number;
63
+ reasoning_output_tokens?: number;
64
+ };
65
+ /**
66
+ * Last running total seen per thread id in this process (LRU, 1000 threads).
67
+ * Exact while a thread's turns run in one process; see the README.
68
+ */
69
+ declare class UsageBaselines {
70
+ private readonly totals;
71
+ get(threadId: string): UsageTotals | undefined;
72
+ set(threadId: string, totals: UsageTotals): void;
73
+ clear(): void;
74
+ get size(): number;
75
+ }
76
+ export declare const usageBaselines: UsageBaselines;
77
+ export declare class TurnTracer {
78
+ private readonly tracer;
79
+ private readonly policy;
80
+ private readonly parentContext;
81
+ private readonly startTimeMs;
82
+ private readonly input;
83
+ private readonly turnOptions;
84
+ private readonly threadOptions;
85
+ private readonly contextAttributes;
86
+ private readonly appSetSession;
87
+ private readonly resumed;
88
+ private turn?;
89
+ private turnContext?;
90
+ private finished;
91
+ private threadId?;
92
+ private lastEventMs;
93
+ private finalResponse?;
94
+ private completed;
95
+ /** `turn.failed` text; the turn failed. */
96
+ private failedMessage?;
97
+ /** Last `error` event text. Fatal only if the turn ends without `turn.completed`. */
98
+ private streamErrorMessage?;
99
+ private streamErrorCount;
100
+ private readonly items;
101
+ private anonymousItems;
102
+ constructor(args: {
103
+ tracer: Tracer;
104
+ policy: ContentPolicy;
105
+ parentContext: Context;
106
+ input: InputLike | undefined;
107
+ turnOptions?: TurnOptionsLike;
108
+ threadOptions?: ThreadOptionsLike;
109
+ threadId?: string | null;
110
+ startTimeMs?: number;
111
+ });
112
+ private get hideErrorText();
113
+ get isFinished(): boolean;
114
+ /** Open the turn span. Called on the first `next()`; idempotent. */
115
+ start(): void;
116
+ /** Record one SDK event. Never throws and never mutates the event. */
117
+ onEvent(event: unknown): void;
118
+ /**
119
+ * End every open span for this turn, the turn span last. Idempotent.
120
+ * The spans always end, even if recording their attributes throws: item
121
+ * spans that already ended were exported with the turn as their parent.
122
+ */
123
+ finish(outcome: FinishOutcome): void;
124
+ /** Statuses and attributes for `finish()`; closes open item spans. */
125
+ private recordFinish;
126
+ private turnStartAttributes;
127
+ private sessionAttributes;
128
+ private setThreadId;
129
+ /**
130
+ * `turn.completed.usage` is the thread's running total, not the turn's own
131
+ * spend (measured on 0.162.1: each resumed turn reports the previous total
132
+ * plus its own requests, also across processes). The promoted
133
+ * `gen_ai.usage.*` keys carry only this turn's new spend: the total minus
134
+ * the last total this process saw for the thread. A new thread starts at
135
+ * zero. A resumed thread with no total seen in this process promotes nothing
136
+ * (`codex.usage.baseline_unknown`); later turns promote their delta.
137
+ * A failed or cancelled turn reports no usage, so its spend lands on the
138
+ * thread's next completed turn. Running totals are always on
139
+ * `codex.cumulative.*`.
140
+ */
141
+ private setUsage;
142
+ private itemKey;
143
+ private onItemStarted;
144
+ private onItemUpdated;
145
+ private onItemCompleted;
146
+ private startItemSpan;
147
+ /** Structural fields always; content only when the policy allows it. */
148
+ private applyItemAttributes;
149
+ private applyItemStatus;
150
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