@opengeni/runtime 6.7.0 → 6.8.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 (49) hide show
  1. package/dist/anthropic-messages.d.ts +14 -1
  2. package/dist/assets/codemode-client.json +1 -1
  3. package/dist/{chunk-3MNZZ2B4.js → chunk-2MBI6D2F.js} +2 -2
  4. package/dist/{chunk-JY5NSZ37.js → chunk-5K2NI7NX.js} +15 -13
  5. package/dist/chunk-5K2NI7NX.js.map +1 -0
  6. package/dist/{chunk-77NQGL66.js → chunk-6MHS5OUN.js} +1 -1
  7. package/dist/chunk-6MHS5OUN.js.map +1 -0
  8. package/dist/{chunk-RZJXTSVA.js → chunk-E2YB7OIA.js} +2 -2
  9. package/dist/{chunk-JF5UTPEU.js → chunk-JRM6HEPY.js} +2 -2
  10. package/dist/{chunk-GFAFQMZV.js → chunk-QNQGZKHJ.js} +3 -3
  11. package/dist/{chunk-FNAYH3SN.js → chunk-RXCYGCX7.js} +1282 -477
  12. package/dist/chunk-RXCYGCX7.js.map +1 -0
  13. package/dist/{chunk-OAW6MMSY.js → chunk-V7MCFH4O.js} +3 -3
  14. package/dist/gmail-rest-mcp.js +3 -3
  15. package/dist/google-calendar-rest-mcp.js +2 -2
  16. package/dist/index.js +8 -8
  17. package/dist/metrics.d.ts +15 -0
  18. package/dist/model-call.js +1 -1
  19. package/dist/model-provider-client.d.ts +3 -0
  20. package/dist/provider-history-adapter.d.ts +0 -6
  21. package/dist/provider-invalid-request.d.ts +12 -0
  22. package/dist/provider-request-tool-names.d.ts +134 -0
  23. package/dist/provider-tool-names.d.ts +4 -5
  24. package/dist/replayable-json-body.d.ts +5 -1
  25. package/dist/sandbox/index.js +2 -2
  26. package/dist/sandbox/routing/backend-resolver.d.ts +6 -5
  27. package/dist/slack-rest-mcp.js +3 -3
  28. package/dist/workspace-tool-gateway.js +8 -8
  29. package/package.json +15 -15
  30. package/src/anthropic-messages.ts +98 -11
  31. package/src/index.ts +2 -1
  32. package/src/metrics.ts +15 -0
  33. package/src/model-provider-client.ts +16 -0
  34. package/src/model-provider-routing.ts +2 -3
  35. package/src/provider-history-adapter.ts +6 -21
  36. package/src/provider-invalid-request.ts +90 -19
  37. package/src/provider-request-tool-names.ts +900 -0
  38. package/src/provider-tool-names.ts +14 -20
  39. package/src/replayable-json-body.ts +171 -3
  40. package/src/sandbox/routing/backend-resolver.ts +9 -9
  41. package/src/single-model-call.ts +2 -1
  42. package/dist/chunk-77NQGL66.js.map +0 -1
  43. package/dist/chunk-FNAYH3SN.js.map +0 -1
  44. package/dist/chunk-JY5NSZ37.js.map +0 -1
  45. /package/dist/{chunk-3MNZZ2B4.js.map → chunk-2MBI6D2F.js.map} +0 -0
  46. /package/dist/{chunk-RZJXTSVA.js.map → chunk-E2YB7OIA.js.map} +0 -0
  47. /package/dist/{chunk-JF5UTPEU.js.map → chunk-JRM6HEPY.js.map} +0 -0
  48. /package/dist/{chunk-GFAFQMZV.js.map → chunk-QNQGZKHJ.js.map} +0 -0
  49. /package/dist/{chunk-OAW6MMSY.js.map → chunk-V7MCFH4O.js.map} +0 -0
@@ -3,8 +3,8 @@ import { SECRET_VALUE_MASK_MIN_CHARS } from "@opengeni/contracts";
3
3
  import { ALIASED_MCP_TOOL_LEAF_LENGTH, isAliasedMcpToolName } from "./mcp-model-tool-name";
4
4
 
