@ai-workbench/connect 0.7.27 → 0.7.29

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.
@@ -1,8 +1,8 @@
1
- import { access, lstat, stat, realpath, readdir, mkdir, open, rename, rm } from 'node:fs/promises';
1
+ import { access, lstat, stat, realpath, mkdir, open, rename, rm } from 'node:fs/promises';
2
2
  import { constants, lstatSync, realpathSync } from 'node:fs';
3
3
  import { join, dirname, basename, isAbsolute } from 'node:path';
4
4
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
5
- import { privateDirectory, readPrivate, readPrivateSync } from "./private-files.js";
5
+ import { privateDirectory, readPrivate } from "./private-files.js";
6
6
  import { fail, ok, need, NeedError } from "./needs.js";
7
7
  const queues = new Map();
8
8
  const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
@@ -10,7 +10,6 @@ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
10
10
  const string = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
11
11
  const path = (v) => string(v) && isAbsolute(v);
12
12
  const digest = (v) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
13
- const decimal = (v) => typeof v === 'string' && /^\d+$/.test(v);
14
13
  const strict = (v, keys) => Object.keys(v).every(k => keys.includes(k));
15
14
  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]);
16
15
  const sameSnapshot = (a, b) => sameInfo(a, b) && a.identity.mtimeNs === b.identity.mtimeNs && a.identity.ctimeNs === b.identity.ctimeNs;
@@ -39,11 +38,11 @@ export function createWorkspaceDirectoryPicker(o) {
39
38
  if (!object(doc) || !strict(doc, ['data', 'checksum']) || !object(doc.data) || doc.checksum !== hash(doc.data))
40
39
  reject('WORKSPACE_PICKER_STORAGE_FAILED');
41
40
  const d = doc.data;
42
- 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))
41
+ 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) || !path(d.host.path)) || !Array.isArray(d.mappings))
43
42
  reject('WORKSPACE_PICKER_STORAGE_FAILED');
44
43
  const names = new Set();
45
44
  for (const m of d.mappings) {
46
- 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))
45
+ if (!object(m) || !digest(m.name) || !path(m.remotePath) || names.has(m.name))
47
46
  reject('WORKSPACE_PICKER_STORAGE_FAILED');
48
47
  names.add(m.name);
49
48
  }
@@ -83,12 +82,8 @@ export function createWorkspaceDirectoryPicker(o) {
83
82
  finally {
84
83
  await rm(temp, { force: true });
85
84
  } }
86
- async function trust(c) { check(c); const current = o.api.getConnectionState(); if (current.phase !== 'connected')
87
- throw new NeedError(current.need ?? need('CONNECTION_LOST')); const t = take(o.api.getModelCatalogTarget('codex')); if (t.instanceId !== c.instanceId || t.epoch !== c.epoch)
88
- 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]) }; }
89
- function guardTrust(c, identity) { check(c); const current = o.api.getConnectionState(); if (current.phase !== 'connected')
90
- 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)
91
- reject('WORKSPACE_LOCATION_CONFLICT'); }
85
+ function hostTarget() { if (disposed)
86
+ reject('DISPOSED'); const t = take(o.api.getModelCatalogTarget('codex')); return { target: t.target, host: t.target.host }; }
92
87
  async function remote(run) { const controller = new AbortController(); controllers.add(controller); try {
93
88
  return take(await run(controller.signal));
94
89
  }
@@ -125,24 +120,15 @@ export function createWorkspaceDirectoryPicker(o) {
125
120
  catch {
126
121
  return reject('WORKSPACE_PICKER_INVALID');
127
122
  } }
128
- async function inspect(s) { check(s.context); let current; if (s.target === 'host') {
129
- const t = await trust(s.context);
130
- if (t.identity !== s.identity)
131
- reject('WORKSPACE_LOCATION_CONFLICT');
132
- if (!o.hostDirectories)
133
- reject('DEPENDENCY_REQUIRED');
134
- current = await remote(signal => o.hostDirectories.inspect(t.target, s.info.requestedPath, signal));
135
- guardTrust(s.context, t.identity);
136
- }
137
- else
138
- current = await localInfo(s.info.requestedPath); check(s.context); if (!sameInfo(s.info, current))
123
+ async function inspect(s) { if (s.target === 'host') {
124
+ if (disposed)
125
+ reject('DISPOSED');
126
+ return s.info;
127
+ } check(s.context); const current = await localInfo(s.info.requestedPath); check(s.context); if (!sameInfo(s.info, current))
139
128
  reject('HOST_DIRECTORY_CHANGED'); if (current.permissions.read !== true || current.permissions.execute !== true)
140
129
  reject('HOST_DIRECTORY_UNREADABLE'); return current; }
141
130
  async function nativePath(p) { const s = await lstat(p, { bigint: true }); if (!s.isDirectory() || s.isSymbolicLink() || await realpath(p) !== p)
142
131
  reject('WORKSPACE_LOCATION_INVALID'); return { device: String(s.dev), inode: String(s.ino) }; }
143
- 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)
144
- reject('WORKSPACE_PICKER_STORAGE_FAILED'); if (j.device !== undefined && (String(s.dev) !== j.device || String(s.ino) !== j.inode))
145
- reject('WORKSPACE_PICKER_STORAGE_FAILED'); return { device: String(s.dev), inode: String(s.ino) }; }
146
132
  const unsubscribe = o.api.onConnectionState?.(() => { for (const controller of controllers)
147
133
  controller.abort(); });
