omp-antigravity-acp-provider 0.2.4 → 0.3.2
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.
- package/AGENT_INSTALL.md +2 -2
- package/README.md +12 -8
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/extension/acp-errors.ts +27 -2
- package/extension/agent-notices.ts +216 -30
- package/extension/auth-sync.ts +15 -7
- package/extension/commands.ts +25 -2
- package/extension/index.ts +112 -12
- package/extension/model-catalog.ts +11 -12
- package/extension/omp-model-whitelist.ts +323 -0
- package/extension/omp-session-lifecycle.ts +3 -3
- package/extension/prompt-cloak.ts +131 -0
- package/extension/quota-usage.ts +12 -3
- package/extension/runtime/acp/antigravity.ts +42 -1
- package/extension/runtime/acp/connection.ts +5 -0
- package/extension/runtime/index.ts +6 -0
- package/extension/runtime/launch.ts +5 -1
- package/extension/runtime/models.ts +43 -4
- package/extension/runtime/prompt.ts +11 -10
- package/extension/runtime/provider.ts +3 -3
- package/extension/runtime/runtime.ts +245 -40
- package/extension/runtime/stream/pi-events.ts +20 -5
- package/extension/runtime/tools/bridge.ts +157 -7
- package/extension/runtime/tools/delivery.ts +260 -0
- package/extension/runtime/tools/relay.ts +32 -1
- package/extension/runtime/tools/schema.ts +189 -0
- package/extension/runtime.mjs +1265 -153
- package/extension/tier-connection.ts +13 -1
- package/extension/tool-relay-protocol.d.mts +2 -2
- package/extension/tool-relay-protocol.mjs +2 -2
- package/extension/tool-routing.ts +193 -16
- package/package.json +2 -2
|
@@ -66,6 +66,17 @@ interface BridgeTool {
|
|
|
66
66
|
description: string;
|
|
67
67
|
inputSchema: Record<string, unknown>;
|
|
68
68
|
originalSchema: Tool["parameters"];
|
|
69
|
+
// Preserved source `_meta`, merged into every tools/list entry.
|
|
70
|
+
meta: Record<string, unknown>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A tools/list entry as serialized toward agy. */
|
|
74
|
+
export interface BridgeToolListing {
|
|
75
|
+
name: string;
|
|
76
|
+
description?: string;
|
|
77
|
+
inputSchema?: unknown;
|
|
78
|
+
_meta?: Record<string, unknown>;
|
|
79
|
+
[key: string]: unknown;
|
|
69
80
|
}
|
|
70
81
|
|
|
71
82
|
export interface PiToolInvocation {
|
|
@@ -104,11 +115,127 @@ export function planProjectedToolNames(tools: readonly ToolProjectionInput[]): r
|
|
|
104
115
|
return projectTools(tools, []).map(tool => tool.piName);
|
|
105
116
|
}
|
|
106
117
|
|
|
118
|
+
// agy holds every MCP tool it loads in one customization budget of roughly
|
|
119
|
+
// 20,000 tokens, counted as ceil(UTF-8 bytes / 3) over each serialized tool
|
|
120
|
+
// entry, and drops whole tools (largest first) past it. Fitting trims only
|
|
121
|
+
// description prose, so every tool, name, schema key, type, enum, required,
|
|
122
|
+
// items and bound stays listed exactly as projected.
|
|
123
|
+
export const TOOL_TOKEN_BUDGET = 18000;
|
|
124
|
+
|
|
125
|
+
function tokensOf(tools: readonly BridgeToolListing[]): number {
|
|
126
|
+
return tools.reduce((total, tool) => total + Math.ceil(Buffer.byteLength(JSON.stringify(tool), "utf8") / 3), 0);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Descriptions cut shorter than this say nothing ("The fil…") and only spend
|
|
130
|
+
// the budget on their key, so a cap below it drops the text entirely.
|
|
131
|
+
const MIN_TEXT = 24;
|
|
132
|
+
|
|
133
|
+
// Shortens text to at most `max` UTF-8 bytes: a trailing Examples block goes
|
|
134
|
+
// first, then a sentence boundary near the cut, marked with "…".
|
|
135
|
+
function cutDescription(text: string, max: number): string | undefined {
|
|
136
|
+
if (Buffer.byteLength(text, "utf8") <= max) return text;
|
|
137
|
+
const bare = text.replace(/\s*\bExamples?:[\s\S]*$/i, "").trimEnd();
|
|
138
|
+
if (bare && Buffer.byteLength(bare, "utf8") <= max) return bare;
|
|
139
|
+
const room = max - Buffer.byteLength("…", "utf8");
|
|
140
|
+
if (room < 4) return undefined;
|
|
141
|
+
let out = "";
|
|
142
|
+
let used = 0;
|
|
143
|
+
for (const ch of bare || text) {
|
|
144
|
+
const size = Buffer.byteLength(ch, "utf8");
|
|
145
|
+
if (used + size > room) break;
|
|
146
|
+
out += ch;
|
|
147
|
+
used += size;
|
|
148
|
+
}
|
|
149
|
+
const stop = Math.max(...[". ", "; ", "。", ";"].map((sep) => out.lastIndexOf(sep)));
|
|
150
|
+
if (stop > out.length / 2) out = out.slice(0, stop + 1);
|
|
151
|
+
return out.trimEnd() + "…";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function trimDescription(text: string, cap: number): string | undefined {
|
|
155
|
+
if (Buffer.byteLength(text, "utf8") <= cap) return text;
|
|
156
|
+
return cap < MIN_TEXT ? undefined : cutDescription(text, cap);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Recursively caps every `description` string; every other key and value
|
|
160
|
+
// passes through untouched, so no schema constraint ever moves.
|
|
161
|
+
function shapeDescriptions(node: unknown, cap: number): unknown {
|
|
162
|
+
if (Array.isArray(node)) return node.map((item) => shapeDescriptions(item, cap));
|
|
163
|
+
if (node === null || typeof node !== "object") return node;
|
|
164
|
+
const out: Record<string, unknown> = {};
|
|
165
|
+
for (const [key, value] of Object.entries(node)) {
|
|
166
|
+
if (key === "description" && typeof value === "string") {
|
|
167
|
+
const text = trimDescription(value, cap);
|
|
168
|
+
if (text !== undefined) out.description = text;
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
out[key] = shapeDescriptions(value, cap);
|
|
172
|
+
}
|
|
173
|
+
return out;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function shapeTool(tool: BridgeToolListing, cap: number): BridgeToolListing {
|
|
177
|
+
const out: BridgeToolListing = { ...tool };
|
|
178
|
+
if (typeof tool.description === "string") {
|
|
179
|
+
const text = trimDescription(tool.description, cap);
|
|
180
|
+
if (text === undefined) delete out.description;
|
|
181
|
+
else out.description = text;
|
|
182
|
+
}
|
|
183
|
+
if (tool.inputSchema !== undefined) out.inputSchema = shapeDescriptions(tool.inputSchema, cap);
|
|
184
|
+
return out;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function longestDescription(tools: readonly BridgeToolListing[]): number {
|
|
188
|
+
let max = 0;
|
|
189
|
+
const visit = (node: unknown): void => {
|
|
190
|
+
if (Array.isArray(node)) {
|
|
191
|
+
for (const item of node) visit(item);
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
if (node === null || typeof node !== "object") return;
|
|
195
|
+
for (const [key, value] of Object.entries(node)) {
|
|
196
|
+
if (key === "description" && typeof value === "string") {
|
|
197
|
+
max = Math.max(max, Buffer.byteLength(value, "utf8"));
|
|
198
|
+
} else {
|
|
199
|
+
visit(value);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
for (const tool of tools) {
|
|
204
|
+
if (typeof tool.description === "string") max = Math.max(max, Buffer.byteLength(tool.description, "utf8"));
|
|
205
|
+
visit(tool.inputSchema);
|
|
206
|
+
}
|
|
207
|
+
return max;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Pure: when the listed tools exceed agy's token budget, progressively
|
|
211
|
+
* shorten only description text (binary-searching one byte cap applied to
|
|
212
|
+
* every description) and never drop a tool. Fitting lists return unchanged. */
|
|
213
|
+
export function fitToolsToBudget(tools: BridgeToolListing[], budget = TOOL_TOKEN_BUDGET): BridgeToolListing[] {
|
|
214
|
+
if (!Array.isArray(tools) || tools.length === 0) return tools;
|
|
215
|
+
if (tokensOf(tools) <= budget) return tools;
|
|
216
|
+
const at = (cap: number): BridgeToolListing[] => tools.map((tool) => shapeTool(tool, cap));
|
|
217
|
+
// Even with every description gone the list is over budget: keep every
|
|
218
|
+
// tool and let agy see as much schema as fits.
|
|
219
|
+
if (tokensOf(at(0)) > budget) return at(0);
|
|
220
|
+
// Largest cap whose shape still fits. At the longest description the
|
|
221
|
+
// shape is the original over-budget list, so the search always narrows.
|
|
222
|
+
let lo = 0;
|
|
223
|
+
let hi = longestDescription(tools);
|
|
224
|
+
while (lo < hi) {
|
|
225
|
+
const mid = Math.ceil((lo + hi) / 2);
|
|
226
|
+
if (tokensOf(at(mid)) <= budget) lo = mid;
|
|
227
|
+
else hi = mid - 1;
|
|
228
|
+
}
|
|
229
|
+
return at(lo);
|
|
230
|
+
}
|
|
231
|
+
|
|
107
232
|
export class PiMcpBridge {
|
|
108
233
|
fingerprint: string;
|
|
109
234
|
readonly omissions: ToolOmission[] = [];
|
|
110
235
|
private readonly token = crypto.randomUUID().replaceAll("-", "");
|
|
111
236
|
private tools: BridgeTool[];
|
|
237
|
+
private revision = 0;
|
|
238
|
+
private fitted: { revision: number; tools: BridgeToolListing[] } | undefined;
|
|
112
239
|
private server: ReturnType<typeof createServer> | undefined;
|
|
113
240
|
private url: string | undefined;
|
|
114
241
|
private readonly responses = new Set<ServerResponse>();
|
|
@@ -122,6 +249,8 @@ export class PiMcpBridge {
|
|
|
122
249
|
this.omissions.length = 0;
|
|
123
250
|
this.tools = projectTools(tools, this.omissions);
|
|
124
251
|
this.fingerprint = projectionFingerprint(this.tools, this.omissions);
|
|
252
|
+
this.revision++;
|
|
253
|
+
this.fitted = undefined;
|
|
125
254
|
}
|
|
126
255
|
|
|
127
256
|
get empty(): boolean {
|
|
@@ -177,6 +306,24 @@ export class PiMcpBridge {
|
|
|
177
306
|
};
|
|
178
307
|
}
|
|
179
308
|
|
|
309
|
+
// agy loads these entries into one shared customization budget; the
|
|
310
|
+
// alwaysLoad meta keeps each tool loaded and the fitting trims only
|
|
311
|
+
// description prose when the budget would otherwise drop tools. The
|
|
312
|
+
// fitted listing depends only on the projected tools, so a revision
|
|
313
|
+
// counter lets repeated tools/list calls reuse it.
|
|
314
|
+
private listing(): BridgeToolListing[] {
|
|
315
|
+
const cached = this.fitted;
|
|
316
|
+
if (cached !== undefined && cached.revision === this.revision) return cached.tools;
|
|
317
|
+
const tools = fitToolsToBudget(this.tools.map((tool) => ({
|
|
318
|
+
name: tool.mcpName,
|
|
319
|
+
description: tool.description,
|
|
320
|
+
inputSchema: tool.inputSchema as { type: "object"; properties?: Record<string, object> },
|
|
321
|
+
_meta: { ...tool.meta, "antigravity/alwaysLoad": true },
|
|
322
|
+
})));
|
|
323
|
+
this.fitted = { revision: this.revision, tools };
|
|
324
|
+
return tools;
|
|
325
|
+
}
|
|
326
|
+
|
|
180
327
|
private async handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
|
|
181
328
|
this.responses.add(response);
|
|
182
329
|
response.once("close", () => this.responses.delete(response));
|
|
@@ -203,13 +350,7 @@ export class PiMcpBridge {
|
|
|
203
350
|
{ name: "pi-antigravity-acp-tools", version: PACKAGE_VERSION },
|
|
204
351
|
{ capabilities: { tools: {} } },
|
|
205
352
|
);
|
|
206
|
-
protocol.setRequestHandler(ListToolsRequestSchema, () => ({
|
|
207
|
-
tools: this.tools.map((tool) => ({
|
|
208
|
-
name: tool.mcpName,
|
|
209
|
-
description: tool.description,
|
|
210
|
-
inputSchema: tool.inputSchema as { type: "object"; properties?: Record<string, object> },
|
|
211
|
-
})),
|
|
212
|
-
}));
|
|
353
|
+
protocol.setRequestHandler(ListToolsRequestSchema, () => ({ tools: this.listing() }));
|
|
213
354
|
protocol.setRequestHandler(CallToolRequestSchema, async (call) => {
|
|
214
355
|
const tool = this.tools.find((candidate) => candidate.mcpName === call.params.name);
|
|
215
356
|
if (!tool) return toolError("Unknown or inactive Pi tool");
|
|
@@ -243,6 +384,14 @@ export class PiMcpBridge {
|
|
|
243
384
|
}
|
|
244
385
|
}
|
|
245
386
|
|
|
387
|
+
// A tool may carry a `_meta` object (e.g. forwarded from an upstream server);
|
|
388
|
+
// keep a copy so tools/list entries can merge it with agy's alwaysLoad marker.
|
|
389
|
+
function preserveMeta(tool: ToolProjectionInput): Record<string, unknown> {
|
|
390
|
+
const meta = (tool as { _meta?: unknown })._meta;
|
|
391
|
+
if (meta === null || typeof meta !== "object" || Array.isArray(meta)) return {};
|
|
392
|
+
return { ...(meta as Record<string, unknown>) };
|
|
393
|
+
}
|
|
394
|
+
|
|
246
395
|
function projectTool(tool: Tool, names: Set<string>): BridgeTool | ToolOmission;
|
|
247
396
|
function projectTool(tool: ToolProjectionInput, names: Set<string>): (Omit<BridgeTool, "originalSchema"> & { originalSchema: unknown }) | ToolOmission;
|
|
248
397
|
function projectTool(tool: ToolProjectionInput, names: Set<string>): (Omit<BridgeTool, "originalSchema"> & { originalSchema: unknown }) | ToolOmission {
|
|
@@ -262,6 +411,7 @@ function projectTool(tool: ToolProjectionInput, names: Set<string>): (Omit<Bridg
|
|
|
262
411
|
description: tool.description ?? "",
|
|
263
412
|
inputSchema: projected.schema,
|
|
264
413
|
originalSchema,
|
|
414
|
+
meta: preserveMeta(tool),
|
|
265
415
|
};
|
|
266
416
|
}
|
|
267
417
|
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
|
2
|
+
|
|
3
|
+
import { parseRelayCallId, TOOL_RELAY_CONTROL_NAME } from "../../tool-relay-protocol.mjs";
|
|
4
|
+
import type { TransferBlock } from "../prompt.ts";
|
|
5
|
+
import { projectedMcpName } from "./relay.ts";
|
|
6
|
+
import type { RelayInvocation, RelayOutcome } from "./relay.ts";
|
|
7
|
+
|
|
8
|
+
export interface DeliveryBoundary {
|
|
9
|
+
readonly promptLive: boolean;
|
|
10
|
+
readonly reusable: boolean;
|
|
11
|
+
readonly prefixIntact: boolean;
|
|
12
|
+
readonly newUserRequest: boolean;
|
|
13
|
+
readonly arriving: ReadonlySet<string>;
|
|
14
|
+
readonly images: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface DeliveryEntry {
|
|
18
|
+
readonly callId: string;
|
|
19
|
+
readonly toolName: string;
|
|
20
|
+
readonly result: CallToolResult;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface DeliveryBatch {
|
|
24
|
+
readonly id: number;
|
|
25
|
+
readonly entries: readonly DeliveryEntry[];
|
|
26
|
+
readonly blocks: readonly TransferBlock[];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface DeliveryDrop {
|
|
30
|
+
readonly callId: string;
|
|
31
|
+
readonly reason: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface DeliveryDecision {
|
|
35
|
+
readonly batch?: DeliveryBatch;
|
|
36
|
+
readonly deferred: readonly string[];
|
|
37
|
+
readonly dropped: readonly DeliveryDrop[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface RelayReader {
|
|
41
|
+
inspect(callId: string): RelayOutcome;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type ObligationState = "open" | "claimed" | "delivered";
|
|
45
|
+
|
|
46
|
+
interface Obligation {
|
|
47
|
+
readonly callId: string;
|
|
48
|
+
readonly toolName: string;
|
|
49
|
+
state: ObligationState;
|
|
50
|
+
batchId?: number;
|
|
51
|
+
// Kept so a binding replacement can hand a settled result to its successor.
|
|
52
|
+
result?: CallToolResult;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function hasUndeliveredRelay(delivery: Pick<RelayDelivery, "open">, callIds: Iterable<string>): boolean {
|
|
56
|
+
const open = new Set(delivery.open());
|
|
57
|
+
for (const callId of callIds) if (open.has(callId)) return true;
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const DEFAULT_MAX_ENVELOPE_BYTES = 96_000;
|
|
62
|
+
|
|
63
|
+
export function relayNoticeCallId(result: CallToolResult): string | undefined {
|
|
64
|
+
if (result.isError) return undefined;
|
|
65
|
+
const text = result.content
|
|
66
|
+
.filter(block => block.type === "text")
|
|
67
|
+
.map(block => block.type === "text" ? block.text : "")
|
|
68
|
+
.join("");
|
|
69
|
+
if (!text.startsWith("Tool still running.") || !text.includes(`Call ${TOOL_RELAY_CONTROL_NAME} with `)) return undefined;
|
|
70
|
+
return parseRelayCallId(text);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export class RelayDelivery {
|
|
74
|
+
private readonly obligations = new Map<string, Obligation>();
|
|
75
|
+
private nextBatch = 1;
|
|
76
|
+
|
|
77
|
+
constructor(
|
|
78
|
+
private readonly relay: RelayReader,
|
|
79
|
+
private readonly maxEnvelopeBytes = DEFAULT_MAX_ENVELOPE_BYTES,
|
|
80
|
+
) {}
|
|
81
|
+
|
|
82
|
+
observe(invocation: RelayInvocation, noticeCallId: string | undefined): void {
|
|
83
|
+
if (noticeCallId === undefined || noticeCallId !== invocation.id) return;
|
|
84
|
+
if (this.obligations.has(invocation.id)) return;
|
|
85
|
+
this.obligations.set(invocation.id, {
|
|
86
|
+
callId: invocation.id,
|
|
87
|
+
toolName: invocation.name,
|
|
88
|
+
state: "open",
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
consume(callId: string, result?: CallToolResult): void {
|
|
93
|
+
if (result && relayNoticeCallId(result) === callId) return;
|
|
94
|
+
const obligation = this.obligations.get(callId);
|
|
95
|
+
if (!obligation || obligation.state === "delivered") return;
|
|
96
|
+
if (obligation.result) {
|
|
97
|
+
obligation.state = "delivered";
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
const outcome = this.relay.inspect(callId);
|
|
101
|
+
if (outcome.kind === "settled") obligation.state = "delivered";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
decide(boundary: DeliveryBoundary): DeliveryDecision {
|
|
105
|
+
const dropped: DeliveryDrop[] = [];
|
|
106
|
+
const deferred: string[] = [];
|
|
107
|
+
const entries: DeliveryEntry[] = [];
|
|
108
|
+
if (!boundary.reusable || !boundary.prefixIntact) {
|
|
109
|
+
for (const obligation of this.obligations.values()) {
|
|
110
|
+
if (obligation.state !== "open") continue;
|
|
111
|
+
this.obligations.delete(obligation.callId);
|
|
112
|
+
dropped.push({ callId: obligation.callId, reason: boundary.reusable ? "prefix-changed" : "binding-replaced" });
|
|
113
|
+
}
|
|
114
|
+
return { deferred, dropped };
|
|
115
|
+
}
|
|
116
|
+
for (const obligation of this.obligations.values()) {
|
|
117
|
+
if (obligation.state !== "open") continue;
|
|
118
|
+
const outcome = obligation.result
|
|
119
|
+
? { kind: "settled" as const, state: obligation.result.isError ? "failed" as const : "fulfilled" as const, result: obligation.result }
|
|
120
|
+
: this.relay.inspect(obligation.callId);
|
|
121
|
+
if (outcome.kind === "unknown" || outcome.kind === "expired" || outcome.kind === "cancelled") {
|
|
122
|
+
this.obligations.delete(obligation.callId);
|
|
123
|
+
dropped.push({ callId: obligation.callId, reason: `relay-${outcome.kind}` });
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (outcome.kind === "outstanding") {
|
|
127
|
+
deferred.push(obligation.callId);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (boundary.promptLive) {
|
|
131
|
+
deferred.push(obligation.callId);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (boundary.arriving.has(obligation.callId)) {
|
|
135
|
+
obligation.state = "delivered";
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
obligation.result = outcome.result;
|
|
139
|
+
entries.push({ callId: obligation.callId, toolName: obligation.toolName, result: outcome.result });
|
|
140
|
+
}
|
|
141
|
+
if (entries.length === 0) return { deferred, dropped };
|
|
142
|
+
const id = this.nextBatch++;
|
|
143
|
+
for (const entry of entries) {
|
|
144
|
+
const obligation = this.obligations.get(entry.callId);
|
|
145
|
+
if (obligation) {
|
|
146
|
+
obligation.state = "claimed";
|
|
147
|
+
obligation.batchId = id;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const flavor = boundary.newUserRequest ? "preface" : "continuation";
|
|
151
|
+
return {
|
|
152
|
+
batch: {
|
|
153
|
+
id,
|
|
154
|
+
entries,
|
|
155
|
+
blocks: toolResultEnvelope(entries, flavor, {
|
|
156
|
+
images: boundary.images,
|
|
157
|
+
maxBytes: this.maxEnvelopeBytes,
|
|
158
|
+
}),
|
|
159
|
+
},
|
|
160
|
+
deferred,
|
|
161
|
+
dropped,
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
commit(batch: DeliveryBatch): void {
|
|
166
|
+
for (const entry of batch.entries) {
|
|
167
|
+
const obligation = this.obligations.get(entry.callId);
|
|
168
|
+
if (obligation?.state === "claimed" && obligation.batchId === batch.id) obligation.state = "delivered";
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
abandon(batch: DeliveryBatch): void {
|
|
173
|
+
for (const entry of batch.entries) {
|
|
174
|
+
const obligation = this.obligations.get(entry.callId);
|
|
175
|
+
if (obligation?.state !== "claimed" || obligation.batchId !== batch.id) continue;
|
|
176
|
+
obligation.state = "open";
|
|
177
|
+
obligation.batchId = undefined;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
settledOpen(): DeliveryEntry[] {
|
|
182
|
+
const entries: DeliveryEntry[] = [];
|
|
183
|
+
for (const obligation of this.obligations.values()) {
|
|
184
|
+
if (obligation.state === "delivered" || obligation.result === undefined) continue;
|
|
185
|
+
entries.push({ callId: obligation.callId, toolName: obligation.toolName, result: obligation.result });
|
|
186
|
+
}
|
|
187
|
+
return entries;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
adopt(entries: readonly DeliveryEntry[]): void {
|
|
191
|
+
for (const entry of entries) {
|
|
192
|
+
if (this.obligations.has(entry.callId)) continue;
|
|
193
|
+
this.obligations.set(entry.callId, {
|
|
194
|
+
callId: entry.callId,
|
|
195
|
+
toolName: entry.toolName,
|
|
196
|
+
state: "open",
|
|
197
|
+
result: entry.result,
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
reset(): void {
|
|
203
|
+
this.obligations.clear();
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
open(): readonly string[] {
|
|
207
|
+
return [...this.obligations.values()].filter(item => item.state !== "delivered").map(item => item.callId);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function toolResultEnvelope(
|
|
212
|
+
entries: readonly DeliveryEntry[],
|
|
213
|
+
flavor: "continuation" | "preface",
|
|
214
|
+
options: { readonly images: boolean; readonly maxBytes: number },
|
|
215
|
+
): TransferBlock[] {
|
|
216
|
+
const share = entries.length > 0 ? Math.max(1, Math.floor(options.maxBytes / entries.length)) : options.maxBytes;
|
|
217
|
+
const blocks: TransferBlock[] = [];
|
|
218
|
+
for (const entry of entries) {
|
|
219
|
+
const full = resultText(entry.result);
|
|
220
|
+
const text = truncateUtf8(full, share);
|
|
221
|
+
const truncated = text !== full;
|
|
222
|
+
blocks.push({
|
|
223
|
+
type: "text",
|
|
224
|
+
text: `<tool_result id="${entry.callId}" name="${projectedMcpName(entry.toolName)}"${entry.result.isError ? ' error="true"' : ""}>\n` +
|
|
225
|
+
`${escapeClosingTag(text)}${truncated ? "\n[tool result truncated for delivery]" : ""}\n</tool_result>\n\n`,
|
|
226
|
+
});
|
|
227
|
+
for (const block of entry.result.content) {
|
|
228
|
+
if (block.type !== "image") continue;
|
|
229
|
+
if (options.images) blocks.push({ type: "image", data: block.data, mimeType: block.mimeType });
|
|
230
|
+
else blocks.push({ type: "text", text: `[image ${block.mimeType} omitted: this agent does not accept image input]` });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (flavor === "continuation") {
|
|
234
|
+
blocks.push({ type: "text", text: "Continue the task with these tool results. These results are final for these call ids; do not call these tools again for them." });
|
|
235
|
+
}
|
|
236
|
+
return blocks;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function resultText(result: CallToolResult): string {
|
|
240
|
+
return result.content
|
|
241
|
+
.filter(block => block.type === "text")
|
|
242
|
+
.map(block => block.type === "text" ? block.text : "")
|
|
243
|
+
.join("\n");
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
function truncateUtf8(text: string, maxBytes: number): string {
|
|
247
|
+
let output = "";
|
|
248
|
+
let bytes = 0;
|
|
249
|
+
for (const character of text) {
|
|
250
|
+
const size = Buffer.byteLength(character, "utf8");
|
|
251
|
+
if (bytes + size > maxBytes) break;
|
|
252
|
+
output += character;
|
|
253
|
+
bytes += size;
|
|
254
|
+
}
|
|
255
|
+
return output;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function escapeClosingTag(text: string): string {
|
|
259
|
+
return text.replaceAll("</tool_result>", "<\\/tool_result>");
|
|
260
|
+
}
|
|
@@ -67,6 +67,13 @@ export const relayControlTool = {
|
|
|
67
67
|
|
|
68
68
|
type RelayState = "pending" | "relayed" | "fulfilled" | "failed" | "cancelled";
|
|
69
69
|
|
|
70
|
+
export type RelayOutcome =
|
|
71
|
+
| { readonly kind: "unknown" }
|
|
72
|
+
| { readonly kind: "expired" }
|
|
73
|
+
| { readonly kind: "outstanding"; readonly state: "pending" | "relayed" }
|
|
74
|
+
| { readonly kind: "settled"; readonly state: "fulfilled" | "failed"; readonly result: CallToolResult }
|
|
75
|
+
| { readonly kind: "cancelled"; readonly reason: string };
|
|
76
|
+
|
|
70
77
|
interface RelayRecord {
|
|
71
78
|
callId: string;
|
|
72
79
|
turn: number;
|
|
@@ -168,6 +175,22 @@ export class ToolRelay {
|
|
|
168
175
|
}
|
|
169
176
|
return outcome.result ?? relayError("The original tool call returned no result");
|
|
170
177
|
}
|
|
178
|
+
inspect(callId: string): RelayOutcome {
|
|
179
|
+
const record = this.records.get(callId);
|
|
180
|
+
if (!record) return { kind: "unknown" };
|
|
181
|
+
if (record.turn < this.turn - 1) return { kind: "expired" };
|
|
182
|
+
if (record.state === "cancelled") {
|
|
183
|
+
return { kind: "cancelled", reason: relayResultText(record.result) };
|
|
184
|
+
}
|
|
185
|
+
if (record.state === "fulfilled" || record.state === "failed") {
|
|
186
|
+
return {
|
|
187
|
+
kind: "settled",
|
|
188
|
+
state: record.state,
|
|
189
|
+
result: record.result ?? relayError("The original tool call returned no result"),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
return { kind: "outstanding", state: record.state };
|
|
193
|
+
}
|
|
171
194
|
|
|
172
195
|
cancelAll(reason: string): void {
|
|
173
196
|
const result = relayError(reason);
|
|
@@ -225,6 +248,14 @@ export class ToolRelay {
|
|
|
225
248
|
}
|
|
226
249
|
}
|
|
227
250
|
|
|
251
|
+
function relayResultText(result: CallToolResult | undefined): string {
|
|
252
|
+
if (!result) return "The original tool call returned no result";
|
|
253
|
+
return result.content
|
|
254
|
+
.filter(block => block.type === "text")
|
|
255
|
+
.map(block => block.type === "text" ? block.text : "")
|
|
256
|
+
.join("");
|
|
257
|
+
}
|
|
258
|
+
|
|
228
259
|
export function relayError(message: string): CallToolResult {
|
|
229
260
|
return { content: [{ type: "text", text: message }], isError: true };
|
|
230
261
|
}
|
|
@@ -232,7 +263,7 @@ export function relayNoticeResult(callId: string): CallToolResult {
|
|
|
232
263
|
return { content: [{ type: "text", text: relayNotice(callId) }], isError: false };
|
|
233
264
|
}
|
|
234
265
|
export function projectedMcpName(name: string): string {
|
|
235
|
-
return `
|
|
266
|
+
return `omp_${name}`.replace(/[^a-zA-Z0-9_-]/gu, "_").slice(0, 64);
|
|
236
267
|
}
|
|
237
268
|
|
|
238
269
|
export function canonicalArguments(value: unknown): string {
|