@ai-workbench/connect 0.7.23 → 0.7.26

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 (62) hide show
  1. package/README.md +20 -73
  2. package/client/index.cjs +93 -65
  3. package/helper/host-directories.cjs +8 -1
  4. package/lib/api.d.ts +21 -163
  5. package/lib/component-download.d.ts +1 -1
  6. package/lib/component-download.js +1 -1
  7. package/lib/component-source.d.ts +6 -27
  8. package/lib/component-source.js +10 -138
  9. package/lib/components.d.ts +1 -1
  10. package/lib/components.js +86 -98
  11. package/lib/connect.d.ts +0 -3
  12. package/lib/connect.js +15 -62
  13. package/lib/connection-messages.d.ts +2 -3
  14. package/lib/connection-messages.js +5 -4
  15. package/lib/conversation-log.d.ts +9 -0
  16. package/lib/conversation-log.js +44 -0
  17. package/lib/cordis.d.ts +1 -4
  18. package/lib/defaults.d.ts +0 -7
  19. package/lib/defaults.js +0 -2
  20. package/lib/enrollment.js +1 -8
  21. package/lib/host-directories.d.ts +6 -4
  22. package/lib/host-directories.js +4 -4
  23. package/lib/host-session-projects.d.ts +8 -58
  24. package/lib/host-session-projects.js +45 -270
  25. package/lib/index.d.ts +2 -11
  26. package/lib/index.js +11 -23
  27. package/lib/integration.d.ts +2 -2
  28. package/lib/integration.js +0 -2
  29. package/lib/native-workspace.d.ts +10 -0
  30. package/lib/needs.js +13 -25
  31. package/lib/ports.d.ts +1 -6
  32. package/lib/profile-runtime.js +59 -152
  33. package/lib/profile-settings.d.ts +6 -1
  34. package/lib/profile-settings.js +3 -5
  35. package/lib/startup.js +2 -2
  36. package/lib/workspace-directory-picker-types.d.ts +44 -0
  37. package/lib/workspace-directory-picker-types.js +1 -0
  38. package/lib/workspace-directory-picker.d.ts +30 -0
  39. package/lib/workspace-directory-picker.js +394 -0
  40. package/lib/workspace-location-types.d.ts +3 -7
  41. package/lib/workspace-locations.d.ts +5 -29
  42. package/lib/workspace-locations.js +81 -204
  43. package/package.json +3 -2
  44. package/helper/projects.cjs +0 -57
  45. package/lib/conversation-detail-settings.d.ts +0 -32
  46. package/lib/conversation-detail-settings.js +0 -119
  47. package/lib/conversation-details.d.ts +0 -30
  48. package/lib/conversation-details.js +0 -595
  49. package/lib/host-session-store.d.ts +0 -27
  50. package/lib/host-session-store.js +0 -130
  51. package/lib/local-acceptance-store.d.ts +0 -18
  52. package/lib/local-acceptance-store.js +0 -133
  53. package/lib/local-user-turn-acceptance.d.ts +0 -76
  54. package/lib/local-user-turn-acceptance.js +0 -289
  55. package/lib/local-user-turn-types.d.ts +0 -40
  56. package/lib/login-diagnostics.d.ts +0 -28
  57. package/lib/login-diagnostics.js +0 -57
  58. package/lib/projects.d.ts +0 -4
  59. package/lib/projects.js +0 -41
  60. package/lib/workspace-bindings.d.ts +0 -64
  61. package/lib/workspace-bindings.js +0 -379
  62. /package/lib/{local-user-turn-types.js → native-workspace.js} +0 -0
