@opengeni/runtime 4.3.0 → 4.4.0-canary.36927100590001

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 (117) hide show
  1. package/dist/agent-instructions/base-behavior.d.ts +8 -0
  2. package/dist/agent-instructions/compose.d.ts +59 -0
  3. package/dist/agent-instructions/identity.d.ts +21 -0
  4. package/dist/agent-instructions/index.d.ts +6 -0
  5. package/dist/agent-instructions/modules/admin.d.ts +3 -0
  6. package/dist/agent-instructions/modules/artifacts.d.ts +7 -0
  7. package/dist/agent-instructions/modules/attachments.d.ts +3 -0
  8. package/dist/agent-instructions/modules/environment.d.ts +11 -0
  9. package/dist/agent-instructions/modules/goals.d.ts +3 -0
  10. package/dist/agent-instructions/modules/knowledge.d.ts +6 -0
  11. package/dist/agent-instructions/modules/machines.d.ts +3 -0
  12. package/dist/agent-instructions/modules/renderer-markdown.d.ts +6 -0
  13. package/dist/agent-instructions/modules/repositories.d.ts +7 -0
  14. package/dist/agent-instructions/modules/sandbox.d.ts +3 -0
  15. package/dist/agent-instructions/modules/skills.d.ts +3 -0
  16. package/dist/agent-instructions/modules/subagents.d.ts +3 -0
  17. package/dist/agent-instructions/runtime-mechanics.d.ts +7 -0
  18. package/dist/agent-instructions/types.d.ts +55 -0
  19. package/dist/assets/codemode-client.json +1 -1
  20. package/dist/{chunk-JUFVYQCY.js → chunk-VDXKKMMD.js} +457 -165
  21. package/dist/chunk-VDXKKMMD.js.map +1 -0
  22. package/dist/{chunk-22M75RJF.js → chunk-ZY655LYR.js} +1636 -709
  23. package/dist/chunk-ZY655LYR.js.map +1 -0
  24. package/dist/claude-subscription-usage.d.ts +3 -1
  25. package/dist/first-party-client.d.ts +1 -0
  26. package/dist/index.d.ts +37 -28
  27. package/dist/index.js +28 -2
  28. package/dist/input-wait-yield.d.ts +4 -0
  29. package/dist/interaction-tools.d.ts +1 -0
  30. package/dist/lazy-tool-transport.d.ts +6 -2
  31. package/dist/mcp-run-credentials.d.ts +3 -2
  32. package/dist/mcp-transport-logger.d.ts +10 -0
  33. package/dist/model-context-inspector.d.ts +17 -1
  34. package/dist/model-preparation-diagnostics.d.ts +9 -0
  35. package/dist/model-provider-routing.d.ts +4 -0
  36. package/dist/model-provider.d.ts +1 -0
  37. package/dist/model-request-capture.d.ts +9 -0
  38. package/dist/replayable-json-body.d.ts +2 -1
  39. package/dist/responses-terminal-error.d.ts +17 -0
  40. package/dist/sandbox/codemode-authority.d.ts +1 -0
  41. package/dist/sandbox/index.d.ts +3 -3
  42. package/dist/sandbox/index.js +5 -1
  43. package/dist/sandbox/provider-command-session.d.ts +6 -0
  44. package/dist/sandbox/providers/modal-command-control.d.ts +7 -0
  45. package/dist/sandbox/providers/modal-command-router-wire.d.ts +8 -0
  46. package/dist/sandbox/providers/modal-command-session.d.ts +2 -1
  47. package/dist/sandbox/providers/modal-command-start-errors.d.ts +9 -0
  48. package/dist/sandbox/providers/modal.d.ts +3 -0
  49. package/dist/sandbox/routing/routing-session.d.ts +5 -4
  50. package/dist/workspace-tool-gateway.js +2 -2
  51. package/package.json +12 -12
  52. package/src/agent-instructions/PROMPT_CHANGELOG.md +149 -0
  53. package/src/agent-instructions/base-behavior.ts +120 -0
  54. package/src/agent-instructions/compose.ts +153 -0
  55. package/src/agent-instructions/identity.ts +42 -0
  56. package/src/agent-instructions/index.ts +24 -0
  57. package/src/agent-instructions/modules/admin.ts +25 -0
  58. package/src/agent-instructions/modules/artifacts.ts +39 -0
  59. package/src/agent-instructions/modules/attachments.ts +12 -0
  60. package/src/agent-instructions/modules/environment.ts +60 -0
  61. package/src/agent-instructions/modules/goals.ts +15 -0
  62. package/src/agent-instructions/modules/knowledge.ts +21 -0
  63. package/src/agent-instructions/modules/machines.ts +17 -0
  64. package/src/agent-instructions/modules/renderer-markdown.ts +17 -0
  65. package/src/agent-instructions/modules/repositories.ts +28 -0
  66. package/src/agent-instructions/modules/sandbox.ts +63 -0
  67. package/src/agent-instructions/modules/skills.ts +19 -0
  68. package/src/agent-instructions/modules/subagents.ts +42 -0
  69. package/src/agent-instructions/runtime-mechanics.ts +55 -0
  70. package/src/agent-instructions/types.ts +83 -0
  71. package/src/bundled_default_skills/opengeni-client/SKILL.md +116 -37
  72. package/src/bundled_default_skills/opengeni-client/references/agent-recipes.md +18 -8
  73. package/src/bundled_default_skills/opengeni-client/references/api-workflows.md +24 -4
  74. package/src/bundled_default_skills/opengeni-client/references/chat-facade-fallback.md +23 -4
  75. package/src/bundled_default_skills/opengeni-client/references/compatibility-and-troubleshooting.md +34 -1
  76. package/src/bundled_default_skills/opengeni-client/references/configure-the-agent.md +248 -0
  77. package/src/bundled_default_skills/opengeni-client/references/customer-skill-template.md +2 -1
  78. package/src/bundled_default_skills/opengeni-client/references/data-tools-and-credentials.md +15 -4
  79. package/src/bundled_default_skills/opengeni-client/references/discovery-and-autonomy.md +2 -2
  80. package/src/bundled_default_skills/opengeni-client/references/isolation-and-authorization.md +5 -3
  81. package/src/bundled_default_skills/opengeni-client/references/product-integration-shapes.md +6 -5
  82. package/src/bundled_default_skills/opengeni-client/references/product-shapes-and-ui.md +36 -3
  83. package/src/bundled_default_skills/opengeni-client/references/proxy-from-any-backend.md +170 -0
  84. package/src/bundled_default_skills/opengeni-client/references/session-history-import.md +147 -0
  85. package/src/bundled_default_skills/opengeni-client/references/usage-allowances.md +189 -0
  86. package/src/bundled_default_skills/opengeni-help/SKILL.md +1 -1
  87. package/src/claude-subscription-usage.ts +23 -4
  88. package/src/first-party-client.ts +4 -0
  89. package/src/index.ts +260 -146
  90. package/src/input-wait-yield.ts +7 -0
  91. package/src/interaction-tools.ts +16 -2
  92. package/src/lazy-tool-transport.ts +46 -16
  93. package/src/mcp-run-credentials.ts +18 -3
  94. package/src/mcp-transport-logger.ts +46 -0
  95. package/src/model-context-inspector.ts +37 -3
  96. package/src/model-preparation-diagnostics.ts +48 -1
  97. package/src/model-provider-client.ts +5 -1
  98. package/src/model-provider-routing.ts +95 -1
  99. package/src/model-provider.ts +1 -0
  100. package/src/model-request-capture.ts +28 -1
  101. package/src/provider-history-adapter.ts +24 -3
  102. package/src/replayable-json-body.ts +19 -2
  103. package/src/responses-terminal-error.ts +136 -0
  104. package/src/sandbox/codemode-authority.ts +4 -0
  105. package/src/sandbox/codemode-client.ts +18 -16
  106. package/src/sandbox/index.ts +45 -9
  107. package/src/sandbox/provider-command-session.ts +12 -0
  108. package/src/sandbox/providers/modal-command-control.ts +118 -12
  109. package/src/sandbox/providers/modal-command-router-wire.ts +40 -4
  110. package/src/sandbox/providers/modal-command-session.ts +36 -1
  111. package/src/sandbox/providers/modal-command-start-errors.ts +27 -0
  112. package/src/sandbox/providers/modal-legacy-command-control.ts +60 -30
  113. package/src/sandbox/providers/modal.ts +43 -2
  114. package/src/sandbox/routing/routing-session.ts +61 -6
  115. package/src/sandbox/turn-tool-cancellation.ts +8 -1
  116. package/dist/chunk-22M75RJF.js.map +0 -1
  117. package/dist/chunk-JUFVYQCY.js.map +0 -1