5
5
  /**
6
- * Tool names in replayed history (docs/model-providers.md, "Tool names in
7
- * history").
6
+ * Tool names in replayed history (docs/model-providers.md, "Tool names on
7
+ * the wire").
8
8
  *
9
9
  * Providers validate tool names in the request's tools and in every history
10
10
  * item that carries tool definitions (`tool_search_output`, `additional_tools`)
@@ -21,9 +21,9 @@ import { ALIASED_MCP_TOOL_LEAF_LENGTH, isAliasedMcpToolName } from "./mcp-model-
21
21
  * `withProviderValidToolNames` gives each such name one valid name, the same
22
22
  * wherever it appears in the request. With the authorized catalog (the lazy
23
23
  * tool transport) a flat name becomes the one tool it denotes, so a later call
24
- * binds to it, and every other name is left to the provider projection
25
- * (which sees only the request's tools): a stable alias on Responses and
26
- * Claude, a historical fact for a Chat call. A request
24
+ * binds to it, and every other name is left as it is: a Chat call replays as a
25
+ * historical fact, and the outbound guard (`provider-request-tool-names.ts`)
26
+ * gives every name still invalid on the wire its stable alias. A request
27
27
  * tool's own name is never rewritten. Valid names, and items without an
28
28
  * invalid one, are returned unchanged and by identity, and a rewritten item
29
29
  * keeps its identity across requests while the mapping is the same, so
@@ -47,12 +47,17 @@ export function isProviderToolName(name: string): boolean {
47
47
  }
48
48
 
49
49
  /**
50
- * The stable alias of a name no authorized tool answers to: its readable
51
- * part with every other character replaced, and a digest of the whole name,
52
- * so two different names never share an alias. At most 57 characters.
50
+ * The stable alias of a tool name: its readable part with every other
51
+ * character replaced, starting with a letter, and a digest of the whole
52
+ * name, so two different names never share an alias. Only letters, digits
53
+ * and `_`, at most 57 characters: narrower than any provider's own format.
53
54
  */
54
55
  export function providerToolNameAlias(name: string): string {
55
- const readable = name.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, ALIAS_READABLE_LENGTH);
56
+ const replaced = name.replace(/[^a-zA-Z0-9_]+/g, "_");
57
+ const readable = (/^[a-zA-Z]/.test(replaced) ? replaced : `t${replaced}`).slice(
58
+ 0,
59
+ ALIAS_READABLE_LENGTH,
60
+ );
56
61
  const digest = createHash("sha256").update(name).digest("hex").slice(0, ALIAS_DIGEST_LENGTH);
57
62
  return `${readable}_${digest}`;
58
63
  }
@@ -110,17 +115,6 @@ export function knownToolNameFor(name: string, known: readonly string[]): string
110
115
  return uniqueMatch(valid, (candidate) => pattern.test(candidate));
111
116
  }
112
117
 
113
- /** The model names of a request's function tools. */
114
- export function requestFunctionToolNames(tools: readonly unknown[] | undefined): string[] {
115
- const names: string[] = [];
116
- for (const tool of tools ?? []) {
117
- if (isRecord(tool) && tool.type === "function" && typeof tool.name === "string") {
118
- names.push(tool.name);
119
- }
120
- }
121
- return names;
122
- }
123
-
124
118
  /** The tools history names are checked against. */
