@linxiraos/pi-agent-core 1.4.6 → 1.4.9
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/CHANGELOG.md +17 -6
- package/dist/types/agent.d.ts +23 -0
- package/dist/types/compaction/branch-summarization.d.ts +2 -3
- package/dist/types/compaction/compaction-v2-streaming.d.ts +2 -1
- package/dist/types/compaction/compaction.d.ts +4 -2
- package/dist/types/compaction/utils.d.ts +8 -22
- package/dist/types/index.d.ts +0 -1
- package/dist/types/sent-tool-definitions.d.ts +11 -5
- package/dist/types/tokenizer.d.ts +10 -9
- package/dist/types/types.d.ts +8 -2
- package/package.json +10 -10
- package/src/agent-loop.ts +14 -41
- package/src/agent.ts +55 -13
- package/src/compaction/anthropic.ts +9 -4
- package/src/compaction/branch-summarization.ts +8 -10
- package/src/compaction/compaction-v2-streaming.ts +26 -19
- package/src/compaction/compaction.ts +33 -17
- package/src/compaction/openai.ts +7 -1
- package/src/compaction/prompts/anthropic-compaction-instructions.md +1 -2
- package/src/compaction/utils.ts +22 -96
- package/src/index.ts +0 -2
- package/src/sent-tool-definitions.ts +22 -5
- package/src/telemetry.ts +0 -8
- package/src/tokenizer.ts +62 -24
- package/src/types.ts +9 -2
- package/dist/types/utils/yield.d.ts +0 -71
- package/src/compaction/prompts/file-operations.md +0 -5
- package/src/utils/yield.ts +0 -183
package/src/agent.ts
CHANGED
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
type ToolResultMessage,
|
|
24
24
|
} from "@linxiraos/pi-ai";
|
|
25
25
|
import type { Dialect } from "@linxiraos/pi-ai/dialect";
|
|
26
|
-
import { openAIResponsesReplaysNativeHistory } from "@linxiraos/pi-ai/providers/openai-responses";
|
|
26
|
+
import { openAIResponsesReplaysNativeHistory } from "@linxiraos/pi-ai/providers/openai-responses-state";
|
|
27
27
|
import type { HarmonyAuditEvent } from "@linxiraos/pi-ai/utils/harmony-leak";
|
|
28
28
|
import { getBundledModel } from "@linxiraos/pi-catalog/models";
|
|
29
29
|
import { logger } from "@linxiraos/pi-utils";
|
|
@@ -69,7 +69,6 @@ import type {
|
|
|
69
69
|
ToolChoiceDirective,
|
|
70
70
|
} from "./types";
|
|
71
71
|
import { isSoftToolRequirement } from "./types";
|
|
72
|
-
import { EventLoopKeepalive } from "./utils/yield";
|
|
73
72
|
|
|
74
73
|
/**
|
|
75
74
|
* Default convertToLlm: Keep only LLM-compatible replay messages.
|
|
@@ -177,6 +176,11 @@ export interface AgentOptions {
|
|
|
177
176
|
* Shared provider state map for session-scoped transport/session caches.
|
|
178
177
|
*/
|
|
179
178
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
179
|
+
/**
|
|
180
|
+
* Tool definitions already sent, for an Agent that replays another Agent's request history
|
|
181
|
+
* (see {@link Agent.copySentToolDefinitions}). Defaults to an empty store.
|
|
182
|
+
*/
|
|
183
|
+
sentToolDefinitions?: SentToolDefinitions;
|
|
180
184
|
|
|
181
185
|
/**
|
|
182
186
|
* Resolves an API key or resolver dynamically for each LLM call.
|
|
@@ -569,6 +573,7 @@ export class Agent {
|
|
|
569
573
|
this.#deadline = opts.deadline;
|
|
570
574
|
this.#promptCacheKey = opts.promptCacheKey;
|
|
571
575
|
this.#providerSessionState = opts.providerSessionState;
|
|
576
|
+
if (opts.sentToolDefinitions) this.#sentToolDefinitions = opts.sentToolDefinitions;
|
|
572
577
|
this.#thinkingBudgets = opts.thinkingBudgets;
|
|
573
578
|
this.#temperature = opts.temperature;
|
|
574
579
|
this.#topP = opts.topP;
|
|
@@ -643,6 +648,20 @@ export class Agent {
|
|
|
643
648
|
this.#promptCacheKey = value;
|
|
644
649
|
}
|
|
645
650
|
|
|
651
|
+
/**
|
|
652
|
+
* A detached copy of the tool definitions this agent has sent (`AgentOptions.sentToolDefinitions`), without the
|
|
653
|
+
* names `keep` rejects.
|
|
654
|
+
*/
|
|
655
|
+
copySentToolDefinitions(keep?: (name: string) => boolean): SentToolDefinitions {
|
|
656
|
+
return this.#sentToolDefinitions.copy(keep);
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/**
|
|
660
|
+
* Fields added to every log record written while this agent runs (the
|
|
661
|
+
* owning session's `sessionId`), so in-process agents' records stay apart.
|
|
662
|
+
*/
|
|
663
|
+
logContext: Readonly<Record<string, unknown>> | undefined;
|
|
664
|
+
|
|
646
665
|
/**
|
|
647
666
|
* Static metadata forwarded to every API request when no resolver is installed
|
|
648
667
|
* (e.g. `metadata.user_id` for Anthropic session attribution). Setting this
|
|
@@ -819,6 +838,23 @@ export class Agent {
|
|
|
819
838
|
this.#pruneToolDescriptions = value;
|
|
820
839
|
}
|
|
821
840
|
|
|
841
|
+
/**
|
|
842
|
+
* Whether requests to `model` actually ship description-stripped tool specs.
|
|
843
|
+
* Owned dialects render full definitions in-band, so they never prune; the
|
|
844
|
+
* loop applies the same rule (`pruneToolDescriptions && !ownedDialect`).
|
|
845
|
+
* Context accounting reads this instead of the raw setting.
|
|
846
|
+
*/
|
|
847
|
+
prunesToolDescriptions(model: Model | undefined): boolean {
|
|
848
|
+
return this.#pruneToolDescriptions && model !== undefined && !this.#ownedDialect(model);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
#ownedDialect(model: Model): Dialect | undefined {
|
|
852
|
+
return (
|
|
853
|
+
(this.#dialectResolver ? this.#dialectResolver(model) : this.#dialect) ??
|
|
854
|
+
resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT)
|
|
855
|
+
);
|
|
856
|
+
}
|
|
857
|
+
|
|
822
858
|
/** Inject/strip the intent field on tool calls; applies from the next prompt run. */
|
|
823
859
|
get intentTracing(): boolean {
|
|
824
860
|
return this.#intentTracing;
|
|
@@ -928,9 +964,7 @@ export class Agent {
|
|
|
928
964
|
): Promise<Context> {
|
|
929
965
|
const model = this.#state.model;
|
|
930
966
|
if (!model) throw new Error("No active model on agent");
|
|
931
|
-
const ownedDialect =
|
|
932
|
-
(this.#dialectResolver ? this.#dialectResolver(model) : this.#dialect) ??
|
|
933
|
-
resolveOwnedDialectFromEnv(Bun.env.PI_DIALECT);
|
|
967
|
+
const ownedDialect = this.#ownedDialect(model);
|
|
934
968
|
const messages = normalizeMessagesForProvider(llmMessages, model);
|
|
935
969
|
const tools = ownedDialect
|
|
936
970
|
? []
|
|
@@ -939,12 +973,11 @@ export class Agent {
|
|
|
939
973
|
pruneDescriptions: this.#pruneToolDescriptions,
|
|
940
974
|
}) ?? []);
|
|
941
975
|
let context: Context = { systemPrompt, messages, tools };
|
|
976
|
+
// Side requests reuse the main loop's sent definitions without recording their own; attached before the
|
|
977
|
+
// transform too, so a request-size clamp in it measures them.
|
|
978
|
+
context = this.#sentToolDefinitions.withInactiveTools(context);
|
|
942
979
|
if (this.#transformProviderContext) context = await this.#transformProviderContext(context, model);
|
|
943
|
-
|
|
944
|
-
if (context.tools?.length) {
|
|
945
|
-
const inactiveTools = this.#sentToolDefinitions.inactiveFor(context.messages, context.tools);
|
|
946
|
-
if (inactiveTools) context = { ...context, inactiveTools };
|
|
947
|
-
}
|
|
980
|
+
context = this.#sentToolDefinitions.withInactiveTools(context);
|
|
948
981
|
return context;
|
|
949
982
|
}
|
|
950
983
|
|
|
@@ -1653,7 +1686,7 @@ export class Agent {
|
|
|
1653
1686
|
promptOptions = imagesOrOptions as AgentPromptOptions | undefined;
|
|
1654
1687
|
}
|
|
1655
1688
|
|
|
1656
|
-
await this.#runLoop(msgs, promptOptions);
|
|
1689
|
+
await this.#inLogContext(() => this.#runLoop(msgs, promptOptions));
|
|
1657
1690
|
}
|
|
1658
1691
|
|
|
1659
1692
|
/**
|
|
@@ -1677,7 +1710,12 @@ export class Agent {
|
|
|
1677
1710
|
return signals.length === 1 ? signals[0] : AbortSignal.any(signals);
|
|
1678
1711
|
}
|
|
1679
1712
|
|
|
1680
|
-
|
|
1713
|
+
continue(signal?: AbortSignal): Promise<void> {
|
|
1714
|
+
// Queued-message hooks run before the loop and are this agent's work too.
|
|
1715
|
+
return this.#inLogContext(() => this.#continue(signal));
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
async #continue(signal?: AbortSignal) {
|
|
1681
1719
|
if (this.#state.isStreaming) {
|
|
1682
1720
|
throw new AgentBusyError();
|
|
1683
1721
|
}
|
|
@@ -1759,6 +1797,11 @@ export class Agent {
|
|
|
1759
1797
|
}
|
|
1760
1798
|
}
|
|
1761
1799
|
|
|
1800
|
+
/** Run `fn` with {@link logContext} on every record it logs. */
|
|
1801
|
+
#inLogContext<T>(fn: () => T): T {
|
|
1802
|
+
return this.logContext ? logger.withContext(this.logContext, fn) : fn();
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1762
1805
|
/**
|
|
1763
1806
|
* Run the agent loop.
|
|
1764
1807
|
* If messages are provided, starts a new conversation turn with those messages.
|
|
@@ -1774,7 +1817,6 @@ export class Agent {
|
|
|
1774
1817
|
if (!model) throw new Error("No model configured");
|
|
1775
1818
|
|
|
1776
1819
|
let skipInitialSteeringPoll = options?.skipInitialSteeringPoll === true;
|
|
1777
|
-
using _ = new EventLoopKeepalive();
|
|
1778
1820
|
if (!runStateClaimed) {
|
|
1779
1821
|
const { promise, resolve } = Promise.withResolvers<void>();
|
|
1780
1822
|
this.#runningPrompt = promise;
|
|
@@ -18,7 +18,6 @@ import type {
|
|
|
18
18
|
Usage,
|
|
19
19
|
} from "@linxiraos/pi-ai";
|
|
20
20
|
import * as AIError from "@linxiraos/pi-ai/error";
|
|
21
|
-
import { resolveAnthropicCompactionEffort } from "@linxiraos/pi-ai/providers/anthropic";
|
|
22
21
|
import {
|
|
23
22
|
supportsAnthropicCompaction,
|
|
24
23
|
supportsBedrockConverseCompaction,
|
|
@@ -251,6 +250,14 @@ export async function requestAnthropicNativeCompaction(
|
|
|
251
250
|
signal: AbortSignal | undefined,
|
|
252
251
|
options: AnthropicNativeCompactionOptions,
|
|
253
252
|
): Promise<AnthropicNativeCompactionResponse> {
|
|
253
|
+
// Pure compaction policy checks must not load the provider; only an actual request needs it.
|
|
254
|
+
const reasoning = isAnthropicMessagesModel(model)
|
|
255
|
+
? (await import("@linxiraos/pi-ai/providers/anthropic")).resolveAnthropicCompactionEffort(
|
|
256
|
+
model,
|
|
257
|
+
request.context.messages,
|
|
258
|
+
request.reasoning,
|
|
259
|
+
)
|
|
260
|
+
: request.reasoning;
|
|
254
261
|
const response = await instrumentedCompleteSimple(
|
|
255
262
|
model,
|
|
256
263
|
request.context,
|
|
@@ -258,9 +265,7 @@ export async function requestAnthropicNativeCompaction(
|
|
|
258
265
|
apiKey,
|
|
259
266
|
signal,
|
|
260
267
|
maxTokens: request.maxTokens,
|
|
261
|
-
reasoning
|
|
262
|
-
? resolveAnthropicCompactionEffort(model, request.context.messages, request.reasoning)
|
|
263
|
-
: request.reasoning,
|
|
268
|
+
reasoning,
|
|
264
269
|
initiatorOverride: options.initiatorOverride,
|
|
265
270
|
metadata: options.metadata,
|
|
266
271
|
fetch: options.fetch,
|
|
@@ -24,15 +24,12 @@ import {
|
|
|
24
24
|
import branchSummaryPrompt from "./prompts/branch-summary.md" with { type: "text" };
|
|
25
25
|
import branchSummaryPreamble from "./prompts/branch-summary-preamble.md" with { type: "text" };
|
|
26
26
|
import {
|
|
27
|
-
computeFileLists,
|
|
28
|
-
createFileOps,
|
|
29
27
|
extractFileOpsFromMessage,
|
|
30
|
-
|
|
28
|
+
incompleteOutputError,
|
|
31
29
|
SUMMARIZATION_SYSTEM_PROMPT,
|
|
32
30
|
serializeConversationForSummary,
|
|
33
31
|
stripReadSelector,
|
|
34
32
|
truncateToolResultForSummary,
|
|
35
|
-
upsertFileOperations,
|
|
36
33
|
} from "./utils";
|
|
37
34
|
|
|
38
35
|
// ============================================================================
|
|
@@ -53,13 +50,11 @@ export interface BranchSummaryDetails {
|
|
|
53
50
|
modifiedFiles: string[];
|
|
54
51
|
}
|
|
55
52
|
|
|
56
|
-
export type { FileOperations } from "./utils";
|
|
57
|
-
|
|
58
53
|
export interface BranchPreparation {
|
|
59
54
|
/** Messages extracted for summarization, in chronological order */
|
|
60
55
|
messages: AgentMessage[];
|
|
61
56
|
/** File operations extracted from tool calls */
|
|
62
|
-
fileOps: FileOperations;
|
|
57
|
+
fileOps: snapcompact.FileOperations;
|
|
63
58
|
/** Total estimated tokens in messages */
|
|
64
59
|
totalTokens: number;
|
|
65
60
|
}
|
|
@@ -251,7 +246,7 @@ export function prepareBranchEntries(
|
|
|
251
246
|
tokenBudget: number = 0,
|
|
252
247
|
): BranchPreparation {
|
|
253
248
|
const messages: AgentMessage[] = [];
|
|
254
|
-
const fileOps = createFileOps();
|
|
249
|
+
const fileOps = snapcompact.createFileOps();
|
|
255
250
|
let totalTokens = 0;
|
|
256
251
|
|
|
257
252
|
// First pass: collect file ops from ALL entries (even if they don't fit in token budget)
|
|
@@ -386,6 +381,9 @@ export async function generateBranchSummary(
|
|
|
386
381
|
if (response.stopReason === "error") {
|
|
387
382
|
return { error: response.errorMessage || "Summarization failed" };
|
|
388
383
|
}
|
|
384
|
+
if (response.stopReason === "length") {
|
|
385
|
+
return { error: incompleteOutputError("Summarization failed") };
|
|
386
|
+
}
|
|
389
387
|
|
|
390
388
|
let summary = response.content
|
|
391
389
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
@@ -396,8 +394,8 @@ export async function generateBranchSummary(
|
|
|
396
394
|
summary = BRANCH_SUMMARY_PREAMBLE + summary;
|
|
397
395
|
|
|
398
396
|
// Compute file lists and append to summary
|
|
399
|
-
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
|
|
400
|
-
summary = upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
397
|
+
const { readFiles, modifiedFiles } = snapcompact.computeFileLists(fileOps);
|
|
398
|
+
summary = snapcompact.upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
401
399
|
|
|
402
400
|
return {
|
|
403
401
|
summary: summary || "No summary generated",
|
|
@@ -11,11 +11,9 @@ import type { Api, CodexCompactionContext, FetchImpl, Model, ProviderSessionStat
|
|
|
11
11
|
import * as AIError from "@linxiraos/pi-ai/error";
|
|
12
12
|
import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
|
|
13
13
|
import { applyCodexResponsesLiteShape } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
type OpenAICodexCompactionBody,
|
|
18
|
-
type OpenAICodexCompatibilityMetadata,
|
|
14
|
+
import type {
|
|
15
|
+
OpenAICodexCompactionBody,
|
|
16
|
+
OpenAICodexCompatibilityMetadata,
|
|
19
17
|
} from "@linxiraos/pi-ai/providers/openai-codex-responses";
|
|
20
18
|
import {
|
|
21
19
|
getOpenAIPromptCacheKey,
|
|
@@ -34,7 +32,7 @@ import {
|
|
|
34
32
|
OPENAI_HEADER_VALUES,
|
|
35
33
|
OPENAI_HEADERS,
|
|
36
34
|
} from "@linxiraos/pi-catalog/wire/codex";
|
|
37
|
-
import { $env, isUnexpectedSocketCloseMessage, logger, ptree, stringifyJson } from "@linxiraos/pi-utils";
|
|
35
|
+
import { $env, isUnexpectedSocketCloseMessage, logger, ptree, stringifyJson, toError } from "@linxiraos/pi-utils";
|
|
38
36
|
import { appendAzureApiVersion, resolveAzureOpenAiBaseUrl } from "./azure-openai-endpoint";
|
|
39
37
|
import { prepareBedrockCompactionRequest } from "./bedrock";
|
|
40
38
|
|
|
@@ -276,6 +274,7 @@ export async function requestCompactionV2Streaming(
|
|
|
276
274
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
277
275
|
codexCompaction?: CodexCompactionContext;
|
|
278
276
|
preferWebsockets?: boolean;
|
|
277
|
+
codexAccessPrograms?: boolean;
|
|
279
278
|
},
|
|
280
279
|
): Promise<CompactionV2Response> {
|
|
281
280
|
let fetchImpl: FetchImpl = options?.fetch ?? globalThis.fetch;
|
|
@@ -293,18 +292,21 @@ export async function requestCompactionV2Streaming(
|
|
|
293
292
|
|
|
294
293
|
const retryWait = options?.retryWait ?? ((delayMs: number) => Bun.sleep(delayMs));
|
|
295
294
|
const isCodexResponses = compactionV2Api(model) === "openai-codex-responses" || model.provider === "openai-codex";
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
295
|
+
let codexMetadata: OpenAICodexCompatibilityMetadata | undefined;
|
|
296
|
+
if (isCodexResponses && !shouldUseCodexProviderTransport(model)) {
|
|
297
|
+
// Metadata generation is request work; importing compaction policy must not load the Codex transport.
|
|
298
|
+
const { createOpenAICodexCompatibilityMetadata } =
|
|
299
|
+
await import("@linxiraos/pi-ai/providers/openai-codex-responses");
|
|
300
|
+
codexMetadata = createOpenAICodexCompatibilityMetadata({
|
|
301
|
+
sessionId: request.sessionId,
|
|
302
|
+
providerSessionState: options?.providerSessionState,
|
|
303
|
+
requestKind: "compaction",
|
|
304
|
+
compaction: createOpenAICodexCompactionRequestContext({
|
|
305
|
+
context: options?.codexCompaction,
|
|
306
|
+
implementation: "responses_compaction_v2",
|
|
307
|
+
}),
|
|
308
|
+
});
|
|
309
|
+
}
|
|
308
310
|
let lastError: Error | undefined;
|
|
309
311
|
|
|
310
312
|
for (let attempt = 0; attempt <= V2_COMPACTION_MAX_RETRIES; attempt++) {
|
|
@@ -315,9 +317,10 @@ export async function requestCompactionV2Streaming(
|
|
|
315
317
|
providerSessionState: options?.providerSessionState,
|
|
316
318
|
codexCompaction: options?.codexCompaction,
|
|
317
319
|
preferWebsockets: options?.preferWebsockets,
|
|
320
|
+
codexAccessPrograms: options?.codexAccessPrograms,
|
|
318
321
|
});
|
|
319
322
|
} catch (err) {
|
|
320
|
-
const error =
|
|
323
|
+
const error = toError(err);
|
|
321
324
|
if (signal?.aborted) throw error;
|
|
322
325
|
|
|
323
326
|
if (isRetryableCompactionError(error) && attempt < V2_COMPACTION_MAX_RETRIES) {
|
|
@@ -351,6 +354,7 @@ async function attemptCompactionV2Streaming(
|
|
|
351
354
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
352
355
|
codexCompaction?: CodexCompactionContext;
|
|
353
356
|
preferWebsockets?: boolean;
|
|
357
|
+
codexAccessPrograms?: boolean;
|
|
354
358
|
},
|
|
355
359
|
): Promise<CompactionV2Response> {
|
|
356
360
|
// Faithful to Codex: append the compaction trigger as the final input item
|
|
@@ -367,6 +371,8 @@ async function attemptCompactionV2Streaming(
|
|
|
367
371
|
}
|
|
368
372
|
|
|
369
373
|
if (shouldUseCodexProviderTransport(model)) {
|
|
374
|
+
// The native transport is only needed when sending a Codex compaction request.
|
|
375
|
+
const { openCodexCompactionEventStream } = await import("@linxiraos/pi-ai/providers/openai-codex-responses");
|
|
370
376
|
const eventStream = await openCodexCompactionEventStream(model, body, {
|
|
371
377
|
apiKey,
|
|
372
378
|
signal,
|
|
@@ -374,6 +380,7 @@ async function attemptCompactionV2Streaming(
|
|
|
374
380
|
sessionId: request.sessionId,
|
|
375
381
|
providerSessionState: options.providerSessionState,
|
|
376
382
|
preferWebsockets: options.preferWebsockets,
|
|
383
|
+
codexAccessPrograms: options.codexAccessPrograms,
|
|
377
384
|
responsesLite: model.useResponsesLite,
|
|
378
385
|
codexCompaction: createOpenAICodexCompactionRequestContext({
|
|
379
386
|
context: options.codexCompaction,
|
|
@@ -27,12 +27,8 @@ import {
|
|
|
27
27
|
import type { Dialect } from "@linxiraos/pi-ai/dialect";
|
|
28
28
|
import * as AIError from "@linxiraos/pi-ai/error";
|
|
29
29
|
import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
|
|
30
|
+
import type { OpenAICodexCompactionBody } from "@linxiraos/pi-ai/providers/openai-codex-responses";
|
|
30
31
|
import type { InputItem as CodexInputItem } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
|
|
31
|
-
import {
|
|
32
|
-
buildTransformedCodexRequestBody,
|
|
33
|
-
type OpenAICodexCompactionBody,
|
|
34
|
-
} from "@linxiraos/pi-ai/providers/openai-codex-responses";
|
|
35
|
-
import { convertTools } from "@linxiraos/pi-ai/providers/openai-responses";
|
|
36
32
|
import { buildResponsesInput, resolveOpenAICompatPolicy } from "@linxiraos/pi-ai/providers/openai-shared";
|
|
37
33
|
import { isSurvivingAssistant } from "@linxiraos/pi-ai/providers/transform-messages";
|
|
38
34
|
import { stripOpenAIResponsesOutputOnlyStatusesForReplay } from "@linxiraos/pi-ai/utils";
|
|
@@ -90,15 +86,12 @@ import handoffDocumentPrompt from "./prompts/handoff-document.md" with { type: "
|
|
|
90
86
|
import snapcompactArchiveContextPrompt from "./prompts/snapcompact-archive-context.md" with { type: "text" };
|
|
91
87
|
|
|
92
88
|
import {
|
|
93
|
-
computeFileLists,
|
|
94
|
-
createFileOps,
|
|
95
89
|
escapeSummaryBoundaryTags,
|
|
96
90
|
extractFileOpsFromMessage,
|
|
97
|
-
|
|
91
|
+
incompleteOutputError,
|
|
98
92
|
SUMMARIZATION_SYSTEM_PROMPT,
|
|
99
93
|
serializeConversationForSummary,
|
|
100
94
|
stripReadSelector,
|
|
101
|
-
upsertFileOperations,
|
|
102
95
|
} from "./utils";
|
|
103
96
|
|
|
104
97
|
// ============================================================================
|
|
@@ -118,8 +111,8 @@ function extractFileOperations(
|
|
|
118
111
|
messages: AgentMessage[],
|
|
119
112
|
entries: SessionEntry[],
|
|
120
113
|
prevCompactionIndex: number,
|
|
121
|
-
): FileOperations {
|
|
122
|
-
const fileOps = createFileOps();
|
|
114
|
+
): snapcompact.FileOperations {
|
|
115
|
+
const fileOps = snapcompact.createFileOps();
|
|
123
116
|
|
|
124
117
|
// Collect from previous compaction's details (if pi-generated)
|
|
125
118
|
if (prevCompactionIndex >= 0) {
|
|
@@ -754,6 +747,8 @@ export interface SummaryOptions {
|
|
|
754
747
|
providerSessionState?: Map<string, ProviderSessionState>;
|
|
755
748
|
/** Whether Codex remote compaction should prefer the provider WebSocket transport. */
|
|
756
749
|
preferWebsockets?: boolean;
|
|
750
|
+
/** Daybreak Blue request on Codex remote compaction; see `StreamOptions.codexAccessPrograms`. */
|
|
751
|
+
codexAccessPrograms?: boolean;
|
|
757
752
|
/** Classification shared by every provider request in this logical compaction. */
|
|
758
753
|
codexCompaction?: CodexCompactionContext;
|
|
759
754
|
/** Provider-visible tools for remote compaction transports that replay native tool history. */
|
|
@@ -1077,6 +1072,9 @@ async function summarizeConversationWindow(
|
|
|
1077
1072
|
if (response.stopReason === "error") {
|
|
1078
1073
|
throw createSummarizationError("Summarization failed", response);
|
|
1079
1074
|
}
|
|
1075
|
+
if (response.stopReason === "length") {
|
|
1076
|
+
throw new Error(incompleteOutputError("Summarization failed"));
|
|
1077
|
+
}
|
|
1080
1078
|
|
|
1081
1079
|
const textContent = response.content
|
|
1082
1080
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
@@ -1184,6 +1182,9 @@ export async function generateHandoffFromContext(
|
|
|
1184
1182
|
if (response.stopReason === "error") {
|
|
1185
1183
|
throw createSummarizationError("Handoff generation failed", response);
|
|
1186
1184
|
}
|
|
1185
|
+
if (response.stopReason === "length") {
|
|
1186
|
+
throw new Error(incompleteOutputError("Handoff generation failed"));
|
|
1187
|
+
}
|
|
1187
1188
|
|
|
1188
1189
|
return response.content
|
|
1189
1190
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
@@ -1307,8 +1308,10 @@ async function generateShortSummary(
|
|
|
1307
1308
|
case "error":
|
|
1308
1309
|
outcome = { kind: "failed", error: response.errorMessage || "Unknown error" };
|
|
1309
1310
|
break;
|
|
1310
|
-
case "stop":
|
|
1311
1311
|
case "length":
|
|
1312
|
+
outcome = { kind: "failed", error: incompleteOutputError("Short summary failed") };
|
|
1313
|
+
break;
|
|
1314
|
+
case "stop":
|
|
1312
1315
|
case "toolUse":
|
|
1313
1316
|
outcome = {
|
|
1314
1317
|
kind: "text",
|
|
@@ -1377,7 +1380,7 @@ export interface CompactionPreparation {
|
|
|
1377
1380
|
/** Preserved opaque compaction payload from the previous compaction, if any. */
|
|
1378
1381
|
previousPreserveData?: Record<string, unknown>;
|
|
1379
1382
|
/** File operations extracted from messagesToSummarize */
|
|
1380
|
-
fileOps: FileOperations;
|
|
1383
|
+
fileOps: snapcompact.FileOperations;
|
|
1381
1384
|
/** Compaction settions from settings.jsonl */
|
|
1382
1385
|
settings: CompactionSettings;
|
|
1383
1386
|
}
|
|
@@ -1769,6 +1772,7 @@ export async function compact(
|
|
|
1769
1772
|
: options?.promptCacheKey,
|
|
1770
1773
|
providerSessionState: options?.providerSessionState,
|
|
1771
1774
|
preferWebsockets: options?.preferWebsockets,
|
|
1775
|
+
codexAccessPrograms: options?.codexAccessPrograms,
|
|
1772
1776
|
codexCompaction: options?.codexCompaction,
|
|
1773
1777
|
tools: options?.tools,
|
|
1774
1778
|
fetch: options?.fetch,
|
|
@@ -1890,6 +1894,9 @@ export async function compact(
|
|
|
1890
1894
|
let codexBody: OpenAICodexCompactionBody | undefined;
|
|
1891
1895
|
let remoteHistory: Array<Record<string, unknown>>;
|
|
1892
1896
|
if (isCodexResponsesModel(model)) {
|
|
1897
|
+
// Load the serializer only when building a Codex compaction request, not session policy setup.
|
|
1898
|
+
const { buildTransformedCodexRequestBody } =
|
|
1899
|
+
await import("@linxiraos/pi-ai/providers/openai-codex-responses");
|
|
1893
1900
|
const previousCodexInput: CodexInputItem[] = [];
|
|
1894
1901
|
for (const item of previousReplacementHistory ?? []) {
|
|
1895
1902
|
if (!isCodexInputItem(item)) {
|
|
@@ -1950,12 +1957,17 @@ export async function compact(
|
|
|
1950
1957
|
? codexBody.instructions
|
|
1951
1958
|
: ""
|
|
1952
1959
|
: remoteSystemPrompt.join("\n\n");
|
|
1960
|
+
// Responses serialization is needed only for this native compaction request.
|
|
1953
1961
|
const tools = codexBody
|
|
1954
1962
|
? Array.isArray(codexBody.tools)
|
|
1955
1963
|
? codexBody.tools
|
|
1956
1964
|
: undefined
|
|
1957
1965
|
: summaryOptions.tools
|
|
1958
|
-
?
|
|
1966
|
+
? (await import("@linxiraos/pi-ai/providers/openai-responses")).convertTools(
|
|
1967
|
+
summaryOptions.tools,
|
|
1968
|
+
model.compat.supportsStrictMode,
|
|
1969
|
+
model,
|
|
1970
|
+
)
|
|
1959
1971
|
: undefined;
|
|
1960
1972
|
const trimmed = trimRemoteCompactionInputToContextWindow(
|
|
1961
1973
|
remoteHistory,
|
|
@@ -1996,6 +2008,7 @@ export async function compact(
|
|
|
1996
2008
|
fetch: summaryOptions.fetch,
|
|
1997
2009
|
providerSessionState: summaryOptions.providerSessionState,
|
|
1998
2010
|
preferWebsockets: summaryOptions.preferWebsockets,
|
|
2011
|
+
codexAccessPrograms: summaryOptions.codexAccessPrograms,
|
|
1999
2012
|
codexCompaction: summaryOptions.codexCompaction,
|
|
2000
2013
|
}),
|
|
2001
2014
|
{ signal },
|
|
@@ -2326,8 +2339,8 @@ export async function compact(
|
|
|
2326
2339
|
});
|
|
2327
2340
|
|
|
2328
2341
|
// Compute file lists and append to summary
|
|
2329
|
-
const { readFiles, modifiedFiles } = computeFileLists(fileOps);
|
|
2330
|
-
summary = upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
2342
|
+
const { readFiles, modifiedFiles } = snapcompact.computeFileLists(fileOps);
|
|
2343
|
+
summary = snapcompact.upsertFileOperations(summary, readFiles, modifiedFiles, fileOps.read);
|
|
2331
2344
|
if (nativeSummary !== undefined) {
|
|
2332
2345
|
// The replayed block (summary and any `tool_changes`) stays
|
|
2333
2346
|
// byte-identical to the API's output so it matches its signature. The
|
|
@@ -2335,7 +2348,7 @@ export async function compact(
|
|
|
2335
2348
|
// summary message with the block and skips its text, so they would
|
|
2336
2349
|
// otherwise be invisible to this provider. Every other provider keeps
|
|
2337
2350
|
// reading the entry text.
|
|
2338
|
-
const filesText = upsertFileOperations("", readFiles, modifiedFiles, fileOps.read) || undefined;
|
|
2351
|
+
const filesText = snapcompact.upsertFileOperations("", readFiles, modifiedFiles, fileOps.read) || undefined;
|
|
2339
2352
|
preserveData = withAnthropicCompactionPreserveData(preserveData, {
|
|
2340
2353
|
provider: model.provider,
|
|
2341
2354
|
content: nativeSummary,
|
|
@@ -2427,6 +2440,9 @@ async function generateTurnPrefixSummary(
|
|
|
2427
2440
|
if (response.stopReason === "error") {
|
|
2428
2441
|
throw createSummarizationError("Turn prefix summarization failed", response);
|
|
2429
2442
|
}
|
|
2443
|
+
if (response.stopReason === "length") {
|
|
2444
|
+
throw new Error(incompleteOutputError("Turn prefix summarization failed"));
|
|
2445
|
+
}
|
|
2430
2446
|
|
|
2431
2447
|
return response.content
|
|
2432
2448
|
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
package/src/compaction/openai.ts
CHANGED
|
@@ -19,7 +19,6 @@ import { attach, create, Flag, ProviderHttpError } from "@linxiraos/pi-ai/error"
|
|
|
19
19
|
import { getCodexAttestationHeader } from "@linxiraos/pi-ai/providers/openai-codex-attestation";
|
|
20
20
|
import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
|
|
21
21
|
import { applyCodexResponsesLiteShape } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
|
|
22
|
-
import { createOpenAICodexCompatibilityMetadata } from "@linxiraos/pi-ai/providers/openai-codex-responses";
|
|
23
22
|
import {
|
|
24
23
|
applyInferenceHeaders,
|
|
25
24
|
applySessionHeader,
|
|
@@ -46,6 +45,7 @@ import {
|
|
|
46
45
|
getOpenAIResponsesHistoryItems,
|
|
47
46
|
getOpenAIResponsesHistoryPayload,
|
|
48
47
|
normalizeResponsesToolCallId,
|
|
48
|
+
stripOpenAIResponsesInternalMetadataForReplay,
|
|
49
49
|
stripOpenAIResponsesOutputOnlyStatusesForReplay,
|
|
50
50
|
truncateResponseItemId,
|
|
51
51
|
} from "@linxiraos/pi-ai/utils";
|
|
@@ -847,6 +847,9 @@ export function buildOpenAiNativeHistory(
|
|
|
847
847
|
msgIndex++;
|
|
848
848
|
}
|
|
849
849
|
|
|
850
|
+
for (let index = 0; index < input.length; index++) {
|
|
851
|
+
input[index] = stripOpenAIResponsesInternalMetadataForReplay(input[index]!);
|
|
852
|
+
}
|
|
850
853
|
return stripOpenAIResponsesOutputOnlyStatusesForReplay(hoistInterleavedResponsesToolBatchMessages(input));
|
|
851
854
|
}
|
|
852
855
|
|
|
@@ -950,6 +953,9 @@ export async function requestOpenAiRemoteCompaction(
|
|
|
950
953
|
|
|
951
954
|
// Codex endpoints require additional auth headers
|
|
952
955
|
if (isCodexResponses) {
|
|
956
|
+
// Keep transport loading on the actual Codex request path, not compaction policy inspection.
|
|
957
|
+
const { createOpenAICodexCompatibilityMetadata } =
|
|
958
|
+
await import("@linxiraos/pi-ai/providers/openai-codex-responses");
|
|
953
959
|
const accountId = getCodexAccountId(apiKey);
|
|
954
960
|
if (accountId) {
|
|
955
961
|
headers[OPENAI_HEADERS.ACCOUNT_ID] = accountId;
|
|
@@ -2,7 +2,6 @@ The conversation above is the complete history to summarize. The API replaces ev
|
|
|
2
2
|
|
|
3
3
|
{{#if extraContext}}
|
|
4
4
|
{{extraContext}}
|
|
5
|
-
|
|
6
5
|
{{/if}}
|
|
7
6
|
{{basePrompt}}
|
|
8
7
|
{{#if customInstructions}}
|
|
@@ -10,4 +9,4 @@ The conversation above is the complete history to summarize. The API replaces ev
|
|
|
10
9
|
Additional focus: {{customInstructions}}
|
|
11
10
|
{{/if}}
|
|
12
11
|
|
|
13
|
-
You MUST NOT call any tools while writing the summary; respond with the summary text only.
|
|
12
|
+
You MUST NOT call any tools while writing the summary; respond with the summary text only.
|