@ai-workbench/connect 0.7.23 → 0.7.27

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 (69) hide show
  1. package/README.md +24 -69
  2. package/client/index.cjs +95 -70
  3. package/helper/host-directories.cjs +8 -1
  4. package/lib/api.d.ts +21 -163
  5. package/lib/component-download.d.ts +1 -1
  6. package/lib/component-download.js +1 -1
  7. package/lib/component-source.d.ts +6 -27
  8. package/lib/component-source.js +10 -138
  9. package/lib/components.d.ts +1 -1
  10. package/lib/components.js +86 -98
  11. package/lib/connect.d.ts +0 -3
  12. package/lib/connect.js +15 -62
  13. package/lib/connection-messages.d.ts +2 -3
  14. package/lib/connection-messages.js +5 -4
  15. package/lib/conversation-log.d.ts +9 -0
  16. package/lib/conversation-log.js +44 -0
  17. package/lib/cordis.d.ts +1 -4
  18. package/lib/defaults.d.ts +0 -10
  19. package/lib/defaults.js +1 -3
  20. package/lib/enrollment.js +1 -8
  21. package/lib/host-directories.d.ts +6 -4
  22. package/lib/host-directories.js +4 -4
  23. package/lib/host-session-projects.d.ts +8 -58
  24. package/lib/host-session-projects.js +45 -270
  25. package/lib/index.d.ts +3 -12
  26. package/lib/index.js +14 -26
  27. package/lib/integration.d.ts +2 -2
  28. package/lib/integration.js +0 -3
  29. package/lib/login.d.ts +0 -8
  30. package/lib/native-workspace.d.ts +10 -0
  31. package/lib/needs.js +15 -27
  32. package/lib/network.d.ts +0 -4
  33. package/lib/network.js +4 -88
  34. package/lib/ports.d.ts +1 -6
  35. package/lib/profile-activation.d.ts +0 -3
  36. package/lib/profile-activation.js +8 -2
  37. package/lib/profile-runtime.js +60 -153
  38. package/lib/profile-settings.d.ts +6 -1
  39. package/lib/profile-settings.js +3 -5
  40. package/lib/provider.d.ts +1 -15
  41. package/lib/provider.js +2 -18
  42. package/lib/startup.js +3 -3
  43. package/lib/workspace-directory-picker-types.d.ts +44 -0
  44. package/lib/workspace-directory-picker-types.js +1 -0
  45. package/lib/workspace-directory-picker.d.ts +30 -0
  46. package/lib/workspace-directory-picker.js +372 -0
  47. package/lib/workspace-location-types.d.ts +3 -7
  48. package/lib/workspace-locations.d.ts +5 -29
  49. package/lib/workspace-locations.js +81 -204
  50. package/package.json +3 -2
  51. package/helper/projects.cjs +0 -57
  52. package/lib/conversation-detail-settings.d.ts +0 -32
  53. package/lib/conversation-detail-settings.js +0 -119
  54. package/lib/conversation-details.d.ts +0 -30
  55. package/lib/conversation-details.js +0 -595
  56. package/lib/host-session-store.d.ts +0 -27
  57. package/lib/host-session-store.js +0 -130
  58. package/lib/local-acceptance-store.d.ts +0 -18
  59. package/lib/local-acceptance-store.js +0 -133
  60. package/lib/local-user-turn-acceptance.d.ts +0 -76
  61. package/lib/local-user-turn-acceptance.js +0 -289
  62. package/lib/local-user-turn-types.d.ts +0 -40
  63. package/lib/login-diagnostics.d.ts +0 -28
  64. package/lib/login-diagnostics.js +0 -57
  65. package/lib/projects.d.ts +0 -4
  66. package/lib/projects.js +0 -41
  67. package/lib/workspace-bindings.d.ts +0 -64
  68. package/lib/workspace-bindings.js +0 -379
  69. /package/lib/{local-user-turn-types.js → native-workspace.js} +0 -0
@@ -1,13 +1,11 @@
1
1
  import { isAbsolute, join } from 'node:path';
2
- import { COMPONENT_SOURCES, preset } from "./component-source.js";
3
- import { L_DEFAULTS, ELECTRON_PIN, CONVERSATION_DETAIL_DEFAULTS } from "./defaults.js";
2
+ import { COMPONENT_SOURCES } from "./component-source.js";
3
+ import { L_DEFAULTS, ELECTRON_PIN } from "./defaults.js";
4
4
  // Owner approved technical values, 2026-10-20 settings decision, part two.