125
119
  export type ToolNameCatalog = {
126
120
  /** Model names of the tools; a history name equal to one is never rewritten. */
@@ -1,6 +1,8 @@
1
1
  import OpenAI, { type APIError } from "openai";
2
2
  import type { APIPromise } from "openai/core/api-promise";
3
+ import { Stream } from "openai/core/streaming";
3
4
  import { types as utilTypes } from "node:util";
5
+ import { CODEX_REQUEST_ID_HEADER } from "@opengeni/codex";
4
6
  import { hasResponsesTurn, markResponsesPrefixReady } from "@opengeni/network/responses-websocket";
5
7
  import {
6
8
  createJsonSafeSummary,
@@ -11,6 +13,16 @@ import {
11
13
  rethrowModelTransportAdmissionRefusal,
12
14
  sdkModelTransportAdmissionFetch,
13
15
  } from "./model-preparation-diagnostics";
16
+ import {
17
+ guardRequestToolNames,
18
+ observeToolNames,
19
+ RejectedToolNames,
20
+ toolNameRejectionOfResponse,
21
+ restoreToolNames,
22
+ type ToolNameAliases,
23
+ type ToolNameObservers,
24
+ type ToolNameWireApi,
25
+ } from "./provider-request-tool-names";
14
26
 
15
27
  const TARGET_CHUNK_CHARS = 64 * 1024;
16
28
  const LARGE_STRING_SOURCE_CHARS = 32 * 1024;
@@ -60,11 +72,140 @@ export type ModelJsonRequestPolicy = (request: {
60
72
  body: Readonly<Record<string, unknown>>;
61
73
  }) => ModelJsonRequestPolicyResult | undefined;
62
74
 
63
- export type ReplayableJsonOpenAIHooks = {
75
+ export type ReplayableJsonOpenAIHooks = ToolNameObservers & {
64
76
  /** Synchronous object-stage policy, run exactly once before serialization. */
65
77
  modelRequestPolicy?: ModelJsonRequestPolicy;
66
78
  };
67
79
 
80
+ /**
81
+ * The tool names of one model request: the body before the outbound guard
82
+ * and the aliases the provider's answer is mapped back with.
83
+ */
84
+ type ToolNameRequest = {
85
+ api: ToolNameWireApi;
86
+ original: Record<string, unknown>;
87
+ aliases: ToolNameAliases;
88
+ /** The strict body, once the provider rejected a tool name; later sends use it. */
89
+ strict?: Record<string, unknown>;
90
+ /** The client's memory of names its route rejected. */
91
+ rejected: RejectedToolNames;
92
+ };
93
+
94
+ /** Each guarded request body's tool names, by the body's identity. */
95
+ const toolNameRequests = new WeakMap<object, ToolNameRequest>();
96
+
97
+ function toolNameApi(path: string): ToolNameWireApi | null {
98
+ const pathname = path.split("?", 1)[0] ?? path;
99
+ if (pathname.endsWith("/responses")) return "responses";
100
+ if (pathname.endsWith("/chat/completions")) return "chat";
101
+ return null;
102
+ }
103
+
104
+ /** A fetch init that sends `body` instead, replayable like the original. */
105
+ function withJsonBody(
106
+ init: RequestInit | undefined,
107
+ body: Record<string, unknown>,
108
+ ): ReplayableRequestInit {
109
+ const replay = new ReplayableJsonBody(body);
110
+ return {
111
+ ...init,
112
+ body: replay.createStream(),
113
+ [REPLAYABLE_REQUEST_BODY_FACTORY]: () => replay.createStream(),
114
+ };
115
+ }
116
+
117
+ /** Headers whose value identifies one request body to a provider or transport. */
118
+ const REQUEST_IDENTITY_HEADERS = ["idempotency-key", CODEX_REQUEST_ID_HEADER];
119
+
120
+ /**
121
+ * The strict resend's init: its own body, and its own request identity, so
122
+ * an idempotency key never pairs the rejected body's answer with the new one.
123
+ */
124
+ function withStrictResend(
125
+ init: RequestInit | undefined,
126
+ body: Record<string, unknown>,
127
+ ): ReplayableRequestInit {
128
+ const next = withJsonBody(init, body);
129
+ if (init?.headers === undefined) return next;
130
+ const headers = new Headers(init.headers);
131
+ for (const name of REQUEST_IDENTITY_HEADERS) {
132
+ const value = headers.get(name);
133
+ if (value !== null) headers.set(name, `${value}:tool-names`);
134
+ }
135
+ return { ...next, headers };
136
+ }
137
+
138
+ /**
139
+ * Resend a request once, with every tool name aliased (strict mode), when
140
+ * the provider answers 400 because of a tool name the outbound guard let
141
+ * through. Any other answer, and the resend's own answer, is returned as it
142
+ * is: the resend is a single step, never repeated, and changes nothing but
143
+ * tool names.
144
+ */
145
+ type ModelFetch = (...args: Parameters<typeof fetch>) => ReturnType<typeof fetch>;
146
+
147
+ function toolNameRetryFetch(
148
+ inner: ModelFetch,
149
+ onRetry: ReplayableJsonOpenAIHooks["onToolNameRetry"],
150
+ ): ModelFetch {
151
+ return async (input, init) => {
152
+ const source = replayableJsonBodySource(init?.body)?.source;
153
+ const names =
154
+ typeof source === "object" && source !== null ? toolNameRequests.get(source) : undefined;
155
+ if (!names) return await inner(input, init);
156
+ // A later send of a request already resent strictly (an SDK retry) stays strict.
157
+ if (names.strict) return await inner(input, withStrictResend(init, names.strict));
158
+ const response = await inner(input, init);
159
+ const rejection = await toolNameRejectionOfResponse(response);
160
+ if (rejection === null) return response;
161
+ const sentAliases = names.aliases;
162
+ const strict = guardRequestToolNames(names.api, names.original, { strict: true });
163
+ // Without a tool name to alias, a resend would repeat the same request.
164
+ if (strict.body === names.original) return response;
165
+ names.strict = strict.body;
166
+ names.aliases = strict.aliases;
167
+ await response.body?.cancel().catch(() => undefined);
168
+ let resent: Response;
169
+ try {
170
+ resent = await inner(input, withStrictResend(init, strict.body));
171
+ } catch (error) {
172
+ observeToolNames(onRetry, { api: names.api, outcome: "failed" });
173
+ throw error;
174
+ }
175
+ if (resent.ok && typeof source === "object" && source !== null) {
176
+ names.rejected.rememberRejection(
177
+ names.api,
178
+ source as Record<string, unknown>,
179
+ sentAliases,
180
+ rejection,
181
+ );
182
+ }
183
+ observeToolNames(onRetry, { api: names.api, outcome: resent.ok ? "completed" : "failed" });
184
+ return resent;
185
+ };
186
+ }
187
+
188
+ async function* restoredStreamEvents<T>(
189
+ stream: AsyncIterable<T>,
190
+ names: ToolNameRequest,
191
+ ): AsyncGenerator<T> {
192
+ for await (const event of stream) yield restoreToolNames(names.api, event, names.aliases);
193
+ }
194
+
195
+ /** A model answer, or its event stream, with aliased tool names mapped back. */
196
+ function restoredAnswer<T>(data: T, names: ToolNameRequest | undefined, client: OpenAI): T {
197
+ if (!names || names.aliases.size === 0) return data;
198
+ if (data instanceof Stream) {
199
+ const stream = data as Stream<unknown>;
200
+ return new Stream(
201
+ () => restoredStreamEvents(stream, names),
202
+ stream.controller,
203
+ client,
204
+ ) as unknown as T;
205
+ }
206
+ return restoreToolNames(names.api, data, names.aliases);
207
+ }
208
+
68
209
  /**
69
210
  * A JSON request body that can be encoded incrementally and replayed exactly.
70
211
  *
@@ -123,13 +264,20 @@ export async function requestBodyText(body: BodyInit | null | undefined): Promis
123
264
  */
124
265
  export class ReplayableJsonOpenAI extends OpenAI {
125
266
  private readonly modelRequestPolicy: ModelJsonRequestPolicy | undefined;
267
+ private readonly onToolNameRepair: ReplayableJsonOpenAIHooks["onToolNameRepair"];
268
+ /** Names this client's route rejected (see RejectedToolNames). */
269
+ private readonly rejectedToolNames = new RejectedToolNames();
126
270
 
127
271
  constructor(options: OpenAIOptions, hooks: ReplayableJsonOpenAIHooks = {}) {
128
272
  super({
129
273
  ...options,
130
- fetch: sdkModelTransportAdmissionFetch(options?.fetch ?? globalThis.fetch),
274
+ fetch: toolNameRetryFetch(
275
+ sdkModelTransportAdmissionFetch(options?.fetch ?? globalThis.fetch),
276
+ hooks.onToolNameRetry,
277
+ ),
131
278
  });
132
279
  this.modelRequestPolicy = hooks.modelRequestPolicy;
280
+ this.onToolNameRepair = hooks.onToolNameRepair;
133
281
  }
134
282
 
135
283
  protected override makeStatusError(
@@ -146,6 +294,7 @@ export class ReplayableJsonOpenAI extends OpenAI {
146
294
  if (!isModelRequestPath(path) || opts === undefined) {
147
295
  return super.post<Rsp>(path, opts);
148
296
  }
297
+ let names: ToolNameRequest | undefined;
149
298
  const wrapped = Promise.resolve(opts).then((resolved) => {
150
299
  const body = resolved.body;
151
300
  let prepared = resolved;
@@ -161,6 +310,21 @@ export class ReplayableJsonOpenAI extends OpenAI {
161
310
  };
162
311
  }
163
312
  }
313
+ // The outbound tool-name guard runs last, on the body as it is sent.
314
+ const api = toolNameApi(path);
315
+ if (api && isJsonRecordBody(prepared.body)) {
316
+ const original = prepared.body;
317
+ const rejected = this.rejectedToolNames;
318
+ const guarded = guardRequestToolNames(api, original, {
319
+ rejected: rejected.forModel(original.model),
320
+ });
321
+ for (const field of guarded.repaired) {
322
+ observeToolNames(this.onToolNameRepair, { api, field });
323
+ }
324
+ names = { api, original, aliases: guarded.aliases, rejected };
325
+ toolNameRequests.set(guarded.body, names);
326
+ if (guarded.body !== original) prepared = { ...prepared, body: guarded.body };
327
+ }
164
328
  if (path.split("?", 1)[0]?.endsWith("/responses")) {
165
329
  markResponsesPrefixReady();
166
330
  // The durable worker owns one step budget for sockets and HTTP alike.
@@ -169,7 +333,11 @@ export class ReplayableJsonOpenAI extends OpenAI {
169
333
  }
170
334
  return wrapJsonRequestOptions(prepared);
171
335
  });
172
- return super.post<Rsp>(path, wrapped);
336
+ // The aliases are final once the response arrived (a strict resend
337
+ // replaces them), so the answer is mapped back with the ones it answers.
338
+ return super
339
+ .post<Rsp>(path, wrapped)
340
+ ._thenUnwrap((data) => restoredAnswer(data, names, this)) as APIPromise<Rsp>;
173
341
  }
174
342
 
175
343
  override async buildRequest(
@@ -165,11 +165,12 @@ export interface ActiveBackendResolverDeps {
165
165
  };
166
166
  /**
167
167
  * Whether `defaultBackend` IS the session's home box — i.e. whether the null pointer
168
- * (== home) may resolve to it. Defaults to TRUE (omitted): a genuine machine-HOME turn
169
- * (home IS the machine) and a Modal-home turn established on its group box both pass/omit
170
- * true, so null resolves to `defaultBackend` as before. Set explicitly FALSE only for a
171
- * machine-primary turn of a Modal-HOME session (pinned to a machine, group box never
172
- * established this turn): the null pointer then has nothing to resolve to THIS turn, so
168
+ * (== home) may resolve to it. Defaults to TRUE (omitted): a turn established on its
169
+ * group box omits it, so null resolves to `defaultBackend` as before. Set explicitly
170
+ * FALSE for every machine-primary turn (pinned to a machine, group box never established
171
+ * this turn). The null pointer is the chat's managed box even when the chat's durable
172
+ * home label is a machine; turn start never resolves null to a machine. It therefore
173
+ * has nothing to resolve to THIS turn, so
173
174
  * rather than silently keep serving the pinned machine as if the detach never happened,
174
175
  * the null branch throws a typed `home_unavailable_this_turn` transition — the detach's
175
176
  * pointer commit stands, and worker failure settlement checkpoints completed work before
@@ -285,16 +286,15 @@ export function makeActiveBackendResolver(
285
286
  ): (pointer: ActivePointer) => Promise<ResolvedActiveBackend> {
286
287
  return async (pointer: ActivePointer): Promise<ResolvedActiveBackend> => {
287
288
  // NULL == the session's HOME backend (issue #341 invariant 1). `defaultBackend`
288
- // is the already-established home the wiring handed us — the Modal group box for a
289
- // Modal-home turn, or the machine itself for a machine-home turn. It is NEVER a
289
+ // is the already-established home the wiring handed us — the session's group box.
290
+ // A machine-pinned turn says so with `defaultIsHome: false`. It is NEVER a
290
291
  // swap target's SelfhostedSession: a clear-to-null must re-land on the home, never
291
292
  // keep serving the machine a prior op swapped to. (The proxy caches by the FULL
292
293
  // pointer tuple, so a clear-to-null — epoch-bumped OR a same-epoch FK null —
293
294
  // invalidates the cached machine and re-enters this branch.) The lease owns the
294
295
  // home box lifecycle; the proxy does not re-establish it.
295
296
  if (pointer.activeSandboxId === null) {
296
- // A machine-pinned turn (Modal-home session pinned to a machine) never
297
- // established its home box, so a mid-turn clear-to-null has no home to resolve
297
+ // A machine-pinned turn never established its home box, so a mid-turn clear-to-null has no home to resolve
298
298
  // THIS attempt. Fail typed-and-specific — the detach was accepted and its pointer
299
299
  // commit STANDS, allowing worker failure settlement to checkpoint and continue the
300
300
  // same logical turn in a new home-primary attempt — instead of silently serving the
@@ -3,7 +3,7 @@ import type { ResolvedModelProvider } from "@opengeni/config";
3
3
  import type { ReasoningEffort } from "@opengeni/contracts";
4
4
  import type OpenAI from "openai";
5
5
  import { AnthropicMessagesModel } from "./anthropic-messages";
6
- import { instrumentedModelFetch } from "./model-provider-client";
6
+ import { instrumentedModelFetch, modelToolNameObservers } from "./model-provider-client";
7
7
  import type { InferenceResidencyRequirement } from "./inference-residency";
8
8
  import { modelResponseUsageFromResponse, type ModelResponseUsage } from "./run-events";
9
9
 
@@ -115,6 +115,7 @@ export async function runSingleModelCall(
115
115
  provider,
116
116
  modelId,
117
117
  instrumentedModelFetch(provider.id, globalThis.fetch, false, residency),
118
+ modelToolNameObservers(provider.id),
118
119
  ),
119
120
  request,
120
121
  options,