@opengeni/runtime 4.6.1 → 4.6.2-canary.39854174564001

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.
@@ -0,0 +1,408 @@
1
+ import type { MCPServer } from "@openai/agents";
2
+ import { z } from "zod";
3
+ import { Buffer } from "node:buffer";
4
+ import {
5
+ defineLocalMcpBridgeDescriptor,
6
+ type LocalMcpBridgeAdapter,
7
+ type LocalMcpBridgeServer,
8
+ } from "@opengeni/capabilities";
9
+ import { readResponseJsonBounded, type FetchLike } from "@opengeni/network";
10
+ import type { McpServerConnectionRef, ToolAuthNeededPayload } from "@opengeni/contracts";
11
+ import type { ResolveConnectionCredentialInput, ResolveConnectionCredentialResult } from "./index";
12
+
13
+ export const OFFICIAL_DRIVE_MCP_URL = "https://drivemcp.googleapis.com/mcp/v1";
14
+ const api = "https://www.googleapis.com/drive/v3/";
15
+ const id = z
16
+ .string()
17
+ .min(1)
18
+ .max(256)
19
+ .regex(/^[a-zA-Z0-9_-]+$/u);
20
+ const file = { fileId: id };
21
+ const role = z.enum(["reader", "commenter", "writer", "fileOrganizer", "organizer"]);
22
+ const definitions = {
23
+ update_file: {
24
+ description:
25
+ "Rename a file or update its description. Requires the app's existing drive.file access to this file.",
26
+ schema: z
27
+ .object({
28
+ ...file,
29
+ name: z.string().min(1).max(1024).optional(),
30
+ description: z.string().max(16000).optional(),
31
+ })
32
+ .strict(),
33
+ },
34
+ overwrite_file_content: {
35
+ description:
36
+ "Overwrite the bytes of an existing binary file, preserving its ID. Requires drive.file access. Does not edit native Google Docs/Sheets contents.",
37
+ schema: z
38
+ .object({
39
+ ...file,
40
+ base64Content: z.string().max(34952536),
41
+ contentMimeType: z
42
+ .string()
43
+ .min(1)
44
+ .max(255)
45
+ .regex(/^[\w.+-]+\/[\w.+-]+$/u),
46
+ })
47
+ .strict(),
48
+ },
49
+ move_file: {
50
+ description:
51
+ "Move an existing file between folders. Specify the current parent and destination. Requires drive.file access.",
52
+ schema: z.object({ ...file, fromParentId: id, toParentId: id }).strict(),
53
+ },
54
+ trash_file: {
55
+ description: "Move a file to Trash. Requires drive.file access.",
56
+ schema: z.object(file).strict(),
57
+ },
58
+ restore_file: {
59
+ description: "Restore a file from Trash. Requires drive.file access.",
60
+ schema: z.object(file).strict(),
61
+ },
62
+ delete_file: {
63
+ description: "Permanently delete a file. This cannot be undone. Requires drive.file access.",
64
+ schema: z.object(file).strict(),
65
+ },
66
+ create_permission: {
67
+ description:
68
+ "Share a file with a user, group, domain, or anyone. Requires drive.file access and sharing permission. Never transfers ownership.",
69
+ schema: z
70
+ .object({
71
+ ...file,
72
+ type: z.enum(["user", "group", "domain", "anyone"]),
73
+ role,
74
+ emailAddress: z.string().email().optional(),
75
+ domain: z.string().min(1).max(253).optional(),
76
+ allowFileDiscovery: z.boolean().optional(),
77
+ })
78
+ .strict(),
79
+ },
80
+ update_permission: {
81
+ description:
82
+ "Change an existing sharing permission's role. Never transfers ownership. Requires drive.file access.",
83
+ schema: z.object({ ...file, permissionId: id, role }).strict(),
84
+ },
85
+ delete_permission: {
86
+ description: "Remove a file's sharing permission. Requires drive.file access.",
87
+ schema: z.object({ ...file, permissionId: id }).strict(),
88
+ },
89
+ get_changes_start_token: {
90
+ description:
91
+ "Get a Drive change-feed checkpoint for an ordinary scheduled agent. Save the returned token for list_changes.",
92
+ schema: z.object({ driveId: id.optional() }).strict(),
93
+ },
94
+ list_changes: {
95
+ description:
96
+ "Read a page of changes since a saved pageToken. Follow nextPageToken; save newStartPageToken only after processing every page. Removed items do not grant access to their old contents.",
97
+ schema: z
98
+ .object({
99
+ pageToken: z.string().min(1).max(2048),
100
+ driveId: id.optional(),
101
+ pageSize: z.number().int().min(1).max(1000).default(100),
102
+ })
103
+ .strict(),
104
+ },
105
+ };
106
+ type ExtraName = keyof typeof definitions;
107
+ const readNames = new Set<ExtraName>(["get_changes_start_token", "list_changes"]);
108
+ export const DRIVE_EXTRA_TOOLS = Object.entries(definitions).map(([name, definition]) => ({
109
+ name,
110
+ description: definition.description,
111
+ inputSchema: z.toJSONSchema(definition.schema) as Awaited<
112
+ ReturnType<MCPServer["listTools"]>
113
+ >[number]["inputSchema"],
114
+ annotations: {
115
+ readOnlyHint: readNames.has(name as ExtraName),
116
+ destructiveHint: !readNames.has(name as ExtraName),
117
+ idempotentHint: readNames.has(name as ExtraName),
118
+ openWorldHint: true,
119
+ },
120
+ }));
121
+ export const DRIVE_MCP_BRIDGE_DESCRIPTOR = defineLocalMcpBridgeDescriptor({
122
+ adapterId: "drive-mcp-extensions",
123
+ providerId: "google-drive",
124
+ catalogIdentity: `mcp:${OFFICIAL_DRIVE_MCP_URL}`,
125
+ authority: "connection",
126
+ toolSurface: "remote_with_reviewed_extensions",
127
+ mutationReplay: "safe_reads_only",
128
+ destinations: [
129
+ { origin: "https://drivemcp.googleapis.com", pathPrefix: "/mcp/v1" },
130
+ { origin: "https://www.googleapis.com", pathPrefix: "/drive/v3/" },
131
+ { origin: "https://www.googleapis.com", pathPrefix: "/upload/drive/v3/files/" },
132
+ ],
133
+ });
134
+ export type DriveMcpBridgeConfig = {
135
+ readonly url: string;
136
+ readonly connectionRef?: McpServerConnectionRef | undefined;
137
+ };
138
+ export type DriveMcpBridgeContext = {
139
+ workspaceId: string;
140
+ subjectId?: string;
141
+ serverId: string;
142
+ resolveCredential: (
143
+ input: ResolveConnectionCredentialInput,
144
+ ) => Promise<ResolveConnectionCredentialResult>;
145
+ onAuthNeeded?: (payload: ToolAuthNeededPayload) => void | Promise<void>;
146
+ onResolvedConnectionId?: (connectionId: string) => void;
147
+ fetchImpl?: FetchLike;
148
+ createRemoteServer: () => MCPServer;
149
+ };
150
+ type DriveToolResult = Awaited<ReturnType<NonNullable<MCPServer["callToolResult"]>>>;
151
+ type ParsedCall = {
152
+ [Name in ExtraName]: { name: Name; input: z.infer<(typeof definitions)[Name]["schema"]> };
153
+ }[ExtraName];
154
+ function inputError(text: string): DriveToolResult {
155
+ return { isError: true, content: [{ type: "text", text }] };
156
+ }
157
+ export class DriveMcpServer implements LocalMcpBridgeServer {
158
+ readonly bridge = DRIVE_MCP_BRIDGE_DESCRIPTOR;
159
+ readonly cacheToolsList = false;
160
+ readonly name: string;
161
+ private readonly remote: MCPServer;
162
+ constructor(
163
+ private readonly config: DriveMcpBridgeConfig,
164
+ private readonly context: DriveMcpBridgeContext,
165
+ ) {
166
+ this.remote = context.createRemoteServer();
167
+ this.name = this.remote.name;
168
+ }
169
+ connect() {
170
+ return this.remote.connect();
171
+ }
172
+ close() {
173
+ return this.remote.close();
174
+ }
175
+ async invalidateToolsCache() {
176
+ await this.remote.invalidateToolsCache();
177
+ }
178
+ async listTools() {
179
+ return mergeDriveMcpTools(await this.remote.listTools());
180
+ }
181
+ async callTool(
182
+ name: string,
183
+ args: Record<string, unknown> | null,
184
+ meta?: Record<string, unknown> | null,
185
+ options?: { signal?: AbortSignal },
186
+ ) {
187
+ return (await this.callToolResult(name, args, meta, options)).content;
188
+ }
189
+ async callToolResult(
190
+ name: string,
191
+ args: Record<string, unknown> | null,
192
+ meta?: Record<string, unknown> | null,
193
+ options?: { signal?: AbortSignal },
194
+ ): Promise<DriveToolResult> {
195
+ options?.signal?.throwIfAborted();
196
+ if (!Object.hasOwn(definitions, name)) {
197
+ const remote = this.remote;
198
+ if (remote.callToolResult) return remote.callToolResult(name, args, meta, options);
199
+ return { content: await remote.callTool(name, args, meta, options) };
200
+ }
201
+ const tool = name as ExtraName;
202
+ const parsed = definitions[tool].schema.safeParse(args ?? {});
203
+ if (!parsed.success)
204
+ return { isError: true, content: [{ type: "text", text: parsed.error.message }] };
205
+ const call = { name: tool, input: parsed.data } as ParsedCall;
206
+ const fileId = "fileId" in call.input ? call.input.fileId : undefined;
207
+ const url = new URL(api + (fileId ? `files/${fileId}` : "changes"));
208
+ const request: RequestInit = { method: "GET" };
209
+ let body: Record<string, unknown> | undefined;
210
+ if (fileId) url.searchParams.set("supportsAllDrives", "true");
211
+ switch (call.name) {
212
+ case "update_file": {
213
+ const { input } = call;
214
+ if (input.name === undefined && input.description === undefined)
215
+ return inputError("Supply name or description.");
216
+ request.method = "PATCH";
217
+ body = {
218
+ ...(input.name !== undefined ? { name: input.name } : {}),
219
+ ...(input.description !== undefined ? { description: input.description } : {}),
220
+ };
221
+ break;
222
+ }
223
+ case "overwrite_file_content": {
224
+ const { input } = call;
225
+ if (
226
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(
227
+ input.base64Content,
228
+ )
229
+ )
230
+ return inputError("base64Content must be canonical base64.");
231
+ const bytes = Buffer.from(input.base64Content, "base64");
232
+ if (bytes.toString("base64") !== input.base64Content)
233
+ return inputError("base64Content must be canonical base64.");
234
+ if (bytes.length > 25 * 1024 * 1024) return inputError("Content exceeds 25 MiB.");
235
+ url.pathname = `/upload/drive/v3/files/${input.fileId}`;
236
+ url.searchParams.set("uploadType", "media");
237
+ request.method = "PATCH";
238
+ request.body = bytes;
239
+ request.headers = { "content-type": input.contentMimeType };
240
+ break;
241
+ }
242
+ case "move_file": {
243
+ const { input } = call;
244
+ if (input.fromParentId === input.toParentId)
245
+ return inputError("The current and destination folders must differ.");
246
+ request.method = "PATCH";
247
+ body = {};
248
+ url.searchParams.set("addParents", input.toParentId);
249
+ url.searchParams.set("removeParents", input.fromParentId);
250
+ break;
251
+ }
252
+ case "trash_file":
253
+ case "restore_file":
254
+ request.method = "PATCH";
255
+ body = { trashed: call.name === "trash_file" };
256
+ break;
257
+ case "delete_file":
258
+ request.method = "DELETE";
259
+ break;
260
+ case "create_permission": {
261
+ const { input } = call;
262
+ const person = input.type === "user" || input.type === "group";
263
+ if (
264
+ person
265
+ ? !input.emailAddress ||
266
+ input.domain !== undefined ||
267
+ input.allowFileDiscovery !== undefined
268
+ : input.emailAddress !== undefined ||
269
+ (input.type === "domain" ? !input.domain : input.domain !== undefined)
270
+ )
271
+ return inputError(
272
+ "User/group sharing requires only emailAddress; domain sharing requires only domain; anyone sharing accepts neither. allowFileDiscovery applies only to domain/anyone.",
273
+ );
274
+ request.method = "POST";
275
+ url.pathname += "/permissions";
276
+ body = Object.fromEntries(Object.entries(input).filter(([key]) => key !== "fileId"));
277
+ break;
278
+ }
279
+ case "update_permission":
280
+ request.method = "PATCH";
281
+ url.pathname += `/permissions/${call.input.permissionId}`;
282
+ body = { role: call.input.role };
283
+ break;
284
+ case "delete_permission":
285
+ request.method = "DELETE";
286
+ url.pathname += `/permissions/${call.input.permissionId}`;
287
+ break;
288
+ case "get_changes_start_token":
289
+ url.pathname += "/startPageToken";
290
+ if (call.input.driveId) url.searchParams.set("driveId", call.input.driveId);
291
+ url.searchParams.set("supportsAllDrives", "true");
292
+ break;
293
+ case "list_changes": {
294
+ const { input } = call;
295
+ for (const key of ["pageToken", "pageSize", "driveId"] as const)
296
+ if (input[key] !== undefined) url.searchParams.set(key, String(input[key]));
297
+ url.searchParams.set("supportsAllDrives", "true");
298
+ url.searchParams.set("includeItemsFromAllDrives", "true");
299
+ url.searchParams.set(
300
+ "fields",
301
+ "nextPageToken,newStartPageToken,changes(fileId,removed,time,driveId,file(id,name,mimeType,modifiedTime,parents,trashed))",
302
+ );
303
+ break;
304
+ }
305
+ }
306
+ if (body) {
307
+ request.body = JSON.stringify(body);
308
+ request.headers = { "content-type": "application/json" };
309
+ }
310
+ const read = readNames.has(tool);
311
+ const credential = await this.context.resolveCredential({
312
+ workspaceId: this.context.workspaceId,
313
+ serverId: this.context.serverId,
314
+ connectionRef: this.config.connectionRef!,
315
+ destinationUrl: url.toString(),
316
+ toolName: name,
317
+ forceRefresh: false,
318
+ ...(this.context.subjectId ? { subjectId: this.context.subjectId } : {}),
319
+ });
320
+ if (credential.status === "auth_needed") {
321
+ await this.context.onAuthNeeded?.({
322
+ ...credential,
323
+ serverId: this.context.serverId,
324
+ toolName: name,
325
+ });
326
+ return {
327
+ isError: true,
328
+ content: [{ type: "text", text: "Reconnect Google Drive to authorize this operation." }],
329
+ };
330
+ }
331
+ this.context.onResolvedConnectionId?.(credential.connectionId);
332
+ if (credential.authorizeProviderRequest && !(await credential.authorizeProviderRequest()))
333
+ throw new Error("Google Drive authority is no longer valid");
334
+ options?.signal?.throwIfAborted();
335
+ let response: Response;
336
+ try {
337
+ response = await (this.context.fetchImpl ?? fetch)(url, {
338
+ ...request,
339
+ headers: { ...credential.headers, ...request.headers },
340
+ redirect: "error",
341
+ signal: AbortSignal.any([
342
+ AbortSignal.timeout(30000),
343
+ ...(options?.signal ? [options.signal] : []),
344
+ ]),
345
+ });
346
+ if (!read && response.status >= 500) {
347
+ await response.body?.cancel().catch(() => undefined);
348
+ throw new DriveMutationOutcomeUnknown();
349
+ }
350
+ } catch (error) {
351
+ if (!read) throw new DriveMutationOutcomeUnknown();
352
+ throw new Error("Google Drive request failed", { cause: error });
353
+ }
354
+ if (response.status === 204) {
355
+ await response.body?.cancel().catch(() => undefined);
356
+ return { content: [{ type: "text", text: "{}" }], structuredContent: {} };
357
+ }
358
+ let payload: Record<string, unknown>;
359
+ try {
360
+ payload = await readResponseJsonBounded(response, 8 * 1024 * 1024, "Google Drive response");
361
+ } catch (error) {
362
+ if (!read && response.ok) throw new DriveMutationOutcomeUnknown();
363
+ throw error;
364
+ }
365
+ return {
366
+ ...(response.ok ? {} : { isError: true }),
367
+ content: [{ type: "text", text: JSON.stringify(payload) }],
368
+ structuredContent: payload,
369
+ };
370
+ }
371
+ }
372
+ class DriveMutationOutcomeUnknown extends Error {
373
+ readonly code = 40102;
374
+ readonly connectorActionOutcome = "uncertain";
375
+ readonly retryable = false;
376
+ constructor() {
377
+ super(
378
+ "Google Drive mutation was submitted but its outcome is uncertain. Inspect the file before trying again.",
379
+ );
380
+ }
381
+ }
382
+ export function isOfficialDriveMcpConfig(config: DriveMcpBridgeConfig): boolean {
383
+ return (
384
+ config.url === OFFICIAL_DRIVE_MCP_URL &&
385
+ config.connectionRef?.providerDomain === "drivemcp.googleapis.com" &&
386
+ config.connectionRef.kind === "oauth2" &&
387
+ config.connectionRef.subjectScope === "subject"
388
+ );
389
+ }
390
+
391
+ export function mergeDriveMcpTools<T extends { name: string }>(remote: T[]) {
392
+ // Never shadow a future official tool with different arguments/semantics.
393
+ const collisions = remote.filter((tool) => Object.hasOwn(definitions, tool.name));
394
+ if (collisions.length)
395
+ throw new Error(
396
+ `Drive tool extension collision: ${collisions.map((tool) => tool.name).join(", ")}`,
397
+ );
398
+ return [...remote, ...structuredClone(DRIVE_EXTRA_TOOLS)];
399
+ }
400
+
401
+ export const DRIVE_MCP_BRIDGE_ADAPTER: LocalMcpBridgeAdapter<
402
+ DriveMcpBridgeConfig,
403
+ DriveMcpBridgeContext
404
+ > = {
405
+ adapterId: DRIVE_MCP_BRIDGE_DESCRIPTOR.adapterId,
406
+ matches: isOfficialDriveMcpConfig,
407
+ create: (config, context) => new DriveMcpServer(config, context),
408
+ };
package/src/index.ts CHANGED
@@ -1,3 +1,5 @@
1
+ export { isOfficialDriveMcpConfig, mergeDriveMcpTools } from "./drive-mcp";
2
+ import { DRIVE_MCP_BRIDGE_ADAPTER, type DriveMcpBridgeContext } from "./drive-mcp";
1
3
  import { sharedKnowledgeGuidance } from "./agent-instructions/modules/knowledge";