5
5
  // 组件直接下载;Claude网页遵循员工系统网络,Codex暂保留N主机代理。
6
6
  export function profileSettings(config, profileDir, platform = process.platform, arch = process.arch) {
7
7
  if (typeof profileDir !== 'string' || !isAbsolute(profileDir))
8
8
  return config;
9
9
  const runtime = platform === 'darwin' && arch === 'arm64' ? { ...ELECTRON_PIN, source: COMPONENT_SOURCES.npmmirror.source } : {};
10
- const chosen = config.helper?.componentDownloadSource;
11
- const selected = chosen === undefined ? {} : { source: preset(chosen) ? COMPONENT_SOURCES[chosen].source : '' };
12
- return { ...config, conversationDetails: { ...CONVERSATION_DETAIL_DEFAULTS, ...config.conversationDetails }, 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, ...selected, cacheDir: config.helper?.cacheDir === undefined ? join(profileDir, 'ai-workbench-connect', 'login-component-cache') : config.helper.cacheDir } };
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 } };
13
11
  }
package/lib/provider.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import type { Ports } from './ports.ts';
2
- import type { ProxyLease } from './login.ts';
3
2
  interface NNeed {
4
3
  code: string;
5
4
  }
@@ -16,7 +15,6 @@ export interface ActivationSettings {
16
15
  startupObservationSeconds: number;
17
16
  shutdownObservationSeconds: number;
18
17
  controlResponseMaxBytes: number;
19
- downloadMaxRedirects: number;
20
18
  }
21
19
  export interface ActivationState {
22
20
  instanceId: string;
@@ -55,19 +53,7 @@ export interface NetworkProvider {
55
53
  onState(listener: (event: {
56
54
  kind: 'lost' | 'restored';
57
55
  }) => void): () => void;
58
- openLoginProxy(signal: AbortSignal): Promise<NResult<{
59
- credentials: {
60
- url: string;
61
- username: string;
62
- password: string;
63
- };
64
- release(): Promise<void>;
65
- }>>;
66
- download(source: string, signal: AbortSignal): Promise<NResult<Response>>;
67
56
  }
68
57
  export declare function mapNetworkNeed(value: NNeed): import("./api.ts").ConnectNeed;
69
- export declare function adaptNetwork(provider: NetworkProvider): NonNullable<Ports['network']> & {
70
- acquireProxy(signal: AbortSignal): Promise<ProxyLease>;
71
- download(source: string, signal: AbortSignal): Promise<Response>;
72
- };
58
+ export declare function adaptNetwork(provider: NetworkProvider): NonNullable<Ports['network']>;
73
59
  export {};
package/lib/provider.js CHANGED
@@ -1,6 +1,6 @@
1
- import { NeedError, need } from "./needs.js";
1
+ import { need } from "./needs.js";
2
2
  export function mapNetworkNeed(value) {
3
- const code = { NEED_ENROLLMENT: 'ENROLLMENT_REQUIRED', ENROLLMENT_REJECTED: 'ENROLLMENT_REJECTED', ENROLLMENT_RESULT_UNKNOWN: 'ENROLLMENT_RESULT_UNKNOWN', LOCAL_STATE_INVALID: 'ENROLLMENT_INVALID', HOST_OFFLINE: 'HOST_OFFLINE', HOST_TRUST_REQUIRED: 'HOST_TRUST_REQUIRED', HOST_KEY_MISMATCH: 'HOST_KEY_MISMATCH', ENROLLMENT_MISMATCH: 'ENROLLMENT_INVALID', CONFIG_INVALID: 'SETTINGS_REQUIRED', SETTINGS_REQUIRED: 'SETTINGS_REQUIRED', SSH_FAILED: 'SSH_FAILED', NETWORK_INTERRUPTED: 'CONNECTION_LOST', CONTROL_UNAVAILABLE: 'CONNECTION_LOST', NETWORK_NOT_READY: 'CONNECTION_LOST', DISPOSED: 'DISPOSED' }[value.code] ?? 'DEPENDENCY_REQUIRED';
3
+ const code = { NEED_ENROLLMENT: 'ENROLLMENT_REQUIRED', ENROLLMENT_REJECTED: 'ENROLLMENT_REJECTED', ENROLLMENT_KEY_REJECTED: 'ENROLLMENT_KEY_REJECTED', LOCAL_STATE_INVALID: 'ENROLLMENT_INVALID', HOST_OFFLINE: 'HOST_OFFLINE', HOST_TRUST_REQUIRED: 'HOST_TRUST_REQUIRED', HOST_KEY_MISMATCH: 'HOST_KEY_MISMATCH', ENROLLMENT_MISMATCH: 'ENROLLMENT_INVALID', CONFIG_INVALID: 'SETTINGS_REQUIRED', SETTINGS_REQUIRED: 'SETTINGS_REQUIRED', SSH_FAILED: 'SSH_FAILED', NETWORK_INTERRUPTED: 'CONNECTION_LOST', CONTROL_UNAVAILABLE: 'CONNECTION_LOST', NETWORK_NOT_READY: 'CONNECTION_LOST', DISPOSED: 'DISPOSED' }[value.code] ?? 'DEPENDENCY_REQUIRED';
4
4
  const direct = ['ACTIVATION_CONFLICT', 'ACTIVATION_CANCELLED', 'ENROLLMENT_CLEANUP_UNBOUND', 'ENROLLMENT_CLEANUP_FAILED', 'ENROLLMENT_MISMATCH', 'LOCAL_STATE_INVALID', 'ALREADY_RUNNING', 'ENROLLMENT_RECEIPT_REQUIRED', 'CONTROL_PROTOCOL_INVALID', 'HELPER_HANDOFF_FAILED', 'HELPER_SHUTDOWN_FORCED'];
5
5
  const result = need(direct.includes(value.code) ? value.code : code);
6
6
  result.officialReason = /^[A-Z][A-Z0-9_]*$/.test(value.code) ? value.code : 'NETWORK_NEED_INVALID';
@@ -19,21 +19,5 @@ export function adaptNetwork(provider) {
19
19
  },
20
20
  onState(listener) { return provider.onState(event => { if (event.kind === 'lost' || event.kind === 'restored')
21
21
  listener({ kind: event.kind }); }); },
22
- async acquireProxy(signal) {
23
- const result = await provider.openLoginProxy(signal);
24
- if (!result.ok)
25
- throw new NeedError(mapNetworkNeed(result.error));
26
- const source = result.value, credentials = source.credentials;
27
- let release;
28
- return { url: credentials.url, get username() { return credentials.username; }, get password() { return credentials.password; }, release: () => release ??= (async () => { try {
29
- await source.release();
30
- }
31
- finally {
32
- credentials.username = '';
33
- credentials.password = '';
34
- } })() };
35
- },
36
- async download(source, signal) { const result = await provider.download(source, signal); if (!result.ok)
37
- throw new NeedError(mapNetworkNeed(result.error)); return result.value; },
38
22
  };
39
23
  }