148
134
  function serial(run) { const before = queues.get(file) ?? Promise.resolve(); const task = before.then(async () => { if (disposed)
@@ -166,20 +152,18 @@ export function createWorkspaceDirectoryPicker(o) {
166
152
  const target = (r.target ?? previous?.target ?? state.lastTarget ?? 'local');
167
153
  if (previous && target !== previous.target)
168
154
  reject('WORKSPACE_PICKER_INVALID');
169
- if (previous)
155
+ if (previous?.target === 'local')
170
156
  check(previous.context);
171
157
  if (target === 'local' && r.path === undefined)
172
158
  return ok({ target, path: '', parentPath: null, entries: [], selectionToken: '' });
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 === 'host' && state.host?.identity === trusted?.identity ? state.host?.path : undefined), notice;
159
+ const trusted = target === 'host' ? hostTarget() : undefined;
160
+ let requested = r.path ?? previous?.info.requestedPath ?? (target === 'host' && (!state.host?.host || state.host.host === trusted?.host) ? state.host?.path : undefined), notice;
177
161
  let info, entries, after = cursor?.kind === 'cursor' ? cursor.after : undefined, nextAfter;
178
162
  async function read() {
179
163
  if (target === 'host') {
180
164
  if (!o.hostDirectories)
181
165
  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));
166
+ return remote(signal => o.hostDirectories.browse(trusted.target, { ...(requested !== undefined ? { path: requested } : {}), pageSize: o.pageSize, ...(after ? { after } : {}) }, signal));
183
167
  }
184
168
  return { ...await localInfo(requested), entries: [] };
185
169
  }
@@ -197,13 +181,13 @@ export function createWorkspaceDirectoryPicker(o) {
197
181
  const { entries: rawEntries, nextAfter: more, ...directory } = page;
198
182
  info = directory;
199
183
  nextAfter = more;
200
- 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 }));
201
- if (previous && !sameSnapshot(previous.info, info))
202
- reject('HOST_DIRECTORY_CHANGED');
203
- check(c);
204
- if (trusted)
205
- guardTrust(c, trusted.identity);
206
- const selected = { kind: 'selection', target, context: c, ...(trusted ? { identity: trusted.identity } : {}), info };
184
+ entries = rawEntries.map(e => ({ name: e.name, path: e.requestedPath, available: !e.errorCode && e.path !== undefined, isSymlink: e.isSymlink }));
185
+ if (target === 'local') {
186
+ if (previous && !sameSnapshot(previous.info, info))
187
+ reject('HOST_DIRECTORY_CHANGED');
188
+ check(c);
189
+ }
190
+ const selected = { kind: 'selection', target, context: c, ...(trusted ? { host: trusted.host } : {}), info };
207
191
  const result = { target, path: info.path, parentPath: info.parentPath, entries, selectionToken: seal(selected), ...(nextAfter ? { nextCursor: seal({ kind: 'cursor', selection: selected, after: nextAfter }) } : {}), ...(notice ? { notice } : {}) };
