@ai-workbench/connect 0.7.49-rc.1 → 0.7.50-rc.1

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 (54) hide show
  1. package/README.md +3 -3
  2. package/client/index.cjs +8 -371
  3. package/helper/auth-status.cjs +8 -14
  4. package/helper/remote-access.sh +91 -0
  5. package/lib/api.d.ts +4 -86
  6. package/lib/components.js +4 -162
  7. package/lib/connect.d.ts +3 -3
  8. package/lib/connect.js +6 -20
  9. package/lib/cordis.d.ts +1 -3
  10. package/lib/defaults.d.ts +0 -3
  11. package/lib/defaults.js +0 -1
  12. package/lib/{profile-runtime.d.ts → enrollment-runtime.d.ts} +1 -1
  13. package/lib/enrollment-runtime.js +31 -0
  14. package/lib/enrollment.d.ts +0 -1
  15. package/lib/enrollment.js +2 -5
  16. package/lib/index.d.ts +0 -4
  17. package/lib/index.js +17 -7
  18. package/lib/integration.d.ts +1 -1
  19. package/lib/integration.js +1 -3
  20. package/lib/needs.js +0 -22
  21. package/lib/ports.d.ts +2 -5
  22. package/lib/private-files.d.ts +0 -2
  23. package/lib/private-files.js +1 -17
  24. package/lib/profile-activation.d.ts +2 -0
  25. package/lib/profile-activation.js +3 -1
  26. package/lib/profile-enrollment.d.ts +2 -1
  27. package/lib/profile-enrollment.js +5 -5
  28. package/lib/remote-access.d.ts +36 -0
  29. package/lib/remote-access.js +103 -0
  30. package/lib/ssh.js +11 -1
  31. package/lib/startup.d.ts +0 -1
  32. package/package.json +3 -9
  33. package/helper/host-directories.cjs +0 -116
  34. package/lib/conversation-log.d.ts +0 -9
  35. package/lib/conversation-log.js +0 -44
  36. package/lib/directory-session.d.ts +0 -7
  37. package/lib/directory-session.js +0 -153
  38. package/lib/host-directories.d.ts +0 -58
  39. package/lib/host-directories.js +0 -84
  40. package/lib/host-session-projects.d.ts +0 -12
  41. package/lib/host-session-projects.js +0 -82
  42. package/lib/local-workspace-context.d.ts +0 -46
  43. package/lib/local-workspace-context.js +0 -17
  44. package/lib/native-workspace.d.ts +0 -11
  45. package/lib/native-workspace.js +0 -1
  46. package/lib/profile-runtime.js +0 -119
  47. package/lib/workspace-directory-picker-types.d.ts +0 -44
  48. package/lib/workspace-directory-picker-types.js +0 -1
  49. package/lib/workspace-directory-picker.d.ts +0 -30
  50. package/lib/workspace-directory-picker.js +0 -328
  51. package/lib/workspace-location-types.d.ts +0 -76
  52. package/lib/workspace-location-types.js +0 -1
  53. package/lib/workspace-locations.d.ts +0 -60
  54. package/lib/workspace-locations.js +0 -439
