@vessel-agent/agent 0.0.0-stage → 2.3.0-beta.3

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.
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Team workspace 归一化与 `team_id` 生成(0.19 S3)。
3
+ *
4
+ * - workspace 是 Team 的唯一分组键;归一化不要求目录存在;
5
+ * - 同一目录的不同写法(junction / symlink、大小写、8.3 短名、NFD / NFC)必须收敛成同一个
6
+ * workspace,否则同一块目录会被切成多个 team;
7
+ * - `team_id` = slug(workspace basename),冲突时追加 sha256 前 8 位;
8
+ * - Windows 比较大小写不敏感,但存储保持原样(只影响比较键)。
9
+ *
10
+ * @module @vessel-agent/agent
11
+ */
12
+
13
+ import { createHash } from 'node:crypto';
14
+ import { realpathSync } from 'node:fs';
15
+ import { homedir } from 'node:os';
16
+ import { basename, join, parse, resolve } from 'node:path';
17
+
18
+ /** `team_id` 基础 slug 的最大长度 */
19
+ export const MAX_TEAM_SLUG_LENGTH = 32;
20
+
21
+ function sha256(value: string): string {
22
+ return createHash('sha256').update(value, 'utf8').digest('hex');
23
+ }
24
+
25
+ /** 可打印 ASCII(0x20–0x7e);非 ASCII / 控制字符无法生成可读 slug */
26
+ function isPrintableAscii(value: string): boolean {
27
+ for (const char of value) {
28
+ const code = char.codePointAt(0) ?? 0;
29
+ if (code < 0x20 || code > 0x7e) return false;
30
+ }
31
+ return true;
32
+ }
33
+
34
+ /** 展开开头的 `~`(`~` / `~/` / `~\`);不解析 `~user` */
35
+ function expandHome(input: string): string {
36
+ if (input === '~') return homedir();
37
+ if (input.startsWith('~/') || input.startsWith('~\\')) return join(homedir(), input.slice(2));
38
+ return input;
39
+ }
40
+
41
+ /** 去掉尾部路径分隔符,但保留根(`/`、`C:\`) */
42
+ function stripTrailingSeparators(value: string): string {
43
+ const root = parse(value).root;
44
+ let result = value;
45
+ while (
46
+ result.length > root.length &&
47
+ (result.endsWith('/') || result.endsWith('\\')) &&
48
+ result !== root
49
+ ) {
50
+ result = result.slice(0, -1);
51
+ }
52
+ return result;
53
+ }
54
+
55
+ /**
56
+ * NFC 归一化:Windows / macOS 文件系统不保证返回规范化过的名字,同一个视觉等价的名字
57
+ * (如 `caf\u00e9` 的 precomposed 与 `cafe\u0301` 的组合写法)会算出不同 basename 与哈希。
58
+ */
59
+ function toNfc(value: string): string {
60
+ return value.normalize('NFC');
61
+ }
62
+
63
+ /**
64
+ * 把路径解析成「这块目录的真实身份」。
65
+ *
66
+ * 取舍:
67
+ * - **存在则 `realpathSync`**:junction / symlink / 大小写 / 8.3 短名 / `..` 都会收敛到同一串,
68
+ * 否则同一块目录会因写法不同被切成多个 team(`team_id` 是分桶键,多切一刀就是两个 team)。
69
+ * 用 `.native` 取操作系统原生结果——JS 实现不跟随 junction。
70
+ * - **不存在则退回普通 `resolve`**:workspace 允许指向还没建的目录(`ensureForWorkspace`
71
+ * 不要求目录存在),此时没有真实身份可查,只能按字面路径算;等目录建好后再次调用会
72
+ * 收敛到真实路径,属已接受的取舍(首次调用者拿到的是字面 slug)。
73
+ * - **失败也退回普通 `resolve`**:权限 / 路径非法 / 非法 UTF-16 等 `realpath` 抛错的场景,
74
+ * 归一化不应当把调用方打断(这些函数的调用方遍布 store 的启动与读路径)。
75
+ * - 前缀 `\\?\` 由 `realpathSync.native` 去掉,长路径写法与普通写法因此收敛。
76
+ */
77
+ function resolveIdentity(value: string): string {
78
+ try {
79
+ return realpathSync.native(value);
80
+ } catch {
81
+ return value;
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 归一化 workspace:trim、展开 `~`、`path.resolve`、解析真实路径、NFC、去尾分隔符。
87
+ * 不需要目录存在(不存在时按字面路径算)。空输入抛错。
88
+ *
89
+ * 顺序要点:先 `resolve` 消掉 `..` 与相对段,再 `realpath`(`\\?\` 前缀下 `..` 不被解析,
90
+ * 必须先用普通 `resolve`);`realpath` 之后再 NFC,最后才去掉尾分隔符——`realpath` 对根目录
91
+ * 会返回 `C:\`,去尾必须放在它之后。
92
+ */
93
+ export function normalizeWorkspace(input: string): string {
94
+ if (typeof input !== 'string' || input.trim() === '') {
95
+ throw new Error('invalid_workspace: workspace must be a non-empty string');
96
+ }
97
+ const absolute = resolve(expandHome(input.trim()));
98
+ return stripTrailingSeparators(toNfc(resolveIdentity(absolute)));
99
+ }
100
+
101
+ /**
102
+ * 比较键:归一化后的精确路径;Windows 上再小写。
103
+ * 只用于相等比较,不用于存储 / 展示。
104
+ */
105
+ export function workspaceKey(workspace: string): string {
106
+ const normalized = normalizeWorkspace(workspace);
107
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
108
+ }
109
+
110
+ /**
111
+ * workspace basename -> `team_id` 基础 slug。
112
+ *
113
+ * 小写、非 `[a-z0-9-]` 折叠为 `-`、去首尾 `-`、最长 32;
114
+ * 数字开头加 `team-` 前缀;空 basename 或非 ASCII basename 用 `team-<6hex>` 兜底。
115
+ */
116
+ export function slugifyWorkspace(workspace: string): string {
117
+ const normalized = normalizeWorkspace(workspace);
118
+ const base = basename(normalized);
119
+ // 非 ASCII 或空 basename(根目录)无法得到可读 slug:用确定性短哈希兜底。
120
+ if (base === '' || !isPrintableAscii(base)) {
121
+ return `team-${sha256(normalized).slice(0, 6)}`;
122
+ }
123
+ let slug = base
124
+ .toLowerCase()
125
+ .replace(/[^a-z0-9-]+/g, '-')
126
+ .replace(/-+/g, '-')
127
+ .replace(/^-+|-+$/g, '');
128
+ if (slug.length > MAX_TEAM_SLUG_LENGTH) {
129
+ slug = slug.slice(0, MAX_TEAM_SLUG_LENGTH).replace(/-+$/g, '');
130
+ }
131
+ if (slug === '') return `team-${sha256(normalized).slice(0, 6)}`;
132
+ return /^[0-9]/.test(slug) ? `team-${slug}` : slug;
133
+ }
134
+
135
+ function sameWorkspace(owner: string, key: string): boolean {
136
+ try {
137
+ return workspaceKey(owner) === key;
138
+ } catch {
139
+ return false;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * 生成 `team_id`:
145
+ * - 基础 slug 未被占用 → 直接用;
146
+ * - 已被**同一** workspace 占用 → 复用;
147
+ * - 已被**不同** workspace 占用 → 追加 `-<sha256(workspace) 前 8 位>`,绝不合并。
148
+ *
149
+ * `taken(id)` 返回该 id 当前所属的 workspace(没有则 undefined)。
150
+ */
151
+ export function teamIdForWorkspace(
152
+ workspace: string,
153
+ taken?: (id: string) => string | undefined,
154
+ ): string {
155
+ const normalized = normalizeWorkspace(workspace);
156
+ const key = workspaceKey(normalized);
157
+ const base = slugifyWorkspace(normalized);
158
+ const baseOwner = taken?.(base);
159
+ if (baseOwner === undefined || sameWorkspace(baseOwner, key)) return base;
160
+
161
+ const suffixed = `${base}-${sha256(normalized).slice(0, 8)}`;
162
+ const suffixedOwner = taken?.(suffixed);
163
+ if (suffixedOwner === undefined || sameWorkspace(suffixedOwner, key)) return suffixed;
164
+ // 同一 workspace 的哈希后缀被别的 workspace 占用:理论上不可达(同 hash 前缀),
165
+ // 也绝不合并——由上层 persist 的 mkdir/写覆盖前再拒绝。
166
+ return suffixed;
167
+ }