@@ -681,6 +681,7 @@ export function createInteractionAttemptToolDefinitions(
681
681
  raw,
682
682
  context,
683
683
  options.execute,
684
+ options.readOnly,
684
685
  ),
685
686
  });
686
687
  };
@@ -1477,6 +1478,7 @@ export type CreateFirstPartyInteractionAttemptToolsInput = Omit<
1477
1478
  scope: AttemptToolScope;
1478
1479
  subjectId?: string;
1479
1480
  subjectLabel?: string;
1481
+ credentialRestriction?: "developer_setup";
1480
1482
  fetch?: typeof globalThis.fetch;
1481
1483
  };
1482
1484
 
@@ -1517,6 +1519,9 @@ export function createFirstPartyInteractionAttemptToolDefinitions(
1517
1519
  turnId: input.scope.turnId,
1518
1520
  attemptId: input.scope.attemptId,
1519
1521
  executionGeneration: input.scope.executionGeneration,
1522
+ ...(input.credentialRestriction
1523
+ ? { credentialRestriction: input.credentialRestriction }
1524
+ : {}),
1520
1525
  exp: Math.floor(Date.now() / 1_000) + 60 * 60,
1521
1526
  });
1522
1527
  const headers = new Headers(init?.headers);
@@ -1915,6 +1920,7 @@ async function safeInteractionExecution<TInput extends z.ZodType, TOutput extend
1915
1920
  value: z.output<TInput>,
1916
1921
  context: AttemptToolExecutionContext,
1917
1922
  ) => Promise<z.input<TOutput> | InteractionExecutionResult<z.input<TOutput>>>,
