@ai-workbench/connect 0.7.11 → 0.7.14

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,65 @@
1
+ import type { ConnectNeed } from './api.ts';
2
+ import type { HostDirectoryInfo, HostDirectoryEntry } from './host-directories.ts';
3
+ export interface WorkspaceLocationItem {
4
+ workspaceId: string;
5
+ workspaceName: string;
6
+ localPath: string;
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;
12
+ remote?: HostDirectoryInfo;
13
+ host?: {
14
+ host: string;
15
+ username: string;
16
+ port: number;
17
+ };
18
+ need?: ConnectNeed;
19
+ }
20
+ export interface WorkspaceLocationState {
21
+ instanceId: string;
22
+ epoch: number;
23
+ revision: number;
24
+ phase: 'loading' | 'ready' | 'failed' | 'disposed';
25
+ pageSize: number;
26
+ items: WorkspaceLocationItem[];
27
+ need?: ConnectNeed;
28
+ }
29
+ export interface WorkspaceLocationContext {
30
+ instanceId: string;
31
+ epoch: number;
32
+ workspaceId: string;
33
+ expectedBindingId: string | null;
34
+ }
35
+ export interface WorkspaceBrowseRequest extends WorkspaceLocationContext {
36
+ path?: string;
37
+ cursor?: string;
38
+ pageSize?: number;
39
+ }
40
+ export interface WorkspaceBrowsePage extends HostDirectoryInfo {
41
+ instanceId: string;
42
+ epoch: number;
43
+ workspaceId: string;
44
+ bindingId: string | null;
45
+ host: {
46
+ host: string;
47
+ username: string;
48
+ port: number;
49
+ };
50
+ selectionToken: string;
51
+ entries: (HostDirectoryEntry & {
52
+ selectionToken?: string;
53
+ })[];
54
+ nextCursor?: string;
55
+ pageSize: number;
56
+ }
57
+ export type WorkspaceSelectRequest = WorkspaceLocationContext & ({
58
+ source: 'local';
59
+ } | {
60
+ source: 'host';
61
+ selectionToken: string;
62
+ } | {
63
+ source: 'legacy-host';
64
+ confirmLegacy: true;
65
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,45 @@
1
+ import type { ConnectApi, Result } from './api.ts';
2
+ import type { NativeWorkspaceRegistry } from './workspace-bindings.ts';
3
+ import type { 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 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
+ interface Options {
23
+ profileDir: string;
24
+ metadataMaxBytes: number;
25
+ pageSize: number;
26
+ api: Pick<ConnectApi, 'getConnectionState' | 'getModelCatalogTarget'>;
27
+ registry: NativeWorkspaceRegistry;
28
+ readLegacy: () => Promise<Legacy[]>;
29
+ hostDirectories?: ReturnType<typeof createHostDirectories>;
30
+ onState?: (s: WorkspaceLocationState) => void;
31
+ nextRevision?: () => number;
32
+ }
33
+ export declare function createWorkspaceLocations(o: Options): {
34
+ getLocalWorkspaceContext: (request: LocalWorkspaceContextRequest) => Promise<Result<LocalWorkspaceContext>>;
35
+ getWorkspaceLocationState: () => WorkspaceLocationState;
36
+ onWorkspaceLocationState(listener: (s: WorkspaceLocationState) => void): () => void;
37
+ refreshWorkspaceLocations: () => Promise<Result<WorkspaceLocationState>>;
38
+ browseWorkspaceHostDirectories: (c: WorkspaceBrowseRequest) => Promise<Result<WorkspaceBrowsePage>>;
39
+ selectWorkspaceLocation: (c: WorkspaceSelectRequest) => Promise<Result<WorkspaceLocationState>>;
40
+ guardLegacySession: (id: string) => Promise<Result<void>>;
41
+ resolveLegacySession: <T>(id: string, resolve: () => Promise<Result<T>>) => Promise<Result<T>>;
42
+ observeConnection(): void;
43
+ dispose(): Promise<unknown>;
44
+ };
45
+ export {};
@@ -0,0 +1,427 @@
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 } from "./private-files.js";
6
+ import { fail, ok, need, NeedError } from "./needs.js";
7
+ import { readLocalWorkspaceProcess } from "./local-workspace-context.js";
8
+ const queues = new Map();
9
+ const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
10
+ const token = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
11
+ const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
12
+ const checksum = (r) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, r.legacyBindingId]);
13
+ const sameNative = (a, b) => a.workspaceId === b.workspaceId && a.localPath === b.localPath && a.localDev === b.localDev && a.localIno === b.localIno;
14
+ const sameDirectory = (a, b) => a.path === b.path && a.requestedPath === b.requestedPath && a.isSymlink === b.isSymlink && JSON.stringify(a.identity) === JSON.stringify(b.identity) && JSON.stringify(a.entryIdentity) === JSON.stringify(b.entryIdentity);
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(), 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 exact(c) { const now = connection(); return !disposed && now.instanceId === c.instanceId && now.epoch === c.epoch; }
22
+ function reject(code) { throw new NeedError(need(code)); }
23
+ function check(c) {
24
+ if (!exact(c))
25
+ reject(disposed ? 'DISPOSED' : 'WORKSPACE_LOCATION_CONFLICT');
26
+ }
27
+ function publish(items, error) {
28
+ snapshot = { ...connection(), revision: (revision = o.nextRevision?.() ?? revision + 1), phase: disposed ? 'disposed' : error ? 'failed' : 'ready', pageSize: o.pageSize, items, ...(error ? { need: need(error) } : {}) };
29
+ for (const listener of listeners)
30
+ listener(structuredClone(snapshot));
31
+ o.onState?.(structuredClone(snapshot));
32
+ }
33
+ function serial(fn) {
34
+ const before = queues.get(file) ?? Promise.resolve();
35
+ const task = before.then(async () => {
36
+ if (disposed)
37
+ return fail('DISPOSED');
38
+ try {
39
+ return await fn();
40
+ }
41
+ catch (e) {
42
+ return e instanceof NeedError ? { ok: false, error: e.need } : fail('WORKSPACE_LOCATION_STORAGE_FAILED');
43
+ }
44
+ });
45
+ tail = task.then(() => { }, () => { });
46
+ const settled = tail;
47
+ queues.set(file, settled);
48
+ void settled.then(() => {
49
+ if (queues.get(file) === settled)
50
+ queues.delete(file);
51
+ });
52
+ return task;
53
+ }
54
+ async function prepare() {
55
+ if (!isAbsolute(o.profileDir) || await realpath(o.profileDir) !== o.profileDir)
56
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
57
+ await privateDirectory(root);
58
+ if (await realpath(root) !== root)
59
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
60
+ if (!Number.isSafeInteger(o.pageSize) || o.pageSize < 1)
61
+ reject('SETTINGS_REQUIRED');
62
+ }
63
+ async function records() {
64
+ let raw;
65
+ try {
66
+ raw = await readPrivate(file, o.metadataMaxBytes);
67
+ }
68
+ catch (e) {
69
+ if (e.code === 'ENOENT')
70
+ return [];
71
+ throw e;
72
+ }
73
+ const data = JSON.parse(raw);
74
+ if (!obj(data) || data.schemaVersion !== 1 || !Array.isArray(data.items))
75
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
76
+ const ids = new Set(), active = new Set();
77
+ for (const r of data.items) {
78
+ if (!obj(r) || !token(r.bindingId) || !token(r.workspaceId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || !['local', 'host', 'legacy-host'].includes(r.source) || typeof r.active !== 'boolean' || r.source === 'legacy-host' && !token(r.legacyBindingId) || r.source !== 'legacy-host' && r.legacyBindingId !== undefined || r.key !== checksum(r) || ids.has(r.bindingId) || r.active && active.has(r.workspaceId) || r.source !== 'local' && (!obj(r.remote) || !isAbsolute(r.remote.path) || !isAbsolute(r.remote.requestedPath) || !obj(r.remote.identity) || !obj(r.remote.entryIdentity) || !obj(r.remote.permissions) || !obj(r.host) || !token(r.host.host) || !token(r.host.username) || !Number.isSafeInteger(r.host.port) || !(/^[a-f0-9]{64}$/.test(r.identity))))
79
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
80
+ ids.add(r.bindingId);
81
+ if (r.active)
82
+ active.add(r.workspaceId);
83
+ }
84
+ return data.items;
85
+ }
86
+ async function save(items, beforeCommit, context) {
87
+ for (const r of items)
88
+ r.key = checksum(r);
89
+ const bytes = JSON.stringify({ schemaVersion: 1, items }) + '\n';
90
+ if (!Number.isSafeInteger(o.metadataMaxBytes) || o.metadataMaxBytes < 1 || Buffer.byteLength(bytes) > o.metadataMaxBytes)
91
+ reject('WORKSPACE_LOCATION_STORAGE_FAILED');
92
+ const temp = join(root, '.locations-' + randomUUID());
93
+ try {
94
+ const h = await open(temp, 'wx', 0o600);
95
+ try {
96
+ await h.writeFile(bytes);
97
+ await h.sync();
98
+ }
99
+ finally {
100
+ await h.close();
101
+ }
102
+ await beforeCommit();
103
+ check(context);
104
+ renameSync(temp, file);
105
+ const d = await open(root, 'r');
106
+ try {
107
+ await d.sync();
108
+ }
109
+ finally {
110
+ await d.close();
111
+ }
112
+ }
113
+ finally {
114
+ await rm(temp, { force: true });
115
+ }
116
+ }
117
+ async function native(id) {
118
+ const matches = o.registry.list().filter(w => w.id === id);
119
+ if (matches.length !== 1)
120
+ reject('WORKSPACE_LOCATION_INVALID');
121
+ const w = matches[0], registered = o.registry.get(id);
122
+ if (!registered || registered.path !== w.path || !isAbsolute(w.path))
123
+ reject('WORKSPACE_LOCATION_INVALID');
124
+ try {
125
+ const localPath = await realpath(w.path), s = await lstat(localPath);
126
+ if (!s.isDirectory() || s.isSymbolicLink())
127
+ reject('WORKSPACE_LOCATION_INVALID');
128
+ return { workspaceId: id, localPath, localDev: s.dev, localIno: s.ino };
129
+ }
130
+ catch {
131
+ reject('WORKSPACE_LOCATION_INVALID');
132
+ }
133
+ }
134
+ async function context(c) {
135
+ if (!obj(c) || !token(c.workspaceId) || !token(c.instanceId) || !Number.isSafeInteger(c.epoch) || !(c.expectedBindingId === null || token(c.expectedBindingId)))
136
+ reject('WORKSPACE_LOCATION_INVALID');
137
+ check(c);
138
+ await prepare();
139
+ const stored = await records(), legacy = await o.readLegacy(), n = await native(c.workspaceId);
140
+ check(c);
141
+ const current = stored.find(r => r.active && r.workspaceId === c.workspaceId), old = legacy.find(r => r.workspaceId === c.workspaceId);
142
+ if ((current?.bindingId ?? old?.bindingId ?? null) !== c.expectedBindingId)
143
+ reject('WORKSPACE_LOCATION_CONFLICT');
144
+ if (current && !sameNative(current, n) || !current && old && !sameNative(old, n))
145
+ reject('WORKSPACE_LOCATION_INVALID');
146
+ return { stored, legacy, n, current, old };
147
+ }
148
+ async function remote(c, run) {
149
+ check(c);
150
+ const controller = new AbortController();
151
+ controllers.add(controller);
152
+ try {
153
+ return await run(controller.signal);
154
+ }
155
+ finally {
156
+ controllers.delete(controller);
157
+ }
158
+ }
159
+ async function target(c) {
160
+ const t = o.api.getModelCatalogTarget('codex');
161
+ if (!t.ok)
162
+ throw new NeedError(t.error);
163
+ const trust = await readPrivate(t.value.target.knownHostsFile, o.metadataMaxBytes);
164
+ check(c);
165
+ const value = t.value.target;
166
+ return { value, identity: hash([value.host, value.username, value.port, value.projectRoot, value.session, trust]) };
167
+ }
168
+ const seal = (data) => { const body = Buffer.from(JSON.stringify(data)).toString('base64url'); return body + '.' + createHmac('sha256', secret).update(body).digest('base64url'); };
169
+ function unseal(value) {
170
+ if (!token(value) || Buffer.byteLength(value) > o.metadataMaxBytes)
171
+ reject('WORKSPACE_LOCATION_CONFLICT');
172
+ const [body, signature, ...extra] = value.split('.');
173
+ if (extra.length || !body || !signature)
174
+ reject('WORKSPACE_LOCATION_CONFLICT');
175
+ const expected = createHmac('sha256', secret).update(body).digest(), actual = Buffer.from(signature, 'base64url');
176
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
177
+ reject('WORKSPACE_LOCATION_CONFLICT');
178
+ try {
179
+ return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
180
+ }
181
+ catch {
182
+ reject('WORKSPACE_LOCATION_CONFLICT');
183
+ }
184
+ }
185
+ async function items(stored, legacy) {
186
+ const result = [];
187
+ for (const w of o.registry.list()) {
188
+ let n;
189
+ try {
190
+ n = await native(w.id);
191
+ }
192
+ catch {
193
+ 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') });
194
+ continue;
195
+ }
196
+ const r = stored.find(r => r.active && r.workspaceId === w.id), old = legacy.find(r => r.workspaceId === w.id);
197
+ const base = { workspaceId: w.id, workspaceName: w.title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? old?.bindingId ?? null };
198
+ if (r) {
199
+ let valid = sameNative(r, n);
200
+ if (valid && r.source !== 'local') {
201
+ try {
202
+ valid = (await target(connection())).identity === r.identity;
203
+ }
204
+ catch {
205
+ valid = false;
206
+ }
207
+ }
208
+ result.push({ ...base, source: r.source, status: valid ? 'selected' : 'invalid', execution: r.source === 'local' ? 'local-pending' : r.source === 'host' ? 'host-pending' : 'legacy-confirmed', ...(r.remote ? { remote: r.remote, host: r.host } : {}), ...(!valid ? { need: need('WORKSPACE_LOCATION_INVALID') } : {}) });
209
+ }
210
+ else if (old) {
211
+ result.push({ ...base, source: 'legacy-host', status: 'legacy-confirmation-required', execution: 'not-selected', legacyPath: old.project.path, ...(!sameNative(old, n) ? { need: need('WORKSPACE_LOCATION_INVALID') } : {}) });
212
+ }
213
+ else
214
+ result.push({ ...base, source: null, status: 'unselected', execution: 'not-selected' });
215
+ }
216
+ return result;
217
+ }
218
+ async function refresh() {
219
+ try {
220
+ await prepare();
221
+ const stored = await records(), legacy = await o.readLegacy();
222
+ publish(await items(stored, legacy));
223
+ return ok(structuredClone(snapshot));
224
+ }
225
+ catch (e) {
226
+ publish(snapshot.items, 'WORKSPACE_LOCATION_STORAGE_FAILED');
227
+ throw e;
228
+ }
229
+ }
230
+ function strict(value, keys) {
231
+ if (Object.keys(value).some(k => !keys.includes(k)))
232
+ reject('WORKSPACE_LOCATION_INVALID');
233
+ }
234
+ async function browse(c) {
235
+ strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'path', 'cursor', 'pageSize']);
236
+ if (c.path !== undefined && (!isAbsolute(c.path) || c.path.includes('\0')) || c.path !== undefined && c.cursor !== undefined || c.pageSize !== undefined && (!Number.isSafeInteger(c.pageSize) || c.pageSize < 1))
237
+ reject('HOST_DIRECTORY_INVALID');
238
+ const x = await context(c), t = await target(c);
239
+ if (!o.hostDirectories)
240
+ reject('DEPENDENCY_REQUIRED');
241
+ let request = { pageSize: c.pageSize ?? o.pageSize, ...(c.path !== undefined ? { path: c.path } : {}) };
242
+ if (c.cursor) {
243
+ const saved = unseal(c.cursor);
244
+ if (saved.kind !== 'cursor' || JSON.stringify(saved.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }) || !sameNative(saved.native, x.n) || saved.identity !== t.identity || c.pageSize !== undefined && c.pageSize !== saved.request.pageSize)
245
+ reject('WORKSPACE_LOCATION_CONFLICT');
246
+ request = saved.request;
247
+ }
248
+ const page = await remote(c, signal => o.hostDirectories.browse(t.value, request, signal));
249
+ check(c);
250
+ if (!page.ok)
251
+ return page;
252
+ if (!sameNative(await native(c.workspaceId), x.n))
253
+ reject('WORKSPACE_LOCATION_CONFLICT');
254
+ check(c);
255
+ const base = { context: { instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }, native: x.n, identity: t.identity };
256
+ const choose = (info) => seal({ kind: 'selection', ...base, info });
257
+ const { entries, nextAfter, ...info } = page.value;
258
+ return ok({ ...info, ...connection(), workspaceId: c.workspaceId, bindingId: c.expectedBindingId, host: { host: t.value.host, username: t.value.username, port: t.value.port }, selectionToken: choose(info), pageSize: request.pageSize, entries: entries.map(e => ({ ...e, ...(e.path && e.identity && !e.errorCode ? { selectionToken: choose({ requestedPath: e.requestedPath, path: e.path, parentPath: info.path, identity: e.identity, entryIdentity: e.entryIdentity, isSymlink: e.isSymlink, permissions: e.permissions }) } : {}) })), ...(nextAfter ? { nextCursor: seal({ kind: 'cursor', ...base, request: { path: info.requestedPath, pageSize: request.pageSize, after: nextAfter, expected: info.identity } }) } : {}) });
259
+ }
260
+ async function select(c) {
261
+ if (!obj(c))
262
+ reject('WORKSPACE_LOCATION_INVALID');
263
+ strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source', ...(c.source === 'host' ? ['selectionToken'] : c.source === 'legacy-host' ? ['confirmLegacy'] : [])]);
264
+ if (!['local', 'host', 'legacy-host'].includes(c.source))
265
+ reject('WORKSPACE_LOCATION_INVALID');
266
+ const x = await context(c);
267
+ let r = { ...x.n, bindingId: randomUUID(), source: c.source, active: true, key: '' };
268
+ if (c.source !== 'local') {
269
+ const t = await target(c);
270
+ if (!o.hostDirectories)
271
+ reject('DEPENDENCY_REQUIRED');
272
+ let selected;
273
+ if (c.source === 'host') {
274
+ const s = unseal(c.selectionToken);
275
+ if (s.kind !== 'selection' || !sameNative(s.native, x.n) || s.identity !== t.identity || JSON.stringify(s.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }))
276
+ reject('WORKSPACE_LOCATION_CONFLICT');
277
+ selected = s.info;
278
+ }
279
+ else {
280
+ if (c.confirmLegacy !== true || !x.old || x.old.phase !== 'bound' || x.old.identity !== t.identity || !sameNative(x.old, x.n))
281
+ reject('WORKSPACE_LOCATION_INVALID');
282
+ const inspected = await remote(c, signal => o.hostDirectories.inspect(t.value, x.old.project.path, signal));
283
+ check(c);
284
+ if (!inspected.ok)
285
+ return inspected;
286
+ selected = inspected.value;
287
+ r.legacyBindingId = x.old.bindingId;
288
+ }
289
+ const inspected = await remote(c, signal => o.hostDirectories.inspect(t.value, selected.requestedPath, signal));
290
+ check(c);
291
+ if (!inspected.ok)
292
+ return inspected;
293
+ if (!sameDirectory(selected, inspected.value))
294
+ reject('HOST_DIRECTORY_CHANGED');
295
+ if (inspected.value.permissions.read !== true || inspected.value.permissions.execute !== true)
296
+ reject('HOST_DIRECTORY_UNREADABLE');
297
+ r = { ...r, remote: inspected.value, identity: t.identity, host: { host: t.value.host, username: t.value.username, port: t.value.port } };
298
+ }
299
+ if (!sameNative(await native(c.workspaceId), x.n))
300
+ reject('WORKSPACE_LOCATION_CONFLICT');
301
+ check(c);
302
+ if (x.current && x.current.source === r.source && JSON.stringify(x.current.remote) === JSON.stringify(r.remote) && x.current.identity === r.identity)
303
+ return ok(structuredClone(snapshot));
304
+ for (const old of x.stored)
305
+ if (old.active && old.workspaceId === c.workspaceId)
306
+ old.active = false;
307
+ if (x.stored.some(old => old.bindingId === r.bindingId))
308
+ reject('WORKSPACE_LOCATION_CONFLICT');
309
+ x.stored.push(r);
310
+ await save(x.stored, async () => {
311
+ if (!sameNative(await native(c.workspaceId), x.n))
312
+ reject('WORKSPACE_LOCATION_CONFLICT');
313
+ check(c);
314
+ }, c);
315
+ publish(await items(x.stored, x.legacy));
316
+ check(c);
317
+ return ok(structuredClone(snapshot));
318
+ }
319
+ function checkLocalContext(c) {
320
+ const current = o.api.getConnectionState();
321
+ if (disposed || current.phase === 'disposed')
322
+ reject('DISPOSED');
323
+ if (current.instanceId !== c.instanceId || current.epoch !== c.epoch)
324
+ reject('WORKSPACE_LOCATION_CONFLICT');
325
+ }
326
+ function registeredLocalPath(id) {
327
+ const matches = o.registry.list().filter(w => w.id === id), registered = o.registry.get(id);
328
+ if (matches.length !== 1 || !registered || registered.id !== id || !isAbsolute(matches[0].path) || registered.path !== matches[0].path)
329
+ reject('WORKSPACE_LOCATION_INVALID');
330
+ return matches[0].path;
331
+ }
332
+ async function localContext(c) {
333
+ checkLocalContext(c);
334
+ await prepare();
335
+ const stored = await records();
336
+ checkLocalContext(c);
337
+ const record = stored.find(r => r.active && r.workspaceId === c.workspaceId);
338
+ if (!record || record.bindingId !== c.expectedBindingId)
339
+ reject('WORKSPACE_LOCATION_CONFLICT');
340
+ if (record.source !== 'local')
341
+ reject('WORKSPACE_LOCATION_INVALID');
342
+ const registeredPath = registeredLocalPath(c.workspaceId);
343
+ const first = await native(c.workspaceId);
344
+ checkLocalContext(c);
345
+ if (!sameNative(record, first))
346
+ reject('WORKSPACE_LOCATION_INVALID');
347
+ const facts = readLocalWorkspaceProcess();
348
+ if (!facts.ok)
349
+ return facts;
350
+ const latest = (await records()).find(r => r.active && r.workspaceId === c.workspaceId);
351
+ checkLocalContext(c);
352
+ if (!latest || latest.bindingId !== record.bindingId || latest.source !== 'local' || !sameNative(record, latest))
353
+ reject('WORKSPACE_LOCATION_CONFLICT');
354
+ const last = await native(c.workspaceId);
355
+ checkLocalContext(c);
356
+ if (!sameNative(record, last))
357
+ reject('WORKSPACE_LOCATION_INVALID');
358
+ // Final synchronous registry check closes changes during the preceding filesystem awaits.
359
+ if (registeredLocalPath(c.workspaceId) !== registeredPath)
360
+ reject('WORKSPACE_LOCATION_INVALID');
361
+ checkLocalContext(c);
362
+ return ok({ version: 1, instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, bindingId: record.bindingId, source: 'local',
363
+ directory: { path: last.localPath, device: last.localDev, inode: last.localIno }, provenance: 'official-workspace-registry', process: facts.value });
364
+ }
365
+ function getLocalWorkspaceContext(request) {
366
+ if (disposed || o.api.getConnectionState().phase === 'disposed')
367
+ return Promise.resolve(fail('DISPOSED'));
368
+ 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))
369
+ return Promise.resolve(fail('WORKSPACE_LOCATION_INVALID'));
370
+ // Copy before queueing: retaining the caller's input cannot change this operation's scope.
371
+ const c = { instanceId: request.instanceId, epoch: request.epoch, workspaceId: request.workspaceId, expectedBindingId: request.expectedBindingId };
372
+ return serial(() => localContext(c));
373
+ }
374
+ async function guard(sessionId) {
375
+ const c = connection();
376
+ check(c);
377
+ await prepare();
378
+ check(c);
379
+ const workspaces = o.registry.list().filter(w => w.sessionIds.includes(sessionId));
380
+ if (workspaces.length !== 1)
381
+ return fail('WORKSPACE_LOCATION_REQUIRED');
382
+ const stored = await records();
383
+ check(c);
384
+ const r = stored.find(r => r.active && r.workspaceId === workspaces[0].id);
385
+ if (!r)
386
+ return fail('WORKSPACE_LOCATION_REQUIRED');
387
+ if (!sameNative(r, await native(r.workspaceId)))
388
+ return fail('WORKSPACE_LOCATION_INVALID');
389
+ check(c);
390
+ if (r.source === 'local')
391
+ return fail('WORKSPACE_EXECUTION_UNAVAILABLE');
392
+ if (r.source === 'host')
393
+ return fail('WORKSPACE_LOCATION_PROVIDER_REQUIRED');
394
+ const t = await target(c), legacy = (await o.readLegacy()).find(old => old.bindingId === r.legacyBindingId);
395
+ check(c);
396
+ if (!legacy || r.identity !== t.identity || legacy.identity !== t.identity || legacy.project.path !== r.remote?.path)
397
+ return fail('WORKSPACE_LOCATION_INVALID');
398
+ const current = o.hostDirectories ? await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal)) : undefined;
399
+ check(c);
400
+ if (!current?.ok || r.remote.path !== current.value.path || r.remote.requestedPath !== current.value.requestedPath || r.remote.identity.device !== current.value.identity.device || r.remote.identity.inode !== current.value.identity.inode || JSON.stringify(r.remote.entryIdentity) !== JSON.stringify(current.value.entryIdentity))
401
+ return fail('WORKSPACE_LOCATION_INVALID');
402
+ return ok(undefined);
403
+ }
404
+ return { getLocalWorkspaceContext, getWorkspaceLocationState: () => structuredClone(snapshot), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), guardLegacySession: (id) => serial(() => guard(id)), resolveLegacySession: (id, resolve) => serial(async () => {
405
+ const c = connection(), before = await guard(id);
406
+ if (!before.ok)
407
+ return before;
408
+ check(c);
409
+ const result = await resolve();
410
+ check(c);
411
+ const after = await guard(id);
412
+ check(c);
413
+ return after.ok ? result : after;
414
+ }), observeConnection() {
415
+ if (disposed)
416
+ return;
417
+ for (const controller of controllers)
418
+ controller.abort();
419
+ publish(snapshot.items.map(i => i.source === 'host' || i.source === 'legacy-host' ? { ...i, status: i.status === 'legacy-confirmation-required' ? i.status : 'invalid', need: need('WORKSPACE_LOCATION_CONFLICT') } : i));
420
+ }, dispose() {
421
+ disposed = true;
422
+ for (const controller of controllers)
423
+ controller.abort();
424
+ listeners.clear();
425
+ return tail;
426
+ } };
427
+ }