208
192
  if (Buffer.byteLength(JSON.stringify(result)) > o.metadataMaxBytes)
209
193
  reject('HOST_DIRECTORY_PAGE_TOO_LARGE');
@@ -215,67 +199,48 @@ export function createWorkspaceDirectoryPicker(o) {
215
199
  const s = unseal(r.selectionToken);
216
200
  if (s.kind !== 'selection' || s.target !== 'host')
217
201
  reject('WORKSPACE_PICKER_INVALID');
218
- const info = await inspect(s), t = await trust(s.context);
219
- if (t.identity !== s.identity)
220
- reject('WORKSPACE_LOCATION_CONFLICT');
202
+ const info = s.info, t = hostTarget();
203
+ if (t.host !== s.host)
204
+ throw new NeedError({ ...need('WORKSPACE_PICKER_INVALID'), message: '当前已连接另一台主机,请返回并重新浏览要操作的主机目录。', officialReason: 'SELECTED_HOST_UNAVAILABLE' });
221
205
  if (!o.hostDirectories?.create)
222
206
  reject('DEPENDENCY_REQUIRED');
223
- const child = await remote(signal => o.hostDirectories.create(t.target, info.path, r.name, info.identity, signal));
224
- guardTrust(s.context, t.identity);
207
+ const child = await remote(signal => o.hostDirectories.create(t.target, info.path, r.name, signal));
225
208
  return browse({ target: 'host', path: child.path });
226
209
  }
227
- function sameSource(item, s) {
228
- if (item?.status !== 'selected' || item.source !== s.target)
229
- return false;
230
- if (s.target === 'local')
231
- return true;
232
- // refresh revalidates the old binding's requested path and entry. A newly
233
- // browsed alias may share its canonical directory without rewriting that binding.
234
- const a = item.remote, b = s.info;
235
- 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]))
236
- return false;
237
- const current = take(o.api.getModelCatalogTarget('codex')).target;
238
- return item.host?.host === current.host && item.host.username === current.username && item.host.port === current.port;
239
- }
210
+ function sameSource(item, s) { return s.target === 'local' ? item?.status === 'selected' && item.source === 'local' : item?.source === 'host' && item.host?.host === s.host && item.remote?.path === s.info.path; }
240
211
  function registrationTitle(j) { return (basename(j.selectedPath) || j.selectedPath) + ' · 正在添加 · ' + j.id; }
212
+ async function selectHost(s) {
213
+ if (disposed)
214
+ reject('DISPOSED');
215
+ if (!s.host || !path(s.info.path))
216
+ reject('WORKSPACE_PICKER_INVALID');
217
+ const existing = o.locations.getWorkspaceLocationState().items.find(i => i.source === 'host' && i.host?.host === s.host && i.remote?.path === s.info.path);
218
+ const name = hash([s.host, s.info.path]), localPath = existing?.localPath ?? join(mappingRoot, name);
219
+ await privateDirectory(mappingRoot);
220
+ await mkdir(localPath, { recursive: true, mode: 0o700 });
221
+ const workspace = o.registry.list().find(w => w.path === localPath) ?? await o.registry.create(localPath, (basename(s.info.path) || s.info.path) + '(远程主机)');
222
+ const saved = take(await o.locations.selectWorkspaceLocation({ ...context(), workspaceId: workspace.id, expectedBindingId: null, source: 'host', host: s.host, path: s.info.path }));
223
+ if (!sameSource(saved.items.find(i => i.workspaceId === workspace.id), s))
224
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
225
+ await save({ ...state, lastTarget: 'host', host: { host: s.host, path: s.info.path }, mappings: [...state.mappings.filter(m => m.name !== name), { name, host: s.host, remotePath: s.info.path }] });
226
+ return ok({ path: localPath, workspaceId: workspace.id, source: 'host' });
227
+ }
241
228
  async function select(r) {
242
229
  if (!object(r) || !strict(r, ['selectionToken']))
243
230
  reject('WORKSPACE_PICKER_INVALID');
244
231
  const selected = unseal(r.selectionToken);
245
232
  if (selected.kind !== 'selection')
246
233
  reject('WORKSPACE_PICKER_INVALID');
247
- const s = selected, info = await inspect(s), guard = () => { check(s.context); if (s.identity)
248
- guardTrust(s.context, s.identity); };
249
- const mapped = s.target === 'host' ? hash([s.identity, info.path]) : undefined, localPath = mapped ? join(mappingRoot, mapped) : info.path;
234
+ if (selected.target === 'host')
235
+ return selectHost(selected);
236
+ const s = selected, info = await inspect(s), guard = () => check(s.context);
237
+ const localPath = info.path;
250
238
  const previous = { ...(state.lastTarget ? { lastTarget: state.lastTarget } : {}), ...(state.local ? { local: state.local } : {}), ...(state.host ? { host: structuredClone(state.host) } : {}) };
251
- 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) };
239
+ const j = { id: randomUUID(), source: s.target, path: localPath, selectedPath: info.path, originalIds: o.registry.list().map(w => w.id) };
252
240
  if (!o.registry.list().some(w => w.path === localPath))
