pi-openai-toolkit 0.23.2 → 0.24.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +83 -83
  3. package/README.md +4 -15
  4. package/README.zh.md +4 -15
  5. package/config.schema.json +264 -278
  6. package/docs/configuration.md +304 -306
  7. package/docs/internals.md +34 -120
  8. package/package.json +123 -136
  9. package/src/compact-client.ts +412 -412
  10. package/src/compaction-projection.ts +35 -35
  11. package/src/config/legacy.ts +469 -519
  12. package/src/config/migration.ts +115 -103
  13. package/src/config/notifications.ts +46 -36
  14. package/src/config/policy.ts +115 -116
  15. package/src/config/v2.ts +1128 -1167
  16. package/src/config.ts +320 -310
  17. package/src/debug.ts +238 -238
  18. package/src/deferred-tool-carryover.ts +282 -282
  19. package/src/details-store.ts +151 -151
  20. package/src/extension-runtime.ts +1095 -1919
  21. package/src/image-generation/extension.ts +189 -189
  22. package/src/image-generation/protocol.ts +579 -579
  23. package/src/image-generation/types.ts +300 -300
  24. package/src/native-fallback.ts +140 -152
  25. package/src/payload-rewrite.ts +515 -515
  26. package/src/pi-context-hook.ts +117 -117
  27. package/src/remote-v2-client.ts +811 -811
  28. package/src/request-context-cache.ts +155 -155
  29. package/src/responses-headers.ts +180 -180
  30. package/src/retired-remote-windows.ts +35 -0
  31. package/src/runtime.ts +875 -865
  32. package/src/serializer.ts +882 -882
  33. package/src/supported-environment.ts +27 -27
  34. package/src/types.ts +541 -565
  35. package/src/web-search/alpha-client.ts +876 -876
  36. package/src/web-search/extension.ts +530 -530
  37. package/src/web-search/payload.ts +299 -299
  38. package/src/web-search/prompt.ts +60 -60
  39. package/src/web-search/types.ts +166 -166
  40. package/tsconfig.check.json +50 -50
  41. package/src/context-management/codex-provider.ts +0 -270
  42. package/src/context-management/history-notes.ts +0 -357
  43. package/src/context-management/manual-compact.ts +0 -247
  44. package/src/context-management/messages.ts +0 -238
  45. package/src/context-management/namespace-tools.ts +0 -426
  46. package/src/context-management/responses-tools.ts +0 -238
  47. package/src/context-management/scoped-compaction.ts +0 -89
  48. package/src/context-management/tool-contract.ts +0 -62
  49. package/src/context-management/tools.ts +0 -371
  50. package/src/context-management/types.ts +0 -168
  51. package/src/context-management/window-budget.ts +0 -83
  52. package/src/context-management/window-bulk.ts +0 -155
  53. package/src/context-management/window-manager.ts +0 -912
  54. package/src/context-management/window-request.ts +0 -125
