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