@jetcrab/pi-desk-ctx 0.0.0-stage → 1.0.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/LICENSE +201 -0
- package/README.md +4 -2
- package/dist/auto-compaction.d.ts +21 -0
- package/dist/auto-compaction.js +31 -0
- package/dist/auto-ignore.d.ts +9 -0
- package/dist/auto-ignore.js +7 -0
- package/dist/browser/chunks/browser-DJVEFCDQ.js +72 -0
- package/dist/browser/entry.js +1 -0
- package/dist/context-analysis.d.ts +21 -0
- package/dist/context-analysis.js +194 -0
- package/dist/context-compaction.d.ts +5 -0
- package/dist/context-compaction.js +14 -0
- package/dist/context-history-tool.d.ts +12 -0
- package/dist/context-history-tool.js +90 -0
- package/dist/context-settings-store.d.ts +4 -0
- package/dist/context-settings-store.js +51 -0
- package/dist/context-settings.d.ts +23 -0
- package/dist/context-settings.js +146 -0
- package/dist/context-skill-path.d.ts +17 -0
- package/dist/context-skill-path.js +64 -0
- package/dist/context-state.d.ts +5 -0
- package/dist/context-state.js +104 -0
- package/dist/context-token-estimate.d.ts +9 -0
- package/dist/context-token-estimate.js +14 -0
- package/dist/context-transform.d.ts +24 -0
- package/dist/context-transform.js +198 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +503 -0
- package/dist/l2-context-settings-biz.d.ts +54 -0
- package/dist/l2-context-settings-biz.js +314 -0
- package/dist/l2-context-settings-view.d.ts +6 -0
- package/dist/l2-context-settings-view.js +128 -0
- package/dist/pi-desk.d.ts +2 -0
- package/dist/pi-desk.js +32 -0
- package/dist/types.d.ts +42 -0
- package/dist/types.js +2 -0
- package/package.json +56 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Pi Desk — pi-desk-ctx
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
包名:`@jetcrab/pi-desk-ctx`。插件接口以源码导出为准,个人配置不随包分发。
|
|
4
|
+
|
|
5
|
+
许可与第三方来源见本目录的 LICENSE 及适用的归属说明。
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { CompactionResult } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { AutoIgnoreDecision } from './auto-ignore.js';
|
|
3
|
+
export declare const CONTEXT_IGNORE_RETRY_SUMMARY = "\u5DF2\u901A\u8FC7\u4E0A\u4E0B\u6587\u5FFD\u7565\u964D\u4F4E\u65E7\u8FC7\u7A0B\u4FE1\u606F\uFF1B\u672C\u68C0\u67E5\u70B9\u672A\u751F\u6210\u4F1A\u8BDD\u6458\u8981\u3002";
|
|
4
|
+
export interface ContextIgnoreRetryDetails {
|
|
5
|
+
contextIgnoreRetry: true;
|
|
6
|
+
ignoredTokens: number;
|
|
7
|
+
reasoningReplayTokens: number;
|
|
8
|
+
providerIgnoredTokens: number;
|
|
9
|
+
}
|
|
10
|
+
export type AutoCompactionReason = 'manual' | 'threshold' | 'overflow';
|
|
11
|
+
export type AutoCompactionIgnoreAction = {
|
|
12
|
+
type: 'none';
|
|
13
|
+
} | {
|
|
14
|
+
type: 'compact';
|
|
15
|
+
} | {
|
|
16
|
+
type: 'cancel';
|
|
17
|
+
} | {
|
|
18
|
+
type: 'retry';
|
|
19
|
+
compaction: CompactionResult<ContextIgnoreRetryDetails>;
|
|
20
|
+
};
|
|
21
|
+
export declare function resolveAutoCompactionIgnoreAction(reason: AutoCompactionReason, willRetry: boolean, decision: AutoIgnoreDecision, firstActiveEntryId: string | undefined, contextTokens: number, contextWindow: number, reserveTokens: number): AutoCompactionIgnoreAction;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const CONTEXT_IGNORE_RETRY_SUMMARY = '已通过上下文忽略降低旧过程信息;本检查点未生成会话摘要。';
|
|
2
|
+
export function resolveAutoCompactionIgnoreAction(reason, willRetry, decision, firstActiveEntryId, contextTokens, contextWindow, reserveTokens) {
|
|
3
|
+
if (reason === 'manual' || !decision.shouldIgnore || decision.cutoffTimestamp === undefined) {
|
|
4
|
+
return { type: 'none' };
|
|
5
|
+
}
|
|
6
|
+
const projectedContextTokens = Math.max(0, contextTokens - decision.potential.providerNetTokens);
|
|
7
|
+
const compactionThreshold = Math.max(0, contextWindow - reserveTokens);
|
|
8
|
+
if (contextWindow <= 0 || projectedContextTokens > compactionThreshold) {
|
|
9
|
+
return { type: 'compact' };
|
|
10
|
+
}
|
|
11
|
+
if (reason === 'threshold' || !willRetry) {
|
|
12
|
+
return { type: 'cancel' };
|
|
13
|
+
}
|
|
14
|
+
if (firstActiveEntryId === undefined) {
|
|
15
|
+
return { type: 'compact' };
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
type: 'retry',
|
|
19
|
+
compaction: {
|
|
20
|
+
summary: CONTEXT_IGNORE_RETRY_SUMMARY,
|
|
21
|
+
firstKeptEntryId: firstActiveEntryId,
|
|
22
|
+
tokensBefore: Math.max(0, contextTokens),
|
|
23
|
+
details: {
|
|
24
|
+
contextIgnoreRetry: true,
|
|
25
|
+
ignoredTokens: decision.potential.netTokens,
|
|
26
|
+
reasoningReplayTokens: decision.potential.reasoningReplayTokens,
|
|
27
|
+
providerIgnoredTokens: decision.potential.providerNetTokens
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { ContextIgnorePotential, ContextIgnoreState } from './types.js';
|
|
2
|
+
export interface AutoIgnoreDecision {
|
|
3
|
+
shouldIgnore: boolean;
|
|
4
|
+
cutoffTimestamp?: number;
|
|
5
|
+
nextState?: ContextIgnoreState;
|
|
6
|
+
potential: ContextIgnorePotential;
|
|
7
|
+
matchedRuleIndex?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare function emptyContextIgnorePotential(): ContextIgnorePotential;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import{createRoot as $e}from"react-dom/client";import{PluginErrorBoundary as Be}from"@jetcrab/pi-desk-sdk/react/base";import{Fragment as be,useId as re,useRef as ve}from"react";import{PluginActionRow as j,PluginAlert as he,PluginButton as T,PluginCheckbox as D,PluginConfirmDialog as ye,PluginInput as Te,PluginLoadingState as Ce,PluginPanelHeader as Pe,PluginScroll as we,PluginSection as ne,PluginSurface as Se,PluginTab as Ee,PluginTabList as Re}from"@jetcrab/pi-desk-sdk/react/base";import{useCallback as q,useEffect as L,useMemo as V,useRef as Y,useState as x}from"react";var pe={enabled:!0,profiles:[{maxContextTokens:4e5,checkpointTokens:32e4,keepRecentUserTurns:3,processTokenBudget:3e4,rules:[{currentTokensAtLeast:28e4,projectedTokensAtMost:5e4}]},{maxContextTokens:6e5,checkpointTokens:48e4,keepRecentUserTurns:3,processTokenBudget:4e4,rules:[{currentTokensAtLeast:4e5,projectedTokensAtMost:5e4},{currentTokensAtLeast:5e5,projectedTokensAtMost:1e5}]},{checkpointTokens:8e5,keepRecentUserTurns:3,processTokenBudget:4e4,rules:[{currentTokensAtLeast:8e5,projectedTokensAtMost:15e4}]}]},H=20,J=50,X=1e8,me=100;function B(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $(e,r,n,t){if(!Number.isInteger(e)||e<n||e>t)throw new Error(`${r} \u5FC5\u987B\u662F ${n} \u5230 ${t} \u7684\u6574\u6570`);return e}function R(e,r){if(e!=null)return $(e,r,0,X)}function fe(e,r){if(!B(e))throw new Error(`${r} \u5FC5\u987B\u662F\u5BF9\u8C61`);let n=R(e.currentTokensAtLeast,`${r}.currentTokensAtLeast`),t=R(e.projectedTokensAtMost,`${r}.projectedTokensAtMost`);if(n===void 0&&t===void 0)throw new Error(`${r} \u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u5224\u65AD\u6761\u4EF6`);return{...n===void 0?{}:{currentTokensAtLeast:n},...t===void 0?{}:{projectedTokensAtMost:t}}}function ge(e,r){let n=`profiles.${r}`;if(!B(e))throw new Error(`${n} \u5FC5\u987B\u662F\u5BF9\u8C61`);let t=R(e.maxContextTokens,`${n}.maxContextTokens`);if(t!==void 0&&t===0)throw new Error(`${n}.maxContextTokens \u5FC5\u987B\u5927\u4E8E 0`);let s=R(e.checkpointTokens,`${n}.checkpointTokens`);if(s!==void 0&&s===0)throw new Error(`${n}.checkpointTokens \u5FC5\u987B\u5927\u4E8E 0`);let i=$(e.keepRecentUserTurns,`${n}.keepRecentUserTurns`,1,me),o=$(e.processTokenBudget,`${n}.processTokenBudget`,0,X);if(!Array.isArray(e.rules)||e.rules.length>J)throw new Error(`${n}.rules \u5FC5\u987B\u662F\u6700\u591A ${J} \u6761\u89C4\u5219\u7684\u6570\u7EC4`);return{...t===void 0?{}:{maxContextTokens:t},...s===void 0?{}:{checkpointTokens:s},keepRecentUserTurns:i,processTokenBudget:o,rules:e.rules.map((l,m)=>fe(l,`${n}.rules.${m}`))}}function G(e){let r=e.profiles.map(n=>({...n.maxContextTokens===void 0?{}:{maxContextTokens:n.maxContextTokens},...n.checkpointTokens===void 0?{}:{checkpointTokens:n.checkpointTokens},keepRecentUserTurns:n.keepRecentUserTurns,processTokenBudget:n.processTokenBudget,rules:n.rules.map(t=>({...t}))})).sort((n,t)=>n.maxContextTokens===void 0?1:t.maxContextTokens===void 0?-1:n.maxContextTokens-t.maxContextTokens);return{enabled:e.enabled,profiles:r}}function K(e){if(!B(e))throw new Error("\u4E0A\u4E0B\u6587\u5FFD\u7565\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof e.enabled!="boolean")throw new Error("enabled \u5FC5\u987B\u662F\u5E03\u5C14\u503C");if(!Array.isArray(e.profiles)||e.profiles.length===0||e.profiles.length>H)throw new Error(`profiles \u5FC5\u987B\u5305\u542B 1 \u5230 ${H} \u4E2A\u6A21\u578B\u914D\u7F6E`);let r=e.profiles.map(ge);if(r.filter(s=>s.maxContextTokens===void 0).length!==1)throw new Error("\u5FC5\u987B\u4E14\u53EA\u80FD\u6709\u4E00\u4E2A\u4E0D\u9650\u5236\u6A21\u578B\u7A97\u53E3\u7684\u901A\u7528\u914D\u7F6E");let t=r.map(s=>s.maxContextTokens).filter(s=>s!==void 0);if(new Set(t).size!==t.length)throw new Error("\u6A21\u578B\u7A97\u53E3\u4E0A\u9650\u4E0D\u80FD\u91CD\u590D");return G({enabled:e.enabled,profiles:r})}function A(){return G(pe)}var P=class extends Error{constructor(n){super(n.message);this.issue=n}},Q=0;function ee(e){return Q+=1,{key:Q,maxContextK:e.maxContextTokens===void 0?null:String(e.maxContextTokens/1e3),checkpointEnabled:e.checkpointTokens!==void 0,checkpointK:e.checkpointTokens===void 0?"":String(e.checkpointTokens/1e3),keepRecentUserTurns:String(e.keepRecentUserTurns),processBudgetK:String(e.processTokenBudget/1e3),rules:e.rules.map(r=>({currentEnabled:r.currentTokensAtLeast!==void 0,currentK:r.currentTokensAtLeast===void 0?"":String(r.currentTokensAtLeast/1e3),projectedEnabled:r.projectedTokensAtMost!==void 0,projectedK:r.projectedTokensAtMost===void 0?"":String(r.projectedTokensAtMost/1e3)}))}}function _(e){return{enabled:e.enabled,profiles:e.profiles.map(ee)}}function ke(e,r,n,t,s,i,o){let l=Number(e),m=Math.round(l*t);if(e.trim()===""||!Number.isInteger(m)||m/t!==l||m<r||m>n)throw new P({profileKey:s,field:i,message:`${o}\u9700\u4E3A ${r/t}\u2013${n/t}${t===1e3?"k":" \u8F6E"}`});return m}function xe(e){let r=new Set,n=e.profiles.map(t=>{let s=(o,l,m,f=0,k=1e8,g=1e3)=>ke(o,f,k,g,t.key,l,m),i=t.maxContextK===null?void 0:s(t.maxContextK,"maxContextK","\u6A21\u578B\u5BB9\u91CF\u4E0A\u9650",1);if(i!==void 0){if(r.has(i))throw new P({profileKey:t.key,field:"maxContextK",message:"\u8FD9\u4E2A\u6A21\u578B\u5BB9\u91CF\u4E0A\u9650\u5DF2\u5B58\u5728"});r.add(i)}return{...i===void 0?{}:{maxContextTokens:i},...t.checkpointEnabled?{checkpointTokens:s(t.checkpointK,"checkpointK","\u8BB0\u5F55\u8FDB\u5C55\u7528\u91CF",1)}:{},keepRecentUserTurns:s(t.keepRecentUserTurns,"keepRecentUserTurns","\u6700\u8FD1\u5BF9\u8BDD\u8F6E\u6570",1,100,1),processTokenBudget:s(t.processBudgetK,"processBudgetK","\u8FC7\u7A0B\u7528\u91CF\u4E0A\u9650"),rules:t.rules.map((o,l)=>{if(!o.currentEnabled&&!o.projectedEnabled)throw new P({profileKey:t.key,field:`rule-${l}`,message:"\u8BF7\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u6761\u4EF6"});return{...o.currentEnabled?{currentTokensAtLeast:s(o.currentK,`current-${l}`,"\u5F53\u524D\u7528\u91CF")}:{},...o.projectedEnabled?{projectedTokensAtMost:s(o.projectedK,`projected-${l}`,"\u5FFD\u7565\u540E\u9884\u8BA1\u7528\u91CF")}:{}}})}});return K({enabled:e.enabled,profiles:n})}function W(e){return[...e].sort((r,n)=>r.maxContextK===null?1:n.maxContextK===null?-1:r.maxContextK===""?1:n.maxContextK===""?-1:Number(r.maxContextK)-Number(n.maxContextK))}function Z(e){return JSON.stringify({enabled:e.enabled,profiles:e.profiles.map(({key:r,...n})=>n)})}function te(e,r,n){let t=V(()=>_(A()),[]),[s,i]=x(t),[o,l]=x(t),[m,f]=x(t.profiles[1].key),[k,g]=x(!1),[ie,M]=x(!0),[ae,de]=x(!1),[O,U]=x(!1),[le,b]=x(null),[ce,F]=x(!1),C=Y(null),v=Z(o)!==Z(s),z=Y(v),h=o.profiles.find(a=>a.key===m)??o.profiles[0],y=V(()=>{try{return{settings:xe(o),issue:null,error:null}}catch(a){return{settings:null,issue:a instanceof P?a.issue:null,error:a instanceof Error?a.message:String(a)}}},[o]);L(()=>{z.current=v},[v]);let I=q((a,c)=>{let p=_(a);i(p),l(p),de(!0),f(p.profiles.find(N=>N.maxContextK===c)?.key??(p.profiles[1]??p.profiles[0]).key)},[]),S=q(async()=>{if(!z.current){M(!0),b(null);try{let a=K(await r.piDesk.invokeGlobal("settings-get",{}));n.aborted||I(a)}catch(a){n.aborted||b(a instanceof Error?a.message:String(a))}finally{n.aborted||M(!1)}}},[I,r,n]);L(()=>{let a=!0;queueMicrotask(()=>{a&&S()});let c=r.connection.subscribe(()=>{r.connection.getSnapshot().status==="ready"&&S()});return()=>{a=!1,c()}},[r,S]),L(()=>(e.setBeforeLeave(()=>!v||new Promise(a=>{C.current?.(!1),C.current=a,F(!0)})),()=>{e.setBeforeLeave(null),C.current?.(!1),C.current=null}),[v,e]);let E=a=>{l(c=>({...c,profiles:c.profiles.map(p=>p.key===h.key?{...p,...a}:p)}))},ue=()=>{if(O||!v)return;if(!y.settings){y.issue?(f(y.issue.profileKey),["maxContextK","checkpointK"].includes(y.issue.field)&&g(!0)):b(y.error);return}U(!0),b(null);let a=JSON.parse(JSON.stringify(y.settings));r.piDesk.invokeGlobal("settings-save",a).then(c=>{n.aborted||(I(K(c),h.maxContextK),r.notify({level:"success",title:"\u8BBE\u7F6E\u5DF2\u4FDD\u5B58"}))}).catch(c=>{if(n.aborted)return;let p=c instanceof Error?c.message:String(c);b(p),r.notify({level:"error",title:"\u8BBE\u7F6E\u4FDD\u5B58\u5931\u8D25",description:p})}).finally(()=>{n.aborted||U(!1)})};return{draft:o,profile:h,issue:y.issue,error:le,loading:ie,loaded:ae,saving:O,dirty:v,advancedOpen:k,leaveOpen:ce,setEnabled(a){l(c=>({...c,enabled:a}))},selectProfile:f,updateProfile:E,updateRule(a,c){E({rules:h.rules.map((p,N)=>N===a?{...p,...c}:p)})},sortProfiles(){l(a=>({...a,profiles:W(a.profiles)}))},addProfile(){let a=A().profiles[1],c=ee({...a,checkpointTokens:void 0,rules:[]});c.maxContextK="",l(p=>({...p,profiles:W([...p.profiles,c])})),f(c.key),g(!0)},deleteProfile(){let a=o.profiles.filter(c=>c.key!==h.key);l({...o,profiles:a}),f(a[0].key)},addRule(){E({rules:[...h.rules,{currentEnabled:!0,currentK:"",projectedEnabled:!0,projectedK:""}]})},removeRule(a){E({rules:h.rules.filter((c,p)=>p!==a)})},setAdvancedOpen:g,cancel(){l(s),b(null)},restoreRecommended(){let a=_(A());l(a),f(a.profiles[1].key),g(!1),b(null)},save:ue,reload(){S()},finishLeave(a){let c=C.current;C.current=null,F(!1),c?.(a)}}}import{Fragment as Ne,jsx as d,jsxs as u}from"react/jsx-runtime";var Ke=`
|
|
2
|
+
.pi-desk-ctx-settings {
|
|
3
|
+
display: flex;
|
|
4
|
+
width: 100%;
|
|
5
|
+
height: 100%;
|
|
6
|
+
min-height: 0;
|
|
7
|
+
flex-direction: column;
|
|
8
|
+
}
|
|
9
|
+
.pi-desk-ctx-scroll { min-height: 0; flex: 1; }
|
|
10
|
+
.pi-desk-ctx-viewport { padding: 1.5rem; }
|
|
11
|
+
.pi-desk-ctx-form { display: grid; max-width: 40rem; gap: 1.5rem; }
|
|
12
|
+
.pi-desk-ctx-check { display: flex; min-height: 2rem; align-items: center; gap: .5rem; cursor: pointer; }
|
|
13
|
+
.pi-desk-ctx-models { display: grid; gap: .5rem; }
|
|
14
|
+
.pi-desk-ctx-model-heading { display: flex; align-items: baseline; justify-content: space-between; gap: .5rem; }
|
|
15
|
+
.pi-desk-ctx-model-heading strong { font-weight: 600; }
|
|
16
|
+
.pi-desk-ctx-note { color: var(--muted-foreground); font-size: .75rem; }
|
|
17
|
+
.pi-desk-ctx-tab-error { color: var(--destructive); }
|
|
18
|
+
.pi-desk-ctx-rules { display: grid; gap: .5rem; }
|
|
19
|
+
.pi-desk-ctx-rule {
|
|
20
|
+
display: grid;
|
|
21
|
+
min-width: 0;
|
|
22
|
+
grid-template-columns: minmax(0,1fr) auto minmax(0,1fr) auto;
|
|
23
|
+
align-items: start;
|
|
24
|
+
gap: .75rem;
|
|
25
|
+
margin: 0;
|
|
26
|
+
border: 0;
|
|
27
|
+
border-radius: .5rem;
|
|
28
|
+
padding: .75rem;
|
|
29
|
+
background: var(--muted);
|
|
30
|
+
}
|
|
31
|
+
.pi-desk-ctx-field { display: grid; min-width: 0; align-content: start; gap: .25rem; }
|
|
32
|
+
.pi-desk-ctx-label { display: flex; min-height: 2rem; align-items: center; font-weight: 500; }
|
|
33
|
+
.pi-desk-ctx-amount { display: grid; min-width: 0; grid-template-columns: 1rem minmax(0,1fr) 1.25rem; align-items: center; gap: .25rem; }
|
|
34
|
+
.pi-desk-ctx-operator { text-align: center; }
|
|
35
|
+
.pi-desk-ctx-unit { color: var(--muted-foreground); font-size: .75rem; }
|
|
36
|
+
.pi-desk-ctx-and { display: grid; height: 2rem; align-items: center; margin-top: 2.25rem; color: var(--muted-foreground); }
|
|
37
|
+
.pi-desk-ctx-remove { margin-top: 2.25rem; }
|
|
38
|
+
.pi-desk-ctx-or { display: flex; align-items: center; gap: .75rem; color: var(--muted-foreground); font-size: .75rem; }
|
|
39
|
+
.pi-desk-ctx-or::before,.pi-desk-ctx-or::after { content: ''; height: 1px; flex: 1; background: var(--border); }
|
|
40
|
+
.pi-desk-ctx-error { color: var(--destructive); font-size: .875rem; }
|
|
41
|
+
.pi-desk-ctx-rule > .pi-desk-ctx-error { grid-column: 1/-1; }
|
|
42
|
+
.pi-desk-ctx-retain { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: .75rem; }
|
|
43
|
+
.pi-desk-ctx-empty { color: var(--muted-foreground); padding: .75rem 0; }
|
|
44
|
+
.pi-desk-ctx-advanced { border-top: 1px solid var(--border); }
|
|
45
|
+
.pi-desk-ctx-advanced > summary { display: flex; min-height: 2rem; align-items: center; gap: .5rem; border-radius: .375rem; padding: .5rem 0; color: var(--muted-foreground); cursor: pointer; list-style: none; }
|
|
46
|
+
.pi-desk-ctx-advanced > summary::-webkit-details-marker { display: none; }
|
|
47
|
+
.pi-desk-ctx-advanced > summary:hover { color: var(--foreground); }
|
|
48
|
+
.pi-desk-ctx-advanced > summary:focus-visible { outline: 2px solid var(--ring); outline-offset: 2px; }
|
|
49
|
+
.pi-desk-ctx-chevron { width: 1rem; height: 1rem; flex: none; transition: transform 150ms ease-out; }
|
|
50
|
+
.pi-desk-ctx-advanced[open] .pi-desk-ctx-chevron { transform: rotate(90deg); }
|
|
51
|
+
.pi-desk-ctx-advanced-content { display: grid; gap: 1rem; padding-top: .5rem; }
|
|
52
|
+
.pi-desk-ctx-checkpoint { display: grid; max-width: 19rem; gap: .25rem; }
|
|
53
|
+
.pi-desk-ctx-range { display: flex; align-items: start; gap: .75rem; }
|
|
54
|
+
.pi-desk-ctx-range > .pi-desk-ctx-field { flex: 1; max-width: 19rem; }
|
|
55
|
+
.pi-desk-ctx-range-delete { margin-top: 2.25rem; }
|
|
56
|
+
.pi-desk-ctx-footer { flex: none; border-top: 1px solid var(--border); padding: .75rem 1rem; }
|
|
57
|
+
.pi-desk-ctx-footer-end { margin-left: auto; }
|
|
58
|
+
.pi-desk-ctx-unsaved { color: var(--muted-foreground); font-size: .75rem; }
|
|
59
|
+
.pi-desk-ctx-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
|
|
60
|
+
@container (max-width:38rem) {
|
|
61
|
+
.pi-desk-ctx-rule { grid-template-columns: minmax(0,1fr) auto; gap: .25rem .75rem; }
|
|
62
|
+
.pi-desk-ctx-and { grid-column: 1; height: 1.5rem; margin: 0; justify-content: center; }
|
|
63
|
+
.pi-desk-ctx-rule > .pi-desk-ctx-field { grid-column: 1; }
|
|
64
|
+
.pi-desk-ctx-remove { grid-column: 2; grid-row: 1; }
|
|
65
|
+
}
|
|
66
|
+
@container (max-width:32rem) {
|
|
67
|
+
.pi-desk-ctx-viewport { padding: 1rem; }
|
|
68
|
+
.pi-desk-ctx-retain { grid-template-columns: minmax(0,1fr); }
|
|
69
|
+
.pi-desk-ctx-unsaved { display: none; }
|
|
70
|
+
}
|
|
71
|
+
@media (prefers-reduced-motion:reduce) { .pi-desk-ctx-chevron { transition: none; } }
|
|
72
|
+
`;function Ae(e,r){let n=e[r];if(n.maxContextK===null)return"\u5176\u4ED6\u6A21\u578B";if(n.maxContextK==="")return"\u65B0\u8303\u56F4";let t=e[r-1]?.maxContextK;return t?`${t}k\u2013${n.maxContextK}k`:`\u2264 ${n.maxContextK}k`}function w({label:e,value:r,unit:n="k",operator:t="\u2264",enabled:s=!0,disabled:i,error:o,onChange:l,onBlur:m,toggle:f}){let k=re();return u("div",{className:"pi-desk-ctx-field",children:[f?u("label",{className:"pi-desk-ctx-check",children:[d(D,{checked:s,disabled:i,"aria-label":`\u5224\u65AD${e}`,onChange:g=>f(g.target.checked)}),e]}):d("label",{className:"pi-desk-ctx-label",htmlFor:k,children:e}),u("div",{className:"pi-desk-ctx-amount",children:[d("span",{className:"pi-desk-ctx-operator","aria-hidden":"true",children:s?t:""}),d(Te,{id:k,type:s?"number":"text",inputMode:s?n==="\u8F6E"?"numeric":"decimal":void 0,step:n==="\u8F6E"?1:.001,value:s?r:"\u4E0D\u9650",disabled:i||!s,"aria-label":`${e}\uFF08${n}\uFF09`,"aria-invalid":!!o,"aria-describedby":o?`${k}-error`:void 0,onChange:g=>l(g.target.value),onBlur:m}),d("span",{className:"pi-desk-ctx-unit","aria-hidden":"true",children:s?n:""})]}),o?d("span",{className:"pi-desk-ctx-error",id:`${k}-error`,children:o}):null]})}function Ie({settings:e}){let{profile:r,saving:n,issue:t}=e,s=i=>t?.profileKey===r.key&&t.field===i?t.message:void 0;return u(Ne,{children:[d(ne,{title:"\u4F55\u65F6\u5FFD\u7565",action:d(T,{variant:"ghost",disabled:n||r.rules.length>=50,onClick:e.addRule,children:"+ \u6DFB\u52A0\u89C4\u5219"}),children:d("div",{className:"pi-desk-ctx-rules",children:r.rules.length===0?d("div",{className:"pi-desk-ctx-empty",children:"\u5C1A\u672A\u8BBE\u7F6E\u81EA\u52A8\u5FFD\u7565\u6761\u4EF6"}):r.rules.map((i,o)=>u(be,{children:[o>0?d("div",{className:"pi-desk-ctx-or",children:"\u6216"}):null,u("fieldset",{className:"pi-desk-ctx-rule",children:[u("legend",{className:"pi-desk-ctx-hidden",children:["\u5FFD\u7565\u6761\u4EF6 ",o+1]}),d(w,{label:"\u5F53\u524D\u7528\u91CF",operator:"\u2265",value:i.currentK,enabled:i.currentEnabled,disabled:n,error:s(`current-${o}`),onChange:l=>e.updateRule(o,{currentK:l}),toggle:l=>e.updateRule(o,{currentEnabled:l})}),d("span",{className:"pi-desk-ctx-and",children:"\u4E14"}),d(w,{label:"\u5FFD\u7565\u540E\u9884\u8BA1",value:i.projectedK,enabled:i.projectedEnabled,disabled:n,error:s(`projected-${o}`),onChange:l=>e.updateRule(o,{projectedK:l}),toggle:l=>e.updateRule(o,{projectedEnabled:l})}),d(T,{variant:"ghost",className:"pi-desk-ctx-remove","aria-label":`\u79FB\u9664\u89C4\u5219 ${o+1}`,disabled:n,onClick:()=>e.removeRule(o),children:"\u79FB\u9664"}),s(`rule-${o}`)?d("span",{className:"pi-desk-ctx-error",role:"alert",children:s(`rule-${o}`)}):null]})]},o))})}),d(ne,{title:"\u4FDD\u7559\u6700\u8FD1\u7684\u8FC7\u7A0B",description:"\u5BF9\u8BDD\u4E0E\u7ED3\u8BBA\u59CB\u7EC8\u4FDD\u7559",children:u("div",{className:"pi-desk-ctx-retain",children:[d(w,{label:"\u6700\u8FD1\u5BF9\u8BDD\u8F6E\u6570",unit:"\u8F6E",value:r.keepRecentUserTurns,disabled:n,error:s("keepRecentUserTurns"),onChange:i=>e.updateProfile({keepRecentUserTurns:i})}),d(w,{label:"\u8FC7\u7A0B\u7528\u91CF\u4E0A\u9650",value:r.processBudgetK,disabled:n,error:s("processBudgetK"),onChange:i=>e.updateProfile({processBudgetK:i})})]})}),u("details",{className:"pi-desk-ctx-advanced",open:e.advancedOpen,onToggle:i=>e.setAdvancedOpen(i.currentTarget.open),children:[u("summary",{children:[d("svg",{className:"pi-desk-ctx-chevron",viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:d("path",{d:"m9 6 6 6-6 6",stroke:"currentColor",strokeWidth:"2"})}),"\u9AD8\u7EA7\u8BBE\u7F6E"]}),u("div",{className:"pi-desk-ctx-advanced-content",children:[u("div",{className:"pi-desk-ctx-checkpoint",children:[u("label",{className:"pi-desk-ctx-check",children:[d(D,{checked:r.checkpointEnabled,disabled:n,onChange:i=>e.updateProfile({checkpointEnabled:i.target.checked})}),"\u4EFB\u52A1\u4E2D\u8BB0\u5F55\u8FDB\u5C55"]}),r.checkpointEnabled?d(w,{label:"\u8FBE\u5230\u7528\u91CF",operator:"\u2265",value:r.checkpointK,disabled:n,error:s("checkpointK"),onChange:i=>e.updateProfile({checkpointK:i})}):null]}),r.maxContextK!==null?u("div",{className:"pi-desk-ctx-range",children:[d(w,{label:"\u6A21\u578B\u5BB9\u91CF\u4E0A\u9650",value:r.maxContextK,disabled:n,error:s("maxContextK"),onChange:i=>e.updateProfile({maxContextK:i}),onBlur:e.sortProfiles}),d(T,{variant:"ghost",className:"pi-desk-ctx-range-delete",disabled:n,onClick:e.deleteProfile,children:"\u5220\u9664\u914D\u7F6E"})]}):null,d(j,{children:d(T,{variant:"ghost",disabled:n||e.draft.profiles.length>=20,onClick:e.addProfile,children:"+ \u6DFB\u52A0\u6A21\u578B\u8303\u56F4"})})]})]})]})}function oe({target:e,host:r,signal:n}){let t=te(e,r,n),s=ve(null),i=re();return u(Se,{className:"pi-desk-ctx-settings","data-pi-desk-ctx-settings":"",children:[d("style",{children:Ke}),d(Pe,{title:"\u4E0A\u4E0B\u6587\u5FFD\u7565",actions:u("label",{className:"pi-desk-ctx-check",children:[d(D,{checked:t.draft.enabled,disabled:t.loading||t.saving,onChange:o=>t.setEnabled(o.target.checked)}),"\u81EA\u52A8\u5FFD\u7565"]})}),d(we,{className:"pi-desk-ctx-scroll",viewportClassName:"pi-desk-ctx-viewport","aria-label":"\u4E0A\u4E0B\u6587\u5FFD\u7565\u8BBE\u7F6E",children:d(Ce,{loading:t.loading,error:t.loaded?null:t.error,onRetry:t.reload,children:u("form",{ref:s,className:"pi-desk-ctx-form",id:`${i}-form`,noValidate:!0,onSubmit:o=>{o.preventDefault(),t.save(),t.issue&&requestAnimationFrame(()=>{s.current?.querySelector('[aria-invalid="true"]')?.focus()})},children:[t.error?d(he,{tone:"error",density:"compact",children:t.error}):null,u("div",{className:"pi-desk-ctx-models",children:[u("div",{className:"pi-desk-ctx-model-heading",children:[d("strong",{children:"\u6A21\u578B\u4E0A\u4E0B\u6587\u5BB9\u91CF"}),d("span",{className:"pi-desk-ctx-note",children:"1k = 1,000 tokens"})]}),d(Re,{label:"\u6A21\u578B\u4E0A\u4E0B\u6587\u5BB9\u91CF",children:t.draft.profiles.map((o,l)=>u(Ee,{id:`${i}-${o.key}`,active:t.profile.key===o.key,"aria-controls":`${i}-fields`,disabled:t.saving,tabIndex:t.profile.key===o.key?0:-1,onKeyDown:m=>{let f=t.draft.profiles.length-1,k=m.key==="ArrowRight"?(l+1)%(f+1):m.key==="ArrowLeft"?(l+f)%(f+1):m.key==="Home"?0:m.key==="End"?f:null;if(k===null)return;m.preventDefault();let g=t.draft.profiles[k];t.selectProfile(g.key),document.getElementById(`${i}-${g.key}`)?.focus()},onClick:()=>t.selectProfile(o.key),children:[Ae(t.draft.profiles,l),t.issue?.profileKey===o.key?u("span",{className:"pi-desk-ctx-tab-error","aria-label":"\u914D\u7F6E\u5F85\u5B8C\u5584",children:[" ","\xB7 !"]}):null]},o.key))})]}),d("div",{role:"tabpanel",id:`${i}-fields`,"aria-labelledby":`${i}-${t.profile.key}`,className:"pi-desk-ctx-form",children:d(Ie,{settings:t})})]})})}),!t.loading&&t.loaded?u(j,{align:"between",className:"pi-desk-ctx-footer",children:[d(T,{variant:"ghost",disabled:t.saving,onClick:t.restoreRecommended,children:"\u6062\u590D\u63A8\u8350"}),u(j,{className:"pi-desk-ctx-footer-end",children:[t.dirty?d("span",{className:"pi-desk-ctx-unsaved",children:"\u672A\u4FDD\u5B58"}):null,t.dirty?d(T,{disabled:t.saving,onClick:t.cancel,children:"\u53D6\u6D88\u4FEE\u6539"}):null,d(T,{variant:"primary",type:"submit",form:`${i}-form`,disabled:!t.dirty||t.saving,children:t.saving?"\u4FDD\u5B58\u4E2D\u2026":"\u4FDD\u5B58"})]})]}):null,d(ye,{open:t.leaveOpen,title:"\u653E\u5F03\u672A\u4FDD\u5B58\u7684\u66F4\u6539\uFF1F",confirmLabel:"\u653E\u5F03\u66F4\u6539",tone:"danger",onConfirm:()=>t.finishLeave(!0),onOpenChange:o=>{o||t.finishLeave(!1)}})]})}import{jsx as se}from"react/jsx-runtime";var Ge={mount({container:e,target:r,host:n,signal:t}){let s=$e(e);return s.render(se(Be,{onError:i=>n.notify({level:"error",title:"\u4E0A\u4E0B\u6587\u5FFD\u7565\u8BBE\u7F6E\u6E32\u67D3\u5931\u8D25",description:i.message}),children:se(oe,{target:r,host:n,signal:t})})),()=>s.unmount()}};export{Ge as contextIgnoreSettingsPage};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function t(e){if(typeof e!="function")throw new Error("Browser Entry factory must be a function");return e}var o=()=>import("./chunks/browser-DJVEFCDQ.js"),a=t(e=>{e.registerContribution("settings-page","context-ignore",{label:"\u4E0A\u4E0B\u6587\u5FFD\u7565",icon:{type:"builtin",name:"bot"},load:()=>o().then(n=>n.contextIgnoreSettingsPage)})});export{a as default};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { AgentMessage } from '@earendil-works/pi-agent-core';
|
|
2
|
+
import { type ContextIgnoreTransformOptions } from './context-skill-path.js';
|
|
3
|
+
import type { ContextIgnoreAnalysis, ContextIgnorePotential, ContextIgnoreState } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* 用当前请求的真实 Provider 上下文校正本地字符估算。
|
|
6
|
+
* signature 是不透明的编码内容,不能假定固定的字符/token 比例。
|
|
7
|
+
*/
|
|
8
|
+
export declare function calibrateProviderTokens(estimatedTokens: number, estimatedContextTokens: number, actualContextTokens: number | null | undefined): number;
|
|
9
|
+
export declare function analyzeContext(messages: AgentMessage[], state: ContextIgnoreState, options?: ContextIgnoreTransformOptions): ContextIgnoreAnalysis;
|
|
10
|
+
export declare function findCutoffTimestamp(messages: AgentMessage[], keepTurns: number): number | undefined;
|
|
11
|
+
export interface RecentProcessCandidate {
|
|
12
|
+
cutoffTimestamp: number;
|
|
13
|
+
nextState: ContextIgnoreState;
|
|
14
|
+
potential: ContextIgnorePotential;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Keeps compressible process details from at most the latest user turns within one shared budget.
|
|
18
|
+
* User messages, assistant text, and protected Skill reads are retained regardless of this boundary.
|
|
19
|
+
*/
|
|
20
|
+
export declare function selectRecentProcessCandidate(messages: AgentMessage[], currentState: ContextIgnoreState, keepTurns: number, processTokenBudget: number, options?: ContextIgnoreTransformOptions): RecentProcessCandidate | undefined;
|
|
21
|
+
export declare function analyzeIgnorePotential(messages: AgentMessage[], currentState: ContextIgnoreState, keepTurns: number, processTokenBudget: number, options?: ContextIgnoreTransformOptions): ContextIgnorePotential;
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { emptyContextIgnorePotential } from './auto-ignore.js';
|
|
2
|
+
import { estimateTokens } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import { estimateReasoningReplayTokens, estimateThinkingBlockTokens, estimateToolCallTokens } from './context-token-estimate.js';
|
|
4
|
+
import { getIgnoredMessageIndexes, transformContextMessages } from './context-transform.js';
|
|
5
|
+
import { getSkillBaseDirs, isSkillContentRead } from './context-skill-path.js';
|
|
6
|
+
function sumReasoningReplayTokens(messages) {
|
|
7
|
+
let tokens = 0;
|
|
8
|
+
for (const message of messages) {
|
|
9
|
+
if (message.role !== 'assistant')
|
|
10
|
+
continue;
|
|
11
|
+
for (const block of message.content) {
|
|
12
|
+
if (block.type === 'thinking')
|
|
13
|
+
tokens += estimateReasoningReplayTokens(block);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return tokens;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* 用当前请求的真实 Provider 上下文校正本地字符估算。
|
|
20
|
+
* signature 是不透明的编码内容,不能假定固定的字符/token 比例。
|
|
21
|
+
*/
|
|
22
|
+
export function calibrateProviderTokens(estimatedTokens, estimatedContextTokens, actualContextTokens) {
|
|
23
|
+
if (actualContextTokens === null ||
|
|
24
|
+
actualContextTokens === undefined ||
|
|
25
|
+
estimatedTokens <= 0 ||
|
|
26
|
+
estimatedContextTokens <= 0) {
|
|
27
|
+
return Math.max(0, estimatedTokens);
|
|
28
|
+
}
|
|
29
|
+
return Math.max(0, Math.round((estimatedTokens * actualContextTokens) / estimatedContextTokens));
|
|
30
|
+
}
|
|
31
|
+
export function analyzeContext(messages, state, options = {}) {
|
|
32
|
+
const transformed = transformContextMessages(messages, state, options);
|
|
33
|
+
const ignoredMessageIndexes = getIgnoredMessageIndexes(messages, state);
|
|
34
|
+
let completeTurns = 0;
|
|
35
|
+
for (const [index, message] of messages.entries()) {
|
|
36
|
+
if (message.role === 'user' && !ignoredMessageIndexes.has(index))
|
|
37
|
+
completeTurns += 1;
|
|
38
|
+
}
|
|
39
|
+
const rawTokens = messages.reduce((total, message) => total + estimateTokens(message), 0);
|
|
40
|
+
const effectiveTokens = transformed.messages.reduce((total, message) => total + estimateTokens(message), 0);
|
|
41
|
+
const ignoredTokens = Math.max(0, rawTokens - effectiveTokens);
|
|
42
|
+
const effectiveReasoningReplayTokens = sumReasoningReplayTokens(transformed.messages);
|
|
43
|
+
const reasoningReplayTokens = Math.max(0, sumReasoningReplayTokens(messages) - effectiveReasoningReplayTokens);
|
|
44
|
+
return {
|
|
45
|
+
rawTokens,
|
|
46
|
+
effectiveTokens,
|
|
47
|
+
providerEffectiveTokens: effectiveTokens + effectiveReasoningReplayTokens,
|
|
48
|
+
ignoredTokens,
|
|
49
|
+
providerIgnoredTokens: ignoredTokens + reasoningReplayTokens,
|
|
50
|
+
reasoningReplayTokens,
|
|
51
|
+
completeTurns
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
export function findCutoffTimestamp(messages, keepTurns) {
|
|
55
|
+
const userMessages = messages.filter((message) => message.role === 'user');
|
|
56
|
+
if (userMessages.length === 0) {
|
|
57
|
+
// 压缩可能将用户消息收进摘要,只保留当前轮的助手过程,仍需按过程预算处理。
|
|
58
|
+
return messages.find((message) => message.role === 'assistant')?.timestamp;
|
|
59
|
+
}
|
|
60
|
+
const index = Math.max(0, userMessages.length - keepTurns);
|
|
61
|
+
return userMessages[index]?.timestamp;
|
|
62
|
+
}
|
|
63
|
+
function createUserTurnCandidateState(currentState, cutoffTimestamp, keepTurns) {
|
|
64
|
+
return {
|
|
65
|
+
...currentState,
|
|
66
|
+
enabled: true,
|
|
67
|
+
mode: currentState.internalTurnCutoffs === undefined ? 'user-turns' : 'combined',
|
|
68
|
+
cutoffTimestamp: Math.max(currentState.cutoffTimestamp ?? 0, cutoffTimestamp),
|
|
69
|
+
keepTurns,
|
|
70
|
+
updatedAt: Date.now()
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
function createPotential(current, candidate) {
|
|
74
|
+
const reasoningReplayTokens = Math.max(0, candidate.reasoningReplayTokens - current.reasoningReplayTokens);
|
|
75
|
+
const netTokens = Math.max(0, current.effectiveTokens - candidate.effectiveTokens);
|
|
76
|
+
return {
|
|
77
|
+
reasoningReplayTokens,
|
|
78
|
+
netTokens,
|
|
79
|
+
providerNetTokens: netTokens + reasoningReplayTokens
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function afterTimestamp(timestamp) {
|
|
83
|
+
return timestamp < Number.MAX_SAFE_INTEGER ? timestamp + 1 : timestamp;
|
|
84
|
+
}
|
|
85
|
+
function createRetainedProcessBudgetIndex(messages, state, options) {
|
|
86
|
+
const internalIgnoredIndexes = getIgnoredMessageIndexes(messages, {
|
|
87
|
+
...state,
|
|
88
|
+
enabled: true,
|
|
89
|
+
cutoffTimestamp: undefined
|
|
90
|
+
});
|
|
91
|
+
const skillBaseDirs = getSkillBaseDirs(messages, options);
|
|
92
|
+
const assistantTokens = [];
|
|
93
|
+
const nonSkillToolCalls = [];
|
|
94
|
+
const toolResults = [];
|
|
95
|
+
const skillToolCallIds = new Set();
|
|
96
|
+
for (const message of messages) {
|
|
97
|
+
if (message.role !== 'assistant')
|
|
98
|
+
continue;
|
|
99
|
+
for (const block of message.content) {
|
|
100
|
+
if (block.type === 'toolCall' && isSkillContentRead(block, skillBaseDirs, options)) {
|
|
101
|
+
skillToolCallIds.add(block.id);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
for (const [messageIndex, message] of messages.entries()) {
|
|
106
|
+
if (message.role === 'toolResult') {
|
|
107
|
+
if (!skillToolCallIds.has(message.toolCallId)) {
|
|
108
|
+
toolResults.push({
|
|
109
|
+
messageIndex,
|
|
110
|
+
toolCallId: message.toolCallId,
|
|
111
|
+
tokens: estimateTokens(message)
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (message.role !== 'assistant')
|
|
117
|
+
continue;
|
|
118
|
+
let tokens = 0;
|
|
119
|
+
for (const block of message.content) {
|
|
120
|
+
if (block.type === 'thinking') {
|
|
121
|
+
tokens += estimateThinkingBlockTokens(block);
|
|
122
|
+
tokens += estimateReasoningReplayTokens(block);
|
|
123
|
+
}
|
|
124
|
+
else if (block.type === 'toolCall' && !skillToolCallIds.has(block.id)) {
|
|
125
|
+
tokens += estimateToolCallTokens(block);
|
|
126
|
+
nonSkillToolCalls.push({ messageIndex, toolCallId: block.id });
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (tokens > 0)
|
|
130
|
+
assistantTokens.push({ messageIndex, tokens });
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
internalIgnoredIndexes,
|
|
134
|
+
assistantTokens,
|
|
135
|
+
nonSkillToolCalls,
|
|
136
|
+
toolResults
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function estimateRetainedCompressibleProcessTokens(messages, state, index) {
|
|
140
|
+
const cutoffTimestamp = state.cutoffTimestamp;
|
|
141
|
+
const isIgnored = (messageIndex) => index.internalIgnoredIndexes.has(messageIndex) ||
|
|
142
|
+
(cutoffTimestamp !== undefined && messages[messageIndex].timestamp < cutoffTimestamp);
|
|
143
|
+
const ignoredToolCallIds = new Set();
|
|
144
|
+
for (const toolCall of index.nonSkillToolCalls) {
|
|
145
|
+
if (isIgnored(toolCall.messageIndex))
|
|
146
|
+
ignoredToolCallIds.add(toolCall.toolCallId);
|
|
147
|
+
}
|
|
148
|
+
let tokens = 0;
|
|
149
|
+
for (const assistant of index.assistantTokens) {
|
|
150
|
+
if (!isIgnored(assistant.messageIndex))
|
|
151
|
+
tokens += assistant.tokens;
|
|
152
|
+
}
|
|
153
|
+
for (const result of index.toolResults) {
|
|
154
|
+
if (!isIgnored(result.messageIndex) && !ignoredToolCallIds.has(result.toolCallId)) {
|
|
155
|
+
tokens += result.tokens;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return tokens;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Keeps compressible process details from at most the latest user turns within one shared budget.
|
|
162
|
+
* User messages, assistant text, and protected Skill reads are retained regardless of this boundary.
|
|
163
|
+
*/
|
|
164
|
+
export function selectRecentProcessCandidate(messages, currentState, keepTurns, processTokenBudget, options = {}) {
|
|
165
|
+
const userCutoffTimestamp = findCutoffTimestamp(messages, keepTurns);
|
|
166
|
+
if (userCutoffTimestamp === undefined)
|
|
167
|
+
return undefined;
|
|
168
|
+
const current = analyzeContext(messages, currentState, options);
|
|
169
|
+
const assistants = messages.filter((message) => message.role === 'assistant' && message.timestamp >= userCutoffTimestamp);
|
|
170
|
+
const latestMessageTimestamp = messages.reduce((latest, message) => Math.max(latest, message.timestamp), userCutoffTimestamp);
|
|
171
|
+
const candidateCutoffs = [
|
|
172
|
+
userCutoffTimestamp,
|
|
173
|
+
...assistants.map((message) => message.timestamp),
|
|
174
|
+
afterTimestamp(latestMessageTimestamp)
|
|
175
|
+
];
|
|
176
|
+
const budgetIndex = createRetainedProcessBudgetIndex(messages, currentState, options);
|
|
177
|
+
for (const cutoffTimestamp of [...new Set(candidateCutoffs)]) {
|
|
178
|
+
const nextState = createUserTurnCandidateState(currentState, cutoffTimestamp, keepTurns);
|
|
179
|
+
const retainedProcessTokens = estimateRetainedCompressibleProcessTokens(messages, nextState, budgetIndex);
|
|
180
|
+
if (retainedProcessTokens > processTokenBudget)
|
|
181
|
+
continue;
|
|
182
|
+
const candidate = analyzeContext(messages, nextState, options);
|
|
183
|
+
return {
|
|
184
|
+
cutoffTimestamp: nextState.cutoffTimestamp,
|
|
185
|
+
nextState,
|
|
186
|
+
potential: createPotential(current, candidate)
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
export function analyzeIgnorePotential(messages, currentState, keepTurns, processTokenBudget, options = {}) {
|
|
192
|
+
return (selectRecentProcessCandidate(messages, currentState, keepTurns, processTokenBudget, options)
|
|
193
|
+
?.potential ?? emptyContextIgnorePotential());
|
|
194
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AgentMessage } from '@earendil-works/pi-agent-core';
|
|
2
|
+
import type { SessionBeforeCompactEvent } from '@earendil-works/pi-coding-agent';
|
|
3
|
+
import type { ContextIgnoreTransformOptions } from './context-skill-path.js';
|
|
4
|
+
import type { ContextIgnoreState } from './types.js';
|
|
5
|
+
export declare function transformCompactionPreparation(preparation: SessionBeforeCompactEvent['preparation'], sessionMessages: AgentMessage[], state: ContextIgnoreState, ignoredTokens: number, options?: ContextIgnoreTransformOptions): void;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { getIgnoredMessageReferences, transformContextMessages } from './context-transform.js';
|
|
2
|
+
export function transformCompactionPreparation(preparation, sessionMessages, state, ignoredTokens, options = {}) {
|
|
3
|
+
if (!state.enabled ||
|
|
4
|
+
(state.cutoffTimestamp === undefined && state.internalTurnCutoffs === undefined)) {
|
|
5
|
+
return;
|
|
6
|
+
}
|
|
7
|
+
const transformOptions = {
|
|
8
|
+
...options,
|
|
9
|
+
ignoredMessages: getIgnoredMessageReferences(sessionMessages, state)
|
|
10
|
+
};
|
|
11
|
+
preparation.messagesToSummarize = transformContextMessages(preparation.messagesToSummarize, state, transformOptions).messages;
|
|
12
|
+
preparation.turnPrefixMessages = transformContextMessages(preparation.turnPrefixMessages, state, transformOptions).messages;
|
|
13
|
+
preparation.tokensBefore = Math.max(0, preparation.tokensBefore - ignoredTokens);
|
|
14
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
export declare const HISTORY_TOOL_RESULT_NAME = "history_tool_result";
|
|
3
|
+
type HistoricalToolStatus = 'ok' | 'error' | 'missing';
|
|
4
|
+
export type HistoricalToolResultDetails = {
|
|
5
|
+
ref: number;
|
|
6
|
+
toolCallId: string;
|
|
7
|
+
toolName: string;
|
|
8
|
+
historicalStatus: HistoricalToolStatus;
|
|
9
|
+
timestamp?: number;
|
|
10
|
+
};
|
|
11
|
+
export declare function registerHistoryToolResult(pi: ExtensionAPI, getToolReferences: () => ReadonlyMap<number, string>): void;
|
|
12
|
+
export {};
|