@@ -1,83 +0,0 @@
1
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import {
3
- CONTEXT_WINDOW_FALLBACK_BUFFER,
4
- CONTEXT_WINDOW_FALLBACK_MESSAGE,
5
- renderContextWindowReminder,
6
- type ContextManagementMessageKind,
7
- type ContextWindowIdentity,
8
- } from "./messages";
9
-
10
- export interface ContextRemaining {
11
- remainingTokens: number | undefined;
12
- windowId: string | undefined;
13
- contextWindow: number;
14
- }
15
-
16
- export class ContextWindowBudget {
17
- private readonly remindedWindows = new Set<string>();
18
- private readonly exhaustedWindows = new Set<string>();
19
-
20
- reset(): void {
21
- this.remindedWindows.clear();
22
- this.exhaustedWindows.clear();
23
- }
24
-
25
- restore(kind: ContextManagementMessageKind, windowId: string): void {
26
- if (kind === "reminder") this.remindedWindows.add(windowId);
27
- if (kind === "fallback") this.exhaustedWindows.add(windowId);
28
- }
29
-
30
- record(
31
- ctx: ExtensionContext,
32
- identity: ContextWindowIdentity,
33
- contextTokens: number | undefined,
34
- contextReminderThresholdPercent: number,
35
- ): { content: string; kind: "fallback" | "reminder" } | undefined {
36
- const remaining = this.remaining(ctx, identity, contextTokens);
37
- if (remaining.remainingTokens === undefined) return undefined;
38
- const windowId = identity.currentWindowId;
39
- if (remaining.remainingTokens <= 0 && !this.exhaustedWindows.has(windowId)) {
40
- this.exhaustedWindows.add(windowId);
41
- return { content: CONTEXT_WINDOW_FALLBACK_MESSAGE, kind: "fallback" };
42
- }
43
- const reminderThreshold =
44
- contextReminderThresholdPercent > 0
45
- ? Math.floor((remaining.contextWindow * contextReminderThresholdPercent) / 100)
46
- : 0;
47
- if (
48
- contextReminderThresholdPercent > 0 &&
49
- remaining.remainingTokens <= reminderThreshold &&
50
- !this.remindedWindows.has(windowId)
51
- ) {
52
- this.remindedWindows.add(windowId);
53
- return { content: renderContextWindowReminder(remaining.remainingTokens), kind: "reminder" };
54
- }
55
- return undefined;
56
- }
57
-
58
- remaining(
59
- ctx: ExtensionContext,
60
- identity: ContextWindowIdentity | undefined,
61
- contextTokens?: number,
62
- ): ContextRemaining {
63
- const usage = ctx.getContextUsage();
64
- const contextWindow = usage?.contextWindow ?? ctx.model?.contextWindow ?? 0;
65
- const limit = Math.max(0, contextWindow - CONTEXT_WINDOW_FALLBACK_BUFFER);
66
- if (usage === undefined && contextTokens === undefined) {
67
- return {
68
- remainingTokens: undefined,
69
- windowId: identity?.currentWindowId,
70
- contextWindow: limit,
71
- };
72
- }
73
- const used = contextTokens ?? usage?.tokens;
74
- return {
75
- remainingTokens:
76
- used === null || used === undefined
77
- ? undefined
78
- : Math.max(0, limit - used),
79
- windowId: identity?.currentWindowId,
80
- contextWindow: limit,
81
- };
82
- }
83
- }
@@ -1,155 +0,0 @@
1
- import {
2
- buildSessionContext,
3
- estimateTokens,
4
- type ExtensionContext,
5
- type SessionEntry,
6
- } from "@earendil-works/pi-coding-agent";
7
- import type { AgentMessage } from "@earendil-works/pi-agent-core";
8
- import type { LeaveManagedModePolicy } from "../types";
9
- import { isContextWindowBoundary } from "./messages";
10
-
11
- /**
12
- * Legacy pure diagnostics retained for config/test compatibility. Runtime model switching no
13
- * longer calls this module: non-window consumers use the current-local projection instead of
14
- * measuring or compacting the durable Remote Context branch.
15
- */
16
-
17
- /**
18
- * Share of the target model's context window above which a projection is considered
19
- * over budget. Estimates are conservative (`estimateTokens` is chars/4 and overestimates),
20
- * so the trigger fires slightly early rather than after a hard provider failure.
21
- */
22
- export const BULK_CLIFF_RATIO = 0.8;
23
-
24
- /** How much larger the durable view must be than the windowed view to call it a cliff. */
25
- export const BULK_EXPANSION_RATIO = 2;
26
-
27
- export type WindowBulkReport = {
28
- /** The window the durable view is measured against; a notice is surfaced once per window and model. */
29
- readonly windowId: string | undefined;
30
- /** Tokens an uncovered model would receive: the whole branch, markers filtered. */
31
- readonly unmanagedTokens: number;
32
- /** Tokens a covered model receives: the current window only. */
33
- readonly managedTokens: number;
34
- readonly targetContextWindow: number;
35
- /** The durable view exceeds `BULK_CLIFF_RATIO` of the model that would receive it. */
36
- readonly overBudget: boolean;
37
- /** The durable view is at least `BULK_EXPANSION_RATIO` times the windowed view. */
38
- readonly expanded: boolean;
39
- };
40
-
41
- /** What the runtime should do about a measured cliff. */
42
- export type BulkCliffAction = "ignore" | "warn" | "compact";
43
-
44
- /**
45
- * `warn` is the default because an automatic compaction costs a real model call. `compact`
46
- * only acts when the durable transcript is also past the target window: a session that is
47
- * merely bigger than its windowed view still fits, and compacting it would be pure loss.
48
- */
49
- export function decideBulkCliffAction(
50
- report: WindowBulkReport,
51
- policy: LeaveManagedModePolicy,
52
- ): BulkCliffAction {
53
- if (!report.expanded) return "ignore";
54
- if (policy === "compact" && report.overBudget) return "compact";
55
- return "warn";
56
- }
57
-
58
- export type BulkCloseOutContext = {
59
- /** What the policy decided for this report. */
60
- action: BulkCliffAction;
61
- /** Pi's run mode: print sessions exit with the turn, so they cannot await a compaction. */
62
- mode: string;
63
- /** When the measurement happened. */
64
- trigger: "model-switch" | "turn-end";
65
- /** Whether a rollover trim is queued for the next eligible compaction. */
66
- hasPendingTrim: boolean;
67
- };
68
-
69
- /**
70
- * Turn a decided action into one that is safe to execute here.
71
- *
72
- * `ExtensionContext.compact()` is fire-and-forget and aborts the running turn. In print mode
73
- * the process exits with the turn, so the summary would be killed mid-request; a turn-end
74
- * close-out on a covered model is also pointless unless a rollover trim is queued, because
75
- * the window policy cancels any other compaction. Both cases degrade to the warning.
76
- */
77
- export function decideBulkCloseOut(context: BulkCloseOutContext): BulkCliffAction {
78
- if (context.action !== "compact") return context.action;
79
- if (context.mode === "print") return "warn";
80
- if (context.trigger === "turn-end" && !context.hasPendingTrim) return "warn";
81
- return "compact";
82
- }
83
-
84
- function sumTokens(messages: readonly AgentMessage[]): number {
85
- let tokens = 0;
86
- for (const message of messages) tokens += estimateTokens(message as never);
87
- return tokens;
88
- }
89
-
90
- /**
91
- * Measure the gap between the durable transcript and the remote window view.
92
- *
93
- * Remote context management retires previous windows *in the request projection*; the
94
- * session branch keeps them, and a boundary compaction only lands when a compaction
95
- * attempt consumes the scheduled trim. That asymmetry is invisible while a covered model
96
- * runs and becomes a cliff the moment the session talks to a model without remote context:
97
- * a window that streamed 25k tokens per request can hand over 400k tokens of history that
98
- * no model has ever been shown, blowing past the new window and making the first manual
99
- * `/compact` summarize the whole pile.
100
- *
101
- * Returns `undefined` when nothing has been retired yet, so young sessions and plain
102
- * Pi transcripts never see a report.
103
- */
104
- export function measureWindowBulk(args: {
105
- readonly messages: readonly AgentMessage[];
106
- contextWindow: number | undefined;
107
- }): WindowBulkReport | undefined {
108
- const { messages, contextWindow } = args;
109
- let boundaryIndex = -1;
110
- for (let index = 0; index < messages.length; index += 1) {
111
- if (isContextWindowBoundary(messages[index]!)) boundaryIndex = index;
112
- }
113
- if (boundaryIndex < 1) return undefined;
114
-
115
- const boundaryMessage = messages[boundaryIndex]!;
116
- const windowId = isContextWindowBoundary(boundaryMessage)
117
- ? boundaryMessage.details.contextManagement.currentWindowId
118
- : undefined;
119
- const window = messages.slice(boundaryIndex);
120
- const managedTokens = sumTokens(window);
121
- const unmanagedTokens = managedTokens + sumTokens(
122
- messages
123
- .slice(0, boundaryIndex)
124
- .filter((message) => !isContextWindowBoundary(message)),
125
- );
126
- const targetContextWindow = typeof contextWindow === "number" && contextWindow > 0 ? contextWindow : 0;
127
- return {
128
- windowId,
129
- unmanagedTokens,
130
- managedTokens,
131
- targetContextWindow,
132
- overBudget: targetContextWindow > 0 && unmanagedTokens > targetContextWindow * BULK_CLIFF_RATIO,
133
- expanded: unmanagedTokens > managedTokens * BULK_EXPANSION_RATIO,
134
- };
135
- }
136
-
137
- /**
138
- * The provider-visible message list for the current branch: Pi's compaction-anchored
139
- * context, exactly as an uncovered model would receive it before the toolkit trims.
140
- */
141
- export function durableContextMessages(entries: readonly SessionEntry[]): AgentMessage[] {
142
- return buildSessionContext(entries as never[]).messages as unknown as AgentMessage[];
143
- }
144
-
145
- /**
146
- * Measure the current branch for a bulk cliff. Returns `undefined` when the session has
147
- * no window state, cannot report a target window, or has retired nothing.
148
- */
149
- export function evaluateWindowBulk(ctx: Pick<ExtensionContext, "sessionManager" | "model">): WindowBulkReport | undefined {
150
- const contextWindow = ctx.model?.contextWindow;
151
- if (typeof contextWindow !== "number" || contextWindow <= 0) return undefined;
152
- const messages = durableContextMessages(ctx.sessionManager.getBranch() as never[]);
153
- if (!messages.some(isContextWindowBoundary)) return undefined;
154
- return measureWindowBulk({ messages, contextWindow });
155
- }