package/lib/startup.js CHANGED
@@ -6,7 +6,7 @@ export function employeeMessage(code, connection) {
6
6
  const message = connectionEmployeeMessage(connection);
7
7
  if (message)
8
8
  return message;
9
- if (code === 'ENROLLMENT_RESULT_UNKNOWN' || code === 'ENROLLMENT_REJECTED')
9
+ if (code === 'ENROLLMENT_KEY_REJECTED' || code === 'ENROLLMENT_REJECTED')
10
10
  return need(code).message;
11
11
  if (code === 'DEPENDENCY_REQUIRED')
12
12
  return '远程主机连接尚未准备好,请联系管理员。';
@@ -145,7 +145,7 @@ export function createStartup(api, providers, emit = () => { }, result = () => {
145
145
  }
146
146
  }
147
147
  }
148
- publish({ ...state, queuedProviders: [], technicalDetails: connected.value.hostContext ? { hostContext: structuredClone(connected.value.hostContext) } : {} });
148
+ publish({ ...state, queuedProviders: [], technicalDetails: {} });
149
149
  ask();
150
150
  }
151
151
  catch {
@@ -293,7 +293,7 @@ export function createStartup(api, providers, emit = () => { }, result = () => {
293
293
  publish({ phase: 'checking', message: '正在连接远程主机…', logins: {}, queuedProviders: [], checkingProviders: [], providerNeeds: {}, technicalDetails: {} });
294
294
  }
295
295
  if (!changed && prior === next.phase && next.recovery && previousRecovery !== next.recovery.phase) {
296
- publish({ ...state, message: next.recovery.message });
296
+ publish({ ...state, message: connectionEmployeeMessage(next) ?? state.message });
297
297
  return;
298
298
  }
299
299
  if (next.phase === 'unavailable' || next.phase === 'disposed') {
@@ -0,0 +1,44 @@
1
+ import type { Result } from './api.ts';
2
+ export type WorkspacePickerTarget = 'local' | 'host';
3
+ export interface WorkspacePickerRequest {
4
+ target?: WorkspacePickerTarget;
5
+ path?: string;
6
+ cursor?: string;
7
+ }
8
+ export interface WorkspacePickerEntry {
9
+ name: string;
10
+ path: string;
11
+ available: boolean;
12
+ isSymlink: boolean;
13
+ }
14
+ export interface WorkspacePickerPage {
15
+ target: WorkspacePickerTarget;
16
+ path: string;
17
+ parentPath: string | null;
18
+ entries: WorkspacePickerEntry[];
19
+ selectionToken: string;
20
+ nextCursor?: string;
21
+ notice?: string;
22
+ }
23
+ export interface WorkspacePickerSelection {
24
+ path: string;
25
+ workspaceId: string;
26
+ source: WorkspacePickerTarget;
27
+ }
28
+ export interface WorkspacePickerSettings {
29
+ slotPriority: number;
30
+ mappingRoot: string;
31
+ pageSize: number;
32
+ metadataMaxBytes: number;
33
+ }
34
+ export interface WorkspaceDirectoryPickerApi {
35
+ getWorkspaceDirectoryPickerSettings(): WorkspacePickerSettings;
36
+ browseWorkspaceDirectories(request: WorkspacePickerRequest): Promise<Result<WorkspacePickerPage>>;
37
+ createWorkspaceDirectory(request: {
38
+ selectionToken: string;
39
+ name: string;
40
+ }): Promise<Result<WorkspacePickerPage>>;
41
+ selectWorkspaceDirectory(request: {
42
+ selectionToken: string;
43
+ }): Promise<Result<WorkspacePickerSelection>>;
44
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ import type { ConnectApi, Result } from './api.ts';
2
+ import type { NativeWorkspace, NativeWorkspaceRegistry } from './native-workspace.ts';
3
+ import type { WorkspaceLocationState, WorkspaceBrowseRequest, WorkspaceBrowsePage, WorkspaceSelectRequest } from './workspace-location-types.ts';
4
+ import type { createHostDirectories } from './host-directories.ts';
5
+ import type { WorkspaceDirectoryPickerApi } from './workspace-directory-picker-types.ts';
6
+ interface Options {
7
+ profileDir: string;
8
+ metadataMaxBytes: number;
9
+ pageSize: number;
10
+ slotPriority: number;
11
+ api: Pick<ConnectApi, 'getConnectionState' | 'getModelCatalogTarget'> & Partial<Pick<ConnectApi, 'onConnectionState'>>;
12
+ registry: NativeWorkspaceRegistry & {
13
+ create(path: string, title?: string): Promise<NativeWorkspace & {
14
+ setTitle?: (title: string) => Promise<void>;
15
+ }>;
16
+ };
17
+ hostDirectories?: ReturnType<typeof createHostDirectories>;
18
+ locations: {
19
+ getWorkspaceLocationState(): WorkspaceLocationState;
20
+ refreshWorkspaceLocations(): Promise<Result<WorkspaceLocationState>>;
21
+ browseWorkspaceHostDirectories(c: WorkspaceBrowseRequest): Promise<Result<WorkspaceBrowsePage>>;
22
+ selectWorkspaceLocation(c: WorkspaceSelectRequest): Promise<Result<WorkspaceLocationState>>;
23
+ captureWorkspacePickerGuard(workspaceId: string, expectedBindingId: string): () => void;
24
+ };
25
+ }
26
+ export declare function createWorkspaceDirectoryPicker(o: Options): WorkspaceDirectoryPickerApi & {
27
+ isPending(workspaceId: string): boolean;
28
+ dispose(): Promise<void>;
29
+ };
30
+ export {};
@@ -0,0 +1,372 @@
1
+ import { access, lstat, stat, realpath, readdir, mkdir, open, rename, rm } from 'node:fs/promises';
2
+ import { constants, lstatSync, realpathSync } from 'node:fs';
3
+ import { join, dirname, basename, 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
+ const queues = new Map();
8
+ const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
9
+ const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
10
+ const string = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
11
+ const path = (v) => string(v) && isAbsolute(v);
12
+ const digest = (v) => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
13
+ const decimal = (v) => typeof v === 'string' && /^\d+$/.test(v);
14
+ const strict = (v, keys) => Object.keys(v).every(k => keys.includes(k));
15
+ 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
+ const sameSnapshot = (a, b) => sameInfo(a, b) && a.identity.mtimeNs === b.identity.mtimeNs && a.identity.ctimeNs === b.identity.ctimeNs;
17
+ export function createWorkspaceDirectoryPicker(o) {
18
+ const root = join(o.profileDir, 'ai-workbench-connect'), mappingRoot = join(root, 'remote-workspaces'), file = join(root, 'directory-picker-state.json'), secret = randomBytes(32), controllers = new Set();
19
+ let activePath;
20
+ let disposed = false, state = { schemaVersion: 1, mappings: [] }, tail = Promise.resolve();
21
+ function reject(code) { throw new NeedError(need(code)); }
22
+ const take = (r) => { if (!r.ok)
23
+ throw new NeedError(r.error); return r.value; };
24
+ function check(c) { if (disposed)
25
+ reject('DISPOSED'); const current = o.api.getConnectionState(); if (current.instanceId !== c.instanceId || current.epoch !== c.epoch)
26
+ reject('WORKSPACE_LOCATION_CONFLICT'); }
27
+ const context = () => { const c = o.api.getConnectionState(); return { instanceId: c.instanceId, epoch: c.epoch }; };
28
+ async function prepare() { if (!path(o.profileDir) || await realpath(o.profileDir) !== o.profileDir)
29
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); if (!Number.isSafeInteger(o.metadataMaxBytes) || o.metadataMaxBytes < 1 || !Number.isSafeInteger(o.pageSize) || o.pageSize < 1 || !Number.isSafeInteger(o.slotPriority) || o.slotPriority >= 0)
30
+ reject('SETTINGS_REQUIRED'); await privateDirectory(root); if (await realpath(root) !== root)
31
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); const parent = await open(o.profileDir, 'r'); try {
32
+ await parent.sync();
33
+ }
34
+ finally {
35
+ await parent.close();
36
+ } }
37
+ function parse(raw) {
38
+ const doc = JSON.parse(raw);
39
+ if (!object(doc) || !strict(doc, ['data', 'checksum']) || !object(doc.data) || doc.checksum !== hash(doc.data))
40
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
41
+ 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))
43
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
44
+ const names = new Set();
45
+ 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))
47
+ reject('WORKSPACE_PICKER_STORAGE_FAILED');
48
+ names.add(m.name);
49
+ }
50
+ // Legacy unfinished journals are no longer execution or picker gates.
51
+ const { journal: ignored, ...current } = d;
52
+ return current;
53
+ }
54
+ async function load() { try {
55
+ return parse(await readPrivate(file, o.metadataMaxBytes));
56
+ }
57
+ catch (e) {
58
+ if (e.code === 'ENOENT')
59
+ return { schemaVersion: 1, mappings: [] };
60
+ throw e;
61
+ } }
62
+ async function save(next, guard) { const data = structuredClone(next), bytes = JSON.stringify({ data, checksum: hash(data) }) + '\n'; if (Buffer.byteLength(bytes) > o.metadataMaxBytes)
63
+ reject('WORKSPACE_PICKER_STORAGE_FAILED'); const temp = join(root, '.directory-picker-' + randomUUID()); try {
64
+ const h = await open(temp, 'wx', 0o600);
65
+ try {
66
+ await h.writeFile(bytes);
67
+ await h.sync();
68
+ }
69
+ finally {
70
+ await h.close();
71
+ }
72
+ guard?.();
73
+ await rename(temp, file);
74
+ const d = await open(root, 'r');
75
+ try {
76
+ await d.sync();
77
+ }
78
+ finally {
79
+ await d.close();
80
+ }
81
+ state = data;
82
+ }
83
+ finally {
84
+ await rm(temp, { force: true });
85
+ } }
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'); }
92
+ async function remote(run) { const controller = new AbortController(); controllers.add(controller); try {
93
+ return take(await run(controller.signal));
94
+ }
95
+ finally {
96
+ controllers.delete(controller);
97
+ } }
98
+ async function localInfo(requestedPath) {
99
+ try {
100
+ const entry = await lstat(requestedPath, { bigint: true }), canonical = await realpath(requestedPath), s = await stat(canonical, { bigint: true });
101
+ if (!s.isDirectory())
102
+ reject('HOST_DIRECTORY_INVALID');
103
+ await access(canonical, constants.R_OK | constants.X_OK);
104
+ return { requestedPath, path: canonical, parentPath: dirname(canonical) === canonical ? null : dirname(canonical), identity: { device: String(s.dev), inode: String(s.ino), mtimeNs: String(s.mtimeNs), ctimeNs: String(s.ctimeNs) }, entryIdentity: { device: String(entry.dev), inode: String(entry.ino) }, isSymlink: entry.isSymbolicLink(), permissions: { read: true, write: null, execute: true, reason: 'HOST_PERMISSION_UNKNOWN' } };
105
+ }
106
+ catch (e) {
107
+ if (e instanceof NeedError)
108
+ throw e;
109
+ const code = e.code;
110
+ if (code === 'ENOENT' || code === 'ENOTDIR' || code === 'ELOOP')
111
+ reject('HOST_DIRECTORY_INVALID');
112
+ if (code === 'EACCES' || code === 'EPERM')
113
+ reject('HOST_DIRECTORY_UNREADABLE');
114
+ throw e;
115
+ }
116
+ }
117
+ function seal(data) { const body = Buffer.from(JSON.stringify(data)).toString('base64url'); const value = body + '.' + createHmac('sha256', secret).update(body).digest('base64url'); if (Buffer.byteLength(value) > o.metadataMaxBytes)
118
+ reject('HOST_DIRECTORY_PAGE_TOO_LARGE'); return value; }
119
+ function unseal(value) { if (!string(value) || Buffer.byteLength(value) > o.metadataMaxBytes)
120
+ reject('WORKSPACE_PICKER_INVALID'); const [body, signature, ...extra] = value.split('.'); if (!body || !signature || extra.length)
121
+ reject('WORKSPACE_PICKER_INVALID'); const expected = createHmac('sha256', secret).update(body).digest(), actual = Buffer.from(signature, 'base64url'); if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
122
+ reject('WORKSPACE_PICKER_INVALID'); try {
123
+ return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
124
+ }
125
+ catch {
126
+ return reject('WORKSPACE_PICKER_INVALID');
127
+ } }
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))
139
+ reject('HOST_DIRECTORY_CHANGED'); if (current.permissions.read !== true || current.permissions.execute !== true)
140
+ reject('HOST_DIRECTORY_UNREADABLE'); return current; }
141
+ async function nativePath(p) { const s = await lstat(p, { bigint: true }); if (!s.isDirectory() || s.isSymbolicLink() || await realpath(p) !== p)
142
+ 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
+ const unsubscribe = o.api.onConnectionState?.(() => { for (const controller of controllers)
147
+ controller.abort(); });
148
+ function serial(run) { const before = queues.get(file) ?? Promise.resolve(); const task = before.then(async () => { if (disposed)
149
+ return fail('DISPOSED'); try {
150
+ await prepare();
151
+ state = await load();
152
+ return await run();
153
+ }
154
+ catch (e) {
155
+ const error = e instanceof NeedError ? e.need : need('WORKSPACE_PICKER_STORAGE_FAILED');
156
+ return { ok: false, error: error.code === 'WORKSPACE_LOCATION_STORAGE_FAILED' ? { ...error, message: need('WORKSPACE_PICKER_STORAGE_FAILED').message, actor: 'employee', action: need('WORKSPACE_PICKER_STORAGE_FAILED').action } : error };
157
+ } }); tail = task.then(() => { }, () => { }); queues.set(file, tail); const waiting = tail; void waiting.then(() => { if (queues.get(file) === waiting)
158
+ queues.delete(file); }); return task; }
159
+ async function browse(r) {
160
+ if (!object(r) || !strict(r, ['target', 'path', 'cursor']) || r.target !== undefined && !['local', 'host'].includes(r.target) || r.path !== undefined && !path(r.path) || r.cursor !== undefined && (!string(r.cursor) || r.path !== undefined))
161
+ reject('WORKSPACE_PICKER_INVALID');
162
+ const c = context(), cursor = r.cursor ? unseal(r.cursor) : undefined;
163
+ if (cursor && cursor.kind !== 'cursor')
164
+ reject('WORKSPACE_PICKER_INVALID');
165
+ const previous = cursor?.kind === 'cursor' ? cursor.selection : undefined;
166
+ const target = (r.target ?? previous?.target ?? state.lastTarget ?? 'local');
167
+ if (previous && target !== previous.target)
168
+ reject('WORKSPACE_PICKER_INVALID');
169
+ if (previous)
170
+ check(previous.context);
171
+ if (target === 'local' && r.path === undefined)
172
+ 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;
177
+ let info, entries, after = cursor?.kind === 'cursor' ? cursor.after : undefined, nextAfter;
178
+ async function read() {
179
+ if (target === 'host') {
180
+ if (!o.hostDirectories)
181
+ reject('DEPENDENCY_REQUIRED');
182
+ return remote(signal => o.hostDirectories.browse(trusted.target, { ...(requested !== undefined ? { path: requested } : {}), pageSize: o.pageSize, ...(after ? { after, expected: previous.info.identity } : {}) }, signal));
183
+ }
184
+ return { ...await localInfo(requested), entries: [] };
185
+ }
186
+ let page;
187
+ try {
188
+ page = await read();
189
+ }
190
+ catch (e) {
191
+ if (r.path !== undefined || r.cursor !== undefined || requested === undefined || !(e instanceof NeedError) || !['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE'].includes(e.need.code))
192
+ throw e;
193
+ requested = undefined;
194
+ notice = '上次选择的远程目录已失效或不可读,已返回远程用户根目录。';
195
+ page = await read();
196
+ }
197
+ const { entries: rawEntries, nextAfter: more, ...directory } = page;
198
+ info = directory;
199
+ 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 };
207
+ 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
+ if (Buffer.byteLength(JSON.stringify(result)) > o.metadataMaxBytes)
209
+ reject('HOST_DIRECTORY_PAGE_TOO_LARGE');
210
+ return ok(result);
211
+ }
212
+ async function create(r) {
213
+ if (!object(r) || !strict(r, ['selectionToken', 'name']) || !string(r.name) || ['.', '..'].includes(r.name) || /[\\/]/.test(r.name))
214
+ reject('WORKSPACE_PICKER_INVALID');
215
+ const s = unseal(r.selectionToken);
216
+ if (s.kind !== 'selection' || s.target !== 'host')
217
+ 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');
221
+ if (!o.hostDirectories?.create)
222
+ 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);
225
+ return browse({ target: 'host', path: child.path });
226
+ }
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
+ }
240
+ function registrationTitle(j) { return (basename(j.selectedPath) || j.selectedPath) + ' · 正在添加 · ' + j.id; }
241
+ async function select(r) {
242
+ if (!object(r) || !strict(r, ['selectionToken']))
243
+ reject('WORKSPACE_PICKER_INVALID');
244
+ const selected = unseal(r.selectionToken);
245
+ if (selected.kind !== 'selection')
246
+ 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;
250
+ 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) };
252
+ if (!o.registry.list().some(w => w.path === localPath))
253
+ activePath = localPath;
254
+ 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));
279
+ guard();
280
+ const matches = o.registry.list().filter(w => w.path === localPath);
281
+ if (matches.length > 1)
282
+ reject('WORKSPACE_LOCATION_CONFLICT');
283
+ let workspace;
284
+ let fresh = take(await o.locations.refreshWorkspaceLocations());
285
+ guard();
286
+ if (matches[0]) {
287
+ workspace = matches[0];
288
+ const item = fresh.items.find(i => i.workspaceId === workspace.id);
289
+ if (!sameSource(item, s))
290
+ reject('WORKSPACE_LOCATION_CONFLICT');
291
+ }
292
+ else {
293
+ workspace = await o.registry.create(localPath, registrationTitle(j));
294
+ if (!workspace || !string(workspace.id) || workspace.path !== localPath || o.registry.get(workspace.id)?.path !== localPath || o.registry.list().filter(w => w.id === workspace.id && w.path === localPath).length !== 1 || j.originalIds.includes(workspace.id) || workspace.title !== registrationTitle(j))
295
+ reject('WORKSPACE_LOCATION_CONFLICT');
296
+ j.workspaceId = workspace.id;
297
+ if (typeof workspace.setTitle !== 'function')
298
+ reject('DEPENDENCY_REQUIRED');
299
+ await workspace.setTitle(basename(info.path) || info.path);
300
+ guard();
301
+ fresh = take(await o.locations.refreshWorkspaceLocations());
302
+ guard();
303
+ const item = fresh.items.find(i => i.workspaceId === workspace.id);
304
+ if (!item || item.bindingId !== null || item.source !== null)
305
+ reject('WORKSPACE_LOCATION_CONFLICT');
306
+ const c = { ...s.context, workspaceId: workspace.id, expectedBindingId: null };
307
+ 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
+ await inspect(s);
316
+ guard();
317
+ const saved = take(await o.locations.selectWorkspaceLocation(request));
318
+ const itemAfter = saved.items.find(i => i.workspaceId === workspace.id);
319
+ if (!sameSource(itemAfter, s) || !itemAfter?.bindingId)
320
+ reject('WORKSPACE_LOCATION_CONFLICT');
321
+ j.bindingId = itemAfter.bindingId;
322
+ }
323
+ const n = mapped ? await mappingPath(j) : await nativePath(localPath);
324
+ if (n.device !== j.device || n.inode !== j.inode)
325
+ reject('WORKSPACE_LOCATION_CONFLICT');
326
+ await inspect(s);
327
+ guard();
328
+ const latest = take(await o.locations.refreshWorkspaceLocations()).items.find(i => i.workspaceId === workspace.id);
329
+ if (!sameSource(latest, s) || j.bindingId !== undefined && latest?.bindingId !== j.bindingId)
330
+ reject('WORKSPACE_LOCATION_CONFLICT');
331
+ guard();
332
+ const bindingGuard = o.locations.captureWorkspacePickerGuard(workspace.id, latest.bindingId);
333
+ const finalGuard = () => { guard(); const matches = o.registry.list().filter(w => w.id === workspace.id), registered = o.registry.get(workspace.id); if (matches.length !== 1 || !registered || matches[0].path !== localPath || registered.path !== localPath)
334
+ reject('WORKSPACE_LOCATION_CONFLICT'); const n = lstatSync(localPath, { bigint: true }); if (!n.isDirectory() || n.isSymbolicLink() || realpathSync(localPath) !== localPath || String(n.dev) !== j.device || String(n.ino) !== j.inode)
335
+ reject('WORKSPACE_LOCATION_CONFLICT'); bindingGuard(); };
336
+ finalGuard();
337
+ // 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 });
341
+ await save(next, finalGuard);
342
+ finalGuard();
343
+ return ok({ path: localPath, workspaceId: workspace.id, source: s.target });
344
+ }
345
+ catch (e) {
346
+ const original = e instanceof NeedError ? e : new NeedError(need('WORKSPACE_PICKER_STORAGE_FAILED'));
347
+ const residual = o.registry.list().some(w => w.path === localPath && !j.originalIds.includes(w.id) && (w.id === j.workspaceId || w.title === registrationTitle(j)));
348
+ // Failed attempts retain their private mapping; no delete or cleanup gate.
349
+ const restored = { ...state };
350
+ delete restored.lastTarget;
351
+ delete restored.local;
352
+ delete restored.host;
353
+ Object.assign(restored, previous);
354
+ try {
355
+ await save(restored);
356
+ }
357
+ catch {
358
+ console.warn('本次未能保存原目录位置;下次选择时重新读取。');
359
+ }
360
+ if (residual) {
361
+ console.warn('本次工作区添加未完成:' + original.need.code);
362
+ throw new NeedError(need('WORKSPACE_PICKER_ROLLBACK_FAILED'));
363
+ }
364
+ throw original;
365
+ }
366
+ finally {
367
+ activePath = undefined;
368
+ }
369
+ }
370
+ return { getWorkspaceDirectoryPickerSettings: () => ({ slotPriority: o.slotPriority, mappingRoot, pageSize: o.pageSize, metadataMaxBytes: o.metadataMaxBytes }), browseWorkspaceDirectories: r => serial(() => browse(r)), createWorkspaceDirectory: r => serial(() => create(r)), selectWorkspaceDirectory: r => serial(() => select(r)), isPending: workspaceId => activePath !== undefined && o.registry.get(workspaceId)?.path === activePath, dispose: async () => { disposed = true; unsubscribe?.(); for (const c of controllers)
371
+ c.abort(); await tail; secret.fill(0); } };
372
+ }
@@ -5,10 +5,9 @@ export interface WorkspaceLocationItem {
5
5
  workspaceName: string;
6
6
  localPath: string;
7
7
  bindingId: string | null;
8
- source: 'local' | 'host' | 'legacy-host' | null;
9
- status: 'unselected' | 'selected' | 'legacy-confirmation-required' | 'invalid';
10
- execution: 'not-selected' | 'local-pending' | 'host-pending' | 'legacy-confirmed';
11
- legacyPath?: string;
8
+ source: 'local' | 'host' | null;
9
+ status: 'unselected' | 'selected' | 'invalid';
10
+ execution: 'not-selected' | 'local-pending' | 'host-pending';
12
11
  remote?: HostDirectoryInfo;
13
12
  host?: {
14
13
  host: string;
@@ -67,7 +66,4 @@ export type WorkspaceSelectRequest = WorkspaceLocationContext & ({
67
66
  } | {
68
67
  source: 'host';
69
68
  selectionToken: string;
70
- } | {
71
- source: 'legacy-host';
72
- confirmLegacy: true;
73
69
  });