@@ -0,0 +1,394 @@
1
+ import { access, lstat, stat, realpath, readdir, mkdir, open, rename, rm } from 'node:fs/promises';
2
+ import { constants, lstatSync, realpathSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { join, dirname, basename, isAbsolute } from 'node:path';
5
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
6
+ import { privateDirectory, readPrivate, readPrivateSync } from "./private-files.js";
7
+ import { fail, ok, need, NeedError } from "./needs.js";
8
+ const queues = new Map();
9
+ const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
10
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
11
+ const string = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
12
+ const path = (v) => string(v) && isAbsolute(v);
13
+ const digest = (v) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
14
+ const decimal = (v) => typeof v === 'string' && /^\d+$/.test(v);
15
+ const strict = (v, keys) => Object.keys(v).every(k => keys.includes(k));
16
+ const sameInfo = (a, b) => a.path === b.path && a.requestedPath === b.requestedPath && a.isSymlink === b.isSymlink && a.identity.device === b.identity.device && a.identity.inode === b.identity.inode && a.entryIdentity.device === b.entryIdentity.device && a.entryIdentity.inode === b.entryIdentity.inode && ['read', 'write', 'execute'].every(k => a.permissions[k] === b.permissions[k]);
17
+ const sameSnapshot = (a, b) => sameInfo(a, b) && a.identity.mtimeNs === b.identity.mtimeNs && a.identity.ctimeNs === b.identity.ctimeNs;
18
+ const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
19
+ export function createWorkspaceDirectoryPicker(o) {
20
+ const root = join(o.profileDir, 'ai-workbench-connect'), mappingRoot = join(root, 'remote-workspaces'), file = join(root, 'directory-picker-state.json'), secret = randomBytes(32), controllers = new Set();
21
+ let activePath;
22
+ let disposed = false, state = { schemaVersion: 1, mappings: [] }, tail = Promise.resolve();
23
+ function reject(code) { throw new NeedError(need(code)); }
24
+ const take = (r) => { if (!r.ok)
25
+ throw new NeedError(r.error); return r.value; };
26
+ function check(c) { if (disposed)
27
+ reject('DISPOSED'); const current = o.api.getConnectionState(); if (current.instanceId !== c.instanceId || current.epoch !== c.epoch)
28
+ reject('WORKSPACE_LOCATION_CONFLICT'); }
29
+ const context = () => { const c = o.api.getConnectionState(); return { instanceId: c.instanceId, epoch: c.epoch }; };
30
+ async function prepare() { if (!path(o.profileDir) || await realpath(o.profileDir) !== o.profileDir)
31
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); if (!Number.isSafeInteger(o.metadataMaxBytes) || o.metadataMaxBytes < 1 || !Number.isSafeInteger(o.pageSize) || o.pageSize < 1 || !Number.isSafeInteger(o.slotPriority) || o.slotPriority >= 0)
32
+ reject('SETTINGS_REQUIRED'); await privateDirectory(root); if (await realpath(root) !== root)
33
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); const parent = await open(o.profileDir, 'r'); try {
34
+ await parent.sync();
35
+ }
36
+ finally {
37
+ await parent.close();
38
+ } }
39
+ function parse(raw) {
40
+ const doc = JSON.parse(raw);
41
+ if (!object(doc) || !strict(doc, ['data', 'checksum']) || !object(doc.data) || doc.checksum !== hash(doc.data))
42
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
43
+ const d = doc.data;
44
+ if (!strict(d, ['schemaVersion', 'lastTarget', 'local', 'host', 'mappings', 'journal']) || d.schemaVersion !== 1 || d.lastTarget !== undefined && !['local', 'host'].includes(d.lastTarget) || d.local !== undefined && !path(d.local) || d.host !== undefined && (!object(d.host) || !strict(d.host, ['identity', 'path']) || !digest(d.host.identity) || !path(d.host.path)) || !Array.isArray(d.mappings))
45
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
46
+ const names = new Set();
47
+ for (const m of d.mappings) {
48
+ if (!object(m) || !strict(m, ['name', 'identity', 'remotePath', 'device', 'inode']) || !digest(m.name) || !digest(m.identity) || !path(m.remotePath) || m.name !== hash([m.identity, m.remotePath]) || !decimal(m.device) || !decimal(m.inode) || names.has(m.name))
49
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
50
+ names.add(m.name);
51
+ }
52
+ // Legacy unfinished journals are no longer execution or picker gates.
53
+ const { journal: ignored, ...current } = d;
54
+ return current;
55
+ }
56
+ async function load() { try {
57
+ return parse(await readPrivate(file, o.metadataMaxBytes));
58
+ }
59
+ catch (e) {
60
+ if (e.code === 'ENOENT')
61
+ return { schemaVersion: 1, mappings: [] };
62
+ throw e;
63
+ } }
64
+ async function save(next, guard) { const data = structuredClone(next), bytes = JSON.stringify({ data, checksum: hash(data) }) + '\n'; if (Buffer.byteLength(bytes) > o.metadataMaxBytes)
65
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); const temp = join(root, '.directory-picker-' + randomUUID()); try {
66
+ const h = await open(temp, 'wx', 0o600);
67
+ try {
68
+ await h.writeFile(bytes);
69
+ await h.sync();
70
+ }
71
+ finally {
72
+ await h.close();
73
+ }
74
+ guard?.();
75
+ await rename(temp, file);
76
+ const d = await open(root, 'r');
77
+ try {
78
+ await d.sync();
79
+ }
80
+ finally {
81
+ await d.close();
82
+ }
83
+ state = data;
84
+ }
85
+ finally {
86
+ await rm(temp, { force: true });
87
+ } }
88
+ async function trust(c) { check(c); const current = o.api.getConnectionState(); if (current.phase !== 'connected')
89
+ throw new NeedError(current.need ?? need('CONNECTION_LOST')); const t = take(o.api.getModelCatalogTarget('codex')); if (t.instanceId !== c.instanceId || t.epoch !== c.epoch)
90
+ reject('WORKSPACE_LOCATION_CONFLICT'); const bytes = await readPrivate(t.target.knownHostsFile, o.metadataMaxBytes); check(c); return { target: t.target, identity: hash([t.target.host, t.target.username, t.target.port, bytes]) }; }
91
+ function guardTrust(c, identity) { check(c); const current = o.api.getConnectionState(); if (current.phase !== 'connected')
92
+ throw new NeedError(current.need ?? need('CONNECTION_LOST')); const t = take(o.api.getModelCatalogTarget('codex')); if (t.instanceId !== c.instanceId || t.epoch !== c.epoch || hash([t.target.host, t.target.username, t.target.port, readPrivateSync(t.target.knownHostsFile, o.metadataMaxBytes)]) !== identity)
93
+ reject('WORKSPACE_LOCATION_CONFLICT'); }
94
+ async function remote(run) { const controller = new AbortController(); controllers.add(controller); try {
95
+ return take(await run(controller.signal));
96
+ }
97
+ finally {
98
+ controllers.delete(controller);
99
+ } }
100
+ async function localInfo(requestedPath) {
101
+ try {
102
+ const entry = await lstat(requestedPath, { bigint: true }), canonical = await realpath(requestedPath), s = await stat(canonical, { bigint: true });
103
+ if (!s.isDirectory())
104
+ reject('HOST_DIRECTORY_INVALID');
105
+ await access(canonical, constants.R_OK | constants.X_OK);
106
+ return { requestedPath, path: canonical, parentPath: dirname(canonical) === canonical ? null : dirname(canonical), identity: { device: String(s.dev), inode: String(s.ino), mtimeNs: String(s.mtimeNs), ctimeNs: String(s.ctimeNs) }, entryIdentity: { device: String(entry.dev), inode: String(entry.ino) }, isSymlink: entry.isSymbolicLink(), permissions: { read: true, write: null, execute: true, reason: 'HOST_PERMISSION_UNKNOWN' } };
107
+ }
108
+ catch (e) {
109
+ if (e instanceof NeedError)
110
+ throw e;
111
+ const code = e.code;
112
+ if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP')
113
+ reject('HOST_DIRECTORY_INVALID');
114
+ if (code === 'EACCES' || code === 'EPERM')
115
+ reject('HOST_DIRECTORY_UNREADABLE');
116
+ throw e;
117
+ }
118
+ }
119
+ function seal(data) { const body = Buffer.from(JSON.stringify(data)).toString('base64url'); const value = body + '.' + createHmac('sha256', secret).update(body).digest('base64url'); if (Buffer.byteLength(value) > o.metadataMaxBytes)
120
+ reject('HOST_DIRECTORY_PAGE_TOO_LARGE'); return value; }
121
+ function unseal(value) { if (!string(value) || Buffer.byteLength(value) > o.metadataMaxBytes)
122
+ reject('WORKSPACE_PICKER_INVALID'); const [body, signature, ...extra] = value.split('.'); if (!body || !signature || extra.length)
123
+ reject('WORKSPACE_PICKER_INVALID'); const expected = createHmac('sha256', secret).update(body).digest(), actual = Buffer.from(signature, 'base64url'); if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
124
+ reject('WORKSPACE_PICKER_INVALID'); try {
125
+ return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
126
+ }
127
+ catch {
128
+ return reject('WORKSPACE_PICKER_INVALID');
129
+ } }
130
+ async function inspect(s) { check(s.context); let current; if (s.target === 'host') {
131
+ const t = await trust(s.context);
132
+ if (t.identity !== s.identity)
133
+ reject('WORKSPACE_LOCATION_CONFLICT');
134
+ if (!o.hostDirectories)
135
+ reject('DEPENDENCY_REQUIRED');
136
+ current = await remote(signal => o.hostDirectories.inspect(t.target, s.info.requestedPath, signal));
137
+ guardTrust(s.context, t.identity);
138
+ }
139
+ else
140
+ current = await localInfo(s.info.requestedPath); check(s.context); if (!sameInfo(s.info, current))
141
+ reject('HOST_DIRECTORY_CHANGED'); if (current.permissions.read !== true || current.permissions.execute !== true)
142
+ reject('HOST_DIRECTORY_UNREADABLE'); return current; }
143
+ async function nativePath(p) { const s = await lstat(p, { bigint: true }); if (!s.isDirectory() || s.isSymbolicLink() || await realpath(p) !== p)
144
+ reject('WORKSPACE_LOCATION_INVALID'); return { device: String(s.dev), inode: String(s.ino) }; }
145
+ async function mappingPath(j) { const s = await lstat(j.path, { bigint: true }); if (!s.isDirectory() || s.isSymbolicLink() || s.uid !== BigInt(process.getuid()) || (s.mode & 63n) !== 0n || await realpath(j.path) !== j.path)
146
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); if (j.device !== undefined && (String(s.dev) !== j.device || String(s.ino) !== j.inode))
147
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); return { device: String(s.dev), inode: String(s.ino) }; }
148
+ const unsubscribe = o.api.onConnectionState?.(() => { for (const controller of controllers)
149
+ controller.abort(); });
150
+ function serial(run) { const before = queues.get(file) ?? Promise.resolve(); const task = before.then(async () => { if (disposed)
151
+ return fail('DISPOSED'); try {
152
+ await prepare();
153
+ state = await load();
154
+ return await run();
155
+ }
156
+ catch (e) {
157
+ const error = e instanceof NeedError ? e.need : need('WORKSPACE_PICKER_STORAGE_FAILED');
158
+ return { ok: false, error: error.code === 'WORKSPACE_LOCATION_STORAGE_FAILED' ? { ...error, message: need('WORKSPACE_PICKER_STORAGE_FAILED').message, actor: 'employee', action: need('WORKSPACE_PICKER_STORAGE_FAILED').action } : error };
159
+ } }); tail = task.then(() => { }, () => { }); queues.set(file, tail); const waiting = tail; void waiting.then(() => { if (queues.get(file) === waiting)
160
+ queues.delete(file); }); return task; }
161
+ async function browse(r) {
162
+ if (!object(r) || !strict(r, ['target', 'path', 'cursor']) || r.target !== undefined && !['local', 'host'].includes(r.target) || r.path !== undefined && !path(r.path) || r.cursor !== undefined && (!string(r.cursor) || r.path !== undefined))
163
+ reject('WORKSPACE_PICKER_INVALID');
164
+ const c = context(), cursor = r.cursor ? unseal(r.cursor) : undefined;
165
+ if (cursor && cursor.kind !== 'cursor')
166
+ reject('WORKSPACE_PICKER_INVALID');
167
+ const previous = cursor?.kind === 'cursor' ? cursor.selection : undefined;
168
+ const target = (r.target ?? previous?.target ?? state.lastTarget ?? 'local');
169
+ if (previous && target !== previous.target)
170
+ reject('WORKSPACE_PICKER_INVALID');
171
+ if (previous)
172
+ check(previous.context);
173
+ const trusted = target === 'host' ? await trust(c) : undefined;
174
+ if (previous && (previous.context.instanceId !== c.instanceId || previous.context.epoch !== c.epoch || previous.identity !== trusted?.identity))
175
+ reject('WORKSPACE_LOCATION_CONFLICT');
176
+ let requested = r.path ?? previous?.info.requestedPath ?? (target === 'local' ? state.local : state.host?.identity === trusted?.identity ? state.host?.path : undefined), notice;
177
+ let info, entries, after = cursor?.kind === 'cursor' ? cursor.after : undefined, nextAfter;
178
+ async function read() {
179
+ if (target === 'host') {
180
+ if (!o.hostDirectories)
181
+ reject('DEPENDENCY_REQUIRED');
182
+ return remote(signal => o.hostDirectories.browse(trusted.target, { ...(requested !== undefined ? { path: requested } : {}), pageSize: o.pageSize, ...(after ? { after, expected: previous.info.identity } : {}) }, signal));
183
+ }
184
+ const parent = await localInfo(requested ?? homedir());
185
+ if (previous && !sameSnapshot(previous.info, parent))
186
+ reject('HOST_DIRECTORY_CHANGED');
187
+ const names = (await readdir(parent.path, { withFileTypes: true })).filter(e => e.isDirectory() || e.isSymbolicLink()).map(e => e.name).sort(binaryCompare).filter(n => after === undefined || binaryCompare(n, after) > 0), children = [];
188
+ for (const name of names) {
189
+ const requestedPath = join(parent.path, name);
190
+ try {
191
+ const child = await localInfo(requestedPath);
192
+ children.push({ ...child, name });
193
+ }
194
+ catch (e) {
195
+ if (!(e instanceof NeedError) || !['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE'].includes(e.need.code))
196
+ throw e;
197
+ const entry = await lstat(requestedPath, { bigint: true });
198
+ children.push({ name, requestedPath, entryIdentity: { device: String(entry.dev), inode: String(entry.ino) }, isSymlink: entry.isSymbolicLink(), permissions: { read: false, write: null, execute: false, reason: 'HOST_PERMISSION_UNKNOWN' }, errorCode: e.need.code });
199
+ }
200
+ if (children.length === o.pageSize)
201
+ break;
202
+ }
203
+ const final = await localInfo(parent.requestedPath);
204
+ if (!sameSnapshot(parent, final))
205
+ reject('HOST_DIRECTORY_CHANGED');
206
+ return { ...parent, entries: children, ...(names.length > children.length ? { nextAfter: children.at(-1).name } : {}) };
207
+ }
208
+ let page;
209
+ try {
210
+ page = await read();
211
+ }
212
+ catch (e) {
213
+ if (r.path !== undefined || r.cursor !== undefined || requested === undefined || !(e instanceof NeedError) || !['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE'].includes(e.need.code))
214
+ throw e;
215
+ requested = undefined;
216
+ notice = target === 'host' ? '上次选择的远程目录已失效或不可读,已返回远程用户根目录。' : '上次选择的本机目录已失效或不可读,已返回用户根目录。';
217
+ page = await read();
218
+ }
219
+ const { entries: rawEntries, nextAfter: more, ...directory } = page;
220
+ info = directory;
221
+ nextAfter = more;
222
+ entries = rawEntries.map(e => ({ name: e.name, path: e.requestedPath, available: !e.errorCode && e.path !== undefined && e.permissions.read === true && e.permissions.execute === true, isSymlink: e.isSymlink }));
223
+ if (previous && !sameSnapshot(previous.info, info))
224
+ reject('HOST_DIRECTORY_CHANGED');
225
+ check(c);
226
+ if (trusted)
227
+ guardTrust(c, trusted.identity);
228
+ const selected = { kind: 'selection', target, context: c, ...(trusted ? { identity: trusted.identity } : {}), info };
229
+ const result = { target, path: info.path, parentPath: info.parentPath, entries, selectionToken: seal(selected), ...(nextAfter ? { nextCursor: seal({ kind: 'cursor', selection: selected, after: nextAfter }) } : {}), ...(notice ? { notice } : {}) };
230
+ if (Buffer.byteLength(JSON.stringify(result)) > o.metadataMaxBytes)
231
+ reject('HOST_DIRECTORY_PAGE_TOO_LARGE');
232
+ return ok(result);
233
+ }
234
+ async function create(r) {
235
+ if (!object(r) || !strict(r, ['selectionToken', 'name']) || !string(r.name) || ['.', '..'].includes(r.name) || /[\\/]/.test(r.name))
236
+ reject('WORKSPACE_PICKER_INVALID');
237
+ const s = unseal(r.selectionToken);
238
+ if (s.kind !== 'selection' || s.target !== 'host')
239
+ reject('WORKSPACE_PICKER_INVALID');
240
+ const info = await inspect(s), t = await trust(s.context);
241
+ if (t.identity !== s.identity)
242
+ reject('WORKSPACE_LOCATION_CONFLICT');
243
+ if (!o.hostDirectories?.create)
244
+ reject('DEPENDENCY_REQUIRED');
245
+ const child = await remote(signal => o.hostDirectories.create(t.target, info.path, r.name, info.identity, signal));
246
+ guardTrust(s.context, t.identity);
247
+ return browse({ target: 'host', path: child.path });
248
+ }
249
+ function sameSource(item, s) {
250
+ if (item?.status !== 'selected' || item.source !== s.target)
251
+ return false;
252
+ if (s.target === 'local')
253
+ return true;
254
+ // refresh revalidates the old binding's requested path and entry. A newly
255
+ // browsed alias may share its canonical directory without rewriting that binding.
256
+ const a = item.remote, b = s.info;
257
+ if (!a || a.path !== b.path || a.identity.device !== b.identity.device || a.identity.inode !== b.identity.inode || !['read', 'write', 'execute'].every(k => a.permissions[k] === b.permissions[k]))
258
+ return false;
259
+ const current = take(o.api.getModelCatalogTarget('codex')).target;
260
+ return item.host?.host === current.host && item.host.username === current.username && item.host.port === current.port;
261
+ }
262
+ function registrationTitle(j) { return (basename(j.selectedPath) || j.selectedPath) + ' · 正在添加 · ' + j.id; }
263
+ async function select(r) {
264
+ if (!object(r) || !strict(r, ['selectionToken']))
265
+ reject('WORKSPACE_PICKER_INVALID');
266
+ const selected = unseal(r.selectionToken);
267
+ if (selected.kind !== 'selection')
268
+ reject('WORKSPACE_PICKER_INVALID');
269
+ const s = selected, info = await inspect(s), guard = () => { check(s.context); if (s.identity)
270
+ guardTrust(s.context, s.identity); };
271
+ const mapped = s.target === 'host' ? hash([s.identity, info.path]) : undefined, localPath = mapped ? join(mappingRoot, mapped) : info.path;
272
+ const previous = { ...(state.lastTarget ? { lastTarget: state.lastTarget } : {}), ...(state.local ? { local: state.local } : {}), ...(state.host ? { host: structuredClone(state.host) } : {}) };
273
+ const j = { id: randomUUID(), source: s.target, path: localPath, selectedPath: info.path, ...(s.identity ? { identity: s.identity, mappingName: mapped } : {}), originalIds: o.registry.list().map(w => w.id) };
274
+ if (!o.registry.list().some(w => w.path === localPath))
275
+ activePath = localPath;
276
+ try {
277
+ if (mapped) {
278
+ await privateDirectory(mappingRoot);
279
+ if (await realpath(mappingRoot) !== mappingRoot)
280
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
281
+ const known = state.mappings.find(m => m.name === mapped);
282
+ try {
283
+ const observed = await mappingPath(j);
284
+ if (known && (known.device !== observed.device || known.inode !== observed.inode) && o.registry.list().some(w => w.path === localPath))
285
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
286
+ if (!known && (await readdir(localPath)).length !== 0)
287
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
288
+ Object.assign(j, observed);
289
+ }
290
+ catch (e) {
291
+ if (e.code !== 'ENOENT')
292
+ throw e;
293
+ await mkdir(localPath, { mode: 0o700 });
294
+ Object.assign(j, await mappingPath(j));
295
+ }
296
+ const current = { name: mapped, identity: s.identity, remotePath: info.path, device: j.device, inode: j.inode };
297
+ await save({ ...state, mappings: [...state.mappings.filter(m => m.name !== mapped), current] }, guard);
298
+ }
299
+ else
300
+ Object.assign(j, await nativePath(localPath));
301
+ guard();
302
+ const matches = o.registry.list().filter(w => w.path === localPath);
303
+ if (matches.length > 1)
304
+ reject('WORKSPACE_LOCATION_CONFLICT');
305
+ let workspace;
306
+ let fresh = take(await o.locations.refreshWorkspaceLocations());
307
+ guard();
308
+ if (matches[0]) {
309
+ workspace = matches[0];
310
+ const item = fresh.items.find(i => i.workspaceId === workspace.id);
311
+ if (!sameSource(item, s))
312
+ reject('WORKSPACE_LOCATION_CONFLICT');
313
+ }
314
+ else {
315
+ workspace = await o.registry.create(localPath, registrationTitle(j));
316
+ if (!workspace || !string(workspace.id) || workspace.path !== localPath || o.registry.get(workspace.id)?.path !== localPath || o.registry.list().filter(w => w.id === workspace.id && w.path === localPath).length !== 1 || j.originalIds.includes(workspace.id) || workspace.title !== registrationTitle(j))
317
+ reject('WORKSPACE_LOCATION_CONFLICT');
318
+ j.workspaceId = workspace.id;
319
+ if (typeof workspace.setTitle !== 'function')
320
+ reject('DEPENDENCY_REQUIRED');
321
+ await workspace.setTitle(basename(info.path) || info.path);
322
+ guard();
323
+ fresh = take(await o.locations.refreshWorkspaceLocations());
324
+ guard();
325
+ const item = fresh.items.find(i => i.workspaceId === workspace.id);
326
+ if (!item || item.bindingId !== null || item.source !== null)
327
+ reject('WORKSPACE_LOCATION_CONFLICT');
328
+ const c = { ...s.context, workspaceId: workspace.id, expectedBindingId: null };
329
+ let request = { ...c, source: 'local' };
330
+ if (s.target === 'host') {
331
+ const page = take(await o.locations.browseWorkspaceHostDirectories({ ...c, path: info.requestedPath }));
332
+ guard();
333
+ if (!sameInfo(info, page))
334
+ reject('HOST_DIRECTORY_CHANGED');
335
+ request = { ...c, source: 'host', selectionToken: page.selectionToken };
336
+ }
337
+ await inspect(s);
338
+ guard();
339
+ const saved = take(await o.locations.selectWorkspaceLocation(request));
340
+ const itemAfter = saved.items.find(i => i.workspaceId === workspace.id);
341
+ if (!sameSource(itemAfter, s) || !itemAfter?.bindingId)
342
+ reject('WORKSPACE_LOCATION_CONFLICT');
343
+ j.bindingId = itemAfter.bindingId;
344
+ }
345
+ const n = mapped ? await mappingPath(j) : await nativePath(localPath);
346
+ if (n.device !== j.device || n.inode !== j.inode)
347
+ reject('WORKSPACE_LOCATION_CONFLICT');
348
+ await inspect(s);
349
+ guard();
350
+ const latest = take(await o.locations.refreshWorkspaceLocations()).items.find(i => i.workspaceId === workspace.id);
351
+ if (!sameSource(latest, s) || j.bindingId !== undefined && latest?.bindingId !== j.bindingId)
352
+ reject('WORKSPACE_LOCATION_CONFLICT');
353
+ guard();
354
+ const bindingGuard = o.locations.captureWorkspacePickerGuard(workspace.id, latest.bindingId);
355
+ const finalGuard = () => { guard(); const matches = o.registry.list().filter(w => w.id === workspace.id), registered = o.registry.get(workspace.id); if (matches.length !== 1 || !registered || matches[0].path !== localPath || registered.path !== localPath)
356
+ reject('WORKSPACE_LOCATION_CONFLICT'); const n = lstatSync(localPath, { bigint: true }); if (!n.isDirectory() || n.isSymbolicLink() || realpathSync(localPath) !== localPath || String(n.dev) !== j.device || String(n.ino) !== j.inode)
357
+ reject('WORKSPACE_LOCATION_CONFLICT'); bindingGuard(); };
358
+ finalGuard();
359
+ // The registration path is blocked only while this call is in flight.
360
+ const next = { ...state, lastTarget: s.target, ...(s.target === 'local' ? { local: info.path } : { host: { identity: s.identity, path: info.path } }), mappings: state.mappings.filter(m => m.name !== mapped) };
361
+ if (mapped)
362
+ next.mappings.push({ name: mapped, identity: s.identity, remotePath: info.path, device: j.device, inode: j.inode });
363
+ await save(next, finalGuard);
364
+ finalGuard();
365
+ return ok({ path: localPath, workspaceId: workspace.id, source: s.target });
366
+ }
367
+ catch (e) {
368
+ const original = e instanceof NeedError ? e : new NeedError(need('WORKSPACE_PICKER_STORAGE_FAILED'));
369
+ const residual = o.registry.list().some(w => w.path === localPath && !j.originalIds.includes(w.id) && (w.id === j.workspaceId || w.title === registrationTitle(j)));
370
+ // Failed attempts retain their private mapping; no delete or cleanup gate.
371
+ const restored = { ...state };
372
+ delete restored.lastTarget;
373
+ delete restored.local;
374
+ delete restored.host;
375
+ Object.assign(restored, previous);
376
+ try {
377
+ await save(restored);
378
+ }
379
+ catch {
380
+ console.warn('本次未能保存原目录位置;下次选择时重新读取。');
381
+ }
382
+ if (residual) {
383
+ console.warn('本次工作区添加未完成:' + original.need.code);
384
+ throw new NeedError(need('WORKSPACE_PICKER_ROLLBACK_FAILED'));
385
+ }
386
+ throw original;
387
+ }
388
+ finally {
389
+ activePath = undefined;
390
+ }
391
+ }
392
+ return { getWorkspaceDirectoryPickerSettings: () => ({ slotPriority: o.slotPriority, mappingRoot, pageSize: o.pageSize, metadataMaxBytes: o.metadataMaxBytes }), browseWorkspaceDirectories: r => serial(() => browse(r)), createWorkspaceDirectory: r => serial(() => create(r)), selectWorkspaceDirectory: r => serial(() => select(r)), isPending: workspaceId => activePath !== undefined && o.registry.get(workspaceId)?.path === activePath, dispose: async () => { disposed = true; unsubscribe?.(); for (const c of controllers)
393
+ c.abort(); await tail; secret.fill(0); } };
394
+ }
@@ -5,10 +5,9 @@ export interface WorkspaceLocationItem {
5
5
  workspaceName: string;
6
6
  localPath: string;
7
7
  bindingId: string | null;
8
- source: 'local' | 'host' | 'legacy-host' | null;
9
- status: 'unselected' | 'selected' | 'legacy-confirmation-required' | 'invalid';
10
- execution: 'not-selected' | 'local-pending' | 'host-pending' | 'legacy-confirmed';
11
- legacyPath?: string;
8
+ source: 'local' | 'host' | null;
9
+ status: 'unselected' | 'selected' | 'invalid';
10
+ execution: 'not-selected' | 'local-pending' | 'host-pending';
12
11
  remote?: HostDirectoryInfo;
13
12
  host?: {
14
13
  host: string;
@@ -67,7 +66,4 @@ export type WorkspaceSelectRequest = WorkspaceLocationContext & ({
67
66
  } | {
68
67
  source: 'host';
69
68
  selectionToken: string;
70
- } | {
71
- source: 'legacy-host';
72
- confirmLegacy: true;
73
69
  });
@@ -1,37 +1,21 @@
1
1
  import type { ConnectApi, Result, SshTarget } from './api.ts';
2
- import type { NativeWorkspaceRegistry } from './workspace-bindings.ts';
2
+ import type { NativeWorkspaceRegistry } from './native-workspace.ts';
3
3
  import type { WorkspaceLocationItem, WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
4
  import type { HostDirectoryInfo, createHostDirectories } from './host-directories.ts';
5
5
  import { type LocalWorkspaceContext, type LocalWorkspaceContextRequest } from './local-workspace-context.ts';
6
- interface Native {
7
- workspaceId: string;
8
- localPath: string;
9
- localDev: number;
10
- localIno: number;
11
- }
12
- interface Legacy extends Native {
13
- identity: string;
14
- bindingId: string;
15
- project: {
16
- name: string;
17
- path: string;
18
- };
19
- phase: string;
20
- sessionIds: string[];
21
- }
22
6
  interface Options {
7
+ isWorkspacePending?: (workspaceId: string) => boolean;
23
8
  profileDir: string;
24
9
  metadataMaxBytes: number;
25
10
  pageSize: number;
26
11
  api: Pick<ConnectApi, 'getConnectionState' | 'getModelCatalogTarget'>;
27
12
  registry: NativeWorkspaceRegistry;
28
- readLegacy: () => Promise<Legacy[]>;
29
13
  hostDirectories?: ReturnType<typeof createHostDirectories>;
30
14
  onState?: (s: WorkspaceLocationState) => void;
31
15
  nextRevision?: () => number;
32
- isHostBindingRevoked?: (bindingId: string) => boolean;
33
16
  }
34
17
  export declare function createWorkspaceLocations(o: Options): {
18
+ captureWorkspacePickerGuard: (workspaceId: string, expectedBindingId: string) => () => void;
35
19
  withHostBinding: <T>(input: import("./workspace-location-types.ts").HostWorkspaceResolveContext, run: (value: {
36
20
  directory: HostDirectoryInfo;
37
21
  target: SshTarget;
@@ -41,13 +25,7 @@ export declare function createWorkspaceLocations(o: Options): {
41
25
  inode: number;
42
26
  };
43
27
  revision: number;
44
- }, guard: () => void) => Promise<Result<T>>, finalize?: () => void, inspectRemote?: boolean) => Promise<Result<T>>;
45
- isHostBindingRevoked: (id: string) => boolean;
46
- withLocalBinding: <T>(c: LocalWorkspaceContextRequest, run: (directory: {
47
- path: string;
48
- device: number;
49
- inode: number;
50
- }, guard: () => void) => Promise<Result<T>>, queue?: "detail-write") => Promise<Result<T>>;
28
+ }, guard: () => void) => Promise<Result<T>>, finalize?: () => void) => Promise<Result<T>>;
51
29
  getLocalWorkspaceContext: (request: LocalWorkspaceContextRequest) => Promise<Result<LocalWorkspaceContext>>;
52
30
  getWorkspaceLocationState: () => {
53
31
  host: {
@@ -67,9 +45,7 @@ export declare function createWorkspaceLocations(o: Options): {
67
45
  refreshWorkspaceLocations: () => Promise<Result<WorkspaceLocationState>>;
68
46
  browseWorkspaceHostDirectories: (c: WorkspaceBrowseRequest) => Promise<Result<WorkspaceBrowsePage>>;
69
47
  selectWorkspaceLocation: (c: WorkspaceSelectRequest) => Promise<Result<WorkspaceLocationState>>;
70
- guardLegacySession: (id: string) => Promise<Result<void>>;
71
- resolveLegacySession: <T>(id: string, resolve: () => Promise<Result<T>>) => Promise<Result<T>>;
72
- observeConnection(): Promise<Result<WorkspaceLocationState>> | undefined;
48
+ observeConnection(): void;
73
49
  dispose(): Promise<void>;
74
50
  };
75
51
  export {};