@xi4z/dsh-utils 0.5.0 → 0.7.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.
Files changed (59) hide show
  1. package/README.md +99 -104
  2. package/cordis.patch.yml +36 -37
  3. package/lib/index.d.ts +5 -63
  4. package/lib/index.js +6 -859
  5. package/lib/index.js.map +1 -1
  6. package/locale/en.json +1 -1
  7. package/locale/zh.json +1 -1
  8. package/package.json +10 -46
  9. package/src/index.ts +6 -927
  10. package/client.js +0 -2330
  11. package/lib/ui-host.d.ts +0 -96
  12. package/lib/ui-host.js +0 -970
  13. package/lib/ui-host.js.map +0 -1
  14. package/packages/approval-policy/lib/index.d.ts +0 -297
  15. package/packages/approval-policy/lib/index.js +0 -425
  16. package/packages/approval-policy/lib/index.js.map +0 -1
  17. package/packages/approval-policy/locale/en.json +0 -6
  18. package/packages/approval-policy/locale/zh.json +0 -6
  19. package/packages/notify/lib/index.d.ts +0 -290
  20. package/packages/notify/lib/index.js +0 -915
  21. package/packages/notify/lib/index.js.map +0 -1
  22. package/packages/notify/locale/en.json +0 -6
  23. package/packages/notify/locale/zh.json +0 -6
  24. package/packages/skill-panel/lib/index.d.ts +0 -49
  25. package/packages/skill-panel/lib/index.js +0 -420
  26. package/packages/skill-panel/lib/index.js.map +0 -1
  27. package/packages/skill-panel/locale/en.json +0 -6
  28. package/packages/skill-panel/locale/zh.json +0 -6
  29. package/packages/utils-agents/lib/git.d.ts +0 -87
  30. package/packages/utils-agents/lib/git.js +0 -403
  31. package/packages/utils-agents/lib/git.js.map +0 -1
  32. package/packages/utils-agents/lib/global-repo.d.ts +0 -57
  33. package/packages/utils-agents/lib/global-repo.js +0 -301
  34. package/packages/utils-agents/lib/global-repo.js.map +0 -1
  35. package/packages/utils-agents/lib/index.d.ts +0 -80
  36. package/packages/utils-agents/lib/index.js +0 -435
  37. package/packages/utils-agents/lib/index.js.map +0 -1
  38. package/packages/utils-agents/lib/legacy.d.ts +0 -30
  39. package/packages/utils-agents/lib/legacy.js +0 -141
  40. package/packages/utils-agents/lib/legacy.js.map +0 -1
  41. package/packages/utils-agents/lib/native.d.ts +0 -74
  42. package/packages/utils-agents/lib/native.js +0 -232
  43. package/packages/utils-agents/lib/native.js.map +0 -1
  44. package/packages/utils-agents/lib/presets.d.ts +0 -34
  45. package/packages/utils-agents/lib/presets.js +0 -312
  46. package/packages/utils-agents/lib/presets.js.map +0 -1
  47. package/packages/utils-agents/lib/shared.d.ts +0 -105
  48. package/packages/utils-agents/lib/shared.js +0 -507
  49. package/packages/utils-agents/lib/shared.js.map +0 -1
  50. package/packages/utils-agents/lib/update.d.ts +0 -129
  51. package/packages/utils-agents/lib/update.js +0 -507
  52. package/packages/utils-agents/lib/update.js.map +0 -1
  53. package/packages/utils-agents/lib/util.d.ts +0 -215
  54. package/packages/utils-agents/lib/util.js +0 -475
  55. package/packages/utils-agents/lib/util.js.map +0 -1
  56. package/packages/utils-agents/locale/en.json +0 -6
  57. package/packages/utils-agents/locale/zh.json +0 -6
  58. package/skills/dsh-approval-policy-config/SKILL.md +0 -96
  59. package/src/ui-host.ts +0 -1073