1923
+ readOnly: boolean,
1918
1924
  ): Promise<AttemptToolResultValue> {
1919
1925
  try {
1920
1926
  const value = inputSchema.parse(raw);
@@ -1936,11 +1942,18 @@ async function safeInteractionExecution<TInput extends z.ZodType, TOutput extend
1936
1942
  if (error instanceof z.ZodError) {
1937
1943
  return interactionErrorResult("invalid_arguments", "Interaction tool arguments are invalid.");
1938
1944
  }
1939
- if (error instanceof OpenGeniApiError && !error.outcomeUnknown && error.status < 500) {
1945
+ // A failed read is still a useful tool result. Preserve the API's public
1946
+ // explanation; mutations and uncertain outcomes retain their failure path.
1947
+ if (
1948
+ error instanceof OpenGeniApiError &&
1949
+ !error.outcomeUnknown &&
1950
+ (error.status < 500 || readOnly)
1951
+ ) {
1940
1952
  return interactionErrorResult(
1941
1953
  error.code ?? `http_${error.status}`,
1942
1954
  boundedErrorMessage(error.message),
1943
1955
  error.retryable,
1956
+ error.correlationId,
1944
1957
  );
1945
1958
  }
1946
1959
  throw error;
@@ -1965,8 +1978,9 @@ function interactionErrorResult(
1965
1978
  code: string,
1966
1979
  message: string,
1967
1980
  retryable = false,
1981
+ requestId?: string,
1968
1982
  ): AttemptToolResultValue {
1969
- const error = { code, message, retryable };
1983
+ const error = { code, message, retryable, ...(requestId ? { requestId } : {}) };
1970
1984
  return {
1971
1985
  isError: true,
1972
1986
  content: [{ type: "text" as const, text: JSON.stringify({ error }) }],
@@ -12,7 +12,11 @@ import {
12
12
  } from "@openai/agents";
13
13
  import { isSearchableMcpFunctionTool, searchToolPool } from "./codex-tool-search";
14
14
  import { MCP_MAX_TOOL_SEARCH_DISCLOSURE_BYTES } from "./mcp-network";
15
- import { notifyModelRequestCapture } from "./model-request-capture";
15
+ import {
16
+ beforeModelRequest,
17
+ modelResponseSettlement,
18
+ notifyModelRequestCapture,
19
+ } from "./model-request-capture";
16
20
 
17
21
  /** Provider-contained progressive-disclosure strategy for one resolved turn. */
18
22
  export type LazyToolTransport = "codex_native" | "openai_native" | "generic_dispatch";
@@ -183,6 +187,7 @@ export class LazyToolRuntime {
183
187
  private activeAgent: object | null = null;
184
188
  private activeRunContext: unknown;
185
189
  readonly controlTools: Tool[];
190
+ private routerWasExposed: boolean;
186
191
 
187
192
  constructor(
188
193
  readonly transport: LazyToolTransport,
@@ -191,7 +196,10 @@ export class LazyToolRuntime {
191
196
  private readonly deferredMcpServerIds: ReadonlySet<string> = mcpServerIds,
192
197
  private readonly preparationIndependentToolNames: ReadonlySet<string> = new Set(),
193
198
  private readonly modelMcpServerIds: () => ReadonlyMap<string, string> = () => new Map(),
199
+ private readonly conditionalRouter = false,
200
+ routerInHistory = false,
194
201
  ) {
202
+ this.routerWasExposed = routerInHistory;
195
203
  this.controlTools =
196
204
  transport !== "generic_dispatch"
197
205
  ? [this.buildNativeSearchTool(), this.buildListTool()]
@@ -214,6 +222,19 @@ export class LazyToolRuntime {
214
222
  return !this.preparationSettled;
215
223
  }
216
224
 
225
+ async prepareConditionalRouter(): Promise<void> {
226
+ if (this.conditionalRouter) await this.ensurePrepared();
227
+ }
228
+
229
+ visibleControlTools(): Tool[] {
230
+ // Pending servers are genuinely deferred, even before tools/list completes.
231
+ this.routerWasExposed ||=
232
+ !this.conditionalRouter ||
233
+ this.searchableToolNames.size > 0 ||
234
+ (this.hasPendingPreparation() && this.deferredMcpServerIds.size > 0);
235
+ return this.routerWasExposed ? this.controlTools : [];
236
+ }
237
+
217
238
  async ensurePrepared(): Promise<void> {
218
239
  await this.toolPreparationReady;
219
240
  this.preparationSettled = true;
@@ -595,6 +616,8 @@ export function installLazyToolRuntime(
595
616
  deferredMcpServerIds: ReadonlySet<string> = mcpServerIds,
596
617
  preparationIndependentToolNames: ReadonlySet<string> = new Set(),
597
618
  modelMcpServerIds?: () => ReadonlyMap<string, string>,
619
+ conditionalRouter = false,
620
+ routerInHistory = false,
598
621
  ): LazyToolRuntime {
599
622
  const runtime = new LazyToolRuntime(
600
623
  transport,
@@ -603,6 +626,8 @@ export function installLazyToolRuntime(
603
626
  deferredMcpServerIds,
604
627
  preparationIndependentToolNames,
605
628
  modelMcpServerIds,
629
+ conditionalRouter,
630
+ routerInHistory,
606
631
  );
607
632
  installLazyToolRuntimeOnAgent(agent, runtime);
608
633
  return runtime;
@@ -626,17 +651,18 @@ function installLazyToolRuntimeOnAgent(agent: CloneCapableAgent, runtime: LazyTo
626
651
  runtime.registerOriginalToolLoader(agent, originalGetAllTools);
627
652
  agent.getAllTools = (async (runContext: unknown) => {
628
653
  runtime.noteToolResolution(agent, runContext);
654
+ await runtime.prepareConditionalRouter();
629
655
  if (runtime.hasPendingPreparation()) {
630
656
  // Deferred MCP projections return an empty list until their shared
631
657
  // preparation fence settles, while required/eager MCP and ordinary agent
632
658
  // tools resolve normally through the policy-wrapped SDK path.
633
659
  const tools = await originalGetAllTools(runContext);
634
660
  runtime.refresh(tools);
635
- return [...tools, ...runtime.controlTools];
661
+ return [...tools, ...runtime.visibleControlTools()];
636
662
  }
637
663
  const tools = await originalGetAllTools(runContext);
638
664
  runtime.refresh(tools);
639
- return [...runtime.configuredExecutionTools(tools), ...runtime.controlTools];
665
+ return [...runtime.configuredExecutionTools(tools), ...runtime.visibleControlTools()];
640
666
  }) as typeof agent.getAllTools;
641
667
 
642
668
  const originalClone = agent.clone?.bind(agent);
@@ -829,6 +855,7 @@ class LazyToolModel implements Model {
829
855
  ) {}
830
856
 
831
857
  async getResponse(request: ModelRequest): Promise<ModelResponse> {
858
+ await beforeModelRequest();
832
859
  const prepared = prepareLazyToolRequest(request, this.runtime);
833
860
  rememberPreparedModelRequest(prepared);
834
861
  void notifyModelRequestCapture(prepared);
@@ -842,6 +869,7 @@ class LazyToolModel implements Model {
842
869
  }
843
870
 
844
871
  async *getStreamedResponse(request: ModelRequest): AsyncIterable<StreamEvent> {
872
+ await beforeModelRequest();
845
873
  const prepared = prepareLazyToolRequest(request, this.runtime);
846
874
  rememberPreparedModelRequest(prepared);
847
875
  void notifyModelRequestCapture(prepared);
@@ -851,19 +879,21 @@ class LazyToolModel implements Model {
851
879
  await this.runtime.ensurePrepared();
852
880
  }
853
881
  }
854
- if (this.runtime.transport === "generic_dispatch" && event.type === "response_done") {
855
- yield {
856
- ...event,
857
- response: {
858
- ...event.response,
859
- output: event.response.output.flatMap((item) =>
860
- transformGenericDispatchCall(item, this.runtime),
861
- ) as typeof event.response.output,
862
- },
863
- } as StreamEvent;
864
- } else {
865
- yield event;
866
- }
882
+ const delivered =
883
+ this.runtime.transport === "generic_dispatch" && event.type === "response_done"
884
+ ? ({
885
+ ...event,
886
+ response: {
887
+ ...event.response,
888
+ output: event.response.output.flatMap((item) =>
889
+ transformGenericDispatchCall(item, this.runtime),
890
+ ) as typeof event.response.output,
891
+ },
892
+ } as StreamEvent)
893
+ : event;
894
+ const settlement = modelResponseSettlement(delivered);
895
+ void settlement?.catch(() => undefined);
896
+ yield delivered;
867
897
  }
868
898
  }
869
899
 
@@ -1,9 +1,14 @@
1
1
  import {
2
2
  CredentialProviderMcpMaterial,
3
3
  normalizeCredentialProviderMcpUrl,
4
+ type McpServerConnectionRef,
4
5
  } from "@opengeni/contracts";
5
6
 
6
- export type RunMcpCredentialTarget = { id: string; url: string };
7
+ export type RunMcpCredentialTarget = {
8
+ id: string;
9
+ url: string;
10
+ connectionRef?: McpServerConnectionRef | undefined;
11
+ };
7
12
  export type RunMcpCredentialMaterial = {
8
13
  mcp?: CredentialProviderMcpMaterial;
9
14
  expiresAt: Date | null;
@@ -43,7 +48,9 @@ export class RunMcpCredentials {
43
48
  targets: readonly RunMcpCredentialTarget[],
44
49
  options: { signal?: AbortSignal; now?: () => number } = {},
45
50
  ) {
46
- this.#targets = targets.map(({ id, url }) => ({ id, url }));
51
+ this.#targets = targets
52
+ .filter((target) => !target.connectionRef)
53
+ .map(({ id, url }) => ({ id, url }));
47
54
  this.#signal = options.signal;
48
55
  this.#now = options.now ?? Date.now;
49
56
  this.#signal?.addEventListener("abort", this.#onAbort, { once: true });
@@ -135,11 +142,12 @@ export class RunMcpCredentials {
135
142
  this.prepare(material)();
136
143
  }
137
144
 
138
- /** Refuse credentials for omitted, local, or rewritten server routes. */
145
+ /** Refuse credentials for native, omitted, local, or rewritten server routes. */
139
146
  assertRemoteTargets(targets: readonly RunMcpCredentialTarget[]): void {
140
147
  this.#remoteTargets = this.#targets.filter((original) =>
141
148
  targets.some(
142
149
  (target) =>
150
+ !target.connectionRef &&
143
151
  target.id === original.id &&
144
152
  normalizedUrl(target.url) !== null &&
145
153
  normalizedUrl(target.url) === normalizedUrl(original.url),
@@ -195,6 +203,13 @@ export class RunMcpCredentials {
195
203
  init?: RequestInit,
196
204
  ): RequestInit | undefined {
197
205
  this.#assertOpen();
206
+ // Native connection authority and attribution own all authentication on
207
+ // this route. Even a stale or manually supplied provider grant must never
208
+ // replace its bearer or inject alternate authentication headers.
209
+ if (target.connectionRef) {
210
+ this.excludeLocalTarget(target.id);
211
+ return init;
212
+ }
198
213
  this.assertAvailable(target.id);
199
214
  const entry = this.#entries.get(target.id);
200
215
  if (!entry) return init;
@@ -0,0 +1,46 @@
1
+ const CLEANUP_MESSAGES = new Set([
2
+ "Failed to terminate MCP session:",
3
+ "Failed to close MCP client:",
4
+ "Failed to close MCP transport:",
5
+ ...[
6
+ "failed MCP reconnect",
7
+ "stale MCP",
8
+ "discarded MCP",
9
+ "replaced MCP",
10
+ "reconnected MCP",
11
+ ].flatMap((name) => [`Failed to close ${name} client:`, `Failed to terminate ${name} session:`]),
12
+ ]);
13
+
14
+ /** SDK cleanup warnings do not imply failed connect, discovery, or tool calls.
15
+ * Emit only fixed labels and the runtime's credential-safe error projection. */
16
+ export function createMcpTransportLogger(
17
+ serverId: string,
18
+ errorFields: (
19
+ error: unknown,
20
+ code: "mcp_cleanup_failed" | "mcp_transport_failed",
21
+ serverId: string,
22
+ ) => unknown,
23
+ ) {
24
+ const logFailure = (message: string, ...args: unknown[]) => {
25
+ const cleanup = CLEANUP_MESSAGES.has(message);
26
+ let error: unknown;
27
+ for (let index = args.length - 1; index >= 0; index--) {
28
+ if (args[index] instanceof Error) {
29
+ error = args[index];
30
+ break;
31
+ }
32
+ }
33
+ console.warn(
34
+ cleanup ? "[mcp] cleanup operation failed" : "[mcp] transport operation failed",
35
+ errorFields(error, cleanup ? "mcp_cleanup_failed" : "mcp_transport_failed", serverId),
36
+ );
37
+ };
38
+ return {
39
+ namespace: "opengeni:mcp-transport",
40
+ debug: () => undefined,
41
+ error: logFailure,
42
+ warn: logFailure,
43
+ dontLogModelData: true,
44
+ dontLogToolData: true,
45
+ };
46
+ }
@@ -2,6 +2,7 @@ import type { ModelRequest, RunContext, SerializedTool, Tool } from "@openai/age
2
2
  import type {
3
3
  ModelContextInstructionLayer,
4
4
  ModelContextInstructionLayerId,
5
+ ModelContextInstructionModule,
5
6
  ModelContextSkill,
6
7
  ModelContextSnapshot,
7
8
  ModelContextTool,
@@ -15,6 +16,13 @@ export type PersistentAgentInstructionLayerDraft = {
15
16
  id: ModelContextInstructionLayerId;
16
17
  title: string;
17
18
  content: string;
19
+ /** Modular operational contract only: its prompt modules in order. */
20
+ modules?: readonly ModelContextInstructionModule[];
21
+ /**
22
+ * Separator placed before this layer. Modular layers set it; legacy layers
23
+ * omit it and keep the historical joins byte-for-byte.
24
+ */
25
+ joinBefore?: string;
18
26
  };
19
27
 
20
28
  function contextTextEstimate(value: unknown): number | null {
@@ -39,6 +47,15 @@ export function buildProviderRequestSnapshot(input: {
39
47
  body: string | null;
40
48
  unavailableReason?: string;
41
49
  requestIndex: number;
50
+ /**
51
+ * The agent's persistent instruction layers. When the wire `instructions`
52
+ * start with them, the snapshot names those sections (identity, the
53
+ * operational contract with its prompt modules, governance, ...) so an
54
+ * inspector can show them with titles. The wire body stays the source of
55
+ * truth; an unrecognized prompt yields no sections.
56
+ */
57
+ persistentLayers?: readonly PersistentAgentInstructionLayerDraft[];
58
+ genesisTitleDirective?: string;
42
59
  }): ModelContextSnapshot {
43
60
  let body = input.body;
44
61
  let unavailableReason = input.unavailableReason;
@@ -61,15 +78,29 @@ export function buildProviderRequestSnapshot(input: {
61
78
  }));
62
79
  const instructionsTokens =
63
80
  parts.find((part) => part.key === "instructions")?.estimatedTokens ?? 0;
81
+ const wireInstructions = typeof payload.instructions === "string" ? payload.instructions : null;
82
+ const sectionLayers =
83
+ wireInstructions && input.persistentLayers?.length
84
+ ? splitCapturedInstructions({
85
+ persistentLayers: input.persistentLayers,
86
+ capturedInstructions: wireInstructions,
87
+ genesisTitleDirective: input.genesisTitleDirective ?? "",
88
+ })
89
+ : [];
90
+ // Only a recognized structure is worth repeating; a raw blob adds nothing.
91
+ const layers = sectionLayers.some((layer) => layer.id !== "sent_system_instructions")
92
+ ? sectionLayers
93
+ : [];
64
94
  const toolsTokens = parts.find((part) => part.key === "tools")?.estimatedTokens ?? 0;
65
95
  return {
66
96
  version: MODEL_CONTEXT_SNAPSHOT_VERSION,
67
97
  source: "model_request",
68
98
  capturedAt: new Date().toISOString(),
69
99
  requestIndex: input.requestIndex,
70
- // Wire body owns the contents. Legacy prefix fields are not reconstructed.
100
+ // Wire body owns the contents. Legacy prefix fields are not reconstructed;
101
+ // `layers` only names sections of the wire instructions.
71
102
  instructions: "",
72
- layers: [],
103
+ layers,
73
104
  tools: [],
74
105
  skills: [],
75
106
  tokens: {
@@ -108,6 +139,7 @@ const LAYER_TITLES: Record<ModelContextInstructionLayerId, string> = {
108
139
  sandbox_preamble: "Sandbox runtime preamble",
109
140
  sandbox_filesystem: "Sandbox filesystem",
110
141
  sent_system_instructions: "Sent system instructions",
142
+ identity: "Identity",
111
143
  };
112
144
 
113
145
  export function joinPersistentAgentInstructionLayers(
@@ -119,7 +151,8 @@ export function joinPersistentAgentInstructionLayers(
119
151
  const previous = layers[index - 1]!;
120
152
  const current = layers[index]!;
121
153
  const separator =
122
- previous.id === "operational_contract" && current.id === "persona_and_core" ? "\n\n" : " ";
154
+ current.joinBefore ??
155
+ (previous.id === "operational_contract" && current.id === "persona_and_core" ? "\n\n" : " ");
123
156
  composed = `${composed}${separator}${current.content}`;
124
157
  }
125
158
  return composed;
@@ -134,6 +167,7 @@ export function countedInstructionLayer(
134
167
  content: draft.content,
135
168
  utf8Bytes: Buffer.byteLength(draft.content, "utf8"),
136
169
  estimatedTokens: estimateTextTokens(draft.content),
170
+ ...(draft.modules ? { modules: draft.modules.map((module) => ({ ...module })) } : {}),
137
171
  };
138
172
  }
139
173
 
@@ -1,5 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { setTraceProcessors, type Span, type Trace, type TracingProcessor } from "@openai/agents";
3
+ import { beforeModelRequest } from "./model-request-capture";
3
4
 
4
5
  export type ModelPreparationPhase =
5
6
  | "sandbox_agent_preparation"
@@ -64,6 +65,10 @@ type ModelPreparationObservation = {
64
65
 
65
66
  const modelPreparationObserver = new AsyncLocalStorage<ModelPreparationObservation>();
66
67
  const modelTransportStartedObserver = new AsyncLocalStorage<() => Promise<void> | void>();
68
+ type ModelTransportAdmission = { refusal?: { error: unknown } };
69
+ type ModelTransportFetch = (...args: Parameters<typeof fetch>) => ReturnType<typeof fetch>;
70
+ const modelTransportAdmission = new AsyncLocalStorage<ModelTransportAdmission>();
71
+ const modelTransportRefusals = new WeakMap<Headers, { error: unknown }>();
67
72
 
68
73
  class ModelPreparationTraceProcessor implements TracingProcessor {
69
74
  async onTraceStart(_trace: Trace): Promise<void> {}
@@ -127,7 +132,49 @@ export function withModelTransportStartedObserver<T>(
127
132
  }
128
133
 
129
134
  export async function recordModelTransportStarted(): Promise<void> {
130
- await modelTransportStartedObserver.getStore()?.();
135
+ try {
136
+ await beforeModelRequest();
137
+ await modelTransportStartedObserver.getStore()?.();
138
+ } catch (error) {
139
+ const admission = modelTransportAdmission.getStore();
140
+ if (admission) admission.refusal = { error };
141
+ throw error;
142
+ }
143
+ }
144
+
145
+ /** The OpenAI SDK retries thrown fetch errors and replaces their identity with
146
+ * APIConnectionError. Carry only our pre-wire refusal through its HTTP-error
147
+ * path, which honors the retry veto. Native transports keep the original throw.
148
+ * Each fetch owns its context even when concurrent turns share a cached client.
149
+ */
150
+ export function sdkModelTransportAdmissionFetch(inner: ModelTransportFetch): ModelTransportFetch {
151
+ return async (input, init) => {
152
+ const admission: ModelTransportAdmission = {};
153
+ return modelTransportAdmission.run(admission, async () => {
154
+ try {
155
+ return await inner(input, init);
156
+ } catch (error) {
157
+ if (!admission.refusal || admission.refusal.error !== error) throw error;
158
+ // This is a local SDK handoff, not a provider or public API response.
159
+ // Identity, not response bytes/headers supplied by a provider, grants
160
+ // access to the original error at the SDK's status-error boundary.
161
+ const response = new Response(null, {
162
+ status: 400,
163
+ headers: { "x-should-retry": "false" },
164
+ });
165
+ modelTransportRefusals.set(response.headers, admission.refusal);
166
+ return response;
167
+ }
168
+ });
169
+ };
170
+ }
171
+
172
+ /** Restore the exact host-owned error after the SDK has suppressed retries. */
173
+ export function rethrowModelTransportAdmissionRefusal(headers: Headers): void {
174
+ const refusal = modelTransportRefusals.get(headers);
175
+ if (!refusal) return;
176
+ modelTransportRefusals.delete(headers);
177
+ throw refusal.error;
131
178
  }
132
179
 
133
180
  /** Record the first routed sandbox operation boundary without publishing an
@@ -29,7 +29,10 @@ import { ReplayableJsonOpenAI } from "./replayable-json-body";
29
29
  import { recordModelTransportStarted } from "./model-preparation-diagnostics";
30
30
  import { captureProviderRequestBody } from "./model-request-capture";
31
31
  import { withoutQuotaExhaustedRetries } from "./provider-quota";
32
- import { observeClaudeUsageResponse } from "./claude-subscription-usage";
32
+ import {
33
+ observeClaudeUsageResponse,
34
+ prepareClaudeSubscriptionRequest,
35
+ } from "./claude-subscription-usage";
33
36
 
34
37
  let runtimeMetricsHooks: RuntimeMetricsHooks | null = null;
35
38
 
@@ -400,6 +403,7 @@ export function instrumentedModelFetch(provider: string, inner: typeof fetch): t
400
403
  if (!isModelCallFetch(input)) {
401
404
  return await inner(input, init);
402
405
  }
406
+ init = await prepareClaudeSubscriptionRequest(provider, input, init);
403
407
  // The attempt-local observer durably checkpoints provider dispatch before
404
408
  // this process can place request bytes on the network.
405
409
  await recordModelTransportStarted();
@@ -8,7 +8,7 @@ import {
8
8
  type ModelRequest,
9
9
  type ResponseStreamEvent,
10
10
  } from "@openai/agents";
11
- import OpenAI from "openai";
11
+ import OpenAI, { APIError } from "openai";
12
12
  import { AnthropicMessagesModel } from "./anthropic-messages";
13
13
  import { instrumentedModelFetch } from "./model-provider-client";
14
14
  import { CODEX_MODEL_ID_PREFIX } from "@opengeni/codex";
@@ -16,6 +16,10 @@ import { XAI_SUBSCRIPTION_MODEL_ID_PREFIX } from "@opengeni/xai-subscription";
16
16
 
17
17
  import { AppendOnlyOpenAIResponsesModel } from "./append-only-responses-model";
18
18
  import { recordModelPreparationMeasurement } from "./model-preparation-diagnostics";
19
+ import {
20
+ ResponsesStreamingTerminalError,
21
+ responsesStreamingTerminalError,
22
+ } from "./responses-terminal-error";
19
23
  import { buildProviderClient } from "./model-provider-client";
20
24
  import {
21
25
  CodexSubscriptionUnavailableError,
@@ -81,6 +85,96 @@ export class OpenGeniResponsesModel extends AppendOnlyOpenAIResponsesModel {
81
85
  super(client, model);
82
86
  }
83
87
 
88
+ protected override _fetchResponse(
89
+ request: ModelRequest,
90
+ stream: false,
91
+ ): Promise<OpenAI.Responses.Response>;
92
+ protected _fetchResponse(
93
+ request: ModelRequest,
94
+ stream: true,
95
+ ): Promise<AsyncIterable<OpenAI.Responses.ResponseStreamEvent>>;
96
+ protected async _fetchResponse(
97
+ request: ModelRequest,
98
+ stream: boolean,
99
+ ): Promise<OpenAI.Responses.Response | AsyncIterable<OpenAI.Responses.ResponseStreamEvent>> {
100
+ if (!stream || !this.ownsResponsesTerminalClassification()) {
101
+ // Subscription transports retain the SDK's request-id and error handling.
102
+ return await super._fetchResponse(request, stream as false);
103
+ }
104
+ // Reuse the SDK's full request conversion, but retain its HTTP receipt
105
+ // before the SDK's stream wrapper discards the response headers.
106
+ const built = this._buildResponsesCreateRequest(request, true);
107
+ const internal = (request as ModelRequest & { _internal?: { runnerManagedRetry?: boolean } })
108
+ ._internal;
109
+ const pending = this._client.responses.create(
110
+ built.requestData as OpenAI.Responses.ResponseCreateParamsStreaming,
111
+ {
112
+ headers: built.sdkRequestHeaders,
113
+ signal: built.signal,
114
+ ...(built.transportExtraQuery ? { query: built.transportExtraQuery } : {}),
115
+ ...(internal?.runnerManagedRetry === true ? { maxRetries: 0 } : {}),
116
+ },
117
+ );
118
+ if (typeof pending.withResponse !== "function") {
119
+ // The SDK also permits custom clients returning only the stream promise.
120
+ // Such clients cannot supply HTTP evidence, but must remain usable.
121
+ return this.classifiedResponseStream(await pending, new Headers(), null);
122
+ }
123
+ const receipt = await pending.withResponse();
124
+ return this.classifiedResponseStream(
125
+ receipt.data,
126
+ receipt.response.headers,
127
+ receipt.request_id,
128
+ );
129
+ }
130
+
131
+ private async *classifiedResponseStream(
132
+ stream: AsyncIterable<OpenAI.Responses.ResponseStreamEvent>,
133
+ headers: Headers,
134
+ requestId: string | null,
135
+ ): AsyncIterable<OpenAI.Responses.ResponseStreamEvent> {
136
+ try {
137
+ for await (const event of stream) {
138
+ const failure = responsesStreamingTerminalError(event, headers);
139
+ if (failure) throw failure;
140
+ // response.done is supported by the pinned terminal reducer but absent
141
+ // from the OpenAI wire declaration.
142
+ const eventType: string = event.type;
143
+ if (
144
+ requestId &&
145
+ (eventType === "response.completed" || eventType === "response.done") &&
146
+ "response" in event &&
147
+ event.response &&
148
+ !("_request_id" in event.response)
149
+ ) {
150
+ // Match the SDK's successful-terminal request-id attachment without
151
+ // making transport metadata enumerable in provider/model data.
152
+ try {
153
+ Object.defineProperty(event.response, "_request_id", {
154
+ value: requestId,
155
+ enumerable: false,
156
+ });
157
+ } catch {
158
+ // Frozen custom response objects remain usable, as in the SDK.
159
+ }
160
+ }
161
+ yield event;
162
+ }
163
+ } catch (error) {
164
+ // The OpenAI parser can throw a top-level `error` before yielding it.
165
+ // Convert inside the stream, before the Agents SDK's span error handler,
166
+ // so even enabled model tracing receives only the structural message.
167
+ if (error instanceof APIError && error.status === undefined && error.error) {
168
+ throw new ResponsesStreamingTerminalError("response.error", error.error, headers);
169
+ }
170
+ throw error;
171
+ }
172
+ }
173
+
174
+ private ownsResponsesTerminalClassification(): boolean {
175
+ return this.provider.kind !== "codex-subscription" && this.provider.kind !== "xai-subscription";
176
+ }
177
+
84
178
  protected override _buildResponsesCreateRequest(request: ModelRequest, stream: boolean) {
85
179
  const startedAt = performance.now();
86
180
  let outcome: "completed" | "failed" = "completed";
@@ -10,6 +10,7 @@ import {
10
10
  import { buildOpenAIClientFromSettings } from "./model-provider-client";
11
11
  import { MultiProviderModelProvider } from "./model-provider-routing";
12
12
 
13
+ export { ResponsesStreamingTerminalError } from "./responses-terminal-error";
13
14
  export {
14
15
  CodexSubscriptionUnavailableError,
15
16
  OrganizationGatewayUnavailableError,
@@ -14,6 +14,27 @@ export type ModelRequestCapture = ((request: ModelRequest) => void | Promise<voi
14
14
  const modelRequestCapture = new AsyncLocalStorage<ModelRequestCapture>();
15
15
  const captureIndices = new WeakMap<object, number>();
16
16
 
17
+ /** Awaited producer-side authority, separate from observational request capture. */
18
+ export type ModelCallLifecycle = {
19
+ beforeModelRequest?: () => Promise<void>;
20
+ /** Register before yielding so the next model entry waits for consumer settlement. */
21
+ onModelResponse?: (event: StreamEvent) => Promise<void>;
22
+ };
23
+ const modelCallLifecycle = new AsyncLocalStorage<ModelCallLifecycle>();
24
+
25
+ export function withModelCallLifecycle<T>(lifecycle: ModelCallLifecycle, fn: () => T): T {
26
+ return modelCallLifecycle.run(lifecycle, fn);
27
+ }
28
+
29
+ export async function beforeModelRequest(): Promise<void> {
30
+ await modelCallLifecycle.getStore()?.beforeModelRequest?.();
31
+ }
32
+
33
+ export function modelResponseSettlement(event: StreamEvent): Promise<void> | undefined {
34
+ if (event.type !== "response_done") return undefined;
35
+ return modelCallLifecycle.getStore()?.onModelResponse?.(event);
36
+ }
37
+
17
38
  /** The same agent can re-enter runAgentStream after in-activity compaction. */
18
39
  export function nextModelContextCaptureIndex(agent: object): number {
19
40
  const index = (captureIndices.get(agent) ?? 0) + 1;
@@ -133,15 +154,21 @@ export class ModelRequestCaptureModel implements Model {
133
154
  constructor(private readonly inner: Model) {}
134
155
 
135
156
  async getResponse(request: ModelRequest) {
157
+ await beforeModelRequest();
136
158
  rememberPreparedModelRequest(request);
137
159
  void notifyModelRequestCapture(request);
138
160
  return this.inner.getResponse(request);
139
161
  }
140
162
 
141
163
  async *getStreamedResponse(request: ModelRequest): AsyncIterable<StreamEvent> {
164
+ await beforeModelRequest();
142
165
  rememberPreparedModelRequest(request);
143
166
  void notifyModelRequestCapture(request);
144
- yield* this.inner.getStreamedResponse(request);
167
+ for await (const event of this.inner.getStreamedResponse(request)) {
168
+ const settlement = modelResponseSettlement(event);
169
+ void settlement?.catch(() => undefined);
170
+ yield event;
171
+ }
145
172
  }
146
173
 
147
174
  getRetryAdvice(args: Parameters<NonNullable<Model["getRetryAdvice"]>>[0]) {