dsh-disk-cleanup 0.0.0-stage → 0.3.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/README.md +113 -2
- package/cordis.patch.yml +24 -0
- package/icon.svg +11 -0
- package/lib/acl.js +122 -0
- package/lib/cleanup.js +207 -0
- package/lib/client.js +194 -0
- package/lib/config.js +116 -0
- package/lib/index.d.ts +33 -0
- package/lib/index.js +434 -0
- package/lib/prompt.js +23 -0
- package/lib/schema.js +125 -0
- package/lib/scratch.js +57 -0
- package/lib/shell-env.js +90 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +85 -4
package/lib/config.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 配置字段、默认值与归一化。
|
|
3
|
+
*
|
|
4
|
+
* 默认值手写一份,schema 只负责设置页表单:包解析不到时 schema 是空壳,
|
|
5
|
+
* 配置就全靠这份手写默认值,两处不一致会让人以为改坏了。
|
|
6
|
+
* @module dsh-disk-cleanup/config
|
|
7
|
+
*/
|
|
8
|
+
import { z } from './schema.js'
|
|
9
|
+
|
|
10
|
+
/** 保留天数下限。 */
|
|
11
|
+
export const MAX_AGE_MIN = 1
|
|
12
|
+
/** 保留天数上限。 */
|
|
13
|
+
export const MAX_AGE_MAX = 365
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 配置 schema,宿主用它渲染设置页表单。
|
|
17
|
+
* 标了 volatile 的字段改完立即生效,不必重载插件。
|
|
18
|
+
*/
|
|
19
|
+
export const Config = z.object({
|
|
20
|
+
enabled: z.boolean().default(true).description('启用插件:注入临时目录、补齐写权限、注入系统提示'),
|
|
21
|
+
scratchDir: z.string().default('').description('scratch 目录;留空用 <DSH_HOME>/cache/scratch'),
|
|
22
|
+
injectShellTemp: z.boolean().default(true).description('把 pwsh / bash 的 TMP / TEMP / TMPDIR 指向 scratch'),
|
|
23
|
+
grantProcessWrite: z.boolean().default(true).description('Windows 上给 scratch 补访问控制项,让受限子进程也能写'),
|
|
24
|
+
promptSection: z.boolean().default(true).description('往系统提示里加一段临时文件落点说明'),
|
|
25
|
+
autoCleanup: z.boolean().default(true).volatile().description('启动时清掉过期的临时文件与残留的空目录'),
|
|
26
|
+
cleanupMaxAgeDays: z.number().step(1).min(MAX_AGE_MIN).max(MAX_AGE_MAX).default(7).volatile()
|
|
27
|
+
.description('保留天数:scratch 里超过这么多天没改动过的条目会被删除'),
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 默认配置。
|
|
32
|
+
*
|
|
33
|
+
* 从 schema 推出来,不另抄一份:两处各写一遍迟早会走样。
|
|
34
|
+
* 标了 volatile 的字段被 schema 包成取值代理,这里统一解成普通值。
|
|
35
|
+
*/
|
|
36
|
+
export const DEFAULT_CONFIG = fallbackDefaults()
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 默认值。
|
|
40
|
+
*
|
|
41
|
+
* 拿得到 schema 就从 schema 取,取不到(插件被单独安装、找不到平台包)就用这份
|
|
42
|
+
* 手写值兜底,两边的取值必须一致,测试会盯着。
|
|
43
|
+
* @returns {Readonly<object>} 默认配置。
|
|
44
|
+
*/
|
|
45
|
+
function fallbackDefaults() {
|
|
46
|
+
const fromSchema = Config({})
|
|
47
|
+
const schemaReady = fromSchema !== null && typeof fromSchema === 'object'
|
|
48
|
+
&& Object.keys(fromSchema).length > 0
|
|
49
|
+
return Object.freeze(schemaReady ? normalize(fromSchema) : {
|
|
50
|
+
enabled: true,
|
|
51
|
+
scratchDir: '',
|
|
52
|
+
injectShellTemp: true,
|
|
53
|
+
grantProcessWrite: true,
|
|
54
|
+
promptSection: true,
|
|
55
|
+
autoCleanup: true,
|
|
56
|
+
cleanupMaxAgeDays: 7,
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 把 schema 解析结果里的 volatile 代理解成普通值。
|
|
62
|
+
* @param {object} input - Schema 解析结果。
|
|
63
|
+
* @returns {object} 全为普通值的配置。
|
|
64
|
+
*/
|
|
65
|
+
function normalize(input) {
|
|
66
|
+
const plain = (value) => {
|
|
67
|
+
if (!isVolatile(value)) return value
|
|
68
|
+
try {
|
|
69
|
+
return Reflect.apply(value.get, value, [])
|
|
70
|
+
} catch {
|
|
71
|
+
return undefined
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return Object.fromEntries(Object.entries(input).map(([key, value]) => [key, plain(value)]))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 判断是不是 volatile 代理。
|
|
79
|
+
* @param {unknown} value - 待判断的值。
|
|
80
|
+
* @returns {boolean} 是代理时为 true。
|
|
81
|
+
*/
|
|
82
|
+
function isVolatile(value) {
|
|
83
|
+
// volatile 值的形状是「只有一个 get 的普通对象」,没有 set / watch。
|
|
84
|
+
return value !== null && typeof value === 'object' && typeof value.get === 'function'
|
|
85
|
+
&& Object.getOwnPropertyNames(value).join() === 'get'
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* 把用户配置合并到默认值上,并做最小校验。
|
|
90
|
+
*
|
|
91
|
+
* 这里再归一一次而不只依赖 schema:cordis.patch.yml 里的 config 是手写的,
|
|
92
|
+
* 类型写错时应当退化到默认值,而不是整条插件启动失败。
|
|
93
|
+
* @param {unknown} raw - cordis.patch.yml 或设置页给出的 config。
|
|
94
|
+
* @returns {typeof DEFAULT_CONFIG} 归一化后的配置。
|
|
95
|
+
*/
|
|
96
|
+
export function resolveConfig(raw) {
|
|
97
|
+
const input = raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}
|
|
98
|
+
const bool = (value, fallback) => (typeof value === 'boolean' ? value : fallback)
|
|
99
|
+
const text = (value, fallback) => (typeof value === 'string' ? value : fallback)
|
|
100
|
+
// 数字与数字字符串都收:设置页写回的是数字,手写 YAML 里写成 "7" 也很常见。
|
|
101
|
+
const requested = typeof input.cleanupMaxAgeDays === 'string' && input.cleanupMaxAgeDays.trim() !== ''
|
|
102
|
+
? Number(input.cleanupMaxAgeDays.trim())
|
|
103
|
+
: input.cleanupMaxAgeDays
|
|
104
|
+
const days = Number.isFinite(requested)
|
|
105
|
+
? Math.min(MAX_AGE_MAX, Math.max(MAX_AGE_MIN, Math.round(requested)))
|
|
106
|
+
: DEFAULT_CONFIG.cleanupMaxAgeDays
|
|
107
|
+
return {
|
|
108
|
+
enabled: bool(input.enabled, DEFAULT_CONFIG.enabled),
|
|
109
|
+
scratchDir: text(input.scratchDir, DEFAULT_CONFIG.scratchDir).trim(),
|
|
110
|
+
injectShellTemp: bool(input.injectShellTemp, DEFAULT_CONFIG.injectShellTemp),
|
|
111
|
+
grantProcessWrite: bool(input.grantProcessWrite, DEFAULT_CONFIG.grantProcessWrite),
|
|
112
|
+
promptSection: bool(input.promptSection, DEFAULT_CONFIG.promptSection),
|
|
113
|
+
autoCleanup: bool(input.autoCleanup, DEFAULT_CONFIG.autoCleanup),
|
|
114
|
+
cleanupMaxAgeDays: days,
|
|
115
|
+
}
|
|
116
|
+
}
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
/** 插件配置(与 `cordis.patch.yml` 里的 config 一致,全部可省略)。 */
|
|
5
|
+
export interface Config {
|
|
6
|
+
/** 关掉整个插件。默认 true。 */
|
|
7
|
+
enabled?: boolean
|
|
8
|
+
/** 自定义 scratch 目录;空串表示用 `<DSH_HOME>/cache/scratch`。 */
|
|
9
|
+
scratchDir?: string
|
|
10
|
+
/** 让 pwsh / bash 的 TMP / TEMP / TMPDIR 指向 scratch。默认 true。 */
|
|
11
|
+
injectShellTemp?: boolean
|
|
12
|
+
/** Windows 上给 scratch 补访问控制项,让受限子进程也能写。默认 true。 */
|
|
13
|
+
grantProcessWrite?: boolean
|
|
14
|
+
/** 往系统提示里加一段说明。默认 true。 */
|
|
15
|
+
promptSection?: boolean
|
|
16
|
+
/** 启动时清掉过期的临时文件与残留的空目录。默认 true。 */
|
|
17
|
+
autoCleanup?: boolean
|
|
18
|
+
/** 保留天数,范围 1–365。默认 7。 */
|
|
19
|
+
cleanupMaxAgeDays?: number
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Cordis 插件身份。 */
|
|
23
|
+
export declare const name: string
|
|
24
|
+
/** 必需服务。 */
|
|
25
|
+
export declare const inject: readonly string[]
|
|
26
|
+
/** 配置 schema:宿主用它渲染设置页表单。 */
|
|
27
|
+
export declare const Config: unknown
|
|
28
|
+
/**
|
|
29
|
+
* 插件入口。
|
|
30
|
+
* @param ctx - 宿主上下文。
|
|
31
|
+
* @param config - 插件配置。
|
|
32
|
+
*/
|
|
33
|
+
export declare function apply(ctx: Context, config?: Config): void
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-disk-cleanup —— 给临时文件一个专用目录。
|
|
3
|
+
*
|
|
4
|
+
* 四条机制:
|
|
5
|
+
* - shell 环境注入:在 pwsh / bash 命令串前把 TMP / TEMP / TMPDIR 指向 scratch,
|
|
6
|
+
* 让脚本里的临时文件默认落在工作区之外。
|
|
7
|
+
* - 权限补齐:会话一创建就给 scratch 追加可写根(文件工具)和访问控制
|
|
8
|
+
* 列表授权(受限子进程),不依赖 shell 命令是否执行。
|
|
9
|
+
* - 系统提示:说明临时文件写 scratch、用户文件留在工作区。
|
|
10
|
+
* - 清理:插件加载时扫一遍 scratch 删掉过期条目与空目录,并清掉 DSH home 下一级的空目录,之后定时检查。
|
|
11
|
+
* @module dsh-disk-cleanup
|
|
12
|
+
*/
|
|
13
|
+
import { Config, resolveConfig } from './config.js'
|
|
14
|
+
import { CLEANUP_INTERVAL_MS, cleanEmptyDirs, cleanScratch, throttled } from './cleanup.js'
|
|
15
|
+
import { dshHome, ensureDir, scratchDirFor, sharedScratchDir } from './scratch.js'
|
|
16
|
+
import { injectShellTemp } from './shell-env.js'
|
|
17
|
+
import { grantProcessWrite, revokeAll } from './acl.js'
|
|
18
|
+
import { scratchPromptText } from './prompt.js'
|
|
19
|
+
|
|
20
|
+
/** Cordis 插件身份(与包名一致)。 */
|
|
21
|
+
export const name = 'dsh-disk-cleanup'
|
|
22
|
+
/** 必需服务:工具注册表与 agent 注册表。 */
|
|
23
|
+
export const inject = ['tools', 'agents']
|
|
24
|
+
|
|
25
|
+
/** 插件配置 schema:宿主用它渲染设置页表单。 */
|
|
26
|
+
export { Config }
|
|
27
|
+
|
|
28
|
+
/** agent → 已装好包装的工具名。用来避免重复注册,也用来记下「当时还没加载」的工具。 */
|
|
29
|
+
const installed = new WeakMap()
|
|
30
|
+
|
|
31
|
+
/** 正在安装中的 agent。注册包装会触发 tools/change,不挡住就会重入、重复注册同一个工具名并抛错。 */
|
|
32
|
+
const installing = new WeakSet()
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 插件入口。
|
|
36
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx - 宿主上下文。
|
|
37
|
+
* @param {unknown} config - cordis.patch.yml 里的 config。
|
|
38
|
+
*/
|
|
39
|
+
export function apply(ctx, config) {
|
|
40
|
+
const cfg = resolveConfig(config)
|
|
41
|
+
if (!cfg.enabled) return
|
|
42
|
+
|
|
43
|
+
/** 可选服务:拿不到就退化(只保留能用的那部分),绝不因此报错。 */
|
|
44
|
+
let sandboxPolicy
|
|
45
|
+
ctx.inject(['sandboxPolicy'], (child) => { sandboxPolicy = child.sandboxPolicy })
|
|
46
|
+
|
|
47
|
+
// 设置页由本插件自己的卡片渲染(客户端半边注册在 plugins.bundle.config 槽),
|
|
48
|
+
// 关掉宿主按 schema 自动生成的那份,免得同一份配置出现两套控件。
|
|
49
|
+
ctx.inject(['settings'], (child) => {
|
|
50
|
+
try {
|
|
51
|
+
child.effect(() => child.settings.configure({ auto: false }, ctx.fiber), 'dsh-disk-cleanup 设置卡片')
|
|
52
|
+
} catch { /* 宿主没有设置服务时保持默认,不影响其余机制 */ }
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 清理入口。插件加载时跑一次,之后每 CLEANUP_INTERVAL_MS 最多再跑一次;
|
|
58
|
+
* 没有常驻定时器,也不落状态文件——进程重启等于重新起算。
|
|
59
|
+
* @returns {Promise<void>}
|
|
60
|
+
*/
|
|
61
|
+
const runCleanup = throttled(CLEANUP_INTERVAL_MS)
|
|
62
|
+
/**
|
|
63
|
+
* 执行一次清理(受节流控制)。
|
|
64
|
+
*
|
|
65
|
+
* 只清共享 scratch:配置里自己指了别处的用户,目录里的东西未必可丢,不替他决定。
|
|
66
|
+
* DSH home 下一级的空目录与 scratch 无关,单独清,只受总开关控制。
|
|
67
|
+
* @returns {Promise<void>}
|
|
68
|
+
*/
|
|
69
|
+
async function cleanup() {
|
|
70
|
+
if (!cfg.autoCleanup) return
|
|
71
|
+
try {
|
|
72
|
+
await runCleanup(async () => {
|
|
73
|
+
if (cfg.scratchDir === '') {
|
|
74
|
+
const scratch = sharedScratchDir()
|
|
75
|
+
await cleanScratch({ dir: scratch, maxAgeDays: cfg.cleanupMaxAgeDays })
|
|
76
|
+
await cleanEmptyDirs({ dir: scratch, recursive: true })
|
|
77
|
+
}
|
|
78
|
+
await cleanEmptyDirs({ dir: dshHome() })
|
|
79
|
+
})
|
|
80
|
+
} catch {
|
|
81
|
+
/* 清理只是收尾,失败了不能连带插件加载失败 */
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* 会话 → 已完成的授权。键里带模式与目录,模式一变就重新授权。
|
|
87
|
+
* @type {WeakMap<object, {key: string, promise: Promise<boolean>}>}
|
|
88
|
+
*/
|
|
89
|
+
const prepared = new WeakMap()
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 会话 → 实际生效的落点。退路可能改掉 scratch 位置,系统提示要跟着改口。
|
|
93
|
+
* @type {WeakMap<object, object>}
|
|
94
|
+
*/
|
|
95
|
+
const effective = new WeakMap()
|
|
96
|
+
|
|
97
|
+
/** session → 已登记过的可写目录,避免同一目录重复注册。 */
|
|
98
|
+
const writableRoots = new WeakMap()
|
|
99
|
+
|
|
100
|
+
/** registerWritableRoot 返回的撤销函数,插件卸载时统一撤销。 */
|
|
101
|
+
const rootDisposers = new Set()
|
|
102
|
+
|
|
103
|
+
/** agent → 已经登记过的目录,避免同一 agent 重复登记。 */
|
|
104
|
+
const agentRoots = new WeakMap()
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 当前驱动链里的会话;工具执行上下文拿不到 agent 时用它兜底。
|
|
108
|
+
* @returns {object | undefined} 会话对象。
|
|
109
|
+
*/
|
|
110
|
+
function currentSession() {
|
|
111
|
+
try {
|
|
112
|
+
return ctx.agents?.currentInitiator?.()?.session
|
|
113
|
+
} catch {
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 取一个可选服务:优先用注入回调拿到的,其次直接问上下文。
|
|
120
|
+
* 注入回调是异步触发的,落点计算可能早于它,所以这里必须能自己取到。
|
|
121
|
+
* @param {string} serviceName - 服务名。
|
|
122
|
+
* @param {unknown} injected - 注入回调里拿到的实例。
|
|
123
|
+
* @returns {unknown} 服务实例,取不到时为 undefined。
|
|
124
|
+
*/
|
|
125
|
+
function service(serviceName, injected) {
|
|
126
|
+
if (injected !== undefined) return injected
|
|
127
|
+
try {
|
|
128
|
+
return typeof ctx.get === 'function' ? ctx.get(serviceName) : undefined
|
|
129
|
+
} catch {
|
|
130
|
+
return undefined
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 读一个会话解析后的沙箱策略。
|
|
136
|
+
* @param {object | undefined} session - 会话对象。
|
|
137
|
+
* @returns {{mode?: string, workspaceRoot?: string}} 策略;取不到时为空对象。
|
|
138
|
+
*/
|
|
139
|
+
function policyFor(session) {
|
|
140
|
+
const policyService = service('sandboxPolicy', sandboxPolicy)
|
|
141
|
+
try {
|
|
142
|
+
return policyService?.resolve({ session }) ?? {}
|
|
143
|
+
} catch {
|
|
144
|
+
return {}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 算出一个会话的落点信息。纯计算,不建目录、不授权。
|
|
150
|
+
*
|
|
151
|
+
* 每次调用都重新读策略:模式可能在会话中途变化,缓存住旧模式会把临时文件
|
|
152
|
+
* 送进当时并不允许写的目录。
|
|
153
|
+
* @param {object | undefined} session - 会话对象。
|
|
154
|
+
* @returns {{mode?: string, workspaceRoot?: string, scratchDir?: string}} 落点信息。
|
|
155
|
+
*/
|
|
156
|
+
function resolveState(session) {
|
|
157
|
+
const policy = policyFor(session)
|
|
158
|
+
const mode = policy.mode
|
|
159
|
+
const workspaceRoot = policy.workspaceRoot ?? session?.header?.cwd
|
|
160
|
+
const state = { mode, workspaceRoot, scratchDir: undefined }
|
|
161
|
+
if (mode === undefined || mode === 'read-only') return state
|
|
162
|
+
|
|
163
|
+
const scratchDir = scratchDirFor({ mode, workspaceRoot, configured: cfg.scratchDir })
|
|
164
|
+
if (scratchDir === undefined) return state
|
|
165
|
+
state.scratchDir = scratchDir
|
|
166
|
+
|
|
167
|
+
return state
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 让一个目录可写:建出来,并补上文件工具与受限子进程各自的权限。
|
|
172
|
+
* @param {object} session - 会话对象。
|
|
173
|
+
* @param {string} mode - 沙箱模式。
|
|
174
|
+
* @param {string | undefined} workspaceRoot - 工作区根。
|
|
175
|
+
* @param {string} dir - 目标目录。
|
|
176
|
+
* @returns {Promise<boolean>} 是否可用。
|
|
177
|
+
*/
|
|
178
|
+
async function makeWritable(session, mode, workspaceRoot, dir) {
|
|
179
|
+
try {
|
|
180
|
+
await ensureDir(dir)
|
|
181
|
+
} catch {
|
|
182
|
+
return false
|
|
183
|
+
}
|
|
184
|
+
// 文件工具的可写根与「是否给子进程补访问控制项」是两件事,分开判断。
|
|
185
|
+
let rooted = true
|
|
186
|
+
const policyService = service('sandboxPolicy', sandboxPolicy)
|
|
187
|
+
try {
|
|
188
|
+
if (typeof policyService?.registerWritableRoot !== 'function') rooted = false
|
|
189
|
+
else {
|
|
190
|
+
let seen = writableRoots.get(session)
|
|
191
|
+
if (seen === undefined) {
|
|
192
|
+
seen = new Set()
|
|
193
|
+
writableRoots.set(session, seen)
|
|
194
|
+
}
|
|
195
|
+
if (!seen.has(dir)) {
|
|
196
|
+
const dispose = policyService.registerWritableRoot(session, dir)
|
|
197
|
+
seen.add(dir)
|
|
198
|
+
if (typeof dispose === 'function') rootDisposers.add(dispose)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
} catch {
|
|
202
|
+
rooted = false
|
|
203
|
+
}
|
|
204
|
+
// 完全权限下没有围栏,不需要给受限子进程补访问控制项。
|
|
205
|
+
if (mode === 'danger-full-access') return rooted
|
|
206
|
+
const processWritable = cfg.grantProcessWrite
|
|
207
|
+
? await grantProcessWrite(workspaceRoot, dir)
|
|
208
|
+
: true
|
|
209
|
+
return rooted && processWritable
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 落实落点:建目录并补权限。首次真正要用时才调用——
|
|
214
|
+
* 会话创建那一刻策略还没落定,提前算会把临时文件送进错误的目录。
|
|
215
|
+
* @param {object | undefined} session - 会话对象。
|
|
216
|
+
* @param {object} state - resolveState 的结果,可能被就地修正为退路目录。
|
|
217
|
+
* @returns {Promise<boolean>} 是否可用。
|
|
218
|
+
*/
|
|
219
|
+
function activate(session, state) {
|
|
220
|
+
if (session === undefined || session === null) return Promise.resolve(false)
|
|
221
|
+
if (state.scratchDir === undefined) return Promise.resolve(false)
|
|
222
|
+
const key = [state.mode, state.scratchDir].join('|')
|
|
223
|
+
const cached = prepared.get(session)
|
|
224
|
+
if (cached !== undefined && cached.key === key) return cached.promise
|
|
225
|
+
const promise = (async () => {
|
|
226
|
+
const dirs = [state.scratchDir]
|
|
227
|
+
let ok = true
|
|
228
|
+
for (const dir of dirs) {
|
|
229
|
+
if (!(await makeWritable(session, state.mode, state.workspaceRoot, dir))) {
|
|
230
|
+
ok = false
|
|
231
|
+
break
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (ok) {
|
|
235
|
+
effective.set(session, state)
|
|
236
|
+
return true
|
|
237
|
+
}
|
|
238
|
+
// 共享目录拿不到权限时退回工作区里的 cache/scratch:至少写入能成。
|
|
239
|
+
if (state.mode !== 'workspace-write' || typeof state.workspaceRoot !== 'string') return false
|
|
240
|
+
const fallback = scratchDirFor({
|
|
241
|
+
mode: state.mode,
|
|
242
|
+
workspaceRoot: state.workspaceRoot,
|
|
243
|
+
configured: cfg.scratchDir,
|
|
244
|
+
sharedCache: false,
|
|
245
|
+
})
|
|
246
|
+
if (fallback === undefined) return false
|
|
247
|
+
if (!(await makeWritable(session, state.mode, state.workspaceRoot, fallback))) return false
|
|
248
|
+
state.scratchDir = fallback
|
|
249
|
+
effective.set(session, state)
|
|
250
|
+
return true
|
|
251
|
+
})()
|
|
252
|
+
prepared.set(session, { key, promise })
|
|
253
|
+
return promise
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 会话创建完成后立即把 scratch 登记为可写目录。
|
|
258
|
+
*
|
|
259
|
+
* 不能等到 shell 命令执行:文件工具(write / edit)不经过 shell 包装,
|
|
260
|
+
* 而 resume / fork 之后原先的登记会失效,agent/created 会再次触发。
|
|
261
|
+
* 登记只是把目录加进可写允许列表,不改变权限模式;明确只读时跳过。
|
|
262
|
+
* @param {object} agent - agent 实例(真实宿主里带 session)。
|
|
263
|
+
* @returns {Promise<boolean>} 是否登记成功。
|
|
264
|
+
*/
|
|
265
|
+
function prepareAgent(agent) {
|
|
266
|
+
const session = agent?.session
|
|
267
|
+
if (session === undefined || session === null) return Promise.resolve(false)
|
|
268
|
+
const policy = policyFor(session)
|
|
269
|
+
if (policy.mode === 'read-only') return Promise.resolve(false)
|
|
270
|
+
const workspaceRoot = policy.workspaceRoot ?? session?.header?.cwd
|
|
271
|
+
// 目录位置与模式无关;只在补访问控制项时区分完全权限(无需给受限进程授权)。
|
|
272
|
+
const mode = policy.mode === 'danger-full-access' ? 'danger-full-access' : 'workspace-write'
|
|
273
|
+
const scratchDir = scratchDirFor({
|
|
274
|
+
mode,
|
|
275
|
+
workspaceRoot,
|
|
276
|
+
configured: cfg.scratchDir,
|
|
277
|
+
})
|
|
278
|
+
if (scratchDir === undefined) return Promise.resolve(false)
|
|
279
|
+
let seen = agentRoots.get(agent)
|
|
280
|
+
if (seen === undefined) {
|
|
281
|
+
seen = new Set()
|
|
282
|
+
agentRoots.set(agent, seen)
|
|
283
|
+
}
|
|
284
|
+
if (seen.has(scratchDir)) return Promise.resolve(true)
|
|
285
|
+
// 不让同一 agent 并发重复走一遍授权;失败则连标记一起撤掉,留给下一次重试。
|
|
286
|
+
const promise = makeWritable(session, mode, workspaceRoot, scratchDir)
|
|
287
|
+
seen.add(scratchDir)
|
|
288
|
+
void promise.then((ok) => { if (!ok) seen.delete(scratchDir) }, () => { seen.delete(scratchDir) })
|
|
289
|
+
return promise
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 包装 shell 工具:在命令串前注入临时目录。
|
|
294
|
+
* @param {object} agentCtx - agent 作用域上下文。
|
|
295
|
+
* @param {'pwsh' | 'bash'} shell - shell 类型。
|
|
296
|
+
* @returns {boolean} 是否注册成功。
|
|
297
|
+
*/
|
|
298
|
+
function wrapShell(agentCtx, shell) {
|
|
299
|
+
if (!cfg.injectShellTemp) return false
|
|
300
|
+
const live = ctx.tools.get(shell)
|
|
301
|
+
if (live === undefined) return false
|
|
302
|
+
agentCtx.tools.register({
|
|
303
|
+
...live,
|
|
304
|
+
async execute(args, exec) {
|
|
305
|
+
const input = args !== null && typeof args === 'object' ? args : {}
|
|
306
|
+
if (typeof input.command !== 'string' || input.command === '') return live.execute(args, exec)
|
|
307
|
+
const execAgent = exec?.agent ?? exec?.caller
|
|
308
|
+
const session = execAgent?.session ?? currentSession()
|
|
309
|
+
const state = resolveState(session)
|
|
310
|
+
if (state.scratchDir === undefined) return live.execute(args, exec)
|
|
311
|
+
if (!(await activate(session, state))) return live.execute(args, exec)
|
|
312
|
+
// activate 成功即保证 scratchDir 有值。
|
|
313
|
+
const command = injectShellTemp(shell, input.command, state.scratchDir)
|
|
314
|
+
if (command === input.command) return live.execute(args, exec)
|
|
315
|
+
return live.execute({ ...input, command }, exec)
|
|
316
|
+
},
|
|
317
|
+
})
|
|
318
|
+
return true
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** 只包装 shell 工具;文件工具的落点由模型自己决定。 */
|
|
322
|
+
const TARGETS = ['pwsh', 'bash']
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* 给一个 agent 装上全部包装;已经装过的跳过。
|
|
326
|
+
* @param {object} agent - agent 实例。
|
|
327
|
+
* @returns {Promise<void>}
|
|
328
|
+
*/
|
|
329
|
+
async function install(agent) {
|
|
330
|
+
if (agent === undefined || agent === null) return
|
|
331
|
+
if (installing.has(agent)) return
|
|
332
|
+
installing.add(agent)
|
|
333
|
+
try {
|
|
334
|
+
await installNow(agent)
|
|
335
|
+
} finally {
|
|
336
|
+
installing.delete(agent)
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* install 的实际内容,由 install 负责重入保护。
|
|
342
|
+
* 目标工具当时还没注册时留待 tools/change 重试,不会永久漏掉。
|
|
343
|
+
* @param {object} agent - agent 实例。
|
|
344
|
+
* @returns {Promise<void>}
|
|
345
|
+
*/
|
|
346
|
+
async function installNow(agent) {
|
|
347
|
+
const agentCtx = agent.ctx
|
|
348
|
+
if (agentCtx === undefined || typeof agentCtx.inject !== 'function') return
|
|
349
|
+
let done = installed.get(agent)
|
|
350
|
+
if (done === undefined) {
|
|
351
|
+
done = new Set()
|
|
352
|
+
installed.set(agent, done)
|
|
353
|
+
}
|
|
354
|
+
const ready = TARGETS.filter(toolName => !done.has(toolName) && ctx.tools.get(toolName) !== undefined)
|
|
355
|
+
if (ready.length === 0) return
|
|
356
|
+
// 真实的 agent 上下文要求先声明依赖才能读 ctx.tools;注册仍落在该 agent 的作用域层。
|
|
357
|
+
await new Promise((resolve) => {
|
|
358
|
+
agentCtx.inject(['tools'], (child) => {
|
|
359
|
+
// 只有真的注册成功才记进 done;目标工具还没出现时留白,等 tools/change 再补。
|
|
360
|
+
for (const toolName of ready) {
|
|
361
|
+
if (wrapShell(child, toolName)) done.add(toolName)
|
|
362
|
+
}
|
|
363
|
+
resolve()
|
|
364
|
+
})
|
|
365
|
+
})
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// agent/created 是串行且被 await 的;返回 Promise 保证输入放行前
|
|
369
|
+
// 包装已装好、scratch 已登记为可写目录。
|
|
370
|
+
ctx.on('agent/created', ({ agent }) =>
|
|
371
|
+
Promise.all([install(agent), prepareAgent(agent)]).then(() => undefined))
|
|
372
|
+
// 工具注册表变化时补装:目标工具可能比本插件晚加载。
|
|
373
|
+
ctx.on('tools/change', () => {
|
|
374
|
+
for (const agent of ctx.agents.list()) {
|
|
375
|
+
void install(agent)
|
|
376
|
+
void prepareAgent(agent)
|
|
377
|
+
}
|
|
378
|
+
})
|
|
379
|
+
for (const agent of ctx.agents.list()) {
|
|
380
|
+
void install(agent)
|
|
381
|
+
void prepareAgent(agent)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// 启动就跑一次清理,之后每 CLEANUP_INTERVAL_MS 再触发一次。
|
|
385
|
+
// 用原生定时器而不是 ctx.interval:后者要注入 cordis 的 timer 服务,
|
|
386
|
+
// 宿主没装就会整个插件起不来,为一次清理不值得。
|
|
387
|
+
// 定时器随插件的 effect 一起清掉,节流器保证两次真正落地间隔不小于间隔值。
|
|
388
|
+
void cleanup()
|
|
389
|
+
ctx.effect(() => {
|
|
390
|
+
const timer = setInterval(() => { void cleanup() }, CLEANUP_INTERVAL_MS)
|
|
391
|
+
// 不阻止进程退出:清理本身不紧急,宿主该退就退。
|
|
392
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
393
|
+
return () => clearInterval(timer)
|
|
394
|
+
})
|
|
395
|
+
|
|
396
|
+
if (cfg.promptSection) {
|
|
397
|
+
ctx.inject(['systemPrompt'], (child) => {
|
|
398
|
+
// 排在 write 工具的说明之后;取不到宿主顺序时用固定兜底值。
|
|
399
|
+
let order = 1201
|
|
400
|
+
try {
|
|
401
|
+
const baseOrder = child.systemPrompt.getSectionOrder('TOOL_WRITE')
|
|
402
|
+
if (Number.isFinite(baseOrder)) order = baseOrder + 1
|
|
403
|
+
} catch {
|
|
404
|
+
/* 宿主未提供顺序表时保留兜底值 */
|
|
405
|
+
}
|
|
406
|
+
child.systemPrompt.section({
|
|
407
|
+
name: 'dsh-disk-cleanup',
|
|
408
|
+
order,
|
|
409
|
+
text: (context) => {
|
|
410
|
+
const session = context?.agent?.session ?? currentSession()
|
|
411
|
+
// 只读会话没有可写落点,讲了也是假的:整段不注入。
|
|
412
|
+
if (policyFor(session).mode === 'read-only') return ''
|
|
413
|
+
const fresh = resolveState(session)
|
|
414
|
+
// 退路可能把 scratch 挪到了工作区,提示要跟着改口;但模式变了(比如切成只读)就先以新模式为准。
|
|
415
|
+
const applied = session === undefined ? undefined : effective.get(session)
|
|
416
|
+
const state = fresh.scratchDir === undefined ? fresh : applied ?? fresh
|
|
417
|
+
return scratchPromptText({ scratchDir: state.scratchDir })
|
|
418
|
+
},
|
|
419
|
+
})
|
|
420
|
+
})
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// 插件卸载时撤销可写根登记、释放授权对象。目录上的访问控制项是 standing 的,
|
|
424
|
+
// 留着给之后的会话复用——撤销了下一个会话就会被挡住。
|
|
425
|
+
if (typeof ctx.effect === 'function') {
|
|
426
|
+
ctx.effect(() => () => {
|
|
427
|
+
for (const dispose of rootDisposers) {
|
|
428
|
+
try { dispose() } catch { /* 单个撤销失败不阻塞其余 */ }
|
|
429
|
+
}
|
|
430
|
+
rootDisposers.clear()
|
|
431
|
+
revokeAll()
|
|
432
|
+
})
|
|
433
|
+
}
|
|
434
|
+
}
|
package/lib/prompt.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 系统提示里那一段说明(软约束,配合硬机制用)。
|
|
3
|
+
* @module dsh-disk-cleanup/prompt
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 生成提示文本。
|
|
8
|
+
*
|
|
9
|
+
* 只说「写哪里」和「为什么别放工作区」,不解释保留天数、定时器这类内部策略:
|
|
10
|
+
* 模型既改不了也用不上,写进提示只是噪音。
|
|
11
|
+
* @param {object} options - 生成输入。
|
|
12
|
+
* @param {string} [options.scratchDir] - 当前会话的 scratch 目录。
|
|
13
|
+
* @returns {string} 一段提示。
|
|
14
|
+
*/
|
|
15
|
+
export function scratchPromptText({ scratchDir } = {}) {
|
|
16
|
+
const lines = [
|
|
17
|
+
'Write temporary files (probe scripts, one-off checks, scratch drafts) to the scratch directory'
|
|
18
|
+
+ (scratchDir === undefined ? '' : ` (${scratchDir})`)
|
|
19
|
+
+ ': the shell\'s TMP/TEMP point there, and these files may be cleaned up later.',
|
|
20
|
+
'Files the user asked for stay in the workspace: give them a real relative path (for example src/main.ts or report.md) and they are written exactly where you say.',
|
|
21
|
+
]
|
|
22
|
+
return lines.join(' ')
|
|
23
|
+
}
|