@ai-workbench/connect 0.7.28 → 0.7.31

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 (68) hide show
  1. package/NOTICE.md +2 -6
  2. package/README.md +8 -22
  3. package/client/index.cjs +17 -11
  4. package/helper/claude-callback.cjs +2 -13
  5. package/helper/host-directories.cjs +7 -12
  6. package/helper/remote-login.cjs +4 -11
  7. package/lib/api.d.ts +13 -7
  8. package/lib/auth-diagnostics.js +1 -1
  9. package/lib/browser-login.d.ts +10 -0
  10. package/lib/browser-login.js +70 -0
  11. package/lib/components.d.ts +1 -3
  12. package/lib/components.js +37 -15
  13. package/lib/connect.js +5 -1
  14. package/lib/defaults.d.ts +0 -10
  15. package/lib/defaults.js +1 -2
  16. package/lib/host-directories.d.ts +2 -3
  17. package/lib/host-directories.js +10 -8
  18. package/lib/host-session-projects.d.ts +2 -13
  19. package/lib/host-session-projects.js +65 -50
  20. package/lib/index.d.ts +0 -9
  21. package/lib/index.js +4 -13
  22. package/lib/integration.d.ts +1 -3
  23. package/lib/integration.js +8 -26
  24. package/lib/login.d.ts +2 -2
  25. package/lib/login.js +11 -9
  26. package/lib/needs.js +2 -2
  27. package/lib/ports.d.ts +1 -0
  28. package/lib/profile-runtime.js +5 -5
  29. package/lib/profile-settings.d.ts +2 -6
  30. package/lib/profile-settings.js +4 -8
  31. package/lib/remote-login.d.ts +1 -1
  32. package/lib/remote-login.js +2 -2
  33. package/lib/startup.js +19 -1
  34. package/lib/workspace-directory-picker.js +51 -95
  35. package/lib/workspace-location-types.d.ts +18 -11
  36. package/lib/workspace-locations.d.ts +2 -12
  37. package/lib/workspace-locations.js +81 -217
  38. package/package.json +3 -6
  39. package/helper/device-panel.cjs +0 -4
  40. package/helper/device-panel.css +0 -1
  41. package/helper/device-panel.html +0 -1
  42. package/helper/device-preload.cjs +0 -5
  43. package/helper/device-window.cjs +0 -60
  44. package/helper/main.cjs +0 -19
  45. package/helper/window.cjs +0 -46
  46. package/lib/archive.d.ts +0 -1
  47. package/lib/archive.js +0 -63
  48. package/lib/cache.d.ts +0 -21
  49. package/lib/cache.js +0 -156
  50. package/lib/component-download.d.ts +0 -34
  51. package/lib/component-download.js +0 -86
  52. package/lib/component-source.d.ts +0 -31
  53. package/lib/component-source.js +0 -18
  54. package/lib/electron.d.ts +0 -8
  55. package/lib/electron.js +0 -83
  56. package/lib/physical-fs.d.ts +0 -3
  57. package/lib/physical-fs.js +0 -7
  58. package/node_modules/pend/LICENSE +0 -23
  59. package/node_modules/pend/README.md +0 -41
  60. package/node_modules/pend/index.js +0 -55
  61. package/node_modules/pend/package.json +0 -18
  62. package/node_modules/pend/test.js +0 -137
  63. package/node_modules/yauzl/LICENSE +0 -21
  64. package/node_modules/yauzl/README.md +0 -1015
  65. package/node_modules/yauzl/crc32.js +0 -45
  66. package/node_modules/yauzl/fd-slicer.js +0 -188
  67. package/node_modules/yauzl/index.js +0 -1096
  68. package/node_modules/yauzl/package.json +0 -40