@@ -1,215 +0,0 @@
1
- /**
2
- * Shared utilities for the utils-agents panel.
3
- *
4
- * This component merges three former sidebar surfaces:
5
- * the preset skill list, the per-preset Git skill repository, and the Markdown
6
- * editor. All filesystem access is funneled through the helpers here so the
7
- * route handlers can stay small and the path rules stay in one place.
8
- *
9
- * @module dsh-utils/utils-agents/util
10
- */
11
- import type { Context } from '@deepseek-ai/cordis';
12
- /** Absolute ceiling for one request body. */
13
- export declare const BODY_LIMIT_BYTES: number;
14
- /** Default per-file read/write limit. */
15
- export declare const DEFAULT_MAX_BYTES: number;
16
- /** The pseudo preset that edits the user/project AGENTS.md chain. */
17
- export declare const GLOBAL_PRESET = "__global__";
18
- /** Directory names never entered while scanning preset Markdown or skills. */
19
- export declare const IGNORED_DIRS: Set<string>;
20
- /** Project-level instruction file names, matching the shipped loader. */
21
- export declare const AGENTS_CANDIDATES: readonly ["AGENTS.md", "CLAUDE.md", "AGENTS.local.md", "CLAUDE.local.md"];
22
- /** Volatile Config fields arrive as live references; get() snapshots. */
23
- export interface VolatileRef<T> {
24
- get(): T;
25
- }
26
- /** One setting as the Loader supplies it: a live reference, or a plain value in tests. */
27
- export type MaybeRef<T> = T | VolatileRef<T>;
28
- /** Raw row config accepted by the component. */
29
- export interface AgentsConfig {
30
- readonly maxBytes?: MaybeRef<number>;
31
- readonly presetDirs?: MaybeRef<readonly string[]>;
32
- readonly presetSourceDirs?: MaybeRef<readonly string[]>;
33
- readonly builtinPresets?: MaybeRef<readonly string[]>;
34
- readonly extraAgentsFiles?: MaybeRef<readonly string[]>;
35
- readonly scanNestedAgents?: MaybeRef<boolean>;
36
- readonly nestedDepth?: MaybeRef<number>;
37
- readonly defaultRepoUrl?: MaybeRef<string>;
38
- readonly defaultBranch?: MaybeRef<string>;
39
- readonly updateCheck?: MaybeRef<boolean>;
40
- readonly updateCheckIntervalHours?: MaybeRef<number>;
41
- readonly updateRegistry?: MaybeRef<string>;
42
- readonly updateAutoInstall?: MaybeRef<boolean>;
43
- }
44
- /** Normalized settings with defaults applied. */
45
- export interface Options {
46
- readonly maxBytes: number;
47
- readonly presetDirs: string[];
48
- readonly presetSourceDirs: string[];
49
- readonly builtinPresets: string[];
50
- readonly extraAgentsFiles: string[];
51
- readonly scanNestedAgents: boolean;
52
- readonly nestedDepth: number;
53
- readonly defaultRepoUrl: string;
54
- readonly defaultBranch: string;
55
- readonly updateCheck: boolean;
56
- readonly updateCheckIntervalHours: number;
57
- readonly updateRegistry: string;
58
- readonly updateAutoInstall: boolean;
59
- }
60
- /** One command failure with the HTTP status it should answer with. */
61
- export declare class AgentsError extends Error {
62
- readonly status: number;
63
- /**
64
- * @param message - user-facing, sanitized message.
65
- * @param status - HTTP status the route answers with.
66
- */
67
- constructor(message: string, status: number);
68
- }
69
- /** One skill inside a preset skills directory. */
70
- export interface SkillRow {
71
- readonly name: string;
72
- readonly description: string;
73
- readonly path: string;
74
- readonly enabled: boolean;
75
- readonly size: number;
76
- readonly mtimeMs: number | null;
77
- }
78
- /** One file the Markdown view can open. */
79
- export interface FileRow {
80
- readonly id: string;
81
- readonly label: string;
82
- readonly path: string;
83
- readonly presetId: string;
84
- readonly kind: 'agents' | 'skill' | 'reference' | 'global';
85
- readonly scope?: string;
86
- readonly exists: boolean;
87
- readonly editable: boolean;
88
- readonly size: number;
89
- readonly mtimeMs: number | null;
90
- }
91
- /** One preset directory as the panel lists it. */
92
- export interface PresetInfo {
93
- readonly id: string;
94
- readonly name: string;
95
- readonly description: string;
96
- readonly path: string;
97
- readonly skills: SkillRow[];
98
- readonly agents: FileRow;
99
- readonly registered?: boolean;
100
- readonly broken?: string;
101
- }
102
- /** One recorded sync attempt. */
103
- export interface SyncRecord {
104
- readonly at: string;
105
- readonly ok: boolean;
106
- readonly commit: string;
107
- readonly skills: number;
108
- readonly message: string;
109
- }
110
- /** Durable per-preset repository configuration. */
111
- export interface RepoState {
112
- repoUrl: string;
113
- branch: string;
114
- targetSubdir: string;
115
- keyPath: string;
116
- recurseSubmodules: boolean;
117
- lastSync: SyncRecord | null;
118
- }
119
- /** The target checkout as the repo view reports it. */
120
- export interface TargetStatus {
121
- exists: boolean;
122
- isRepo: boolean;
123
- branch: string | null;
124
- commit: string | null;
125
- dirty: boolean;
126
- skills: number;
127
- }
128
- /** Normalize the volatile row settings once per request. */
129
- export declare function normalizeOptions(config: AgentsConfig | undefined): Options;
130
- /** npm registry asked for the published version of this bundle. */
131
- export declare const DEFAULT_UPDATE_REGISTRY = "https://registry.npmjs.org";
132
- /** Hours between two automatic published-version checks. */
133
- export declare const DEFAULT_UPDATE_INTERVAL_HOURS = 6;
134
- /** Upper bound for the automatic check interval. */
135
- export declare const MAX_UPDATE_INTERVAL_HOURS = 168;
136
- /**
137
- * Snapshot one live Config field.
138
- * @param value - plain value or volatile reference.
139
- * @param fallback - default.
140
- * @returns the plain value.
141
- */
142
- export declare function refValue<T>(value: MaybeRef<T> | undefined, fallback: T): T;
143
- /** Trim, drop empty entries, and de-duplicate one string list. */
144
- export declare function stringList(value: unknown): string[];
145
- /** $DSH_HOME, falling back to ~/.dsh. */
146
- export declare function dshHome(): string;
147
- /** $DSH_AGENTS_HOME, falling back to ~/.agents. */
148
- export declare function agentsHome(): string;
149
- /** $DSH_HOME/storages/dsh-utils-agents. */
150
- export declare function agentsStorageDir(): string;
151
- /** All configured preset roots, defaults first. */
152
- export declare function presetRoots(options: Options): string[];
153
- /** Stable storage name for one preset id. */
154
- export declare function presetStorageName(id: string): string;
155
- /**
156
- * Expand a configured path to an absolute path.
157
- * @param raw - configured value; ~ and $VAR / braced VAR are expanded.
158
- * @returns absolute path.
159
- */
160
- export declare function expandAbsolute(raw: string): string;
161
- /** Join a relative path under a root and refuse escapes. */
162
- export declare function insideJoin(root: string, rel: string): string;
163
- /** Whether a path is strictly inside a directory. */
164
- export declare function isInside(parent: string, child: string): boolean;
165
- /** Whether a directory exists and is a directory. */
166
- export declare function directoryOf(path: string): Promise<boolean>;
167
- /** Whether any path exists (file, directory, or symlink). */
168
- export declare function exists(path: string): Promise<boolean>;
169
- /** Recursively collect paths under one directory with a depth bound. */
170
- export declare function walkFiles(dir: string, depth: number, ignored: Set<string>, visit: (path: string) => void, ctx: Context): Promise<void>;
171
- /** Build one file row for an existing or missing path. */
172
- export declare function fileRow(id: string, label: string, path: string, presetId: string, kind: FileRow['kind']): Promise<FileRow>;
173
- /** Read one file, refusing oversized files and non-regular files. */
174
- export declare function readTextFile(path: string, maxBytes: number): Promise<{
175
- content: string;
176
- row: FileRow;
177
- }>;
178
- /**
179
- * Write one file atomically, preserving mode and detecting a stale browser
180
- * copy. A missing file is created when baseMtimeMs is null.
181
- */
182
- export declare function writeTextFile(path: string, content: string, baseMtimeMs: number | null, maxBytes: number): Promise<{
183
- bytes: number;
184
- mtimeMs: number | null;
185
- }>;
186
- /** Parse one buffered JSON request body, with a size cap. */
187
- export declare function readJsonBody(request: Request): Promise<unknown>;
188
- /** Trimmed non-empty text, or null. */
189
- export declare function optionalText(value: string | null | undefined): string | null;
190
- /** Required trimmed text. */
191
- export declare function requiredText(value: unknown, message: string): string;
192
- /** Build one JSON response. */
193
- export declare function json(value: unknown, status: number): Response;
194
- /** Map an error to the route's JSON failure shape. */
195
- export declare function failure(ctx: Context, action: string, error: unknown): Response;
196
- /** Render an unknown error for a log line or route payload. */
197
- export declare function errorMessage(error: unknown): string;
198
- /** Resolve the session working directory with the same fallbacks as the skill panel. */
199
- export declare function resolveCwd(ctx: Context, sessionId: string | null, signal: AbortSignal): Promise<string>;
200
- /** The preset id recorded on the live session, when the host exposes it. */
201
- export declare function sessionPresetOf(ctx: Context, sessionId: string | null): string | null;
202
- /** Read one host service defensively. */
203
- export declare function serviceOf(ctx: Context, name: string): Record<string, any> | undefined;
204
- /** Resolve a live Agent for a session id. */
205
- export declare function agentOf(ctx: Context, sessionId: string): Record<string, any> | undefined;
206
- /** Project root: the nearest ancestor holding .git, else the working directory. */
207
- export declare function findProjectRoot(cwd: string): Promise<string>;
208
- /** Directories from the project root down to the working directory. */
209
- export declare function projectChain(root: string, cwd: string): string[];
210
- /** Human-readable scope label for one directory. */
211
- export declare function scopeOf(dir: string, cwd: string, root: string): string;
212
- /** Base64url encode one id component. */
213
- export declare function encodeIdPart(value: string): string;
214
- /** Decode one id component, rejecting non-canonical spellings. */
215
- export declare function decodeIdPart(value: string): string;
@@ -1,475 +0,0 @@
1
- /**
2
- * Shared utilities for the utils-agents panel.
3
- *
4
- * This component merges three former sidebar surfaces:
5
- * the preset skill list, the per-preset Git skill repository, and the Markdown
6
- * editor. All filesystem access is funneled through the helpers here so the
7
- * route handlers can stay small and the path rules stay in one place.
8
- *
9
- * @module dsh-utils/utils-agents/util
10
- */
11
- import { randomBytes } from 'node:crypto';
12
- import { lstat, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
13
- import { homedir } from 'node:os';
14
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
15
- /** Absolute ceiling for one request body. */
16
- export const BODY_LIMIT_BYTES = 8 * 1024 * 1024;
17
- /** Default per-file read/write limit. */
18
- export const DEFAULT_MAX_BYTES = 512 * 1024;
19
- /** The pseudo preset that edits the user/project AGENTS.md chain. */
20
- export const GLOBAL_PRESET = '__global__';
21
- /** Directory names never entered while scanning preset Markdown or skills. */
22
- export const IGNORED_DIRS = new Set(['.git', 'node_modules', '.temp', '.tmp', 'dist', 'build', 'target', '.venv', 'venv', '__pycache__', '.dsh-utils']);
23
- /** Project-level instruction file names, matching the shipped loader. */
24
- export const AGENTS_CANDIDATES = ['AGENTS.md', 'CLAUDE.md', 'AGENTS.local.md', 'CLAUDE.local.md'];
25
- /** One command failure with the HTTP status it should answer with. */
26
- export class AgentsError extends Error {
27
- status;
28
- /**
29
- * @param message - user-facing, sanitized message.
30
- * @param status - HTTP status the route answers with.
31
- */
32
- constructor(message, status) {
33
- super(message);
34
- this.name = 'AgentsError';
35
- this.status = status;
36
- }
37
- }
38
- /** Normalize the volatile row settings once per request. */
39
- export function normalizeOptions(config) {
40
- return {
41
- maxBytes: clamp(refValue(config?.maxBytes, DEFAULT_MAX_BYTES), 1024, BODY_LIMIT_BYTES),
42
- presetDirs: stringList(refValue(config?.presetDirs, [])),
43
- presetSourceDirs: stringList(refValue(config?.presetSourceDirs, [])),
44
- builtinPresets: stringList(refValue(config?.builtinPresets, ['standard', 'ptc', 'minimal', 'creator'])),
45
- extraAgentsFiles: stringList(refValue(config?.extraAgentsFiles, [])),
46
- scanNestedAgents: refValue(config?.scanNestedAgents, false) === true,
47
- nestedDepth: clamp(refValue(config?.nestedDepth, 3), 1, 8),
48
- defaultRepoUrl: stringValue(refValue(config?.defaultRepoUrl, 'https://github.com/xi4z/skills'), 'https://github.com/xi4z/skills'),
49
- defaultBranch: stringValue(refValue(config?.defaultBranch, 'Agent'), 'Agent'),
50
- updateCheck: refValue(config?.updateCheck, true) === true,
51
- updateCheckIntervalHours: clamp(refValue(config?.updateCheckIntervalHours, DEFAULT_UPDATE_INTERVAL_HOURS), 1, MAX_UPDATE_INTERVAL_HOURS),
52
- updateRegistry: registryValue(refValue(config?.updateRegistry, DEFAULT_UPDATE_REGISTRY)),
53
- updateAutoInstall: refValue(config?.updateAutoInstall, true) === true,
54
- };
55
- }
56
- /** npm registry asked for the published version of this bundle. */
57
- export const DEFAULT_UPDATE_REGISTRY = 'https://registry.npmjs.org';
58
- /** Hours between two automatic published-version checks. */
59
- export const DEFAULT_UPDATE_INTERVAL_HOURS = 6;
60
- /** Upper bound for the automatic check interval. */
61
- export const MAX_UPDATE_INTERVAL_HOURS = 168;
62
- /** One registry base URL, ignoring trailing slashes; anything not http(s) falls back. */
63
- function registryValue(value) {
64
- const text = typeof value === 'string' ? value.trim() : '';
65
- if (!/^https?:\/\/[^\s]+$/i.test(text))
66
- return DEFAULT_UPDATE_REGISTRY;
67
- return text.replace(/\/+$/, '');
68
- }
69
- /**
70
- * Snapshot one live Config field.
71
- * @param value - plain value or volatile reference.
72
- * @param fallback - default.
73
- * @returns the plain value.
74
- */
75
- export function refValue(value, fallback) {
76
- if (value === undefined)
77
- return fallback;
78
- if (value !== null && typeof value === 'object' && typeof value.get === 'function') {
79
- try {
80
- return value.get();
81
- }
82
- catch {
83
- return fallback;
84
- }
85
- }
86
- return value;
87
- }
88
- /** Clamp one numeric setting. */
89
- function clamp(value, min, max) {
90
- if (!Number.isFinite(value))
91
- return min;
92
- return Math.min(max, Math.max(min, Math.trunc(value)));
93
- }
94
- /** One non-empty string setting or its fallback. */
95
- function stringValue(value, fallback) {
96
- return typeof value === 'string' && value.trim() !== '' ? value.trim() : fallback;
97
- }
98
- /** Trim, drop empty entries, and de-duplicate one string list. */
99
- export function stringList(value) {
100
- if (!Array.isArray(value))
101
- return [];
102
- const out = [];
103
- const seen = new Set();
104
- for (const entry of value) {
105
- if (typeof entry !== 'string')
106
- continue;
107
- const text = entry.trim();
108
- if (text === '' || seen.has(text))
109
- continue;
110
- seen.add(text);
111
- out.push(text);
112
- }
113
- return out;
114
- }
115
- /** $DSH_HOME, falling back to ~/.dsh. */
116
- export function dshHome() {
117
- const override = process.env.DSH_HOME;
118
- if (typeof override === 'string' && override.trim() !== '')
119
- return resolve(override.trim());
120
- return join(homedir(), '.dsh');
121
- }
122
- /** $DSH_AGENTS_HOME, falling back to ~/.agents. */
123
- export function agentsHome() {
124
- const override = process.env.DSH_AGENTS_HOME;
125
- if (typeof override === 'string' && override.trim() !== '')
126
- return resolve(override.trim());
127
- return join(homedir(), '.agents');
128
- }
129
- /** $DSH_HOME/storages/dsh-utils-agents. */
130
- export function agentsStorageDir() {
131
- return join(dshHome(), 'storages', 'dsh-utils-agents');
132
- }
133
- /** All configured preset roots, defaults first. */
134
- export function presetRoots(options) {
135
- const roots = new Set([join(dshHome(), '.agent-presets'), join(agentsHome(), '.agent-presets')]);
136
- for (const raw of options.presetDirs) {
137
- try {
138
- roots.add(expandAbsolute(raw));
139
- }
140
- catch {
141
- // An invalid extra root is ignored at list time.
142
- }
143
- }
144
- return [...roots];
145
- }
146
- /** Stable storage name for one preset id. */
147
- export function presetStorageName(id) {
148
- if (/^[A-Za-z0-9._-]+$/.test(id) && id !== '.' && id !== '..')
149
- return id;
150
- return Buffer.from(id, 'utf8').toString('base64url');
151
- }
152
- /**
153
- * Expand a configured path to an absolute path.
154
- * @param raw - configured value; ~ and $VAR / braced VAR are expanded.
155
- * @returns absolute path.
156
- */
157
- export function expandAbsolute(raw) {
158
- let value = raw.trim();
159
- if (value === '')
160
- throw new Error('路径为空');
161
- if (value === '~')
162
- value = homedir();
163
- else if (value.startsWith('~/') || value.startsWith('~\\'))
164
- value = join(homedir(), value.slice(2));
165
- value = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (match, braced, bare) => {
166
- const variable = braced ?? bare ?? '';
167
- const resolved = process.env[variable];
168
- if (resolved === undefined)
169
- throw new Error('环境变量 ' + variable + ' 未设置');
170
- return resolved;
171
- });
172
- if (!isAbsolute(value))
173
- throw new Error('必须是绝对路径');
174
- return resolve(value);
175
- }
176
- /** Join a relative path under a root and refuse escapes. */
177
- export function insideJoin(root, rel) {
178
- if (rel === '' || rel.includes('\u0000'))
179
- throw new AgentsError('相对路径不合法', 400);
180
- if (isAbsolute(rel))
181
- throw new AgentsError('相对路径不能是绝对路径', 400);
182
- const base = resolve(root);
183
- const path = resolve(base, rel);
184
- if (!isInside(base, path) || path === base)
185
- throw new AgentsError('路径越界', 400);
186
- return path;
187
- }
188
- /** Whether a path is strictly inside a directory. */
189
- export function isInside(parent, child) {
190
- const rel = relative(parent, child);
191
- return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);
192
- }
193
- /** Whether a directory exists and is a directory. */
194
- export async function directoryOf(path) {
195
- try {
196
- return (await stat(path)).isDirectory();
197
- }
198
- catch {
199
- return false;
200
- }
201
- }
202
- /** Whether any path exists (file, directory, or symlink). */
203
- export async function exists(path) {
204
- try {
205
- await lstat(path);
206
- return true;
207
- }
208
- catch {
209
- return false;
210
- }
211
- }
212
- /** Recursively collect paths under one directory with a depth bound. */
213
- export async function walkFiles(dir, depth, ignored, visit, ctx) {
214
- if (depth < 0)
215
- return;
216
- let items;
217
- try {
218
- items = await readdir(dir, { withFileTypes: true });
219
- }
220
- catch (error) {
221
- if (error.code !== 'ENOENT')
222
- ctx.logger.debug('utils-agents: cannot scan ' + dir + ': ' + errorMessage(error));
223
- return;
224
- }
225
- items.sort((left, right) => left.name.localeCompare(right.name));
226
- for (const item of items) {
227
- if (ignored.has(item.name))
228
- continue;
229
- const path = join(dir, item.name);
230
- if (item.isDirectory()) {
231
- await walkFiles(path, depth - 1, ignored, visit, ctx);
232
- }
233
- else if (item.isFile() || item.isSymbolicLink()) {
234
- visit(path);
235
- }
236
- }
237
- }
238
- /** Build one file row for an existing or missing path. */
239
- export async function fileRow(id, label, path, presetId, kind) {
240
- let info;
241
- try {
242
- info = await lstat(path);
243
- }
244
- catch (error) {
245
- if (error.code !== 'ENOENT')
246
- throw error;
247
- const parent = await directoryOf(dirname(path));
248
- return { id, label, path, presetId, kind, exists: false, editable: parent, size: 0, mtimeMs: null };
249
- }
250
- const parent = await directoryOf(dirname(path));
251
- return {
252
- id,
253
- label,
254
- path,
255
- presetId,
256
- kind,
257
- exists: true,
258
- editable: parent && info.isFile(),
259
- size: info.isFile() ? info.size : 0,
260
- mtimeMs: Number.isFinite(info.mtimeMs) ? info.mtimeMs : null,
261
- };
262
- }
263
- /** Read one file, refusing oversized files and non-regular files. */
264
- export async function readTextFile(path, maxBytes) {
265
- const info = await lstat(path);
266
- if (info.isSymbolicLink())
267
- throw new AgentsError('拒绝读取符号链接', 409);
268
- if (!info.isFile())
269
- throw new AgentsError('目标不是普通文件', 409);
270
- if (info.size > maxBytes)
271
- throw new AgentsError('文件超过 ' + maxBytes + ' 字节上限', 413);
272
- const content = await readFile(path, 'utf8');
273
- return { content, row: await fileRow('', basename(path), path, '', 'reference') };
274
- }
275
- /**
276
- * Write one file atomically, preserving mode and detecting a stale browser
277
- * copy. A missing file is created when baseMtimeMs is null.
278
- */
279
- export async function writeTextFile(path, content, baseMtimeMs, maxBytes) {
280
- if (Buffer.byteLength(content, 'utf8') > maxBytes)
281
- throw new AgentsError('内容超过 ' + maxBytes + ' 字节上限', 413);
282
- if (content.includes('\u0000'))
283
- throw new AgentsError('内容不能包含 NUL 字符', 400);
284
- let existing;
285
- try {
286
- existing = await lstat(path);
287
- }
288
- catch (error) {
289
- if (error.code !== 'ENOENT')
290
- throw error;
291
- }
292
- if (existing !== undefined && existing.isSymbolicLink())
293
- throw new AgentsError('拒绝写入符号链接,避免改到链接目标', 409);
294
- if (existing !== undefined && !existing.isFile())
295
- throw new AgentsError('目标不是普通文件', 409);
296
- if (existing !== undefined && baseMtimeMs !== null && Math.abs(existing.mtimeMs - baseMtimeMs) > 1) {
297
- throw new AgentsError('文件已在别处修改,请重读后再保存', 409);
298
- }
299
- if (existing === undefined && baseMtimeMs !== null)
300
- throw new AgentsError('文件已被删除,请刷新文件列表', 409);
301
- const directory = dirname(path);
302
- if (!(await directoryOf(directory)))
303
- throw new AgentsError('目标目录不存在', 409);
304
- const mode = existing !== undefined ? existing.mode & 0o777 : 0o644;
305
- const temp = join(directory, '.' + basename(path) + '.' + randomBytes(6).toString('hex') + '.tmp');
306
- try {
307
- await writeFile(temp, content, { mode, flag: 'wx' });
308
- await rename(temp, path);
309
- }
310
- catch (error) {
311
- await rm(temp, { force: true });
312
- if (process.platform === 'win32' && existing !== undefined) {
313
- await writeFile(path, content, { mode });
314
- }
315
- else {
316
- throw error;
317
- }
318
- }
319
- const after = await stat(path);
320
- return { bytes: Buffer.byteLength(content, 'utf8'), mtimeMs: Number.isFinite(after.mtimeMs) ? after.mtimeMs : null };
321
- }
322
- /** Parse one buffered JSON request body, with a size cap. */
323
- export async function readJsonBody(request) {
324
- const text = await request.text();
325
- if (Buffer.byteLength(text, 'utf8') > BODY_LIMIT_BYTES)
326
- throw new AgentsError('请求体过大', 413);
327
- try {
328
- return JSON.parse(text);
329
- }
330
- catch {
331
- throw new AgentsError('请求体不是合法 JSON', 400);
332
- }
333
- }
334
- /** Trimmed non-empty text, or null. */
335
- export function optionalText(value) {
336
- if (typeof value !== 'string')
337
- return null;
338
- const text = value.trim();
339
- return text === '' ? null : text;
340
- }
341
- /** Required trimmed text. */
342
- export function requiredText(value, message) {
343
- if (typeof value !== 'string')
344
- throw new AgentsError(message, 400);
345
- const text = value.trim();
346
- if (text === '')
347
- throw new AgentsError(message, 400);
348
- return text;
349
- }
350
- /** Build one JSON response. */
351
- export function json(value, status) {
352
- return new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' } });
353
- }
354
- /** Map an error to the route's JSON failure shape. */
355
- export function failure(ctx, action, error) {
356
- if (error instanceof AgentsError)
357
- return json({ error: error.message }, error.status);
358
- ctx.logger.warn('utils-agents: ' + action + ': ' + errorMessage(error));
359
- return json({ error: errorMessage(error) }, 500);
360
- }
361
- /** Render an unknown error for a log line or route payload. */
362
- export function errorMessage(error) {
363
- return error instanceof Error ? error.message : String(error);
364
- }
365
- /** Resolve the session working directory with the same fallbacks as the skill panel. */
366
- export async function resolveCwd(ctx, sessionId, signal) {
367
- const agent = sessionId === null ? undefined : agentOf(ctx, sessionId);
368
- const workingDirectory = serviceOf(ctx, 'workingDirectory');
369
- if (agent !== undefined && workingDirectory !== undefined && typeof workingDirectory.ensure === 'function') {
370
- try {
371
- const cwd = await workingDirectory.ensure(agent, signal);
372
- if (typeof cwd === 'string' && cwd !== '')
373
- return cwd;
374
- }
375
- catch (error) {
376
- ctx.logger.debug('utils-agents: working directory lookup failed: ' + errorMessage(error));
377
- }
378
- }
379
- const header = agentHeader(agent);
380
- const sessionCwd = header.cwd;
381
- if (typeof sessionCwd === 'string' && sessionCwd !== '')
382
- return sessionCwd;
383
- const fallback = workingDirectory?.defaultDirectory;
384
- if (typeof fallback === 'string' && fallback !== '')
385
- return fallback;
386
- return process.cwd();
387
- }
388
- /** The preset id recorded on the live session, when the host exposes it. */
389
- export function sessionPresetOf(ctx, sessionId) {
390
- if (sessionId === null)
391
- return null;
392
- const preset = agentHeader(agentOf(ctx, sessionId)).agentPreset;
393
- return typeof preset === 'string' && preset !== '' ? preset : null;
394
- }
395
- /** The session fields this component reads. */
396
- function agentHeader(agent) {
397
- return agent?.session?.header ?? {};
398
- }
399
- /** Read one host service defensively. */
400
- export function serviceOf(ctx, name) {
401
- const get = ctx.get;
402
- if (typeof get !== 'function')
403
- return undefined;
404
- try {
405
- return get.call(ctx, name);
406
- }
407
- catch {
408
- return undefined;
409
- }
410
- }
411
- /** Resolve a live Agent for a session id. */
412
- export function agentOf(ctx, sessionId) {
413
- const agents = serviceOf(ctx, 'agents');
414
- if (agents === undefined || typeof agents.get !== 'function')
415
- return undefined;
416
- try {
417
- return agents.get(sessionId);
418
- }
419
- catch {
420
- return undefined;
421
- }
422
- }
423
- /** Project root: the nearest ancestor holding .git, else the working directory. */
424
- export async function findProjectRoot(cwd) {
425
- let dir = resolve(cwd);
426
- for (let step = 0; step < 64; step += 1) {
427
- if (await exists(join(dir, '.git')))
428
- return dir;
429
- const parent = dirname(dir);
430
- if (parent === dir)
431
- break;
432
- dir = parent;
433
- }
434
- return resolve(cwd);
435
- }
436
- /** Directories from the project root down to the working directory. */
437
- export function projectChain(root, cwd) {
438
- const chain = [];
439
- let dir = resolve(cwd);
440
- for (let step = 0; step < 64; step += 1) {
441
- chain.push(dir);
442
- if (dir === root)
443
- break;
444
- const parent = dirname(dir);
445
- if (parent === dir)
446
- break;
447
- dir = parent;
448
- }
449
- if (!chain.includes(root))
450
- chain.push(root);
451
- return chain.reverse();
452
- }
453
- /** Human-readable scope label for one directory. */
454
- export function scopeOf(dir, cwd, root) {
455
- if (dir === cwd)
456
- return '当前目录';
457
- if (dir === root)
458
- return '项目根';
459
- const rel = relative(root, dir);
460
- return rel === '' ? '项目根' : rel.split(sep).join('/');
461
- }
462
- /** Base64url encode one id component. */
463
- export function encodeIdPart(value) {
464
- return Buffer.from(value, 'utf8').toString('base64url');
465
- }
466
- /** Decode one id component, rejecting non-canonical spellings. */
467
- export function decodeIdPart(value) {
468
- if (!/^[A-Za-z0-9_-]+$/.test(value))
469
- throw new AgentsError('文件 id 不合法', 400);
470
- const text = Buffer.from(value, 'base64url').toString('utf8');
471
- if (encodeIdPart(text) !== value)
472
- throw new AgentsError('文件 id 不合法', 400);
473
- return text;
474
- }
475
- //# sourceMappingURL=util.js.map