@@ -1,60 +0,0 @@
1
- import type { ConnectApi, Result } from './api.ts';
2
- import type { NativeWorkspaceRegistry } from './native-workspace.ts';
3
- import type { WorkspaceLocationItem, WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
- import type { createHostDirectories } from './host-directories.ts';
5
- import { type LocalWorkspaceContext, type LocalWorkspaceContextRequest } from './local-workspace-context.ts';
6
- interface Options {
7
- isWorkspacePending?: (workspaceId: string) => boolean;
8
- profileDir: string;
9
- metadataMaxBytes: number;
10
- pageSize: number;
11
- api: Pick<ConnectApi, 'getConnectionState' | 'getModelCatalogTarget'>;
12
- registry: NativeWorkspaceRegistry;
13
- sessions?: {
14
- get(id: string): {
15
- header: {
16
- parentSession?: string;
17
- };
18
- } | undefined;
19
- };
20
- hostDirectories?: ReturnType<typeof createHostDirectories>;
21
- onState?: (s: WorkspaceLocationState) => void;
22
- nextRevision?: () => number;
23
- }
24
- export declare function createWorkspaceLocations(o: Options): {
25
- retireEmployee: (expected: {
26
- host: string;
27
- username: string;
28
- port: number;
29
- }) => Promise<Result<undefined>>;
30
- guardEmployee: (sessionId: string, target: {
31
- host: string;
32
- username: string;
33
- }, source: {
34
- host: string;
35
- path: string;
36
- }) => Promise<void>;
37
- captureWorkspacePickerGuard: (workspaceId: string, expectedBindingId: string) => () => void;
38
- getLocalWorkspaceContext: (request: LocalWorkspaceContextRequest) => Promise<Result<LocalWorkspaceContext>>;
39
- getWorkspaceLocationState: () => {
40
- host: {
41
- host: string;
42
- username: string;
43
- port: number;
44
- } | null;
45
- instanceId: string;
46
- epoch: number;
47
- revision: number;
48
- phase: "loading" | "ready" | "failed" | "disposed";
49
- pageSize: number;
50
- items: WorkspaceLocationItem[];
51
- need?: import("./api.ts").ConnectNeed;
52
- };
53
- onWorkspaceLocationState(listener: (s: WorkspaceLocationState) => void): () => void;
54
- refreshWorkspaceLocations: () => Promise<Result<WorkspaceLocationState>>;
55
- browseWorkspaceHostDirectories: (c: WorkspaceBrowseRequest) => Promise<Result<WorkspaceBrowsePage>>;
56
- selectWorkspaceLocation: (c: WorkspaceSelectRequest) => Promise<Result<WorkspaceLocationState>>;
57
- observeConnection(): void;
58
- dispose(): Promise<void>;
59
- };
60
- export {};
@@ -1,439 +0,0 @@
1
- import { renameSync } from 'node:fs';
2
- import { lstat, realpath, open, rm } from 'node:fs/promises';
3
- import { join, isAbsolute } from 'node:path';
4
- import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
5
- import { privateDirectory, readPrivate, readPrivateSync } from "./private-files.js";
6
- import { fail, ok, need, NeedError } from "./needs.js";
7
- import { readLocalWorkspaceProcess } from "./local-workspace-context.js";
8
- import { isDeepStrictEqual } from 'node:util';
9
- const queues = new Map();
10
- const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
11
- const token = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
12
- const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
13
- const checksum = (r) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, undefined]);
14
- const sameNative = (a, b) => a.workspaceId === b.workspaceId && a.localPath === b.localPath && a.localDev === b.localDev && a.localIno === b.localIno;
15
- export function createWorkspaceLocations(o) {
16
- const controllers = new Set();
17
- const root = join(o.profileDir, 'ai-workbench-connect'), file = join(root, 'locations.json'), secret = randomBytes(32), listeners = new Set();
18
- let disposed = false, revision = 0, tail = Promise.resolve();
19
- let snapshot = { ...connection(), host: currentHost(), revision: 0, phase: 'loading', pageSize: o.pageSize, items: [] };
20
- function connection() { const c = o.api.getConnectionState(); return { instanceId: c.instanceId, epoch: c.epoch }; }
21
- function currentHost() { const c = o.api.getConnectionState(); if (c.phase !== 'connected')
22
- return null; const r = o.api.getModelCatalogTarget('codex'); if (!r.ok || r.value.instanceId !== c.instanceId || r.value.epoch !== c.epoch)
23
- return null; const { host, username, port } = r.value.target; return { host, username, port }; }
24
- function exact(c) { const now = connection(); return !disposed && now.instanceId === c.instanceId && now.epoch === c.epoch; }
25
- function reject(code) { throw new NeedError(need(code)); }
26
- function check(c) {
27
- if (!exact(c))
28
- reject(disposed ? 'DISPOSED' : 'WORKSPACE_LOCATION_CONFLICT');
29
- }
30
- function publish(items, error) {
31
- snapshot = { ...connection(), host: currentHost(), revision: (revision = o.nextRevision?.() ?? revision + 1), phase: disposed ? 'disposed' : error ? 'failed' : 'ready', pageSize: o.pageSize, items, ...(error ? { need: need(error) } : {}) };
32
- let failed = false, firstError;
33
- const notify = (listener) => { try {
34
- listener(structuredClone(snapshot));
35
- }
36
- catch (e) {
37
- if (!failed) {
38
- failed = true;
39
- firstError = e;
40
- }
41
- } };
42
- for (const listener of listeners)
43
- notify(listener);
44
- if (o.onState)
45
- notify(o.onState);
46
- if (failed)
47
- throw firstError;
48
- }
49
- function serial(fn) {
50
- const before = queues.get(file) ?? Promise.resolve();
51
- const task = before.then(async () => {
52
- if (disposed)
53
- return fail('DISPOSED');
54
- try {
55
- return await fn();
56
- }
57
- catch (e) {
58
- return e instanceof NeedError ? { ok: false, error: e.need } : fail('WORKSPACE_LOCATION_STORAGE_FAILED');
59
- }
60
- });
61
- const settled = task.then(() => { }, () => { });
62
- tail = settled;
63
- queues.set(file, settled);
64
- void settled.then(() => {
65
- if (queues.get(file) === settled)
66
- queues.delete(file);
67
- });
68
- return task;
69
- }
70
- async function prepare() {
71
- if (!isAbsolute(o.profileDir) || await realpath(o.profileDir) !== o.profileDir)
72
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
73
- await privateDirectory(root);
74
- if (await realpath(root) !== root)
75
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
76
- if (!Number.isSafeInteger(o.pageSize) || o.pageSize < 1)
77
- reject('SETTINGS_REQUIRED');
78
- }
79
- async function records() {
80
- let raw;
81
- try {
82
- raw = await readPrivate(file, o.metadataMaxBytes);
83
- }
84
- catch (e) {
85
- if (e.code === 'ENOENT')
86
- return [];
87
- throw e;
88
- }
89
- return parseRecords(raw);
90
- }
91
- function parseRecords(raw) {
92
- const data = JSON.parse(raw);
93
- if (!obj(data) || data.schemaVersion !== 1 || !Array.isArray(data.items))
94
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
95
- const result = [], ids = new Set(), active = new Set();
96
- for (const r of data.items) {
97
- if (r?.source === 'legacy-host')
98
- continue;
99
- if (!obj(r) || !token(r.workspaceId) || typeof r.active !== 'boolean' || r.active && active.has(r.workspaceId))
100
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
101
- if (r.source === 'host') {
102
- // 旧记录仅取主机与路径;旧 identity/key/dev/ino 不再属于主机来源合同。
103
- if (!obj(r.host) || !token(r.host.host) || !obj(r.remote) || !token(r.remote.path) || !isAbsolute(r.remote.path))
104
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
105
- if (r.host.username !== undefined && !/^emp-[a-z0-9][a-z0-9-]*$/.test(r.host.username))
106
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
107
- if (r.sessionIds !== undefined && (!Array.isArray(r.sessionIds) || r.sessionIds.some((id) => !token(id)) || new Set(r.sessionIds).size !== r.sessionIds.length))
108
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
109
- result.push({ workspaceId: r.workspaceId, source: 'host', active: r.active, ...(r.sessionIds !== undefined ? { sessionIds: [...r.sessionIds] } : {}), host: { host: r.host.host, ...(r.host.username ? { username: r.host.username } : {}) }, remote: { path: r.remote.path } });
110
- }
111
- else {
112
- if (r.source !== 'local' || !token(r.bindingId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || r.key !== checksum(r) || r.legacyBindingId !== undefined || r.revoked !== undefined || ids.has(r.bindingId))
113
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
114
- ids.add(r.bindingId);
115
- result.push(r);
116
- }
117
- if (r.active)
118
- active.add(r.workspaceId);
119
- }
120
- return result;
121
- }
122
- function guardStoredBinding(expected) {
123
- const current = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === expected.workspaceId);
124
- if (!current)
125
- reject('WORKSPACE_LOCATION_CONFLICT');
126
- if (!isDeepStrictEqual(current, expected))
127
- reject('WORKSPACE_LOCATION_CONFLICT');
128
- }
129
- async function save(items, beforeCommit, context) {
130
- for (const r of items)
131
- if (r.source === 'local')
132
- r.key = checksum(r);
133
- const bytes = JSON.stringify({ schemaVersion: 1, items }) + '\n';
134
- if (!Number.isSafeInteger(o.metadataMaxBytes) || o.metadataMaxBytes < 1 || Buffer.byteLength(bytes) > o.metadataMaxBytes)
135
- reject('WORKSPACE_LOCATION_STORAGE_FAILED');
136
- const temp = join(root, '.locations-' + randomUUID());
137
- try {
138
- const h = await open(temp, 'wx', 0o600);
139
- try {
140
- await h.writeFile(bytes);
141
- await h.sync();
142
- }
143
- finally {
144
- await h.close();
145
- }
146
- await beforeCommit();
147
- if (context)
148
- check(context);
149
- renameSync(temp, file);
150
- const d = await open(root, 'r');
151
- try {
152
- await d.sync();
153
- }
154
- finally {
155
- await d.close();
156
- }
157
- }
158
- finally {
159
- await rm(temp, { force: true });
160
- }
161
- }
162
- async function native(id) {
163
- const matches = o.registry.list().filter(w => w.id === id);
164
- if (matches.length !== 1)
165
- reject('WORKSPACE_LOCATION_INVALID');
166
- const w = matches[0], registered = o.registry.get(id);
167
- if (!registered || registered.path !== w.path || !isAbsolute(w.path))
168
- reject('WORKSPACE_LOCATION_INVALID');
169
- try {
170
- const localPath = await realpath(w.path), s = await lstat(localPath);
171
- if (!s.isDirectory() || s.isSymbolicLink())
172
- reject('WORKSPACE_LOCATION_INVALID');
173
- return { workspaceId: id, localPath, localDev: s.dev, localIno: s.ino };
174
- }
175
- catch {
176
- reject('WORKSPACE_LOCATION_INVALID');
177
- }
178
- }
179
- async function context(c) {
180
- if (!obj(c) || !token(c.workspaceId) || !token(c.instanceId) || !Number.isSafeInteger(c.epoch) || !(c.expectedBindingId === null || token(c.expectedBindingId)))
181
- reject('WORKSPACE_LOCATION_INVALID');
182
- check(c);
183
- await prepare();
184
- const stored = await records(), n = await native(c.workspaceId);
185
- check(c);
186
- const current = stored.find(r => r.active && r.workspaceId === c.workspaceId);
187
- if ((current?.bindingId ?? null) !== c.expectedBindingId)
188
- reject('WORKSPACE_LOCATION_CONFLICT');
189
- if (current?.source === 'local' && !sameNative(current, n))
190
- reject('WORKSPACE_LOCATION_INVALID');
191
- return { stored, n, current };
192
- }
193
- async function remote(c, run) {
194
- check(c);
195
- const controller = new AbortController();
196
- controllers.add(controller);
197
- try {
198
- return await run(controller.signal);
199
- }
200
- finally {
201
- controllers.delete(controller);
202
- }
203
- }
204
- function target() { const t = o.api.getModelCatalogTarget('codex'); if (!t.ok)
205
- throw new NeedError(t.error); return t.value.target; }
206
- const seal = (data) => { const body = Buffer.from(JSON.stringify(data)).toString('base64url'); return body + '.' + createHmac('sha256', secret).update(body).digest('base64url'); };
207
- function unseal(value) {
208
- if (!token(value) || Buffer.byteLength(value) > o.metadataMaxBytes)
209
- reject('WORKSPACE_LOCATION_CONFLICT');
210
- const [body, signature, ...extra] = value.split('.');
211
- if (extra.length || !body || !signature)
212
- reject('WORKSPACE_LOCATION_CONFLICT');
213
- const expected = createHmac('sha256', secret).update(body).digest(), actual = Buffer.from(signature, 'base64url');
214
- if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
215
- reject('WORKSPACE_LOCATION_CONFLICT');
216
- try {
217
- return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
218
- }
219
- catch {
220
- reject('WORKSPACE_LOCATION_CONFLICT');
221
- }
222
- }
223
- async function items(stored) {
224
- const result = [];
225
- for (const w of o.registry.list()) {
226
- const r = stored.find(r => r.active && r.workspaceId === w.id);
227
- if (r?.source === 'host') {
228
- const title = w.title.replace(/(本机)$|(远程主机)$/u, '') + '(远程主机)';
229
- if (w.setTitle && w.title !== title)
230
- await w.setTitle(title);
231
- result.push({ workspaceId: w.id, workspaceName: title, localPath: w.path, bindingId: null, source: 'host', host: r.host, remote: r.remote });
232
- continue;
233
- }
234
- let n;
235
- try {
236
- n = await native(w.id);
237
- }
238
- catch {
239
- result.push({ workspaceId: w.id, workspaceName: w.title, localPath: w.path, bindingId: null, source: null, status: 'invalid', execution: 'not-selected', need: need('WORKSPACE_LOCATION_INVALID') });
240
- continue;
241
- }
242
- let title = w.title;
243
- if (r && w.setTitle) {
244
- title = w.title.replace(/(本机)$|(远程主机)$/u, '') + '(本机)';
245
- if (title !== w.title)
246
- await w.setTitle(title);
247
- }
248
- const valid = !r || sameNative(r, n);
249
- result.push({ workspaceId: w.id, workspaceName: title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? null, source: r ? 'local' : null, status: r ? (valid ? 'selected' : 'invalid') : 'unselected', execution: r ? 'local-pending' : 'not-selected', ...(!valid ? { need: need('WORKSPACE_LOCATION_INVALID') } : {}) });
250
- }
251
- return result;
252
- }
253
- async function refresh() { try {
254
- await prepare();
255
- publish(await items(await records()));
256
- return ok(structuredClone(snapshot));
257
- }
258
- catch (e) {
259
- publish(snapshot.items, e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED');
260
- throw e;
261
- } }
262
- function strict(value, keys) {
263
- if (Object.keys(value).some(k => !keys.includes(k)))
264
- reject('WORKSPACE_LOCATION_INVALID');
265
- }
266
- async function browse(c) {
267
- await prepare();
268
- if (!token(c.workspaceId) || c.path !== undefined && (!token(c.path) || !isAbsolute(c.path)))
269
- reject('HOST_DIRECTORY_INVALID');
270
- const t = target();
271
- if (!o.hostDirectories)
272
- reject('DEPENDENCY_REQUIRED');
273
- const previous = c.cursor ? unseal(c.cursor) : undefined;
274
- const page = await remote(connection(), signal => o.hostDirectories.browse(t, { ...(c.path ? { path: c.path } : previous ? { path: previous.path } : {}), pageSize: c.pageSize ?? o.pageSize, ...(previous ? { after: previous.after } : {}) }, signal));
275
- if (!page.ok)
276
- return page;
277
- const host = { host: t.host, username: t.username, port: t.port };
278
- return ok({ ...page.value, ...connection(), workspaceId: c.workspaceId, bindingId: c.expectedBindingId, host, pageSize: c.pageSize ?? o.pageSize, selectionToken: seal({ host: t.host, path: page.value.path }), entries: page.value.entries.map(e => ({ ...e, selectionToken: seal({ host: t.host, path: e.path ?? e.requestedPath }) })), ...(page.value.nextAfter ? { nextCursor: seal({ path: page.value.path, after: page.value.nextAfter }) } : {}) });
279
- }
280
- async function select(c) {
281
- if (!obj(c) || !['local', 'host'].includes(c.source))
282
- reject('WORKSPACE_LOCATION_INVALID');
283
- if (c.source === 'host') {
284
- await prepare();
285
- const selected = 'selectionToken' in c ? unseal(c.selectionToken) : c;
286
- if (!token(c.workspaceId) || !token(selected.host) || !token(selected.path) || !isAbsolute(selected.path))
287
- reject('HOST_DIRECTORY_INVALID');
288
- const stored = await records();
289
- for (const old of stored)
290
- if (old.workspaceId === c.workspaceId)
291
- old.active = false;
292
- stored.push({ workspaceId: c.workspaceId, source: 'host', active: true, host: { host: selected.host }, remote: { path: selected.path } });
293
- await save(stored, async () => { });
294
- publish(await items(stored));
295
- return ok(structuredClone(snapshot));
296
- }
297
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source']);
298
- const x = await context(c);
299
- if (x.current?.source === 'local')
300
- return ok(structuredClone(snapshot));
301
- const r = { ...x.n, bindingId: randomUUID(), source: 'local', active: true, key: '' };
302
- for (const old of x.stored)
303
- if (old.active && old.workspaceId === c.workspaceId)
304
- old.active = false;
305
- x.stored.push(r);
306
- await save(x.stored, async () => { if (!sameNative(await native(c.workspaceId), x.n))
307
- reject('WORKSPACE_LOCATION_CONFLICT'); check(c); }, c);
308
- publish(await items(x.stored));
309
- check(c);
310
- return ok(structuredClone(snapshot));
311
- }
312
- function checkPending(id) { if (o.isWorkspacePending?.(id))
313
- reject('WORKSPACE_PICKER_ROLLBACK_FAILED'); }
314
- function checkLocalContext(c) {
315
- checkPending(c.workspaceId);
316
- const current = o.api.getConnectionState();
317
- if (disposed || current.phase === 'disposed')
318
- reject('DISPOSED');
319
- if (current.instanceId !== c.instanceId || current.epoch !== c.epoch)
320
- reject('WORKSPACE_LOCATION_CONFLICT');
321
- }
322
- function registeredLocalPath(id) {
323
- const matches = o.registry.list().filter(w => w.id === id), registered = o.registry.get(id);
324
- if (matches.length !== 1 || !registered || registered.id !== id || !isAbsolute(matches[0].path) || registered.path !== matches[0].path)
325
- reject('WORKSPACE_LOCATION_INVALID');
326
- return matches[0].path;
327
- }
328
- async function localContext(c) {
329
- checkLocalContext(c);
330
- await prepare();
331
- const stored = await records();
332
- const record = stored.find(r => r.active && r.workspaceId === c.workspaceId);
333
- if (!record || record.bindingId !== c.expectedBindingId)
334
- reject('WORKSPACE_LOCATION_CONFLICT');
335
- if (record.source !== 'local')
336
- reject('WORKSPACE_LOCATION_INVALID');
337
- const registeredPath = registeredLocalPath(c.workspaceId);
338
- const first = await native(c.workspaceId);
339
- if (!sameNative(record, first))
340
- reject('WORKSPACE_LOCATION_INVALID');
341
- const facts = readLocalWorkspaceProcess();
342
- if (!facts.ok)
343
- return facts;
344
- const latest = (await records()).find(r => r.active && r.workspaceId === c.workspaceId);
345
- if (!latest || latest.bindingId !== record.bindingId || latest.source !== 'local' || !sameNative(record, latest))
346
- reject('WORKSPACE_LOCATION_CONFLICT');
347
- const last = await native(c.workspaceId);
348
- if (!sameNative(record, last))
349
- reject('WORKSPACE_LOCATION_INVALID');
350
- // Final synchronous registry check closes changes during the preceding filesystem awaits.
351
- if (registeredLocalPath(c.workspaceId) !== registeredPath)
352
- reject('WORKSPACE_LOCATION_INVALID');
353
- checkLocalContext(c);
354
- return ok({ version: 1, instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, bindingId: record.bindingId, source: 'local',
355
- directory: { path: last.localPath, device: last.localDev, inode: last.localIno }, provenance: 'official-workspace-registry', process: facts.value });
356
- }
357
- function getLocalWorkspaceContext(request) {
358
- if (disposed || o.api.getConnectionState().phase === 'disposed')
359
- return Promise.resolve(fail('DISPOSED'));
360
- if (!obj(request) || Object.keys(request).sort().join(',') !== 'epoch,expectedBindingId,instanceId,workspaceId' || !token(request.instanceId) || !Number.isSafeInteger(request.epoch) || request.epoch < 0 || !token(request.workspaceId) || !token(request.expectedBindingId))
361
- return Promise.resolve(fail('WORKSPACE_LOCATION_INVALID'));
362
- if (o.isWorkspacePending?.(request.workspaceId))
363
- return Promise.resolve(fail('WORKSPACE_PICKER_ROLLBACK_FAILED'));
364
- // Copy before queueing: retaining the caller's input cannot change this operation's scope.
365
- const c = { instanceId: request.instanceId, epoch: request.epoch, workspaceId: request.workspaceId, expectedBindingId: request.expectedBindingId };
366
- return serial(() => localContext(c));
367
- }
368
- function captureWorkspacePickerGuard(workspaceId, expectedBindingId) {
369
- const original = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === workspaceId);
370
- if (!original || original.source !== 'local' || original.bindingId !== expectedBindingId)
371
- reject('WORKSPACE_LOCATION_CONFLICT');
372
- const registeredPath = registeredLocalPath(workspaceId);
373
- return () => { guardStoredBinding(original); if (registeredLocalPath(workspaceId) !== registeredPath)
374
- reject('WORKSPACE_LOCATION_INVALID'); };
375
- }
376
- async function retireEmployee(expected) {
377
- return serial(async () => {
378
- const stored = await records(), registry = o.registry.list();
379
- const hosts = stored.filter((r) => r.source === 'host' && r.host.host === expected.host);
380
- for (const workspaceId of new Set(hosts.map(r => r.workspaceId))) {
381
- const history = hosts.filter(r => r.workspaceId === workspaceId), native = registry.filter(w => w.id === workspaceId);
382
- const assigned = new Set(history.flatMap(r => r.sessionIds ?? []));
383
- const unassigned = [...new Set(native.flatMap(w => w.sessionIds))].filter(id => !assigned.has(id));
384
- let own = history.find(r => r.host.username === expected.username);
385
- for (const r of history)
386
- if (!r.host.username) {
387
- r.host.username = expected.username;
388
- if (native.length)
389
- r.sessionIds = [];
390
- own ??= r;
391
- }
392
- if (!own && (unassigned.length || !native.length)) {
393
- const source = history.find(r => r.active) ?? history[history.length - 1];
394
- own = { workspaceId, source: 'host', active: false, host: { host: expected.host, username: expected.username }, remote: { ...source.remote } };
395
- stored.push(own);
396
- }
397
- // 仅补本身份尚未归属的会话;旧员工快照和当前来源均保持。
398
- if (own && native.length)
399
- own.sessionIds = [...new Set([...(own.sessionIds ?? []), ...unassigned])];
400
- }
401
- await save(parseRecords(JSON.stringify({ schemaVersion: 1, items: stored })), async () => { });
402
- publish(snapshot.items);
403
- return ok(undefined);
404
- });
405
- }
406
- async function guardEmployee(sessionId, target, source) {
407
- if (disposed)
408
- reject('DISPOSED');
409
- // DSH子代理子会话不是workspace成员:沿live parentSession取最近的登记祖先,按它的归属核对。
410
- const member = (id) => o.registry.list().some(w => w.sessionIds.includes(id)), seen = new Set();
411
- while (!member(sessionId)) {
412
- seen.add(sessionId);
413
- const parent = o.sessions?.get(sessionId)?.header.parentSession;
414
- if (!parent || seen.has(parent) || !o.sessions?.get(parent))
415
- break;
416
- sessionId = parent;
417
- }
418
- const ids = new Set(o.registry.list().filter(w => w.sessionIds.includes(sessionId)).map(w => w.id));
419
- // Missing historical registry information keeps the original source-path refusal.
420
- const stored = await records();
421
- if (disposed)
422
- reject('DISPOSED');
423
- if (stored.some(r => r.source === 'host' && r.host.host === source.host && r.host.host === target.host && r.host.username && r.host.username !== target.username && (r.sessionIds?.includes(sessionId) || r.remote.path === source.path && (!ids.size || r.sessionIds === undefined && ids.has(r.workspaceId)))))
424
- reject('WORKSPACE_LOCATION_INVALID');
425
- }
426
- return { retireEmployee, guardEmployee, captureWorkspacePickerGuard, getLocalWorkspaceContext, getWorkspaceLocationState: () => ({ ...structuredClone(snapshot), host: currentHost() }), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), observeConnection() {
427
- if (disposed)
428
- return;
429
- for (const controller of controllers)
430
- controller.abort();
431
- publish(snapshot.items);
432
- }, dispose() {
433
- disposed = true;
434
- for (const controller of controllers)
435
- controller.abort();
436
- listeners.clear();
437
- return tail.then(() => { });
438
- } };
439
- }