package/lib/needs.js CHANGED
@@ -43,11 +43,11 @@ const entries = {
43
43
  DEPENDENCY_REQUIRED: { layer: 'integration', message: '远程主机连接的连接组件没有装好,请联系管理员。', requires: '提供方契约与适配器', actor: 'administrator', action: { id: 'supply-dependency', label: '提供集成前置条件', available: false } },
44
44
  SETTINGS_REQUIRED: { layer: 'settings', message: '远程主机连接设置暂不可用,请查看技术详情。', requires: '已确认的连接设置', actor: 'administrator', action: { id: 'configure-settings', label: '确认具名设置', available: false } },
45
45
  AUTH_STATUS_INVALID: { layer: 'auth', message: '暂时无法确认登录状态,可检查本机网络后重新检查。', requires: '有效的官方 CLI 登录状态', actor: 'administrator', action: { id: 'inspect-auth-status', label: '检查官方 CLI', available: false } },
46
- LOGIN_FAILED: { layer: 'auth', message: '登录未完成,窗口已关闭或助手失败,可以重新授权。', requires: '完成 AI 授权', actor: 'employee', action: { id: 'open-login', label: '重新授权', available: true } },
46
+ LOGIN_FAILED: { layer: 'auth', message: '登录未完成,可以立即重新发起登录。', requires: '完成 AI 授权', actor: 'employee', action: { id: 'open-login', label: '重新授权', available: true } },
47
47
  HOST_TRUST_REQUIRED: { layer: 'ssh', message: '远程主机连接还缺少可信的连接信息,请联系管理员。', requires: 'host.knownHosts', actor: 'administrator', action: { id: 'supply-host-trust', label: '提供主机信任材料', available: false } },
48
48
  HOST_KEY_MISMATCH: { layer: 'ssh', message: '主机身份与已开通的信任材料不符,需要管理员检查。', requires: '匹配的主机公钥', actor: 'administrator', action: { id: 'verify-host-trust', label: '检查主机身份', available: false } },
49
49
  PROJECT_PROTOCOL_INVALID: { layer: 'projects', message: '本次未能读取工作区位置,可重新打开目录选择器再选。', requires: '匹配版本的工作区服务', actor: 'administrator', action: { id: 'inspect-project-protocol', label: '检查工作区接口', available: false } },
50
- PROJECT_BINDING_INVALID: { layer: 'projects', message: '会话的文件来源已变化,请新建会话继续。', requires: '新会话与当前文件来源', actor: 'employee', action: { id: 'new-session', label: '新建会话', available: true } },
50
+ PROJECT_BINDING_INVALID: { layer: 'projects', message: '本轮工作区准备失败,原会话历史仍可查看。请查看技术详情后再试。', requires: '可核对的会话与工作区关系', actor: 'employee', action: { id: 'inspect-remote-details', label: '查看技术详情', available: true } },
51
51
  PROJECT_BINDING_REQUIRED: { layer: 'projects', message: '请在会话中选择已关联的远程工作区。', requires: '当前会话的可信远程工作区关联', actor: 'employee', action: { id: 'select-workspace', label: '选择工作区', available: true } },
52
52
  DISPOSED: { layer: 'integration', message: '连接插件已卸载,需要重新启用插件。', requires: '已启用的连接插件', actor: 'employee', action: { id: 'enable-plugin', label: '启用插件', available: false } },
53
53
  };
package/lib/ports.d.ts CHANGED
@@ -35,6 +35,7 @@ export interface Ports {
35
35
  status(target: SshTarget, provider: Provider, signal: AbortSignal): Promise<Result<CommandResult>>;
36
36
  };
37
37
  login?: {
38
+ interaction?: ReturnType<typeof import('./browser-login.ts').createBrowserLogin>;
38
39
  run(target: SshTarget, provider: Provider, signal: AbortSignal): Promise<Result<void>>;
39
40
  };
40
41
  }
@@ -54,14 +54,16 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network, autoStart
54
54
  };
55
55
  api.readConversationLog = readLogs;
56
56
  const beforeContract = api.getContractInfo;
57
- const currentContract = () => api.getConnectionState().phase === 'disposed' ? beforeContract() : ({ ...beforeContract(), conversationLog: 1, ...(api.getWorkspaceLocationState ? { workspaceLocations: 1 } : {}), ...(api.getLocalWorkspaceContext ? { localWorkspaceContext: 1 } : {}), ...(api.getWorkspaceDirectoryPickerSettings ? { workspaceDirectoryPicker: 1 } : {}), ...(api.resolveSessionProject !== unavailableHost ? { hostWorkspaceResolution: 1 } : {}) });
57
+ const currentContract = () => api.getConnectionState().phase === 'disposed' ? beforeContract() : ({ ...beforeContract(), conversationLog: 1, ...(api.getWorkspaceLocationState ? { workspaceLocations: 1 } : {}), ...(api.getLocalWorkspaceContext ? { localWorkspaceContext: 1 } : {}), ...(api.getWorkspaceDirectoryPickerSettings ? { workspaceDirectoryPicker: 1 } : {}), ...(api.resolveSessionProject !== unavailableHost ? { hostWorkspaceResolution: 2 } : {}) });
58
58
  api.getContractInfo = currentContract;
59
59
  ctx.effect(() => () => { if (api.getContractInfo === currentContract)
60
60
  api.getContractInfo = beforeContract; if (api.appendRemoteConversationDetail === log.append)
61
61
  api.appendRemoteConversationDetail = beforeAppend; if (api.readConversationLog === readLogs)
62
62
  api.readConversationLog = beforeRead; });
63
63
  const unavailableHost = async () => fail('DEPENDENCY_REQUIRED');