2
4
  import { measureMcpPhase } from "@opengeni/observability";
3
5
  import { interactionToolErrorOutput, type InteractionToolErrorResult } from "./interaction-tools";
@@ -895,11 +897,17 @@ export type {
895
897
 
896
898
  ensureReadableStreamFrom();
897
899
 
898
- type BuiltInMcpBridgeContext = GmailRestMcpBridgeContext & SlackRestMcpBridgeContext;
900
+ type BuiltInMcpBridgeContext = GmailRestMcpBridgeContext &
901
+ SlackRestMcpBridgeContext &
902
+ DriveMcpBridgeContext;
899
903
  const BUILT_IN_MCP_BRIDGE_ADAPTERS: readonly LocalMcpBridgeAdapter<
900
904
  GmailRestMcpBridgeConfig,
901
905
  BuiltInMcpBridgeContext
902
- >[] = Object.freeze([GMAIL_REST_MCP_BRIDGE_ADAPTER, SLACK_REST_MCP_BRIDGE_ADAPTER]);
906
+ >[] = Object.freeze([
907
+ GMAIL_REST_MCP_BRIDGE_ADAPTER,
908
+ SLACK_REST_MCP_BRIDGE_ADAPTER,
909
+ DRIVE_MCP_BRIDGE_ADAPTER,
910
+ ]);
903
911
  const SANDBOX_LIFECYCLE_COMMAND_TIMEOUT_MS = 120_000;
904
912
 
905
913
  /**
@@ -5463,6 +5471,28 @@ export async function prepareAgentTools(
5463
5471
  // auth misses are logged, not published: Apps is discovered on every
5464
5472
  // turn, so a setup card would repeat on each one (see codexAppsAuthFetch).
5465
5473
  const bestEffort = isCodexAppsMcpServer(config) || optional || !!config.connectionRef;
5474
+ const remoteRequestInit = await mcpServerRequestInit(settings, config);
5475
+ const createRemoteServer = () =>
5476
+ new MCPServerStreamableHttp({
5477
+ url,
5478
+ name: config.name ?? config.id,
5479
+ cacheToolsList: config.cacheToolsList,
5480
+ // The upstream transport logger receives raw thrown errors, whose
5481
+ // messages may contain response bodies, URLs, headers, or echoed
5482
+ // credentials. Keep its diagnostic surface structural only.
5483
+ // This logger spans tool invocation as well as setup. Only the
5484
+ // connect/list lifecycle wrappers may add setup-safe recovery facts.
5485
+ logger: mcpTransportLogger(config.id),
5486
+ // codex_apps returns connector tools with empty `outputSchema: {}` that the
5487
+ // MCP SDK's strict Tool schema rejects (fails the turn during tools/list);
5488
+ // sanitize the response on the wire before validation. The namespace Set
5489
+ // also captures each tool's original connector namespace (P4 Part B.1).
5490
+ fetch: fetchImpl,
5491
+ ...mcpStreamableHttpClientOptions({ firstParty }),
5492
+ ...remoteRequestInit,
5493
+ ...(config.timeoutMs ? { timeout: config.timeoutMs } : {}),
5494
+ ...mcpSessionTimeoutOptions(config),
5495
+ });
5466
5496
  // First-party bridges are ordinary in-process MCP servers selected by
5467
5497
  // adapter-owned matchers. Adding another provider extends this registry;
5468
5498
  // generic transport/catalog code never branches on provider identity.
@@ -5476,6 +5506,7 @@ export async function prepareAgentTools(
5476
5506
  ...(config.connectionRef ? { connectionRef: config.connectionRef } : {}),
5477
5507
  },
5478
5508
  {
5509
+ createRemoteServer,
5479
5510
  workspaceId: options.workspaceId ?? "",
5480
5511
  ...(options.credentialSubjectId ? { subjectId: options.credentialSubjectId } : {}),
5481
5512
  serverId: config.id,
@@ -5507,28 +5538,7 @@ export async function prepareAgentTools(
5507
5538
  : {}),
5508
5539
  },
5509
5540
  );
5510
- const innerServer =
5511
- bridge ??
5512
- new MCPServerStreamableHttp({
5513
- url,
5514
- name: config.name ?? config.id,
5515
- cacheToolsList: config.cacheToolsList,
5516
- // The upstream transport logger receives raw thrown errors, whose
5517
- // messages may contain response bodies, URLs, headers, or echoed
5518
- // credentials. Keep its diagnostic surface structural only.
5519
- // This logger spans tool invocation as well as setup. Only the
5520
- // connect/list lifecycle wrappers may add setup-safe recovery facts.
5521
- logger: mcpTransportLogger(config.id),
5522
- // codex_apps returns connector tools with empty `outputSchema: {}` that the
5523
- // MCP SDK's strict Tool schema rejects (fails the turn during tools/list);
5524
- // sanitize the response on the wire before validation. The namespace Set
5525
- // also captures each tool's original connector namespace (P4 Part B.1).
5526
- fetch: fetchImpl,
5527
- ...mcpStreamableHttpClientOptions({ firstParty }),
5528
- ...(await mcpServerRequestInit(settings, config)),
5529
- ...(config.timeoutMs ? { timeout: config.timeoutMs } : {}),
5530
- ...mcpSessionTimeoutOptions(config),
5531
- });
5541
+ const innerServer = bridge ?? createRemoteServer();
5532
5542
  if (bridge) options.runMcpCredentials?.excludeLocalTarget(config.id);
5533
5543
  const server = configureMcpOperationRecovery(
5534
5544
  new PrefixedMcpServer(
@@ -2557,10 +2557,10 @@ export function createInteractionAttemptToolDefinitions(
2557
2557
  definitions.push({
2558
2558
  identity: { serverId: "interaction", toolName: "cua_" + tool.name },
2559
2559
  modelName: "interaction__cua_" + tool.name,
2560
- codemodePath: ["computer", tool.name],
2560
+ codemodePath: ["interaction", "cua", tool.name],
2561
2561
  title: tool.name,
2562
2562
  description:
2563
- "Native CUA computer tool; requires a CUA-backed computer_open session. " +
2563
+ "Native CUA computer tool; requires a CUA-backed computer_open session. Other CUA tools it names are interaction__cua_<name> (in Code Mode interaction.cua.<name>); steps inside run_steps keep the plain name. " +
2564
2564
  tool.description,
2565
2565
  inputSchema,
2566
2566
  ...(outputSchema ? { outputSchema } : {}),
@@ -8,7 +8,7 @@ import type {
8
8
  ModelContextTool,
9
9
  } from "@opengeni/contracts";
10
10
  import { MODEL_CONTEXT_SNAPSHOT_VERSION } from "@opengeni/contracts";
11
- import { estimateSerializedValueTokens, estimateTextTokens } from "./context-compaction";
11
+ import { estimateTextTokens } from "./context-compaction";
12
12
  import { lazyToolRuntimeForAgent } from "./lazy-tool-transport";
13
13
  import type { EffectiveSkillSelection } from "./runtime-skills";
14
14
 
@@ -25,7 +25,7 @@ export type PersistentAgentInstructionLayerDraft = {
25
25
  joinBefore?: string;
26
26
  };
27
27
 
28
- function contextTextEstimate(value: unknown): number | null {
28
+ function contextTextEstimate(value: unknown, serialized?: string): number | null {
29
29
  const containsNonText = (part: unknown): boolean => {
30
30
  if (Array.isArray(part)) return part.some(containsNonText);
31
31
  if (!part || typeof part !== "object") return false;
@@ -39,7 +39,13 @@ function contextTextEstimate(value: unknown): number | null {
39
39
  return true;
40
40
  return Object.values(record).some(containsNonText);
41
41
  };
42
- return containsNonText(value) ? null : estimateSerializedValueTokens(value);
42
+ if (containsNonText(value)) return null;
43
+ // Provider parts are parsed JSON. Reuse the representation already needed
44
+ // for byte accounting rather than traversing that tree again for its length
45
+ // and then again for its non-ASCII count. Strings retain the raw-text rule.
46
+ return estimateTextTokens(
47
+ typeof value === "string" ? value : (serialized ?? JSON.stringify(value)),
48
+ );
43
49
  }
44
50
 
45
51
  export function buildProviderRequestSnapshot(input: {
@@ -70,12 +76,17 @@ export function buildProviderRequestSnapshot(input: {
70
76
  body = null;
71
77
  unavailableReason = "The provider body is not a JSON object.";
72
78
  }
73
- const parts = Object.entries(payload).map(([key, value]) => ({
74
- key,
75
- estimatedTokens: contextTextEstimate(value),
76
- utf8Bytes: Buffer.byteLength(JSON.stringify(value), "utf8"),
77
- ...(Array.isArray(value) ? { itemEstimatedTokens: value.map(contextTextEstimate) } : {}),
78
- }));
79
+ const parts = Object.entries(payload).map(([key, value]) => {
80
+ const serialized = JSON.stringify(value);
81
+ return {
82
+ key,
83
+ estimatedTokens: contextTextEstimate(value, serialized),
84
+ utf8Bytes: Buffer.byteLength(serialized, "utf8"),
85
+ ...(Array.isArray(value)
86
+ ? { itemEstimatedTokens: value.map((item) => contextTextEstimate(item)) }
87
+ : {}),
88
+ };
89
+ });
79
90
  const instructionsTokens =
80
91
  parts.find((part) => part.key === "instructions")?.estimatedTokens ?? 0;
81
92
  const wireInstructions = typeof payload.instructions === "string" ? payload.instructions : null;
@@ -364,16 +375,14 @@ function countedTool(input: {
364
375
  schema?: unknown;
365
376
  }): ModelContextTool {
366
377
  const schema = input.schema;
367
- const utf8Bytes = Buffer.byteLength(
368
- JSON.stringify({
369
- name: input.name,
370
- type: input.type,
371
- description: input.description,
372
- namespace: input.namespace,
373
- schema,
374
- }),
375
- "utf8",
376
- );
378
+ const serialized = JSON.stringify({
379
+ name: input.name,
380
+ type: input.type,
381
+ description: input.description,
382
+ namespace: input.namespace,
383
+ schema,
384
+ });
385
+ const utf8Bytes = Buffer.byteLength(serialized, "utf8");
377
386
  return {
378
387
  name: input.name,
379
388
  type: input.type,
@@ -382,13 +391,7 @@ function countedTool(input: {
382
391
  ...(input.namespace ? { namespace: input.namespace } : {}),
383
392
  ...(schema !== undefined ? { schema } : {}),
384
393
  utf8Bytes,
385
- estimatedTokens: estimateSerializedValueTokens({
386
- name: input.name,
387
- type: input.type,
388
- description: input.description,
389
- namespace: input.namespace,
390
- schema,
391
- }),
394
+ estimatedTokens: estimateTextTokens(serialized),
392
395
  };
393
396
  }
394
397