dsh-te-prune 0.0.0-stage → 0.1.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.
- package/LICENSE +202 -0
- package/README.md +19 -2
- package/cordis.patch.yml +5 -0
- package/lib/index.d.ts +77 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +312 -0
- package/lib/index.js.map +1 -0
- package/package.json +77 -3
- package/src/index.ts +374 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,20 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-te-prune
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Stops sending tool definitions the model never calls. Every tool schema rides
|
|
4
|
+
along on every request; this component counts, per repository, how many
|
|
5
|
+
sessions a tool has gone unused, and hides it after `idleSessions` (default 5).
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
dsh plugin --profile <profile> add dsh-te-prune
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
**Off by default.** Hiding a tool changes the cached request prefix, so it is
|
|
12
|
+
only a win if the saved schema tokens exceed what the change costs; the decision
|
|
13
|
+
is made once at session start and held for the whole session. Harness basics are
|
|
14
|
+
never hidden, and `maxHidden` bounds the total to 8 tools.
|
|
15
|
+
|
|
16
|
+
- `/te-prune` shows idle counters, `/te-prune restore` returns a tool and keeps it.
|
|
17
|
+
|
|
18
|
+
Part of [dsh-tokeneconomizer](https://github.com/SonettoGu14/dsh-tokeneconomizer) — install
|
|
19
|
+
`dsh-te` for all three components.
|
|
20
|
+
Licensed Apache-2.0.
|
package/cordis.patch.yml
ADDED
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool pruning: stop paying for tools a repository has never used.
|
|
3
|
+
*
|
|
4
|
+
* Every tool definition is re-sent on every request, so an unused tool is a
|
|
5
|
+
* standing tax on the prompt. This component counts, per repository, how many
|
|
6
|
+
* sessions have ended without a given tool being called; once a tool has been
|
|
7
|
+
* idle for enough sessions it is hidden through the registry's own scoped
|
|
8
|
+
* restriction — never by editing anyone's settings — and one command gives it
|
|
9
|
+
* back for good.
|
|
10
|
+
*
|
|
11
|
+
* Why the decision is made once, at session start: the tool set is part of the
|
|
12
|
+
* cached request prefix, so changing it mid-session throws away the cache. A
|
|
13
|
+
* stable set per session costs nothing; a set that shifts per step costs a lot.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-te-prune
|
|
16
|
+
*/
|
|
17
|
+
import { Service, type Context } from '@deepseek-ai/cordis';
|
|
18
|
+
import z from '@deepseek-ai/schemastery';
|
|
19
|
+
import type { Session } from '@deepseek-ai/dsh-session';
|
|
20
|
+
/** Settings for the pruning component. */
|
|
21
|
+
export interface Config {
|
|
22
|
+
/** Off by default: hiding a tool changes the request prefix. */
|
|
23
|
+
enabled: boolean;
|
|
24
|
+
/** Sessions a tool may stay idle before it becomes a candidate. */
|
|
25
|
+
idleSessions: number;
|
|
26
|
+
/** Never hide more than this many tools in one session. */
|
|
27
|
+
maxHidden: number;
|
|
28
|
+
/** Tool names that are never hidden, whatever their usage. */
|
|
29
|
+
protected: string[];
|
|
30
|
+
}
|
|
31
|
+
export declare const name = "dsh-te-prune";
|
|
32
|
+
export declare const Config: z<Config>;
|
|
33
|
+
/**
|
|
34
|
+
* Per-repository pruning state and per-session application.
|
|
35
|
+
* Exposed on the context as `tePrune`.
|
|
36
|
+
*/
|
|
37
|
+
export declare class Prune extends Service {
|
|
38
|
+
private readonly config;
|
|
39
|
+
static inject: string[];
|
|
40
|
+
private readonly watching;
|
|
41
|
+
/** Settles in flight, awaited by the `session/flush` durability checkpoint. */
|
|
42
|
+
private readonly pending;
|
|
43
|
+
private readonly repos;
|
|
44
|
+
constructor(ctx: Context, config: Config);
|
|
45
|
+
protected [Service.init](): Promise<void>;
|
|
46
|
+
/** Note that a tool ran. */
|
|
47
|
+
private observe;
|
|
48
|
+
/** The watcher for one session. */
|
|
49
|
+
private watchOf;
|
|
50
|
+
/** Load (and cache) the pruning state of the session's repository. */
|
|
51
|
+
private repoOf;
|
|
52
|
+
/** Names this component must never hide. */
|
|
53
|
+
private protectedNames;
|
|
54
|
+
/** Candidates: idle long enough, not protected, not restored, visible right now. */
|
|
55
|
+
private candidates;
|
|
56
|
+
/** Hide this session's candidates, once, before the tools are assembled. */
|
|
57
|
+
private maybeRestrict;
|
|
58
|
+
/**
|
|
59
|
+
* Fold a finished session into the repository's idle counters.
|
|
60
|
+
* @param session - the session that just ended.
|
|
61
|
+
*/
|
|
62
|
+
settle(session: Session): Promise<void>;
|
|
63
|
+
/** Give every hidden tool back, permanently. */
|
|
64
|
+
restore(session: Session): Promise<string>;
|
|
65
|
+
/** Human-readable listing for `/te-prune`. */
|
|
66
|
+
report(session: Session): string;
|
|
67
|
+
/** Whether any session is currently being watched (used by tests). */
|
|
68
|
+
get watchingCount(): number;
|
|
69
|
+
}
|
|
70
|
+
declare module '@deepseek-ai/cordis' {
|
|
71
|
+
interface Context {
|
|
72
|
+
tePrune: Prune;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** Mount the component. */
|
|
76
|
+
export declare function apply(ctx: Context, config: Config): void;
|
|
77
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,OAAO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C,MAAM,CAAC;IA6BhD,8CAA8C;IAC9C,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM;IAsBhC,sEAAsE;IACtE,IAAI,aAAa,IAAI,MAAM,CAE1B;CACF;AAED,OAAO,QAAQ,qBAAqB,CAAC;IACnC,UAAU,OAAO;QACf,OAAO,EAAE,KAAK,CAAA;KACf;CACF;AAED,2BAA2B;AAC3B,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,IAAI,CAGxD"}
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool pruning: stop paying for tools a repository has never used.
|
|
3
|
+
*
|
|
4
|
+
* Every tool definition is re-sent on every request, so an unused tool is a
|
|
5
|
+
* standing tax on the prompt. This component counts, per repository, how many
|
|
6
|
+
* sessions have ended without a given tool being called; once a tool has been
|
|
7
|
+
* idle for enough sessions it is hidden through the registry's own scoped
|
|
8
|
+
* restriction — never by editing anyone's settings — and one command gives it
|
|
9
|
+
* back for good.
|
|
10
|
+
*
|
|
11
|
+
* Why the decision is made once, at session start: the tool set is part of the
|
|
12
|
+
* cached request prefix, so changing it mid-session throws away the cache. A
|
|
13
|
+
* stable set per session costs nothing; a set that shifts per step costs a lot.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-te-prune
|
|
16
|
+
*/
|
|
17
|
+
import { Service } from '@deepseek-ai/cordis';
|
|
18
|
+
import z from '@deepseek-ai/schemastery';
|
|
19
|
+
import { readJson, repoKeyDirName, resolveRepoKey, stateRoot, writeJsonAtomic } from 'dsh-te-core';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
export const name = 'dsh-te-prune';
|
|
22
|
+
/** Whether this session is a delegation of another one. */
|
|
23
|
+
function isSubagent(session) {
|
|
24
|
+
return session.header?.origin === 'subagent';
|
|
25
|
+
}
|
|
26
|
+
/** Tools whose meaning is the session itself: hiding them breaks the harness. */
|
|
27
|
+
const ALWAYS_PROTECTED = [
|
|
28
|
+
'bash',
|
|
29
|
+
'bash_persistent',
|
|
30
|
+
'read',
|
|
31
|
+
'write',
|
|
32
|
+
'edit',
|
|
33
|
+
'glob',
|
|
34
|
+
'grep',
|
|
35
|
+
'todo_write',
|
|
36
|
+
'ask_user_question',
|
|
37
|
+
'working_directory',
|
|
38
|
+
'job_output',
|
|
39
|
+
'job_kill',
|
|
40
|
+
'job_list',
|
|
41
|
+
'subagent',
|
|
42
|
+
'subagent_fork',
|
|
43
|
+
'list_agents',
|
|
44
|
+
'send_message',
|
|
45
|
+
'wait_agent',
|
|
46
|
+
'present',
|
|
47
|
+
// Hiding these is self-defeating: they are how a long session stays cheap and
|
|
48
|
+
// how an agent reaches the facts/skills it was told about.
|
|
49
|
+
'compress',
|
|
50
|
+
'decompress',
|
|
51
|
+
'search_context',
|
|
52
|
+
'skill',
|
|
53
|
+
'read_image',
|
|
54
|
+
];
|
|
55
|
+
export const Config = z.object({
|
|
56
|
+
enabled: z.boolean().default(false),
|
|
57
|
+
idleSessions: z.number().min(1).default(5),
|
|
58
|
+
maxHidden: z.number().min(0).default(8),
|
|
59
|
+
protected: z.array(z.string()).default([]),
|
|
60
|
+
});
|
|
61
|
+
/** Tool names visible from the registry, when the service is present. */
|
|
62
|
+
function visibleTools(ctx) {
|
|
63
|
+
const tools = ctx.get('tools');
|
|
64
|
+
if (tools === undefined)
|
|
65
|
+
return [];
|
|
66
|
+
return tools.schemas().map((schema) => schema.name);
|
|
67
|
+
}
|
|
68
|
+
/** Where one repository's pruning state lives. */
|
|
69
|
+
function repoPrunePath(key) {
|
|
70
|
+
return join(stateRoot(), 'repos', repoKeyDirName(key), 'prune.json');
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Per-repository pruning state and per-session application.
|
|
74
|
+
* Exposed on the context as `tePrune`.
|
|
75
|
+
*/
|
|
76
|
+
export class Prune extends Service {
|
|
77
|
+
config;
|
|
78
|
+
static inject = ['commands'];
|
|
79
|
+
watching = new Map();
|
|
80
|
+
/** Settles in flight, awaited by the `session/flush` durability checkpoint. */
|
|
81
|
+
pending = new Map();
|
|
82
|
+
repos = new Map();
|
|
83
|
+
constructor(ctx, config) {
|
|
84
|
+
super(ctx, 'tePrune');
|
|
85
|
+
this.config = config;
|
|
86
|
+
}
|
|
87
|
+
async [Service.init]() {
|
|
88
|
+
this.ctx.on('tools/result', (exec, result) => {
|
|
89
|
+
this.observe(exec, result);
|
|
90
|
+
});
|
|
91
|
+
// `agent/created` is after `agentCtx` exists and before the first prompt is
|
|
92
|
+
// assembled. Doing this any later would send the first request with the full
|
|
93
|
+
// tool block and then change it, which re-reads the whole prompt uncached.
|
|
94
|
+
this.ctx.on('agent/created', async ({ agent }) => {
|
|
95
|
+
if (isSubagent(agent.session))
|
|
96
|
+
return;
|
|
97
|
+
await this.maybeRestrict(agent);
|
|
98
|
+
});
|
|
99
|
+
this.ctx.on('session/disposed', (session) => {
|
|
100
|
+
// Teardown does not await listeners; the write is drained by the awaited
|
|
101
|
+
// `session/flush` checkpoint rather than racing the process exit.
|
|
102
|
+
this.pending.set(session.id, this.settle(session)
|
|
103
|
+
.catch((error) => {
|
|
104
|
+
// Losing a pruning pass is harmless; never fail the session over it.
|
|
105
|
+
this.ctx.logger('dsh-te-prune').warn('prune state not settled: %s', String(error));
|
|
106
|
+
})
|
|
107
|
+
.finally(() => this.pending.delete(session.id)));
|
|
108
|
+
});
|
|
109
|
+
this.ctx.on('session/flush', async () => {
|
|
110
|
+
await Promise.all([...this.pending.values()]);
|
|
111
|
+
});
|
|
112
|
+
this.ctx.effect(() => this.ctx.commands.register({
|
|
113
|
+
name: 'te-prune',
|
|
114
|
+
description: 'Show or restore tools hidden by dsh-te-prune',
|
|
115
|
+
input: { hint: 'restore' },
|
|
116
|
+
handler: async (invocation) => {
|
|
117
|
+
const session = invocation.agent.session;
|
|
118
|
+
// A resumed session may have no in-memory state yet; load it so the
|
|
119
|
+
// command answers from disk instead of claiming nothing was measured.
|
|
120
|
+
await this.repoOf(session);
|
|
121
|
+
const raw = invocation.rawInput.trim().toLowerCase();
|
|
122
|
+
if (raw === 'restore') {
|
|
123
|
+
return { kind: 'success', text: await this.restore(session) };
|
|
124
|
+
}
|
|
125
|
+
return { kind: 'success', text: this.report(session) };
|
|
126
|
+
},
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
/** Note that a tool ran. */
|
|
130
|
+
observe(exec, _result) {
|
|
131
|
+
const session = exec.agent?.session;
|
|
132
|
+
if (session === undefined)
|
|
133
|
+
return;
|
|
134
|
+
this.watchOf(session).used.add(exec.name);
|
|
135
|
+
}
|
|
136
|
+
/** The watcher for one session. */
|
|
137
|
+
watchOf(session) {
|
|
138
|
+
const existing = this.watching.get(session.id);
|
|
139
|
+
if (existing !== undefined)
|
|
140
|
+
return existing;
|
|
141
|
+
const created = { used: new Set(), hidden: [], decided: false };
|
|
142
|
+
this.watching.set(session.id, created);
|
|
143
|
+
return created;
|
|
144
|
+
}
|
|
145
|
+
/** Load (and cache) the pruning state of the session's repository. */
|
|
146
|
+
async repoOf(session) {
|
|
147
|
+
const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key;
|
|
148
|
+
const cached = this.repos.get(key);
|
|
149
|
+
if (cached !== undefined)
|
|
150
|
+
return cached;
|
|
151
|
+
const stored = await readJson(repoPrunePath(key));
|
|
152
|
+
const repo = stored !== undefined && stored.version === 1 && typeof stored.tools === 'object'
|
|
153
|
+
? stored
|
|
154
|
+
: { version: 1, key, sessions: 0, tools: {}, restored: [] };
|
|
155
|
+
if (!Array.isArray(repo.restored))
|
|
156
|
+
repo.restored = [];
|
|
157
|
+
this.repos.set(key, repo);
|
|
158
|
+
return repo;
|
|
159
|
+
}
|
|
160
|
+
/** Names this component must never hide. */
|
|
161
|
+
protectedNames() {
|
|
162
|
+
return new Set([...ALWAYS_PROTECTED, ...this.config.protected]);
|
|
163
|
+
}
|
|
164
|
+
/** Candidates: idle long enough, not protected, not restored, visible right now. */
|
|
165
|
+
candidates(repo, available) {
|
|
166
|
+
const keep = this.protectedNames();
|
|
167
|
+
const restored = new Set(repo.restored);
|
|
168
|
+
return available
|
|
169
|
+
.filter((tool) => !keep.has(tool) && !restored.has(tool))
|
|
170
|
+
.filter((tool) => {
|
|
171
|
+
const record = repo.tools[tool];
|
|
172
|
+
return record !== undefined && record.idle >= this.config.idleSessions;
|
|
173
|
+
})
|
|
174
|
+
.sort((left, right) => {
|
|
175
|
+
const a = repo.tools[left];
|
|
176
|
+
const b = repo.tools[right];
|
|
177
|
+
if (a === undefined || b === undefined)
|
|
178
|
+
return 0;
|
|
179
|
+
return b.idle - a.idle;
|
|
180
|
+
})
|
|
181
|
+
.slice(0, this.config.maxHidden);
|
|
182
|
+
}
|
|
183
|
+
/** Hide this session's candidates, once, before the tools are assembled. */
|
|
184
|
+
async maybeRestrict(agent) {
|
|
185
|
+
const session = agent.session;
|
|
186
|
+
const watch = this.watchOf(session);
|
|
187
|
+
if (watch.decided)
|
|
188
|
+
return;
|
|
189
|
+
watch.decided = true;
|
|
190
|
+
const repo = await this.repoOf(session);
|
|
191
|
+
// The restriction must be installed on the agent's own scope: a
|
|
192
|
+
// context-global one would mask the tool for every agent in the process,
|
|
193
|
+
// and the registry rejects it outright.
|
|
194
|
+
const tools = agent.ctx.get('tools');
|
|
195
|
+
if (tools === undefined)
|
|
196
|
+
return;
|
|
197
|
+
const available = tools.schemas().map((schema) => schema.name);
|
|
198
|
+
const deny = this.candidates(repo, available);
|
|
199
|
+
if (deny.length === 0)
|
|
200
|
+
return;
|
|
201
|
+
try {
|
|
202
|
+
watch.hidden = deny;
|
|
203
|
+
watch.dispose = tools.restrict({ deny });
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
// A name registered only for this agent, or one that disappeared between
|
|
207
|
+
// listing and restricting, makes the whole filter invalid. Hiding tools is
|
|
208
|
+
// an optimization: leave the set untouched rather than fail the session.
|
|
209
|
+
watch.hidden = [];
|
|
210
|
+
this.ctx.logger('dsh-te-prune').warn('could not hide idle tools: %s', String(error));
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Fold a finished session into the repository's idle counters.
|
|
215
|
+
* @param session - the session that just ended.
|
|
216
|
+
*/
|
|
217
|
+
async settle(session) {
|
|
218
|
+
// A subagent child is a delegation of the session that already counts: it
|
|
219
|
+
// would otherwise age every tool it never had reason to call.
|
|
220
|
+
if (isSubagent(session))
|
|
221
|
+
return;
|
|
222
|
+
const watch = this.watching.get(session.id);
|
|
223
|
+
this.watching.delete(session.id);
|
|
224
|
+
try {
|
|
225
|
+
watch?.dispose?.();
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
// The agent scope may already be torn down; the restriction died with it.
|
|
229
|
+
}
|
|
230
|
+
const repo = await this.repoOf(session);
|
|
231
|
+
const ordinal = repo.sessions + 1;
|
|
232
|
+
const available = visibleTools(this.ctx);
|
|
233
|
+
const seen = new Set([...available, ...watch?.used ?? [], ...this.protectedNames()]);
|
|
234
|
+
for (const tool of seen) {
|
|
235
|
+
const record = repo.tools[tool] ?? { idle: 0, lastUsed: 0, uses: 0 };
|
|
236
|
+
const used = watch?.used.has(tool) === true;
|
|
237
|
+
repo.tools[tool] = {
|
|
238
|
+
idle: used ? 0 : record.idle + 1,
|
|
239
|
+
lastUsed: used ? ordinal : record.lastUsed,
|
|
240
|
+
uses: record.uses + (used ? 1 : 0),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
repo.sessions = ordinal;
|
|
244
|
+
this.repos.set(repo.key, repo);
|
|
245
|
+
await writeJsonAtomic(repoPrunePath(repo.key), repo);
|
|
246
|
+
}
|
|
247
|
+
/** Give every hidden tool back, permanently. */
|
|
248
|
+
async restore(session) {
|
|
249
|
+
const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key;
|
|
250
|
+
const repo = await this.repoOf(session);
|
|
251
|
+
// The live mask must go too, or the tool stays hidden until this session ends
|
|
252
|
+
// even though the command promises it back.
|
|
253
|
+
const watch = this.watching.get(session.id);
|
|
254
|
+
try {
|
|
255
|
+
watch?.dispose?.();
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
// The agent scope may already be gone; nothing left to release.
|
|
259
|
+
}
|
|
260
|
+
if (watch !== undefined) {
|
|
261
|
+
watch.dispose = undefined;
|
|
262
|
+
watch.hidden = [];
|
|
263
|
+
}
|
|
264
|
+
const hidden = Object.entries(repo.tools)
|
|
265
|
+
.filter(([tool, record]) => !this.protectedNames().has(tool) && record.idle >= this.config.idleSessions)
|
|
266
|
+
.map(([tool]) => tool);
|
|
267
|
+
repo.restored = [...new Set([...repo.restored, ...hidden])];
|
|
268
|
+
for (const tool of hidden) {
|
|
269
|
+
const record = repo.tools[tool];
|
|
270
|
+
if (record !== undefined)
|
|
271
|
+
record.idle = 0;
|
|
272
|
+
}
|
|
273
|
+
await writeJsonAtomic(repoPrunePath(key), repo);
|
|
274
|
+
return hidden.length === 0
|
|
275
|
+
? `Nothing pruned in ${key}.`
|
|
276
|
+
: `Restored ${hidden.join(', ')} — they will never be hidden again.`;
|
|
277
|
+
}
|
|
278
|
+
/** Human-readable listing for `/te-prune`. */
|
|
279
|
+
report(session) {
|
|
280
|
+
const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key;
|
|
281
|
+
const repo = this.repos.get(key);
|
|
282
|
+
if (repo === undefined || repo.sessions === 0)
|
|
283
|
+
return `Nothing measured yet for ${key}.`;
|
|
284
|
+
const watch = this.watching.get(session.id);
|
|
285
|
+
const keep = this.protectedNames();
|
|
286
|
+
const rows = Object.entries(repo.tools)
|
|
287
|
+
.filter(([tool]) => !keep.has(tool))
|
|
288
|
+
.sort((left, right) => right[1].idle - left[1].idle)
|
|
289
|
+
.map(([tool, record]) => {
|
|
290
|
+
const state = repo.restored.includes(tool)
|
|
291
|
+
? 'kept'
|
|
292
|
+
: record.idle >= this.config.idleSessions
|
|
293
|
+
? 'hidden next session'
|
|
294
|
+
: 'visible';
|
|
295
|
+
return `${tool.padEnd(18)} idle ${String(record.idle).padStart(2)}/${this.config.idleSessions} uses ${String(record.uses).padStart(3)} ${state}`;
|
|
296
|
+
});
|
|
297
|
+
const head = `Pruning for ${key} (${repo.sessions} sessions, hides at ${this.config.idleSessions} idle)`;
|
|
298
|
+
const hidden = watch?.hidden.length ? `Hidden this session: ${watch.hidden.join(', ')}` : undefined;
|
|
299
|
+
return [head, hidden, ...rows].filter((line) => line !== undefined).join('\n');
|
|
300
|
+
}
|
|
301
|
+
/** Whether any session is currently being watched (used by tests). */
|
|
302
|
+
get watchingCount() {
|
|
303
|
+
return this.watching.size;
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
/** Mount the component. */
|
|
307
|
+
export function apply(ctx, config) {
|
|
308
|
+
if (!config.enabled)
|
|
309
|
+
return;
|
|
310
|
+
ctx.plugin(Prune, config);
|
|
311
|
+
}
|
|
312
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,OAAO,EAAgB,MAAM,qBAAqB,CAAA;AAC3D,OAAO,CAAC,MAAM,0BAA0B,CAAA;AAKxC,OAAO,EAAE,QAAQ,EAAE,cAAc,EAAE,cAAc,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAClG,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAchC,MAAM,CAAC,MAAM,IAAI,GAAG,cAAc,CAAA;AAElC,2DAA2D;AAC3D,SAAS,UAAU,CAAC,OAAgB;IAClC,OAAO,OAAO,CAAC,MAAM,EAAE,MAAM,KAAK,UAAU,CAAA;AAC9C,CAAC;AAED,iFAAiF;AACjF,MAAM,gBAAgB,GAAsB;IAC1C,MAAM;IACN,iBAAiB;IACjB,MAAM;IACN,OAAO;IACP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AAwB,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,SAAS,CAAA;QACnG,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;IAChF,CAAC;IAED,sEAAsE;IACtE,IAAI,aAAa;QACf,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAA;IAC3B,CAAC;;AASH,2BAA2B;AAC3B,MAAM,UAAU,KAAK,CAAC,GAAY,EAAE,MAAc;IAChD,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,OAAM;IAC3B,GAAG,CAAC,MAAM,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;AAC3B,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,80 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-te-prune",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Evidence-driven tool-set pruning across sessions.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "lib/index.js",
|
|
8
|
+
"types": "lib/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./lib/index.d.ts",
|
|
12
|
+
"import": "./lib/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
15
|
+
"./package.json": "./package.json"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"lib",
|
|
19
|
+
"src",
|
|
20
|
+
"cordis.patch.yml"
|
|
21
|
+
],
|
|
22
|
+
"repository": {
|
|
23
|
+
"type": "git",
|
|
24
|
+
"url": "git+https://github.com/SonettoGu14/dsh-tokeneconomizer.git",
|
|
25
|
+
"directory": "packages/prune"
|
|
26
|
+
},
|
|
27
|
+
"engines": {
|
|
28
|
+
"node": ">=24.9.0",
|
|
29
|
+
"dsh": ">=0.2.2-rc.3 <0.3.0"
|
|
30
|
+
},
|
|
31
|
+
"dsh": {
|
|
32
|
+
"bundle": {
|
|
33
|
+
"patch": "./cordis.patch.yml"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"dsh-te-core": "0.1.1",
|
|
41
|
+
"@deepseek-ai/schemastery": "^3.19.0"
|
|
42
|
+
},
|
|
43
|
+
"peerDependencies": {
|
|
44
|
+
"@deepseek-ai/dsh": ">=0.2.2-rc.3 <0.3.0",
|
|
45
|
+
"@deepseek-ai/cordis": "^4.1.0",
|
|
46
|
+
"@deepseek-ai/dsh-session": ">=0.2.2-rc.3 <0.3.0",
|
|
47
|
+
"@deepseek-ai/dsh-agent": ">=0.2.2-rc.3 <0.3.0",
|
|
48
|
+
"@deepseek-ai/dsh-tools": ">=0.2.2-rc.3 <0.3.0",
|
|
49
|
+
"@deepseek-ai/dsh-commands": ">=0.2.2-rc.3 <0.3.0"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@deepseek-ai/cordis": "^4.1.0",
|
|
53
|
+
"@deepseek-ai/dsh-agent": "0.2.2-rc.3",
|
|
54
|
+
"@deepseek-ai/dsh-session": "0.2.2-rc.3",
|
|
55
|
+
"@deepseek-ai/dsh-tools": "0.2.2-rc.3",
|
|
56
|
+
"@deepseek-ai/dsh-commands": "0.2.2-rc.3"
|
|
57
|
+
},
|
|
58
|
+
"peerDependenciesMeta": {
|
|
59
|
+
"@deepseek-ai/cordis": {
|
|
60
|
+
"optional": false
|
|
61
|
+
},
|
|
62
|
+
"@deepseek-ai/dsh-session": {
|
|
63
|
+
"optional": false
|
|
64
|
+
},
|
|
65
|
+
"@deepseek-ai/dsh-agent": {
|
|
66
|
+
"optional": false
|
|
67
|
+
},
|
|
68
|
+
"@deepseek-ai/dsh-tools": {
|
|
69
|
+
"optional": false
|
|
70
|
+
},
|
|
71
|
+
"@deepseek-ai/dsh-commands": {
|
|
72
|
+
"optional": false
|
|
73
|
+
}
|
|
74
|
+
},
|
|
75
|
+
"homepage": "https://github.com/SonettoGu14/dsh-tokeneconomizer/tree/master/packages/prune#readme",
|
|
76
|
+
"bugs": {
|
|
77
|
+
"url": "https://github.com/SonettoGu14/dsh-tokeneconomizer/issues"
|
|
78
|
+
},
|
|
79
|
+
"scripts": {}
|
|
6
80
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool pruning: stop paying for tools a repository has never used.
|
|
3
|
+
*
|
|
4
|
+
* Every tool definition is re-sent on every request, so an unused tool is a
|
|
5
|
+
* standing tax on the prompt. This component counts, per repository, how many
|
|
6
|
+
* sessions have ended without a given tool being called; once a tool has been
|
|
7
|
+
* idle for enough sessions it is hidden through the registry's own scoped
|
|
8
|
+
* restriction — never by editing anyone's settings — and one command gives it
|
|
9
|
+
* back for good.
|
|
10
|
+
*
|
|
11
|
+
* Why the decision is made once, at session start: the tool set is part of the
|
|
12
|
+
* cached request prefix, so changing it mid-session throws away the cache. A
|
|
13
|
+
* stable set per session costs nothing; a set that shifts per step costs a lot.
|
|
14
|
+
*
|
|
15
|
+
* @module dsh-te-prune
|
|
16
|
+
*/
|
|
17
|
+
import { Service, type Context } from '@deepseek-ai/cordis'
|
|
18
|
+
import z from '@deepseek-ai/schemastery'
|
|
19
|
+
import type {} from '@deepseek-ai/dsh-commands'
|
|
20
|
+
import type { Agent } from '@deepseek-ai/dsh-agent'
|
|
21
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
22
|
+
import type { ToolExecution, ToolExecutionResult, ToolsService } from '@deepseek-ai/dsh-tools'
|
|
23
|
+
import { readJson, repoKeyDirName, resolveRepoKey, stateRoot, writeJsonAtomic } from 'dsh-te-core'
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
|
|
26
|
+
/** Settings for the pruning component. */
|
|
27
|
+
export interface Config {
|
|
28
|
+
/** Off by default: hiding a tool changes the request prefix. */
|
|
29
|
+
enabled: boolean
|
|
30
|
+
/** Sessions a tool may stay idle before it becomes a candidate. */
|
|
31
|
+
idleSessions: number
|
|
32
|
+
/** Never hide more than this many tools in one session. */
|
|
33
|
+
maxHidden: number
|
|
34
|
+
/** Tool names that are never hidden, whatever their usage. */
|
|
35
|
+
protected: string[]
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const name = 'dsh-te-prune'
|
|
39
|
+
|
|
40
|
+
/** Whether this session is a delegation of another one. */
|
|
41
|
+
function isSubagent(session: Session): boolean {
|
|
42
|
+
return session.header?.origin === 'subagent'
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Tools whose meaning is the session itself: hiding them breaks the harness. */
|
|
46
|
+
const ALWAYS_PROTECTED: readonly string[] = [
|
|
47
|
+
'bash',
|
|
48
|
+
'bash_persistent',
|
|
49
|
+
'read',
|
|
50
|
+
'write',
|
|
51
|
+
'edit',
|
|
52
|
+
'glob',
|
|
53
|
+
'grep',
|
|
54
|
+
'todo_write',
|
|
55
|
+
'ask_user_question',
|
|
56
|
+
'working_directory',
|
|
57
|
+
'job_output',
|
|
58
|
+
'job_kill',
|
|
59
|
+
'job_list',
|
|
60
|
+
'subagent',
|
|
61
|
+
'subagent_fork',
|
|
62
|
+
'list_agents',
|
|
63
|
+
'send_message',
|
|
64
|
+
'wait_agent',
|
|
65
|
+
'present',
|
|
66
|
+
// Hiding these is self-defeating: they are how a long session stays cheap and
|
|
67
|
+
// how an agent reaches the facts/skills it was told about.
|
|
68
|
+
'compress',
|
|
69
|
+
'decompress',
|
|
70
|
+
'search_context',
|
|
71
|
+
'skill',
|
|
72
|
+
'read_image',
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
export const Config: z<Config> = z.object({
|
|
76
|
+
enabled: z.boolean().default(false),
|
|
77
|
+
idleSessions: z.number().min(1).default(5),
|
|
78
|
+
maxHidden: z.number().min(0).default(8),
|
|
79
|
+
protected: z.array(z.string()).default([]),
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
/** One tool's history in one repository. */
|
|
83
|
+
interface ToolRecord {
|
|
84
|
+
/** Consecutive sessions that ended without calling it. */
|
|
85
|
+
idle: number
|
|
86
|
+
/** Sessions since the repository was first observed. */
|
|
87
|
+
lastUsed: number
|
|
88
|
+
uses: number
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Per-repository pruning state. */
|
|
92
|
+
interface RepoPrune {
|
|
93
|
+
version: 1
|
|
94
|
+
key: string
|
|
95
|
+
/** Sessions observed in this repository. */
|
|
96
|
+
sessions: number
|
|
97
|
+
tools: Record<string, ToolRecord>
|
|
98
|
+
/** Tools the user asked to keep forever. */
|
|
99
|
+
restored: string[]
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** What one live session has used. */
|
|
103
|
+
interface SessionWatch {
|
|
104
|
+
used: Set<string>
|
|
105
|
+
/** Tools hidden for this session, with the disposer that unhides them. */
|
|
106
|
+
hidden: string[]
|
|
107
|
+
dispose?: () => void
|
|
108
|
+
decided: boolean
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Tool names visible from the registry, when the service is present. */
|
|
112
|
+
function visibleTools(ctx: Context): string[] {
|
|
113
|
+
const tools = ctx.get('tools') as ToolsService | undefined
|
|
114
|
+
if (tools === undefined) return []
|
|
115
|
+
return tools.schemas().map((schema) => schema.name)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Where one repository's pruning state lives. */
|
|
119
|
+
function repoPrunePath(key: string): string {
|
|
120
|
+
return join(stateRoot(), 'repos', repoKeyDirName(key), 'prune.json')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Per-repository pruning state and per-session application.
|
|
125
|
+
* Exposed on the context as `tePrune`.
|
|
126
|
+
*/
|
|
127
|
+
export class Prune extends Service {
|
|
128
|
+
static inject = ['commands']
|
|
129
|
+
|
|
130
|
+
private readonly watching = new Map<string, SessionWatch>()
|
|
131
|
+
|
|
132
|
+
/** Settles in flight, awaited by the `session/flush` durability checkpoint. */
|
|
133
|
+
private readonly pending = new Map<string, Promise<void>>()
|
|
134
|
+
|
|
135
|
+
private readonly repos = new Map<string, RepoPrune>()
|
|
136
|
+
|
|
137
|
+
constructor(ctx: Context, private readonly config: Config) {
|
|
138
|
+
super(ctx, 'tePrune')
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
protected async [Service.init](): Promise<void> {
|
|
142
|
+
this.ctx.on('tools/result', (exec, result) => {
|
|
143
|
+
this.observe(exec, result)
|
|
144
|
+
})
|
|
145
|
+
// `agent/created` is after `agentCtx` exists and before the first prompt is
|
|
146
|
+
// assembled. Doing this any later would send the first request with the full
|
|
147
|
+
// tool block and then change it, which re-reads the whole prompt uncached.
|
|
148
|
+
this.ctx.on('agent/created', async ({ agent }) => {
|
|
149
|
+
if (isSubagent(agent.session)) return
|
|
150
|
+
await this.maybeRestrict(agent)
|
|
151
|
+
})
|
|
152
|
+
this.ctx.on('session/disposed', (session) => {
|
|
153
|
+
// Teardown does not await listeners; the write is drained by the awaited
|
|
154
|
+
// `session/flush` checkpoint rather than racing the process exit.
|
|
155
|
+
this.pending.set(
|
|
156
|
+
session.id,
|
|
157
|
+
this.settle(session)
|
|
158
|
+
.catch((error: unknown) => {
|
|
159
|
+
// Losing a pruning pass is harmless; never fail the session over it.
|
|
160
|
+
this.ctx.logger('dsh-te-prune').warn('prune state not settled: %s', String(error))
|
|
161
|
+
})
|
|
162
|
+
.finally(() => this.pending.delete(session.id)),
|
|
163
|
+
)
|
|
164
|
+
})
|
|
165
|
+
this.ctx.on('session/flush', async () => {
|
|
166
|
+
await Promise.all([...this.pending.values()])
|
|
167
|
+
})
|
|
168
|
+
this.ctx.effect(() =>
|
|
169
|
+
this.ctx.commands.register({
|
|
170
|
+
name: 'te-prune',
|
|
171
|
+
description: 'Show or restore tools hidden by dsh-te-prune',
|
|
172
|
+
input: { hint: 'restore' },
|
|
173
|
+
handler: async (invocation) => {
|
|
174
|
+
const session = invocation.agent.session
|
|
175
|
+
// A resumed session may have no in-memory state yet; load it so the
|
|
176
|
+
// command answers from disk instead of claiming nothing was measured.
|
|
177
|
+
await this.repoOf(session)
|
|
178
|
+
const raw = invocation.rawInput.trim().toLowerCase()
|
|
179
|
+
if (raw === 'restore') {
|
|
180
|
+
return { kind: 'success', text: await this.restore(session) }
|
|
181
|
+
}
|
|
182
|
+
return { kind: 'success', text: this.report(session) }
|
|
183
|
+
},
|
|
184
|
+
}),
|
|
185
|
+
)
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Note that a tool ran. */
|
|
189
|
+
private observe(exec: ToolExecution, _result: ToolExecutionResult): void {
|
|
190
|
+
const session = exec.agent?.session
|
|
191
|
+
if (session === undefined) return
|
|
192
|
+
this.watchOf(session).used.add(exec.name)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The watcher for one session. */
|
|
196
|
+
private watchOf(session: Session): SessionWatch {
|
|
197
|
+
const existing = this.watching.get(session.id)
|
|
198
|
+
if (existing !== undefined) return existing
|
|
199
|
+
const created: SessionWatch = { used: new Set(), hidden: [], decided: false }
|
|
200
|
+
this.watching.set(session.id, created)
|
|
201
|
+
return created
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Load (and cache) the pruning state of the session's repository. */
|
|
205
|
+
private async repoOf(session: Session): Promise<RepoPrune> {
|
|
206
|
+
const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key
|
|
207
|
+
const cached = this.repos.get(key)
|
|
208
|
+
if (cached !== undefined) return cached
|
|
209
|
+
const stored = await readJson<RepoPrune>(repoPrunePath(key))
|
|
210
|
+
const repo: RepoPrune =
|
|
211
|
+
stored !== undefined && stored.version === 1 && typeof stored.tools === 'object'
|
|
212
|
+
? stored
|
|
213
|
+
: { version: 1, key, sessions: 0, tools: {}, restored: [] }
|
|
214
|
+
if (!Array.isArray(repo.restored)) repo.restored = []
|
|
215
|
+
this.repos.set(key, repo)
|
|
216
|
+
return repo
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Names this component must never hide. */
|
|
220
|
+
private protectedNames(): Set<string> {
|
|
221
|
+
return new Set([...ALWAYS_PROTECTED, ...this.config.protected])
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Candidates: idle long enough, not protected, not restored, visible right now. */
|
|
225
|
+
private candidates(repo: RepoPrune, available: readonly string[]): string[] {
|
|
226
|
+
const keep = this.protectedNames()
|
|
227
|
+
const restored = new Set(repo.restored)
|
|
228
|
+
return available
|
|
229
|
+
.filter((tool) => !keep.has(tool) && !restored.has(tool))
|
|
230
|
+
.filter((tool) => {
|
|
231
|
+
const record = repo.tools[tool]
|
|
232
|
+
return record !== undefined && record.idle >= this.config.idleSessions
|
|
233
|
+
})
|
|
234
|
+
.sort((left, right) => {
|
|
235
|
+
const a = repo.tools[left]
|
|
236
|
+
const b = repo.tools[right]
|
|
237
|
+
if (a === undefined || b === undefined) return 0
|
|
238
|
+
return b.idle - a.idle
|
|
239
|
+
})
|
|
240
|
+
.slice(0, this.config.maxHidden)
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Hide this session's candidates, once, before the tools are assembled. */
|
|
244
|
+
private async maybeRestrict(agent: Agent): Promise<void> {
|
|
245
|
+
const session = agent.session
|
|
246
|
+
const watch = this.watchOf(session)
|
|
247
|
+
if (watch.decided) return
|
|
248
|
+
watch.decided = true
|
|
249
|
+
const repo = await this.repoOf(session)
|
|
250
|
+
// The restriction must be installed on the agent's own scope: a
|
|
251
|
+
// context-global one would mask the tool for every agent in the process,
|
|
252
|
+
// and the registry rejects it outright.
|
|
253
|
+
const tools = agent.ctx.get('tools') as ToolsService | undefined
|
|
254
|
+
if (tools === undefined) return
|
|
255
|
+
const available = tools.schemas().map((schema) => schema.name)
|
|
256
|
+
const deny = this.candidates(repo, available)
|
|
257
|
+
if (deny.length === 0) return
|
|
258
|
+
try {
|
|
259
|
+
watch.hidden = deny
|
|
260
|
+
watch.dispose = tools.restrict({ deny })
|
|
261
|
+
} catch (error) {
|
|
262
|
+
// A name registered only for this agent, or one that disappeared between
|
|
263
|
+
// listing and restricting, makes the whole filter invalid. Hiding tools is
|
|
264
|
+
// an optimization: leave the set untouched rather than fail the session.
|
|
265
|
+
watch.hidden = []
|
|
266
|
+
this.ctx.logger('dsh-te-prune').warn('could not hide idle tools: %s', String(error))
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Fold a finished session into the repository's idle counters.
|
|
272
|
+
* @param session - the session that just ended.
|
|
273
|
+
*/
|
|
274
|
+
async settle(session: Session): Promise<void> {
|
|
275
|
+
// A subagent child is a delegation of the session that already counts: it
|
|
276
|
+
// would otherwise age every tool it never had reason to call.
|
|
277
|
+
if (isSubagent(session)) return
|
|
278
|
+
const watch = this.watching.get(session.id)
|
|
279
|
+
this.watching.delete(session.id)
|
|
280
|
+
try {
|
|
281
|
+
watch?.dispose?.()
|
|
282
|
+
} catch {
|
|
283
|
+
// The agent scope may already be torn down; the restriction died with it.
|
|
284
|
+
}
|
|
285
|
+
const repo = await this.repoOf(session)
|
|
286
|
+
const ordinal = repo.sessions + 1
|
|
287
|
+
const available = visibleTools(this.ctx)
|
|
288
|
+
const seen = new Set([...available, ...watch?.used ?? [], ...this.protectedNames()])
|
|
289
|
+
|
|
290
|
+
for (const tool of seen) {
|
|
291
|
+
const record = repo.tools[tool] ?? { idle: 0, lastUsed: 0, uses: 0 }
|
|
292
|
+
const used = watch?.used.has(tool) === true
|
|
293
|
+
repo.tools[tool] = {
|
|
294
|
+
idle: used ? 0 : record.idle + 1,
|
|
295
|
+
lastUsed: used ? ordinal : record.lastUsed,
|
|
296
|
+
uses: record.uses + (used ? 1 : 0),
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
repo.sessions = ordinal
|
|
301
|
+
this.repos.set(repo.key, repo)
|
|
302
|
+
await writeJsonAtomic(repoPrunePath(repo.key), repo)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** Give every hidden tool back, permanently. */
|
|
306
|
+
async restore(session: Session): Promise<string> {
|
|
307
|
+
const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key
|
|
308
|
+
const repo = await this.repoOf(session)
|
|
309
|
+
// The live mask must go too, or the tool stays hidden until this session ends
|
|
310
|
+
// even though the command promises it back.
|
|
311
|
+
const watch = this.watching.get(session.id)
|
|
312
|
+
try {
|
|
313
|
+
watch?.dispose?.()
|
|
314
|
+
} catch {
|
|
315
|
+
// The agent scope may already be gone; nothing left to release.
|
|
316
|
+
}
|
|
317
|
+
if (watch !== undefined) {
|
|
318
|
+
watch.dispose = undefined
|
|
319
|
+
watch.hidden = []
|
|
320
|
+
}
|
|
321
|
+
const hidden = Object.entries(repo.tools)
|
|
322
|
+
.filter(([tool, record]) => !this.protectedNames().has(tool) && record.idle >= this.config.idleSessions)
|
|
323
|
+
.map(([tool]) => tool)
|
|
324
|
+
repo.restored = [...new Set([...repo.restored, ...hidden])]
|
|
325
|
+
for (const tool of hidden) {
|
|
326
|
+
const record = repo.tools[tool]
|
|
327
|
+
if (record !== undefined) record.idle = 0
|
|
328
|
+
}
|
|
329
|
+
await writeJsonAtomic(repoPrunePath(key), repo)
|
|
330
|
+
return hidden.length === 0
|
|
331
|
+
? `Nothing pruned in ${key}.`
|
|
332
|
+
: `Restored ${hidden.join(', ')} — they will never be hidden again.`
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Human-readable listing for `/te-prune`. */
|
|
336
|
+
report(session: Session): string {
|
|
337
|
+
const key = resolveRepoKey(session.header?.cwd ?? process.cwd()).key
|
|
338
|
+
const repo = this.repos.get(key)
|
|
339
|
+
if (repo === undefined || repo.sessions === 0) return `Nothing measured yet for ${key}.`
|
|
340
|
+
const watch = this.watching.get(session.id)
|
|
341
|
+
const keep = this.protectedNames()
|
|
342
|
+
const rows = Object.entries(repo.tools)
|
|
343
|
+
.filter(([tool]) => !keep.has(tool))
|
|
344
|
+
.sort((left, right) => right[1].idle - left[1].idle)
|
|
345
|
+
.map(([tool, record]) => {
|
|
346
|
+
const state = repo.restored.includes(tool)
|
|
347
|
+
? 'kept'
|
|
348
|
+
: record.idle >= this.config.idleSessions
|
|
349
|
+
? 'hidden next session'
|
|
350
|
+
: 'visible'
|
|
351
|
+
return `${tool.padEnd(18)} idle ${String(record.idle).padStart(2)}/${this.config.idleSessions} uses ${String(record.uses).padStart(3)} ${state}`
|
|
352
|
+
})
|
|
353
|
+
const head = `Pruning for ${key} (${repo.sessions} sessions, hides at ${this.config.idleSessions} idle)`
|
|
354
|
+
const hidden = watch?.hidden.length ? `Hidden this session: ${watch.hidden.join(', ')}` : undefined
|
|
355
|
+
return [head, hidden, ...rows].filter((line) => line !== undefined).join('\n')
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Whether any session is currently being watched (used by tests). */
|
|
359
|
+
get watchingCount(): number {
|
|
360
|
+
return this.watching.size
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
declare module '@deepseek-ai/cordis' {
|
|
365
|
+
interface Context {
|
|
366
|
+
tePrune: Prune
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Mount the component. */
|
|
371
|
+
export function apply(ctx: Context, config: Config): void {
|
|
372
|
+
if (!config.enabled) return
|
|
373
|
+
ctx.plugin(Prune, config)
|
|
374
|
+
}
|