253
241
  activePath = localPath;
254
242
  try {
255
- if (mapped) {
256
- await privateDirectory(mappingRoot);
257
- if (await realpath(mappingRoot) !== mappingRoot)
258
- reject('WORKSPACE_PICKER_STORAGE_FAILED');
259
- const known = state.mappings.find(m => m.name === mapped);
260
- try {
261
- const observed = await mappingPath(j);
262
- if (known && (known.device !== observed.device || known.inode !== observed.inode) && o.registry.list().some(w => w.path === localPath))
263
- reject('WORKSPACE_PICKER_STORAGE_FAILED');
264
- if (!known && (await readdir(localPath)).length !== 0)
265
- reject('WORKSPACE_PICKER_STORAGE_FAILED');
266
- Object.assign(j, observed);
267
- }
268
- catch (e) {
269
- if (e.code !== 'ENOENT')
270
- throw e;
271
- await mkdir(localPath, { mode: 0o700 });
272
- Object.assign(j, await mappingPath(j));
273
- }
274
- const current = { name: mapped, identity: s.identity, remotePath: info.path, device: j.device, inode: j.inode };
275
- await save({ ...state, mappings: [...state.mappings.filter(m => m.name !== mapped), current] }, guard);
276
- }
277
- else
278
- Object.assign(j, await nativePath(localPath));
243
+ Object.assign(j, await nativePath(localPath));
279
244
  guard();
280
245
  const matches = o.registry.list().filter(w => w.path === localPath);
281
246
  if (matches.length > 1)
@@ -305,13 +270,6 @@ export function createWorkspaceDirectoryPicker(o) {
305
270
  reject('WORKSPACE_LOCATION_CONFLICT');
306
271
  const c = { ...s.context, workspaceId: workspace.id, expectedBindingId: null };
307
272
  let request = { ...c, source: 'local' };
308
- if (s.target === 'host') {
309
- const page = take(await o.locations.browseWorkspaceHostDirectories({ ...c, path: info.requestedPath }));
310
- guard();
311
- if (!sameInfo(info, page))
312
- reject('HOST_DIRECTORY_CHANGED');
313
- request = { ...c, source: 'host', selectionToken: page.selectionToken };
314
- }
315
273
  await inspect(s);
316
274
  guard();
317
275
  const saved = take(await o.locations.selectWorkspaceLocation(request));
@@ -320,7 +278,7 @@ export function createWorkspaceDirectoryPicker(o) {
320
278
  reject('WORKSPACE_LOCATION_CONFLICT');
321
279
  j.bindingId = itemAfter.bindingId;
322
280
  }
323
- const n = mapped ? await mappingPath(j) : await nativePath(localPath);
281
+ const n = await nativePath(localPath);
324
282
  if (n.device !== j.device || n.inode !== j.inode)
325
283
  reject('WORKSPACE_LOCATION_CONFLICT');
326
284
  await inspect(s);
@@ -335,9 +293,7 @@ export function createWorkspaceDirectoryPicker(o) {
335
293
  reject('WORKSPACE_LOCATION_CONFLICT'); bindingGuard(); };
336
294
  finalGuard();
337
295
  // The registration path is blocked only while this call is in flight.
338
- 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) };
339
- if (mapped)
340
- next.mappings.push({ name: mapped, identity: s.identity, remotePath: info.path, device: j.device, inode: j.inode });
296
+ const next = { ...state, lastTarget: s.target, local: info.path, mappings: state.mappings };
341
297
  await save(next, finalGuard);
