dsh-injection-manager 0.0.0-stage → 2.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/CHANGELOG.md +642 -0
- package/CONTRIBUTING.md +49 -0
- package/LICENSE +21 -0
- package/README.md +371 -2
- package/README.zh.md +330 -0
- package/SECURITY.md +35 -0
- package/client.js +4928 -0
- package/cordis.patch.yml +4 -0
- package/docs/ARCHITECTURE.md +195 -0
- package/docs/COMPATIBILITY.md +60 -0
- package/docs/DETAIL.de.md +1 -0
- package/docs/DETAIL.es.md +1 -0
- package/docs/DETAIL.fr.md +1 -0
- package/docs/DETAIL.ja.md +1 -0
- package/docs/DETAIL.md +149 -0
- package/docs/DETAIL.pt.md +1 -0
- package/docs/DETAIL.ru.md +1 -0
- package/docs/DETAIL.zh.md +105 -0
- package/docs/FAQ.md +96 -0
- package/docs/PERFORMANCE.md +73 -0
- package/docs/images/demo.gif +0 -0
- package/docs/images/dock.png +0 -0
- package/docs/images/panel-dark.png +0 -0
- package/docs/images/panel-drawer.png +0 -0
- package/docs/images/panel-insights.png +0 -0
- package/docs/images/panel-manage-expanded.png +0 -0
- package/docs/images/panel-manage.png +0 -0
- package/docs/images/panel-settings.png +0 -0
- package/docs/images/panel-sidebar.png +0 -0
- package/docs/preview.svg +178 -0
- package/icon.svg +20 -0
- package/index.js +304 -0
- package/lib/actions.js +33 -0
- package/lib/apply.js +230 -0
- package/lib/compaction.js +126 -0
- package/lib/content.js +360 -0
- package/lib/events.js +216 -0
- package/lib/group.js +141 -0
- package/lib/health.js +210 -0
- package/lib/history.js +47 -0
- package/lib/hostinfo.js +83 -0
- package/lib/instructions.js +142 -0
- package/lib/measure.js +51 -0
- package/lib/policy.js +189 -0
- package/lib/presets.js +45 -0
- package/lib/pressure.js +146 -0
- package/lib/routes.js +877 -0
- package/lib/settings.js +32 -0
- package/lib/snapshot.js +785 -0
- package/lib/stats.js +394 -0
- package/lib/text.js +292 -0
- package/lib/trend.js +168 -0
- package/locale/de.json +413 -0
- package/locale/en.json +413 -0
- package/locale/es.json +413 -0
- package/locale/fr.json +413 -0
- package/locale/ja.json +413 -0
- package/locale/pt.json +413 -0
- package/locale/ru.json +413 -0
- package/locale/zh.json +413 -0
- package/package.json +85 -4
- package/screenshots.json +11 -0
package/index.js
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// 上下文注入管理 — Context Injection Manager.
|
|
2
|
+
//
|
|
3
|
+
// One place that answers "what is this session about to be given before its
|
|
4
|
+
// first request, and which of it can I turn off?" and then applies the answer
|
|
5
|
+
// to every new session.
|
|
6
|
+
//
|
|
7
|
+
// Design boundaries, kept deliberately narrow:
|
|
8
|
+
// - Read-only toward the workspace: the plugin never edits AGENTS.md,
|
|
9
|
+
// SKILL.md or any project file. Every switch is a scoped registration.
|
|
10
|
+
// - The panel's numbers, the tool card and the applied policy all come from
|
|
11
|
+
// one snapshot, so they cannot drift apart.
|
|
12
|
+
// - Only sessions created after a policy change are affected; a running
|
|
13
|
+
// conversation is never rewritten mid-flight.
|
|
14
|
+
import { createRequire } from 'node:module'
|
|
15
|
+
import { homedir } from 'node:os'
|
|
16
|
+
import { join } from 'node:path'
|
|
17
|
+
import { applyPolicyForAgent, releaseAll, savePolicy } from './lib/apply.js'
|
|
18
|
+
import { createRoutes, ROUTES } from './lib/routes.js'
|
|
19
|
+
import { buildSnapshot, planBudget, policyFromPlan } from './lib/snapshot.js'
|
|
20
|
+
import { watchCompaction } from './lib/compaction.js'
|
|
21
|
+
import { CONTENT_CHANNELS, TOOL_CONTENT_LIMIT, collectContent } from './lib/content.js'
|
|
22
|
+
import { appendEvent } from './lib/events.js'
|
|
23
|
+
import { buildHealth } from './lib/health.js'
|
|
24
|
+
import { presetPolicy } from './lib/presets.js'
|
|
25
|
+
import { readPolicy } from './lib/policy.js'
|
|
26
|
+
import { setSettings } from './lib/settings.js'
|
|
27
|
+
import { pushUndo, undoLastPolicy } from './lib/actions.js'
|
|
28
|
+
import { renderCard, renderHealthLine, renderHealthText, renderText } from './lib/text.js'
|
|
29
|
+
|
|
30
|
+
export const name = 'injection-manager'
|
|
31
|
+
|
|
32
|
+
// A linked plugin directory has no node_modules of its own, so the schema
|
|
33
|
+
// library must be resolved from the profile that loaded us. If no anchor works
|
|
34
|
+
// (a non-profile launch), Config stays undefined and the plugin still runs with
|
|
35
|
+
// the defaults in lib/settings.js.
|
|
36
|
+
function loadSchema() {
|
|
37
|
+
const anchors = []
|
|
38
|
+
if (process.env.DSH_PROFILE_DIR) anchors.push(join(process.env.DSH_PROFILE_DIR, 'package.json'))
|
|
39
|
+
const home = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
40
|
+
const profile = process.env.DSH_PROFILE || 'desktop'
|
|
41
|
+
anchors.push(join(home, 'profiles', profile, 'package.json'))
|
|
42
|
+
for (const anchor of anchors) {
|
|
43
|
+
try {
|
|
44
|
+
return createRequire(anchor)('@deepseek-ai/schemastery')
|
|
45
|
+
} catch {
|
|
46
|
+
/* try the next anchor */
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return undefined
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const Schema = loadSchema()
|
|
53
|
+
|
|
54
|
+
// Presentation and one seeding default. Every actual switch lives in
|
|
55
|
+
// policy.json, so this form stays short and safe to edit.
|
|
56
|
+
export const Config =
|
|
57
|
+
Schema === undefined
|
|
58
|
+
? undefined
|
|
59
|
+
: Schema.object({
|
|
60
|
+
dock: Schema.boolean()
|
|
61
|
+
.default(true)
|
|
62
|
+
.description('在输入框旁显示「注入 xxk · 可关 xx%」徽标;关掉只隐藏入口,不影响策略。'),
|
|
63
|
+
refreshOnFocus: Schema.boolean()
|
|
64
|
+
.default(true)
|
|
65
|
+
.description('窗口重新获得焦点时刷新面板,多窗口同时开关时不会看到旧数字。'),
|
|
66
|
+
showRawNames: Schema.boolean()
|
|
67
|
+
.default(true)
|
|
68
|
+
.description('在中文条目名旁显示原始键名(如 harness:identity),排障时有用。'),
|
|
69
|
+
budgetTokens: Schema.number()
|
|
70
|
+
.default(0)
|
|
71
|
+
.description('策略文件还没有时的默认预算 token(0 = 不设);只在首次使用前作为初始值。'),
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
// Hard dependencies: the tool needs the registry, the snapshot needs the prompt
|
|
75
|
+
// registry, skills and the working directory, the panel needs a web server, and
|
|
76
|
+
// the routes need to resolve a live agent. `webServer` must be declared here
|
|
77
|
+
// rather than fetched with ctx.get(): during early boot it is undefined and the
|
|
78
|
+
// routes would silently never register.
|
|
79
|
+
export const inject = ['tools', 'systemPrompt', 'skills', 'workingDirectory', 'agents', 'webServer', 'commands']
|
|
80
|
+
|
|
81
|
+
const TOOL_NAME = 'context_injection'
|
|
82
|
+
|
|
83
|
+
const TOOL_DESCRIPTION =
|
|
84
|
+
'查看本轮请求将注入给模型的上下文构成:系统提示词段落、运行时上下文、技能目录、工具 schema、工作区规则,各占多少字符与估算 token,以及哪些条目可以关闭。只读:本工具不改策略、不改任何文件;开关在侧栏「上下文注入」面板里。可选参数 {channel, name}:只返回该条目的原文(单条 ≤32KB),不带参数才返回完整清单。'
|
|
85
|
+
|
|
86
|
+
const SINGLE_CONTENT_HINT = 'channel 和 name 必须同时提供(如 {channel:"tools", name:"read"});不带参数调用才返回完整清单。'
|
|
87
|
+
|
|
88
|
+
function resolveAgent(ctx, exec) {
|
|
89
|
+
if (exec?.agent !== undefined) return { agent: exec.agent, source: 'exec.agent' }
|
|
90
|
+
try {
|
|
91
|
+
const initiator = ctx.agents.currentInitiator()
|
|
92
|
+
if (initiator !== undefined) return { agent: initiator, source: 'initiator' }
|
|
93
|
+
} catch {
|
|
94
|
+
/* no initiator boundary */
|
|
95
|
+
}
|
|
96
|
+
return { agent: undefined, source: 'none' }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function createTool(ctx) {
|
|
100
|
+
return {
|
|
101
|
+
name: TOOL_NAME,
|
|
102
|
+
description: TOOL_DESCRIPTION,
|
|
103
|
+
parameters: {
|
|
104
|
+
type: 'object',
|
|
105
|
+
properties: {
|
|
106
|
+
channel: {
|
|
107
|
+
type: 'string',
|
|
108
|
+
enum: [...CONTENT_CHANNELS],
|
|
109
|
+
description: '可选:只读查看单条内容所属的通道;必须同时提供 name。',
|
|
110
|
+
},
|
|
111
|
+
name: {
|
|
112
|
+
type: 'string',
|
|
113
|
+
description: '可选:条目名,与 /summary items[].name 一致(段落名 / 上下文名 / 技能名 / 工具名 / 规则文件路径);必须同时提供 channel。',
|
|
114
|
+
},
|
|
115
|
+
},
|
|
116
|
+
additionalProperties: false,
|
|
117
|
+
},
|
|
118
|
+
timeoutMs: 30000,
|
|
119
|
+
output: {
|
|
120
|
+
schema: {},
|
|
121
|
+
render: (_args, value) => [{ type: 'text', text: String(value?.card ?? value?.text ?? value?.content ?? '') }],
|
|
122
|
+
},
|
|
123
|
+
async execute(args, exec) {
|
|
124
|
+
const { agent, source } = resolveAgent(ctx, exec)
|
|
125
|
+
const channel = typeof args?.channel === 'string' && args.channel.length > 0 ? args.channel : undefined
|
|
126
|
+
const name = typeof args?.name === 'string' && args.name.trim().length > 0 ? args.name.trim() : undefined
|
|
127
|
+
if (channel !== undefined || name !== undefined) {
|
|
128
|
+
// Single-item mode: the caller asked to read one row, not the whole
|
|
129
|
+
// snapshot. Hard-capped at 32KB so a page of prompt text cannot flood a
|
|
130
|
+
// model turn; the full snapshot stays behind the no-argument call.
|
|
131
|
+
if (channel === undefined || name === undefined) {
|
|
132
|
+
return { ok: false, error: 'invalid-arguments', message: SINGLE_CONTENT_HINT }
|
|
133
|
+
}
|
|
134
|
+
const result = await collectContent(ctx, agent, channel, name, exec?.signal, { limit: TOOL_CONTENT_LIMIT })
|
|
135
|
+
if (result.ok !== true) {
|
|
136
|
+
return JSON.parse(
|
|
137
|
+
JSON.stringify({ ok: false, error: result.error ?? 'content-failed', message: result.message ?? '', channel, name }),
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
const payload = {
|
|
141
|
+
ok: true,
|
|
142
|
+
item: result.item,
|
|
143
|
+
contentType: result.contentType,
|
|
144
|
+
content: result.content,
|
|
145
|
+
bytes: result.bytes,
|
|
146
|
+
truncated: result.truncated,
|
|
147
|
+
limit: result.limit,
|
|
148
|
+
...(result.sourcePath === undefined ? {} : { sourcePath: result.sourcePath }),
|
|
149
|
+
...(result.note === undefined ? {} : { note: result.note }),
|
|
150
|
+
}
|
|
151
|
+
return JSON.parse(JSON.stringify(payload))
|
|
152
|
+
}
|
|
153
|
+
const snapshot = await buildSnapshot(ctx, agent, source, exec?.signal)
|
|
154
|
+
const payload = {
|
|
155
|
+
ok: true,
|
|
156
|
+
apiVersion: 2,
|
|
157
|
+
...snapshot,
|
|
158
|
+
text: renderText(snapshot),
|
|
159
|
+
card: renderCard(snapshot),
|
|
160
|
+
}
|
|
161
|
+
// The tool result must be lossless JSON.
|
|
162
|
+
return JSON.parse(JSON.stringify(payload))
|
|
163
|
+
},
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export function createCommand(ctx) {
|
|
168
|
+
return {
|
|
169
|
+
name: 'inject',
|
|
170
|
+
description: '查看首轮上下文注入清单;`/inject health` 看健康检查,`/inject minimal|all` 切换预设,`/inject budget 20000` 设定预算。',
|
|
171
|
+
async handler(invocation) {
|
|
172
|
+
const agent = invocation?.agent
|
|
173
|
+
const sessionId = typeof agent?.id === 'string' && agent.id.length > 0 ? agent.id : undefined
|
|
174
|
+
const raw = typeof invocation?.rawInput === 'string' ? invocation.rawInput.trim() : ''
|
|
175
|
+
const snapshot = await buildSnapshot(ctx, agent, 'command', invocation?.signal)
|
|
176
|
+
try {
|
|
177
|
+
const [command, value] = raw.split(/\s+/).filter((part) => part.length > 0)
|
|
178
|
+
if (command === undefined) {
|
|
179
|
+
// The full report plus a single health line: the line is the "should I
|
|
180
|
+
// care?" answer, and `/inject health` is the detail behind it.
|
|
181
|
+
return { kind: 'success', text: `${renderText(snapshot)}\n\n${renderHealthLine(buildHealth(snapshot))}` }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (command === 'health') {
|
|
185
|
+
return { kind: 'success', text: renderHealthText(buildHealth(snapshot)) }
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
if (command === 'all' || command === 'minimal') {
|
|
189
|
+
const names = {
|
|
190
|
+
sections: snapshot.items.filter((item) => item.channel === 'sections').map((item) => item.name),
|
|
191
|
+
contexts: snapshot.items.filter((item) => item.channel === 'contexts').map((item) => item.name),
|
|
192
|
+
skills: snapshot.items.filter((item) => item.channel === 'skills').map((item) => item.name),
|
|
193
|
+
tools: snapshot.items.filter((item) => item.channel === 'tools').map((item) => item.name),
|
|
194
|
+
}
|
|
195
|
+
const state = await readPolicy()
|
|
196
|
+
pushUndo(state.policy)
|
|
197
|
+
const next = presetPolicy(command, names)
|
|
198
|
+
next.prompt = state.policy.prompt
|
|
199
|
+
next.budget = state.policy.budget
|
|
200
|
+
await savePolicy(next, { sessionId, kind: 'preset', params: { name: command, via: 'command' } })
|
|
201
|
+
const after = await buildSnapshot(ctx, agent, 'command', invocation?.signal)
|
|
202
|
+
return {
|
|
203
|
+
kind: 'success',
|
|
204
|
+
text: `已切换预设:${command}\n新会话首轮 ≈ ${after.policy.preview.after} token(−${after.policy.preview.savedTokens})\n\n${renderText(after)}`,
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (command === 'budget') {
|
|
209
|
+
const tokens = Number(value)
|
|
210
|
+
if (!Number.isFinite(tokens) || tokens <= 0) {
|
|
211
|
+
return { kind: 'error', text: '用法:/inject budget <token 数>,例如 /inject budget 20000' }
|
|
212
|
+
}
|
|
213
|
+
const state = await readPolicy()
|
|
214
|
+
pushUndo(state.policy)
|
|
215
|
+
await savePolicy(
|
|
216
|
+
{ ...state.policy, budget: { tokens: Math.round(tokens) } },
|
|
217
|
+
{ sessionId, kind: 'budget', params: { tokens: Math.round(tokens), via: 'command' } },
|
|
218
|
+
)
|
|
219
|
+
return { kind: 'success', text: `首轮注入预算已设为 ${Math.round(tokens)} token(新会话生效)。` }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (command === 'apply') {
|
|
223
|
+
const state = await readPolicy()
|
|
224
|
+
const target = Number(value) > 0 ? Math.round(Number(value)) : state.policy.budget.tokens
|
|
225
|
+
if (!Number.isFinite(target) || target <= 0) {
|
|
226
|
+
return { kind: 'error', text: '用法:/inject apply [token 数],或用 /inject budget <token 数> 先设预算。' }
|
|
227
|
+
}
|
|
228
|
+
const plan = planBudget(state.policy, snapshot.items, target)
|
|
229
|
+
if (plan.drop.length === 0) {
|
|
230
|
+
return { kind: 'success', text: `当前首轮注入 ${plan.before} token 已在 ${plan.target} 预算内,无需关闭。` }
|
|
231
|
+
}
|
|
232
|
+
pushUndo(state.policy)
|
|
233
|
+
const next = policyFromPlan(state.policy, plan)
|
|
234
|
+
next.prompt = state.policy.prompt
|
|
235
|
+
next.budget = { tokens: plan.target }
|
|
236
|
+
await savePolicy(next, {
|
|
237
|
+
sessionId,
|
|
238
|
+
kind: 'budget',
|
|
239
|
+
params: { tokens: plan.target, dropped: plan.drop.length, saved: plan.savedTokens, via: 'plan' },
|
|
240
|
+
tokensDelta: -plan.savedTokens,
|
|
241
|
+
})
|
|
242
|
+
const after = await buildSnapshot(ctx, agent, 'command', invocation?.signal)
|
|
243
|
+
const suites = (plan.dropGroups ?? []).map((group) => ` ${group.label} · ${group.count} 项 · ${group.tokens} token`).join('\n')
|
|
244
|
+
return {
|
|
245
|
+
kind: 'success',
|
|
246
|
+
text: `已按 ${plan.target} token 预算应用:关闭 ${plan.drop.length} 项(−${plan.savedTokens}),预计首轮 ${plan.after}。\n${suites}\n\n${renderText(after)}`,
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
if (command === 'undo') {
|
|
251
|
+
await undoLastPolicy({ sessionId, params: { via: 'command' } })
|
|
252
|
+
const after = await buildSnapshot(ctx, agent, 'command', invocation?.signal)
|
|
253
|
+
return {
|
|
254
|
+
kind: 'success',
|
|
255
|
+
text: `已撤销上一步策略。新会话首轮 ≈ ${after.policy.preview.after} token。`,
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
return {
|
|
260
|
+
kind: 'error',
|
|
261
|
+
text: '可用:/inject · /inject health · /inject all · /inject minimal · /inject budget <token 数> · /inject apply [token 数] · /inject undo',
|
|
262
|
+
}
|
|
263
|
+
} catch (error) {
|
|
264
|
+
return { kind: 'error', text: `注入策略操作失败:${error?.message ?? error}` }
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function apply(ctx, config) {
|
|
271
|
+
setSettings(config)
|
|
272
|
+
ctx.tools.register(createTool(ctx))
|
|
273
|
+
|
|
274
|
+
ctx.effect(() => ctx.commands.register(createCommand(ctx)), 'injection-manager command')
|
|
275
|
+
|
|
276
|
+
const routes = createRoutes(ctx)
|
|
277
|
+
for (const [key, path] of Object.entries(ROUTES)) {
|
|
278
|
+
const handler = routes[key]
|
|
279
|
+
if (typeof handler !== 'function') continue
|
|
280
|
+
ctx.effect(() => ctx.webServer.register({ kind: 'exact', path, handler }), `injection-manager route ${key}`)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// The only moment a policy can still influence the first assemble().
|
|
284
|
+
ctx.on('agent/created', async (payload) => {
|
|
285
|
+
const sessionId = typeof payload?.agent?.id === 'string' ? payload.agent.id : undefined
|
|
286
|
+
// Fire-and-forget: session creation is serial and blocks the first request,
|
|
287
|
+
// so the feed write must not sit in its critical path.
|
|
288
|
+
void appendEvent({
|
|
289
|
+
sessionId,
|
|
290
|
+
kind: 'session-created',
|
|
291
|
+
params: { source: typeof payload?.source === 'string' ? payload.source : 'unknown' },
|
|
292
|
+
})
|
|
293
|
+
await applyPolicyForAgent(ctx, payload?.agent, payload?.source)
|
|
294
|
+
})
|
|
295
|
+
|
|
296
|
+
// Compaction receipts: "it threw away 78k tokens for you" is a durable log
|
|
297
|
+
// fact, not an inference from a shrinking total.
|
|
298
|
+
ctx.effect(() => {
|
|
299
|
+
const dispose = watchCompaction(ctx)
|
|
300
|
+
return typeof dispose === 'function' ? dispose : () => {}
|
|
301
|
+
}, 'injection-manager compaction receipts')
|
|
302
|
+
|
|
303
|
+
ctx.effect(() => () => releaseAll(), 'injection-manager cleanup')
|
|
304
|
+
}
|
package/lib/actions.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Policy actions shared by the HTTP surface and the slash command.
|
|
2
|
+
//
|
|
3
|
+
// `undo` lives here so both entry points pop the same history stack and write
|
|
4
|
+
// through the same atomic path; duplicating it would let the two drift.
|
|
5
|
+
import { popUndo, pushUndo, restoreAt } from './history.js'
|
|
6
|
+
import { normalizePolicy } from './policy.js'
|
|
7
|
+
import { savePolicy } from './apply.js'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `meta` is forwarded to savePolicy so the event feed records an undo as an
|
|
11
|
+
* undo (with its session) instead of a generic policy write.
|
|
12
|
+
*/
|
|
13
|
+
export async function undoLastPolicy(meta = {}) {
|
|
14
|
+
const previous = popUndo()
|
|
15
|
+
if (previous === undefined) throw new Error('nothing-to-undo')
|
|
16
|
+
const restored = normalizePolicy(previous.policy)
|
|
17
|
+
await savePolicy(restored, { ...meta, kind: typeof meta.kind === 'string' ? meta.kind : 'undo' })
|
|
18
|
+
return restored
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function restorePolicyAt(index, meta = {}) {
|
|
22
|
+
const entry = restoreAt(index)
|
|
23
|
+
if (entry === undefined) throw new Error('nothing-to-restore')
|
|
24
|
+
const restored = normalizePolicy(entry.policy)
|
|
25
|
+
await savePolicy(restored, {
|
|
26
|
+
...meta,
|
|
27
|
+
kind: typeof meta.kind === 'string' ? meta.kind : 'undo',
|
|
28
|
+
params: { index, ...(meta.params !== null && typeof meta.params === 'object' ? meta.params : {}) },
|
|
29
|
+
})
|
|
30
|
+
return restored
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export { pushUndo }
|
package/lib/apply.js
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// Apply the saved policy to one newly created session.
|
|
2
|
+
//
|
|
3
|
+
// Every effect is scoped to the agent's own context, so:
|
|
4
|
+
// - the running session is never touched (only sessions created afterwards),
|
|
5
|
+
// - unloading the plugin or disposing the agent removes the effects,
|
|
6
|
+
// - no workspace file is read or written for a switch to work.
|
|
7
|
+
//
|
|
8
|
+
// Sections and dynamic contexts cannot be shadowed by re-registering a
|
|
9
|
+
// same-named contribution: agent presets already register those names *in the
|
|
10
|
+
// agent scope*, and a second registration there throws "already registered in
|
|
11
|
+
// this scope". The supported rewrite point is the scoped
|
|
12
|
+
// `system-prompt/assemble` waterfall, which receives the resolved sections and
|
|
13
|
+
// contexts and lets a listener drop or rewrite them. Tools are removed with
|
|
14
|
+
// `tools.restrict()`; skills are hidden with a same-name, non-invocable
|
|
15
|
+
// registration in the agent's skill layer.
|
|
16
|
+
import { buildSnapshot, appliedAgents, countChannelState, setLastApplication } from './snapshot.js'
|
|
17
|
+
import { appendEvent } from './events.js'
|
|
18
|
+
import { writePolicy } from './policy.js'
|
|
19
|
+
|
|
20
|
+
// Registrations a policy created, keyed by agent id, so plugin unload can undo
|
|
21
|
+
// them even if the agent outlives the plugin.
|
|
22
|
+
const disposers = new Map()
|
|
23
|
+
|
|
24
|
+
// Evidence that the scoped waterfall really ran, surfaced by GET /diag.
|
|
25
|
+
// Registration succeeding is not proof; a counted rewrite is.
|
|
26
|
+
let rewriteCount = 0
|
|
27
|
+
let lastRewrite = null
|
|
28
|
+
export const rewriteStats = () => ({ count: rewriteCount, last: lastRewrite })
|
|
29
|
+
|
|
30
|
+
export function releaseAll() {
|
|
31
|
+
for (const list of disposers.values()) {
|
|
32
|
+
for (const dispose of list) {
|
|
33
|
+
try {
|
|
34
|
+
if (typeof dispose === 'function') dispose()
|
|
35
|
+
} catch (error) {
|
|
36
|
+
console.error('[injection-manager] disposer failed', error)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
disposers.clear()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function remember(agent, dispose) {
|
|
44
|
+
if (typeof dispose !== 'function') return
|
|
45
|
+
const key = typeof agent.id === 'string' ? agent.id : 'unknown'
|
|
46
|
+
const list = disposers.get(key) ?? []
|
|
47
|
+
list.push(dispose)
|
|
48
|
+
disposers.set(key, list)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Wait for a declared-dependency child context, without hanging forever. */
|
|
52
|
+
function withScope(agentCtx, deps, run) {
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
let settled = false
|
|
55
|
+
let timer
|
|
56
|
+
|
|
57
|
+
const finish = (error) => {
|
|
58
|
+
if (settled) return
|
|
59
|
+
settled = true
|
|
60
|
+
if (timer !== undefined) clearTimeout(timer)
|
|
61
|
+
if (error === undefined) resolve()
|
|
62
|
+
else reject(error)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
try {
|
|
66
|
+
agentCtx.inject(deps, (scoped) => {
|
|
67
|
+
try {
|
|
68
|
+
run(scoped)
|
|
69
|
+
finish()
|
|
70
|
+
} catch (error) {
|
|
71
|
+
finish(error)
|
|
72
|
+
}
|
|
73
|
+
return () => {}
|
|
74
|
+
})
|
|
75
|
+
} catch (error) {
|
|
76
|
+
finish(error)
|
|
77
|
+
return
|
|
78
|
+
}
|
|
79
|
+
timer = setTimeout(() => finish(new Error('scoped dependencies did not resolve within 2000ms')), 2000)
|
|
80
|
+
})
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Apply one already-built snapshot (same numbers the panel shows). */
|
|
84
|
+
async function applySnapshotPolicy(agent, snapshot, report) {
|
|
85
|
+
const policy = snapshot.policy
|
|
86
|
+
const excluded = policy.preview.excluded
|
|
87
|
+
const prefix = policy.prompt.prefix.trim()
|
|
88
|
+
const suffix = policy.prompt.suffix.trim()
|
|
89
|
+
|
|
90
|
+
const sectionsOff = new Set(excluded.sections ?? [])
|
|
91
|
+
if (prefix.length > 0) sectionsOff.delete('deployment:persona-prefix')
|
|
92
|
+
if (suffix.length > 0) sectionsOff.delete('deployment:persona-suffix')
|
|
93
|
+
|
|
94
|
+
const contextsOff = new Set(excluded.contexts ?? [])
|
|
95
|
+
const skillsOff = excluded.skills ?? []
|
|
96
|
+
const toolsOff = excluded.tools ?? []
|
|
97
|
+
|
|
98
|
+
const rewrite = async (assembly, context, next) => {
|
|
99
|
+
// Cordis may pass (payload, next) or (payload, context, next) depending on
|
|
100
|
+
// the waterfall's arity; accept both instead of crashing a session's first
|
|
101
|
+
// prompt over a signature detail.
|
|
102
|
+
const proceed = typeof next === 'function' ? next : context
|
|
103
|
+
const resolved = await proceed()
|
|
104
|
+
rewriteCount += 1
|
|
105
|
+
const before = { sections: (resolved.sections ?? []).length, contexts: (resolved.contexts ?? []).length }
|
|
106
|
+
const out = { ...resolved }
|
|
107
|
+
out.sections = (resolved.sections ?? [])
|
|
108
|
+
.filter((section) => !sectionsOff.has(section?.name))
|
|
109
|
+
.map((section) => {
|
|
110
|
+
if (prefix.length > 0 && section?.name === 'deployment:persona-prefix') {
|
|
111
|
+
return { ...section, text: prefix, interpolate: false }
|
|
112
|
+
}
|
|
113
|
+
if (suffix.length > 0 && section?.name === 'deployment:persona-suffix') {
|
|
114
|
+
return { ...section, text: suffix, interpolate: false }
|
|
115
|
+
}
|
|
116
|
+
return section
|
|
117
|
+
})
|
|
118
|
+
// A custom prefix/suffix also works when the deployment has no persona
|
|
119
|
+
// section registered at all.
|
|
120
|
+
const has = (name) => out.sections.some((section) => section?.name === name)
|
|
121
|
+
if (prefix.length > 0 && !has('deployment:persona-prefix')) {
|
|
122
|
+
out.sections = [{ name: 'deployment:persona-prefix', order: 0, text: prefix, interpolate: false }, ...out.sections]
|
|
123
|
+
}
|
|
124
|
+
if (suffix.length > 0 && !has('deployment:persona-suffix')) {
|
|
125
|
+
out.sections = [...out.sections, { name: 'deployment:persona-suffix', order: 10200, text: suffix, interpolate: false }]
|
|
126
|
+
}
|
|
127
|
+
out.contexts = (resolved.contexts ?? []).filter((context) => !contextsOff.has(context?.name))
|
|
128
|
+
lastRewrite = {
|
|
129
|
+
at: Date.now(),
|
|
130
|
+
before,
|
|
131
|
+
after: { sections: out.sections.length, contexts: out.contexts.length },
|
|
132
|
+
agent: typeof agent.id === 'string' ? agent.id : undefined,
|
|
133
|
+
}
|
|
134
|
+
return out
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The waterfall must be registered on the agent's own context: dispatch is
|
|
138
|
+
// scope-filtered, so this listener runs for this agent only.
|
|
139
|
+
remember(agent, agent.ctx.on('system-prompt/assemble', rewrite))
|
|
140
|
+
|
|
141
|
+
await withScope(agent.ctx, ['tools', 'skills'], (scoped) => {
|
|
142
|
+
const applied = {
|
|
143
|
+
sections: [...sectionsOff],
|
|
144
|
+
customPrefix: prefix.length > 0,
|
|
145
|
+
customSuffix: suffix.length > 0,
|
|
146
|
+
contexts: [...contextsOff],
|
|
147
|
+
skills: [],
|
|
148
|
+
tools: [],
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
for (const name of skillsOff) {
|
|
152
|
+
// A same-name runtime skill in the agent layer wins over the global
|
|
153
|
+
// catalog entry and is not model-invocable, so the catalog drops it.
|
|
154
|
+
remember(
|
|
155
|
+
agent,
|
|
156
|
+
scoped.skills.register({
|
|
157
|
+
name,
|
|
158
|
+
description: 'hidden by dsh-injection-manager policy',
|
|
159
|
+
content: '',
|
|
160
|
+
source: 'runtime',
|
|
161
|
+
invocation: { modelInvocable: false, userInvocable: false },
|
|
162
|
+
}),
|
|
163
|
+
)
|
|
164
|
+
applied.skills.push(name)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (toolsOff.length > 0) {
|
|
168
|
+
// Deny the exact names that exist right now; an unknown name throws.
|
|
169
|
+
remember(agent, scoped.tools.restrict({ deny: toolsOff }))
|
|
170
|
+
applied.tools.push(...toolsOff)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
report.applied = applied
|
|
174
|
+
report.counts = countChannelState(snapshot.items, snapshot.policy)
|
|
175
|
+
})
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Entry point for `agent/created`.
|
|
180
|
+
* Only fresh sessions are touched: resume and compact already carry a prompt
|
|
181
|
+
* and history, and rewriting those mid-flight is not what a default policy
|
|
182
|
+
* means.
|
|
183
|
+
*/
|
|
184
|
+
export async function applyPolicyForAgent(ctx, agent, source) {
|
|
185
|
+
if (agent === undefined || agent === null) return
|
|
186
|
+
const report = {
|
|
187
|
+
at: Date.now(),
|
|
188
|
+
sessionId: typeof agent.id === 'string' ? agent.id : '(unknown)',
|
|
189
|
+
source,
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (appliedAgents.has(agent)) return
|
|
193
|
+
if (source !== 'startup' && source !== 'clear') {
|
|
194
|
+
report.skipped = `source=${source}: policy applies to new sessions only`
|
|
195
|
+
setLastApplication({ at: Date.now(), report })
|
|
196
|
+
return
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
const snapshot = await buildSnapshot(ctx, agent, 'policy', undefined)
|
|
201
|
+
await applySnapshotPolicy(agent, snapshot, report)
|
|
202
|
+
report.projectedTokens = snapshot.policy.preview.after
|
|
203
|
+
report.savedTokens = snapshot.policy.preview.savedTokens
|
|
204
|
+
appliedAgents.add(agent)
|
|
205
|
+
console.info('[injection-manager] policy applied', report)
|
|
206
|
+
} catch (error) {
|
|
207
|
+
report.error = String(error?.message ?? error)
|
|
208
|
+
console.error('[injection-manager] policy apply failed', report, error)
|
|
209
|
+
} finally {
|
|
210
|
+
setLastApplication({ at: Date.now(), report })
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Persist a policy computed elsewhere (preset, budget plan, panel action).
|
|
216
|
+
* `meta` describes the event row for the insights feed; the write itself is
|
|
217
|
+
* unchanged, so a missing/odd meta can never block a policy save.
|
|
218
|
+
*/
|
|
219
|
+
export async function savePolicy(policy, meta = {}) {
|
|
220
|
+
const written = await writePolicy(policy)
|
|
221
|
+
console.info('[injection-manager] policy saved', { path: written.path })
|
|
222
|
+
await appendEvent({
|
|
223
|
+
sessionId: typeof meta?.sessionId === 'string' ? meta.sessionId : undefined,
|
|
224
|
+
kind: typeof meta?.kind === 'string' ? meta.kind : 'policy-saved',
|
|
225
|
+
params: meta?.params !== null && typeof meta?.params === 'object' ? meta.params : {},
|
|
226
|
+
tokensDelta: Number.isFinite(meta?.tokensDelta) ? meta.tokensDelta : 0,
|
|
227
|
+
dedupeKey: typeof meta?.dedupeKey === 'string' ? meta.dedupeKey : undefined,
|
|
228
|
+
})
|
|
229
|
+
return written.policy
|
|
230
|
+
}
|