pi-openai-toolkit 0.5.0 → 0.7.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.
- package/README.md +22 -33
- package/README_zh.md +22 -33
- package/package.json +8 -12
- package/src/config.ts +70 -51
- package/src/deferred-tool-carryover.ts +280 -0
- package/src/extension-runtime.ts +9 -1
- package/src/inline-compaction.ts +1264 -0
- package/src/payload-rewrite.ts +22 -16
- package/src/types.ts +94 -20
- package/tsconfig.check.json +3 -8
- package/extensions/reasoning-translation.ts +0 -2
- package/src/reasoning-translation/client.ts +0 -187
- package/src/reasoning-translation/extension.ts +0 -105
- package/src/reasoning-translation/persistence.ts +0 -73
- package/src/reasoning-translation/segmenter.ts +0 -60
- package/src/reasoning-translation/state.ts +0 -399
- package/src/reasoning-translation/types.ts +0 -64
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import type { ResponsesCompatibleRequestPayload } from "./runtime";
|
|
2
|
+
import { isDeferredToolCarryover, type DeferredToolCarryoverV1 } from "./types";
|
|
3
|
+
|
|
4
|
+
type JsonObject = Record<string, unknown>;
|
|
5
|
+
|
|
6
|
+
type DeferredToolCompat = {
|
|
7
|
+
supportsAdditionalTools?: boolean;
|
|
8
|
+
supportsToolSearch?: boolean;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export type DeferredToolCarryoverMode = "additional-tools" | "tool-search";
|
|
12
|
+
|
|
13
|
+
export type DeferredToolCarryoverRewrite = {
|
|
14
|
+
payload: ResponsesCompatibleRequestPayload;
|
|
15
|
+
changed: boolean;
|
|
16
|
+
mode?: DeferredToolCarryoverMode;
|
|
17
|
+
movedToolNames: string[];
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
function isRecord(value: unknown): value is JsonObject {
|
|
21
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function getDeferredToolName(value: unknown): string | undefined {
|
|
25
|
+
if (!isRecord(value) || (value.type !== "function" && value.type !== "custom")) {
|
|
26
|
+
return undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
return typeof value.name === "string" && value.name.trim().length > 0 ? value.name : undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function hasOptionalBooleanField(value: JsonObject, field: string): boolean {
|
|
33
|
+
return value[field] === undefined || typeof value[field] === "boolean";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function hasOptionalBooleanOrNullField(value: JsonObject, field: string): boolean {
|
|
37
|
+
return value[field] === undefined || value[field] === null || typeof value[field] === "boolean";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function isCustomToolFormat(value: unknown): boolean {
|
|
41
|
+
if (!isRecord(value)) return false;
|
|
42
|
+
if (value.type === "text") return true;
|
|
43
|
+
return (
|
|
44
|
+
value.type === "grammar" &&
|
|
45
|
+
(value.syntax === "lark" || value.syntax === "regex") &&
|
|
46
|
+
typeof value.definition === "string"
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Validate only the provider-facing function/custom shapes emitted by official Pi. */
|
|
51
|
+
function isDeferredToolSchema(value: unknown): value is JsonObject {
|
|
52
|
+
const name = getDeferredToolName(value);
|
|
53
|
+
if (!name || !isRecord(value)) return false;
|
|
54
|
+
|
|
55
|
+
if (value.type === "function") {
|
|
56
|
+
return (
|
|
57
|
+
"parameters" in value &&
|
|
58
|
+
(value.parameters === null || isRecord(value.parameters)) &&
|
|
59
|
+
hasOptionalBooleanOrNullField(value, "strict") &&
|
|
60
|
+
hasOptionalBooleanField(value, "defer_loading") &&
|
|
61
|
+
(value.description === undefined || value.description === null || typeof value.description === "string")
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return (
|
|
66
|
+
hasOptionalBooleanField(value, "defer_loading") &&
|
|
67
|
+
(value.description === undefined || typeof value.description === "string") &&
|
|
68
|
+
(value.format === undefined || isCustomToolFormat(value.format))
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function addLoadedToolSchemas(tools: unknown, loaded: Set<string>): boolean {
|
|
73
|
+
if (!Array.isArray(tools)) return false;
|
|
74
|
+
for (const tool of tools) {
|
|
75
|
+
const name = getDeferredToolName(tool);
|
|
76
|
+
if (!name || !isDeferredToolSchema(tool)) return false;
|
|
77
|
+
loaded.add(name);
|
|
78
|
+
}
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function isCompletedClientToolSearchCall(value: JsonObject): value is JsonObject & { call_id: string } {
|
|
83
|
+
if (
|
|
84
|
+
value.type !== "tool_search_call" ||
|
|
85
|
+
typeof value.call_id !== "string" ||
|
|
86
|
+
value.call_id.length === 0 ||
|
|
87
|
+
value.execution !== "client" ||
|
|
88
|
+
value.status !== "completed" ||
|
|
89
|
+
!isRecord(value.arguments)
|
|
90
|
+
) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return (
|
|
95
|
+
typeof value.arguments.query === "string" &&
|
|
96
|
+
typeof value.arguments.limit === "number" &&
|
|
97
|
+
Number.isInteger(value.arguments.limit) &&
|
|
98
|
+
value.arguments.limit >= 0
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function collectLoadedToolNames(input: readonly unknown[], startIndex: number): Set<string> | undefined {
|
|
103
|
+
const loaded = new Set<string>();
|
|
104
|
+
|
|
105
|
+
for (let index = startIndex; index < input.length; index += 1) {
|
|
106
|
+
const item = input[index];
|
|
107
|
+
if (!isRecord(item)) continue;
|
|
108
|
+
|
|
109
|
+
if (item.type === "additional_tools") {
|
|
110
|
+
if (item.role !== "developer" || !addLoadedToolSchemas(item.tools, loaded)) return undefined;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
if (item.type === "tool_search_call") {
|
|
115
|
+
if (!isCompletedClientToolSearchCall(item)) return undefined;
|
|
116
|
+
const output = input[index + 1];
|
|
117
|
+
if (
|
|
118
|
+
!isRecord(output) ||
|
|
119
|
+
output.type !== "tool_search_output" ||
|
|
120
|
+
output.call_id !== item.call_id ||
|
|
121
|
+
output.execution !== "client" ||
|
|
122
|
+
output.status !== "completed" ||
|
|
123
|
+
!addLoadedToolSchemas(output.tools, loaded)
|
|
124
|
+
) {
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
index += 1;
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (item.type === "tool_search_output") return undefined;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return loaded;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function createToolSearchCallId(compactionEntryId: string, names: readonly string[]): string {
|
|
138
|
+
let hash = 2166136261;
|
|
139
|
+
for (const value of `${compactionEntryId}\u0000${names.join("\u0000")}`) {
|
|
140
|
+
hash ^= value.codePointAt(0) ?? 0;
|
|
141
|
+
hash = Math.imul(hash, 16777619);
|
|
142
|
+
}
|
|
143
|
+
return `pi_tool_load_${(hash >>> 0).toString(16).padStart(8, "0")}`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function cloneTool(value: JsonObject): JsonObject | undefined {
|
|
147
|
+
try {
|
|
148
|
+
return structuredClone(value);
|
|
149
|
+
} catch {
|
|
150
|
+
return undefined;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function selectMode(compat: DeferredToolCompat | undefined): DeferredToolCarryoverMode | undefined {
|
|
155
|
+
if (compat?.supportsAdditionalTools === true) return "additional-tools";
|
|
156
|
+
if (compat?.supportsToolSearch === true) return "tool-search";
|
|
157
|
+
return undefined;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function createLoadPoint(
|
|
161
|
+
mode: DeferredToolCarryoverMode,
|
|
162
|
+
compactionEntryId: string,
|
|
163
|
+
schemas: readonly JsonObject[],
|
|
164
|
+
): JsonObject[] | undefined {
|
|
165
|
+
const clonedSchemas: JsonObject[] = [];
|
|
166
|
+
for (const schema of schemas) {
|
|
167
|
+
const clone = cloneTool(schema);
|
|
168
|
+
if (!clone) return undefined;
|
|
169
|
+
if (mode === "tool-search") clone.defer_loading = true;
|
|
170
|
+
clonedSchemas.push(clone);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
if (mode === "additional-tools") {
|
|
174
|
+
return [{ type: "additional_tools", role: "developer", tools: clonedSchemas }];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const names = clonedSchemas.map((schema) => getDeferredToolName(schema));
|
|
178
|
+
if (names.some((name): name is undefined => name === undefined)) return undefined;
|
|
179
|
+
const callId = createToolSearchCallId(compactionEntryId, names as string[]);
|
|
180
|
+
return [
|
|
181
|
+
{
|
|
182
|
+
type: "tool_search_call",
|
|
183
|
+
call_id: callId,
|
|
184
|
+
execution: "client",
|
|
185
|
+
status: "completed",
|
|
186
|
+
arguments: { query: (names as string[]).join(" "), limit: names.length },
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
type: "tool_search_output",
|
|
190
|
+
call_id: callId,
|
|
191
|
+
execution: "client",
|
|
192
|
+
status: "completed",
|
|
193
|
+
tools: clonedSchemas,
|
|
194
|
+
},
|
|
195
|
+
];
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Restore cache-stack's activated function/custom schemas after an opaque
|
|
200
|
+
* compaction checkpoint. This is deliberately fail-open: malformed state or
|
|
201
|
+
* payloads leave the provider request untouched so Pi keeps its immediate-tool
|
|
202
|
+
* fallback behavior.
|
|
203
|
+
*/
|
|
204
|
+
export function rewritePayloadWithDeferredToolCarryover(args: {
|
|
205
|
+
payload: ResponsesCompatibleRequestPayload;
|
|
206
|
+
carryover?: DeferredToolCarryoverV1;
|
|
207
|
+
compactionEntryId: string;
|
|
208
|
+
checkpointEndIndex: number;
|
|
209
|
+
compat?: DeferredToolCompat;
|
|
210
|
+
}): DeferredToolCarryoverRewrite {
|
|
211
|
+
const unchanged: DeferredToolCarryoverRewrite = {
|
|
212
|
+
payload: args.payload,
|
|
213
|
+
changed: false,
|
|
214
|
+
movedToolNames: [],
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const mode = selectMode(args.compat);
|
|
218
|
+
if (!mode || !args.carryover || !isDeferredToolCarryover(args.carryover) || !Array.isArray(args.payload.input)) {
|
|
219
|
+
return unchanged;
|
|
220
|
+
}
|
|
221
|
+
if (!Number.isInteger(args.checkpointEndIndex) || args.checkpointEndIndex < 0 || args.checkpointEndIndex > args.payload.input.length) {
|
|
222
|
+
return unchanged;
|
|
223
|
+
}
|
|
224
|
+
if (!Array.isArray(args.payload.tools)) return unchanged;
|
|
225
|
+
|
|
226
|
+
const carryoverNames = new Set(
|
|
227
|
+
args.carryover.toolNames
|
|
228
|
+
.map((name) => name.trim())
|
|
229
|
+
.filter((name) => name.length > 0 && name !== "web_search"),
|
|
230
|
+
);
|
|
231
|
+
if (carryoverNames.size === 0) return unchanged;
|
|
232
|
+
|
|
233
|
+
const schemasByName = new Map<string, JsonObject>();
|
|
234
|
+
const duplicateNames = new Set<string>();
|
|
235
|
+
for (const tool of args.payload.tools) {
|
|
236
|
+
const name = getDeferredToolName(tool);
|
|
237
|
+
if (!name || !carryoverNames.has(name)) continue;
|
|
238
|
+
if (!isDeferredToolSchema(tool)) return unchanged;
|
|
239
|
+
const schema = tool;
|
|
240
|
+
if (schemasByName.has(name)) {
|
|
241
|
+
duplicateNames.add(name);
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
schemasByName.set(name, schema);
|
|
245
|
+
}
|
|
246
|
+
for (const name of duplicateNames) schemasByName.delete(name);
|
|
247
|
+
if (schemasByName.size === 0) return unchanged;
|
|
248
|
+
|
|
249
|
+
const loadedNames = collectLoadedToolNames(args.payload.input, args.checkpointEndIndex);
|
|
250
|
+
if (!loadedNames) return unchanged;
|
|
251
|
+
const matchingNames = [...schemasByName.keys()];
|
|
252
|
+
const movedNames = matchingNames.filter((name) => !loadedNames.has(name));
|
|
253
|
+
const matchingNameSet = new Set(matchingNames);
|
|
254
|
+
const nextTools = args.payload.tools.filter((tool) => {
|
|
255
|
+
const name = getDeferredToolName(tool);
|
|
256
|
+
return !name || !matchingNameSet.has(name);
|
|
257
|
+
});
|
|
258
|
+
const toolsChanged = nextTools.length !== args.payload.tools.length;
|
|
259
|
+
if (movedNames.length === 0 && !toolsChanged) return unchanged;
|
|
260
|
+
|
|
261
|
+
const nextInput = [...args.payload.input];
|
|
262
|
+
if (movedNames.length > 0) {
|
|
263
|
+
const schemas = movedNames.map((name) => schemasByName.get(name));
|
|
264
|
+
if (schemas.some((schema): schema is undefined => schema === undefined)) return unchanged;
|
|
265
|
+
const loadPoint = createLoadPoint(mode, args.compactionEntryId, schemas as JsonObject[]);
|
|
266
|
+
if (!loadPoint) return unchanged;
|
|
267
|
+
nextInput.splice(args.checkpointEndIndex, 0, ...loadPoint);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return {
|
|
271
|
+
payload: {
|
|
272
|
+
...args.payload,
|
|
273
|
+
tools: nextTools,
|
|
274
|
+
input: nextInput,
|
|
275
|
+
},
|
|
276
|
+
changed: true,
|
|
277
|
+
mode,
|
|
278
|
+
movedToolNames: movedNames,
|
|
279
|
+
};
|
|
280
|
+
}
|
package/src/extension-runtime.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
} from "./payload-rewrite";
|
|
16
16
|
import { getCompactionRequestExtras, rememberRequestContext } from "./request-context-cache";
|
|
17
17
|
import { executeRemoteV2Compaction } from "./remote-v2-client";
|
|
18
|
+
import { registerInlineCompactionRuntime } from "./inline-compaction";
|
|
18
19
|
import {
|
|
19
20
|
resolveNativeCompactionEnvironment,
|
|
20
21
|
resolveRemoteCompactionExecution,
|
|
@@ -25,6 +26,7 @@ import {
|
|
|
25
26
|
createNativeCompactionDetails,
|
|
26
27
|
createNativeCompactionResult,
|
|
27
28
|
COMPACTION_EXTENSION_ID,
|
|
29
|
+
getLatestDeferredToolCarryover,
|
|
28
30
|
isNativeCompactionDetails,
|
|
29
31
|
type CompactionConfig,
|
|
30
32
|
type NativeCompactionDetails,
|
|
@@ -99,7 +101,8 @@ async function runResponsesNativeCompact(
|
|
|
99
101
|
): Promise<ResponsesCompactOutcome> {
|
|
100
102
|
const { consumer, compactor } = execution;
|
|
101
103
|
const instructions = buildCompactionInstructions(ctx.getSystemPrompt(), event.customInstructions);
|
|
102
|
-
const branchEntries = ctx.sessionManager.getBranch();
|
|
104
|
+
const branchEntries = event.branchEntries ?? ctx.sessionManager.getBranch();
|
|
105
|
+
const deferredToolCarryover = getLatestDeferredToolCarryover(branchEntries);
|
|
103
106
|
const latestNativeCompaction = resolveLatestNativeCompactionEntry(branchEntries, {
|
|
104
107
|
baseUrl: consumer.baseUrl,
|
|
105
108
|
});
|
|
@@ -217,6 +220,7 @@ async function runResponsesNativeCompact(
|
|
|
217
220
|
model: compactor.model,
|
|
218
221
|
baseUrl: compactor.baseUrl,
|
|
219
222
|
},
|
|
223
|
+
deferredToolCarryover,
|
|
220
224
|
compactedWindow: compactResult.compactedWindow,
|
|
221
225
|
compactResponseId: compactResult.compactResponseId,
|
|
222
226
|
createdAt: compactResult.createdAt,
|
|
@@ -537,6 +541,8 @@ async function handleBeforeProviderRequest(event: BeforeProviderRequestEvent, ct
|
|
|
537
541
|
}
|
|
538
542
|
|
|
539
543
|
export default function (pi: ExtensionAPI) {
|
|
544
|
+
const inlineCompaction = registerInlineCompactionRuntime(pi, loadToolkitConfig);
|
|
545
|
+
|
|
540
546
|
pi.on("session_start", (_event, ctx) => {
|
|
541
547
|
const { config: toolkitConfig, source, warnings } = loadToolkitConfig();
|
|
542
548
|
const config = toolkitConfig.compaction;
|
|
@@ -570,4 +576,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
570
576
|
|
|
571
577
|
pi.on("session_before_compact", handleSessionBeforeCompact);
|
|
572
578
|
pi.on("before_provider_request", handleBeforeProviderRequest);
|
|
579
|
+
pi.on("turn_end", (event, ctx) => inlineCompaction.handlePublicTurnEnd(event, ctx));
|
|
580
|
+
pi.on("session_shutdown", (_event, ctx) => inlineCompaction.dispose(ctx));
|
|
573
581
|
}
|