342
298
  finalGuard();
343
299
  return ok({ path: localPath, workspaceId: workspace.id, source: s.target });
@@ -6,18 +6,21 @@ export interface WorkspaceLocationItem {
6
6
  localPath: string;
7
7
  bindingId: string | null;
8
8
  source: 'local' | 'host' | null;
9
- status: 'unselected' | 'selected' | 'invalid';
10
- execution: 'not-selected' | 'local-pending' | 'host-pending';
11
- remote?: HostDirectoryInfo;
9
+ status?: 'unselected' | 'selected' | 'invalid';
10
+ execution?: 'not-selected' | 'local-pending';
11
+ remote?: Pick<HostDirectoryInfo, 'path'>;
12
12
  host?: {
13
13
  host: string;
14
- username: string;
15
- port: number;
14
+ username?: string;
15
+ port?: number;
16
16
  };
17
17
  need?: ConnectNeed;
18
18
  }
19
- export interface HostWorkspaceResolveContext extends WorkspaceLocationContext {
20
- expectedBindingId: string;
19
+ /** 会话创建时记录;由 X 持久化,后续轮次只读同一来源。 */
20
+ export interface HostWorkspaceResolveContext {
21
+ source: 'host';
22
+ host: string;
23
+ path: string;
21
24
  }
22
25
  export interface WorkspaceLocationState {
23
26
  host: {
@@ -51,8 +54,8 @@ export interface WorkspaceBrowsePage extends HostDirectoryInfo {
51
54
  bindingId: string | null;
52
55
  host: {
53
56
  host: string;
54
- username: string;
55
- port: number;
57
+ username?: string;
58
+ port?: number;
56
59
  };
57
60
  selectionToken: string;
58
61
  entries: (HostDirectoryEntry & {
@@ -63,7 +66,11 @@ export interface WorkspaceBrowsePage extends HostDirectoryInfo {
63
66
  }
64
67
  export type WorkspaceSelectRequest = WorkspaceLocationContext & ({
65
68
  source: 'local';
66
- } | {
69
+ } | ({
67
70
  source: 'host';
71
+ } & ({
68
72
  selectionToken: string;
69
- });
73
+ } | {
74
+ host: string;
75
+ path: string;
76
+ })));
@@ -1,7 +1,7 @@
1
- import type { ConnectApi, Result, SshTarget } from './api.ts';
1
+ import type { ConnectApi, Result } from './api.ts';
2
2
  import type { NativeWorkspaceRegistry } from './native-workspace.ts';
3
3
  import type { WorkspaceLocationItem, WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
- import type { HostDirectoryInfo, createHostDirectories } from './host-directories.ts';
4
+ import type { createHostDirectories } from './host-directories.ts';
5
5
  import { type LocalWorkspaceContext, type LocalWorkspaceContextRequest } from './local-workspace-context.ts';
6
6
  interface Options {
7
7
  isWorkspacePending?: (workspaceId: string) => boolean;
@@ -16,16 +16,6 @@ interface Options {
16
16
  }
17
17
  export declare function createWorkspaceLocations(o: Options): {
18
18
  captureWorkspacePickerGuard: (workspaceId: string, expectedBindingId: string) => () => void;
19
- withHostBinding: <T>(input: import("./workspace-location-types.ts").HostWorkspaceResolveContext, run: (value: {
20
- directory: HostDirectoryInfo;
21
- target: SshTarget;
22
- local: {
23
- path: string;
24
- device: number;
25
- inode: number;
26
- };
27
- revision: number;
28
- }, guard: () => void) => Promise<Result<T>>, finalize?: () => void) => Promise<Result<T>>;
29
19
  getLocalWorkspaceContext: (request: LocalWorkspaceContextRequest) => Promise<Result<LocalWorkspaceContext>>;
30
20
  getWorkspaceLocationState: () => {
31
21
  host: {