64
- api.resolveSessionProject = unavailableHost;
64
+ const host = createHostSessionProjects({ api, hostDirectories: ports.hostDirectories });
65
+ api.resolveSessionProject = host.resolve;
66
+ ctx.effect(() => () => { api.resolveSessionProject = unavailableHost; host.dispose(); });
65
67
  let locationRevision = 0;
66
68
  ctx.inject(['profileContext', 'workspaceRegistry', 'sessions'], native => {
67
69
  const registry = native.get('workspaceRegistry');
@@ -82,10 +84,8 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network, autoStart
82
84
  api.refreshWorkspaceLocations = locations.refreshWorkspaceLocations;
83
85
  api.browseWorkspaceHostDirectories = locations.browseWorkspaceHostDirectories;
84
86
  api.selectWorkspaceLocation = locations.selectWorkspaceLocation;
85
- const host = createHostSessionProjects({ api, registry, services: () => ({ sessions: native.get('sessions') }), withHostBinding: locations.withHostBinding });
86
- api.resolveSessionProject = host.resolve;
87
87
  native.effect(() => { void locations.refreshWorkspaceLocations(); return api.onConnectionState(() => locations.observeConnection()); });
88
- native.effect(() => () => { api.resolveSessionProject = unavailableHost; delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; delete api.getWorkspaceDirectoryPickerSettings; delete api.browseWorkspaceDirectories; delete api.createWorkspaceDirectory; delete api.selectWorkspaceDirectory; host.dispose(); return Promise.all([locations.dispose(), picker?.dispose()]); });
88
+ native.effect(() => () => { delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; delete api.getWorkspaceDirectoryPickerSettings; delete api.browseWorkspaceDirectories; delete api.createWorkspaceDirectory; delete api.selectWorkspaceDirectory; return Promise.all([locations.dispose(), picker?.dispose()]); });
89
89
  });
90
90
  if (autoStart)
91
91
  void api.refreshLoginPrompts();
@@ -1,7 +1,3 @@
1
1
  import type { Config } from './index.ts';
2
- export type RuntimeConfig = Config & {
3
- helper?: NonNullable<Config['helper']> & {
4
- source?: string;
5
- };
6
- };
7
- export declare function profileSettings(config: Config, profileDir?: string, platform?: string, arch?: string): RuntimeConfig;
2
+ export type RuntimeConfig = Config;
3
+ export declare function profileSettings(config: Config, profileDir?: string, _platform?: string, _arch?: string): RuntimeConfig;
@@ -1,11 +1,7 @@
1
- import { isAbsolute, join } from 'node:path';
2
- import { COMPONENT_SOURCES } from "./component-source.js";
3
- import { L_DEFAULTS, ELECTRON_PIN } from "./defaults.js";
4
- // Owner approved technical values, 2026-10-20 settings decision, part two.
5
- // 组件直接下载;Claude网页遵循员工系统网络,Codex暂保留N主机代理。
6
- export function profileSettings(config, profileDir, platform = process.platform, arch = process.arch) {
1
+ import { isAbsolute } from 'node:path';
2
+ import { L_DEFAULTS } from "./defaults.js";
3
+ export function profileSettings(config, profileDir, _platform = process.platform, _arch = process.arch) {
7
4
  if (typeof profileDir !== 'string' || !isAbsolute(profileDir))
8
5
  return config;
9
- const runtime = platform === 'darwin' && arch === 'arm64' ? { ...ELECTRON_PIN, source: COMPONENT_SOURCES.npmmirror.source } : {};
10
- return { ...config, commandOutputMaxBytes: config.commandOutputMaxBytes === undefined ? L_DEFAULTS.commandOutputMaxBytes : config.commandOutputMaxBytes, helper: { ...runtime, componentDownloadMaxRedirects: L_DEFAULTS.componentDownloadMaxRedirects, componentObservationIntervalMs: L_DEFAULTS.componentObservationIntervalMs, maxDownloadBytes: L_DEFAULTS.maxDownloadBytes, maxExtractedBytes: L_DEFAULTS.maxExtractedBytes, loginOutputMaxBytes: L_DEFAULTS.loginOutputMaxBytes, ipcMaxBytes: L_DEFAULTS.ipcMaxBytes, remoteKillGraceMs: L_DEFAULTS.remoteKillGraceMs, ...config.helper, ...(platform === 'darwin' && arch === 'arm64' ? { source: COMPONENT_SOURCES.npmmirror.source } : {}), cacheDir: config.helper?.cacheDir === undefined ? join(profileDir, 'ai-workbench-connect', 'login-component-cache') : config.helper.cacheDir } };
6
+ return { ...config, commandOutputMaxBytes: config.commandOutputMaxBytes === undefined ? L_DEFAULTS.commandOutputMaxBytes : config.commandOutputMaxBytes, helper: { remoteKillGraceMs: config.helper?.remoteKillGraceMs === undefined ? L_DEFAULTS.remoteKillGraceMs : config.helper.remoteKillGraceMs, loginOutputMaxBytes: config.helper?.loginOutputMaxBytes === undefined ? L_DEFAULTS.loginOutputMaxBytes : config.helper.loginOutputMaxBytes } };
11
7
  }
@@ -1,2 +1,2 @@
1
1
  import type { Provider } from './api.ts';
2
- export declare function remoteLoginCommand(provider: Provider, killGraceMs: number, probeIsolate?: boolean): string;
2
+ export declare function remoteLoginCommand(provider: Provider, killGraceMs: number): string;
@@ -1,9 +1,9 @@
1
1
  import { readFileSync } from 'node:fs';
2
- export function remoteLoginCommand(provider, killGraceMs, probeIsolate = false) {
2
+ export function remoteLoginCommand(provider, killGraceMs) {
3
3
  if (provider !== 'claude' && provider !== 'codex')
4
4
  throw Error('LOGIN_PROVIDER_INVALID');
5
5
  if (!Number.isSafeInteger(killGraceMs) || killGraceMs < 0 || killGraceMs > 2147483647)
6
6
  throw Error('REMOTE_KILL_GRACE_REQUIRED');
7
7
  const source = readFileSync(new URL('../helper/remote-login.cjs', import.meta.url), 'utf8');
8
- return "node -e '" + source.replaceAll("'", "'\\''") + "' -- " + provider + ' ' + killGraceMs + (probeIsolate ? ' --probe-isolate' : '');
8
+ return "node -e '" + source.replaceAll("'", "'\\''") + "' -- " + provider + ' ' + killGraceMs;
9
9
  }
package/lib/startup.js CHANGED
@@ -188,7 +188,7 @@ export function createStartup(api, providers, emit = () => { }, result = () => {
188
188
  const mine = generation;
189
189
  checkSerial++;
190
190
  authorizationId = requestId;
191
- publish({ ...state, phase: 'authorizing', queuedProviders: [], checkingProviders: [...new Set([...state.checkingProviders, provider])], message: '请在授权窗口完成本人登录。' });
191
+ publish({ ...state, phase: 'authorizing', queuedProviders: [], checkingProviders: [...new Set([...state.checkingProviders, provider])], technicalDetails: {}, message: '请在默认浏览器完成本人登录。' });
192
192
  const superseded = () => { const failure = authFailure('connect-check-login', 'STATUS_SUPERSEDED'); if (state.requestId === requestId)
193
193
  publish({ ...state, phase: 'idle', requestId: undefined, provider: undefined }); result({ requestId, provider, outcome: 'invalidated', need: failure.error }); ask(); return failure; };
194
194
  const run = async () => {
@@ -209,6 +209,24 @@ export function createStartup(api, providers, emit = () => { }, result = () => {
209
209
  const finalTicket = resultTickets.get(verified);
210
210
  if (!login.current || !finalTicket || !currentTicket(finalTicket))
211
211
  return superseded();
212
+ if (provider === 'claude' && !verified.ok && verified.error.code === 'LOGIN_FAILED') {
213
+ // A failed attempt is not evidence about the CLI's current sign-in state.
214
+ const refreshed = await observeCheck(provider, () => api.checkLogin(provider));
215
+ if (disposed || mine !== generation)
216
+ return fail(disposed ? 'DISPOSED' : 'CONNECTION_LOST');
217
+ if (!refreshed.current)
218
+ return superseded();
219
+ publish({ ...state, phase: 'idle', requestId: undefined, provider: undefined, technicalDetails: { code: 'LOGIN_FAILED', loginFailureMessage: verified.error.message !== need('LOGIN_FAILED').message ? verified.error.message : undefined } });
220
+ if (disposed || mine !== generation) {
221
+ result({ requestId, provider, outcome: 'invalidated', need: currentNeed(disposed ? 'DISPOSED' : 'CONNECTION_LOST') });
222
+ return fail(disposed ? 'DISPOSED' : 'CONNECTION_LOST');
223
+ }
224
+ result({ requestId, provider, outcome: 'failed', need: verified.error });
225
+ if (disposed || mine !== generation)
226
+ return fail(disposed ? 'DISPOSED' : 'CONNECTION_LOST');
227
+ ask();
228
+ return verified;
229
+ }
212
230
  if (!verified.ok || !verified.value.loggedIn) {
213
231
  const code = verified.ok ? 'LOGIN_FAILED' : verified.error.code;
214
232
  providerFailed(provider, code, verified.ok ? currentNeed(code) : verified.error);
@@ -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: {