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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +3 -3
  2. package/client/index.cjs +8 -371
  3. package/helper/auth-status.cjs +8 -14
  4. package/helper/remote-access.sh +91 -0
  5. package/lib/api.d.ts +4 -86
  6. package/lib/components.js +4 -162
  7. package/lib/connect.d.ts +3 -3
  8. package/lib/connect.js +6 -20
  9. package/lib/cordis.d.ts +1 -3
  10. package/lib/defaults.d.ts +0 -3
  11. package/lib/defaults.js +0 -1
  12. package/lib/{profile-runtime.d.ts → enrollment-runtime.d.ts} +1 -1
  13. package/lib/enrollment-runtime.js +31 -0
  14. package/lib/enrollment.d.ts +0 -1
  15. package/lib/enrollment.js +2 -5
  16. package/lib/index.d.ts +0 -4
  17. package/lib/index.js +17 -7
  18. package/lib/integration.d.ts +1 -1
  19. package/lib/integration.js +1 -3
  20. package/lib/needs.js +0 -22
  21. package/lib/ports.d.ts +2 -5
  22. package/lib/private-files.d.ts +0 -2
  23. package/lib/private-files.js +1 -17
  24. package/lib/profile-activation.d.ts +2 -0
  25. package/lib/profile-activation.js +3 -1
  26. package/lib/profile-enrollment.d.ts +2 -1
  27. package/lib/profile-enrollment.js +5 -5
  28. package/lib/remote-access.d.ts +36 -0
  29. package/lib/remote-access.js +103 -0
  30. package/lib/ssh.js +11 -1
  31. package/lib/startup.d.ts +0 -1
  32. package/package.json +3 -9
  33. package/helper/host-directories.cjs +0 -116
  34. package/lib/conversation-log.d.ts +0 -9
  35. package/lib/conversation-log.js +0 -44
  36. package/lib/directory-session.d.ts +0 -7
  37. package/lib/directory-session.js +0 -153
  38. package/lib/host-directories.d.ts +0 -58
  39. package/lib/host-directories.js +0 -84
  40. package/lib/host-session-projects.d.ts +0 -12
  41. package/lib/host-session-projects.js +0 -82
  42. package/lib/local-workspace-context.d.ts +0 -46
  43. package/lib/local-workspace-context.js +0 -17
  44. package/lib/native-workspace.d.ts +0 -11
  45. package/lib/native-workspace.js +0 -1
  46. package/lib/profile-runtime.js +0 -119
  47. package/lib/workspace-directory-picker-types.d.ts +0 -44
  48. package/lib/workspace-directory-picker-types.js +0 -1
  49. package/lib/workspace-directory-picker.d.ts +0 -30
  50. package/lib/workspace-directory-picker.js +0 -328
  51. package/lib/workspace-location-types.d.ts +0 -76
  52. package/lib/workspace-location-types.js +0 -1
  53. package/lib/workspace-locations.d.ts +0 -60
  54. package/lib/workspace-locations.js +0 -439
@@ -1,116 +0,0 @@
1
- const fs=require('node:fs/promises');
2
- const {constants}=require('node:fs');
3
- const path=require('node:path');
4
- const os=require('node:os');
5
- const error=(code,exception)=>({protocolVersion:1,ok:false,error:{code,...(['ENOENT','ENOTDIR','EACCES','EPERM','EIO','ELOOP'].includes(exception?.code)?{systemCode:exception.code}:{})}});
6
- const identity=stat=>({device:String(stat.dev),inode:String(stat.ino),mtimeNs:String(stat.mtimeNs),ctimeNs:String(stat.ctimeNs)});
7
- const entryIdentity=stat=>({device:String(stat.dev),inode:String(stat.ino)});
8
- const binaryCompare=(a,b)=>Buffer.compare(Buffer.from(a),Buffer.from(b));
9
- const validPath=value=>typeof value==='string'&&path.isAbsolute(value)&&!value.includes('\0');
10
- const invalid=()=>Object.assign(new Error('HOST_DIRECTORY_INVALID'),{directoryCode:'HOST_DIRECTORY_INVALID'});
11
- const classify=exception=>exception?.directoryCode??(['ENOENT','ENOTDIR','ELOOP'].includes(exception?.code)?'HOST_DIRECTORY_INVALID':'HOST_DIRECTORY_UNREADABLE');
12
- const unknownPermissions=()=>({read:null,write:null,execute:null,reason:'HOST_PERMISSION_UNKNOWN'});
13
- async function permissions(target){
14
- const result={};let unknown=false;
15
- for(const [key,mode] of [['read',constants.R_OK],['write',constants.W_OK],['execute',constants.X_OK]]){
16
- try{await fs.access(target,mode);result[key]=true;}catch(exception){result[key]=['EACCES','EPERM'].includes(exception?.code)?false:null;if(result[key]===null)unknown=true;}
17
- }
18
- if(unknown)result.reason='HOST_PERMISSION_UNKNOWN';return result;
19
- }
20
- async function observe(requestedPath){
21
- const entry=await fs.lstat(requestedPath,{bigint:true});
22
- const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())throw invalid();
23
- return {requestedPath,path:resolved,parentPath:path.dirname(resolved)===resolved?null:path.dirname(resolved),identity:identity(stat),entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink(),permissions:await permissions(resolved)};
24
- }
25
- async function directoryEntry(requestedPath,name){
26
- const entry=await fs.lstat(requestedPath,{bigint:true});if(!entry.isDirectory()&&!entry.isSymbolicLink())return null;
27
- const base={name,requestedPath,entryIdentity:entryIdentity(entry),isSymlink:entry.isSymbolicLink()};
28
- try{
29
- const resolved=await fs.realpath(requestedPath);const stat=await fs.stat(resolved,{bigint:true});if(!stat.isDirectory())return null;
30
- const access=await permissions(resolved);
31
- return {...base,path:resolved,identity:identity(stat),permissions:access};
32
- }catch(exception){return {...base,permissions:unknownPermissions(),errorCode:classify(exception)};}
33
- }
34
- async function execute(request){
35
- if(request?.protocolVersion!==1||!['browse','inspect','create'].includes(request.operation))return error('PROJECT_PROTOCOL_INVALID');
36
- if(!Number.isSafeInteger(request.maxOutputBytes)||request.maxOutputBytes<1)return error('HOST_DIRECTORY_INVALID');
37
- if(request.path!==undefined&&!validPath(request.path))return error('HOST_DIRECTORY_INVALID');
38
- if(request.operation==='inspect'&&request.path===undefined)return error('HOST_DIRECTORY_INVALID');
39
- if(request.operation==='browse'&&(!Number.isSafeInteger(request.pageSize)||request.pageSize<1||request.after!==undefined&&(typeof request.after!=='string'||request.after===''||request.after==='.'||request.after==='..'||request.after.includes(path.sep)||request.after.includes('\0'))))return error('HOST_DIRECTORY_INVALID');
40
- if(request.operation==='create'&&(!validPath(request.path)||typeof request.name!=='string'||['','.','..'].includes(request.name)||/[\\/\x00-\x1f\x7f]/.test(request.name)))return error('HOST_DIRECTORY_INVALID');
41
- const requestedPath=request.path??os.homedir();
42
- try{
43
- if(request.operation==='inspect'){const stat=await fs.stat(requestedPath);if(!stat.isDirectory())throw invalid();const result={protocolVersion:1,ok:true,value:{path:requestedPath}};return Buffer.byteLength(JSON.stringify(result)+'\n')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;}
44
- const before=await observe(requestedPath);
45
- if(request.operation==='create'){
46
- const child=path.join(before.path,request.name);
47
- try{await fs.mkdir(child);}catch(exception){return error(exception?.code==='EEXIST'?'HOST_DIRECTORY_EXISTS':classify(exception));}
48
- const result={protocolVersion:1,ok:true,value:await observe(child)};
49
- return Buffer.byteLength(JSON.stringify(result)+'\n','utf8')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;
50
- }
51
- let value=before;
52
- if(request.operation==='browse'){
53
- // Keep only the smallest pageSize+1 eligible names, independent of readdir order.
54
- const window=[];
55
- for await(const dirent of await fs.opendir(requestedPath)){
56
- const name=dirent.name;if(request.after!==undefined&&binaryCompare(name,request.after)<=0)continue;
57
- if(!dirent.isDirectory()&&!dirent.isSymbolicLink()&&(dirent.isFile()||dirent.isBlockDevice()||dirent.isCharacterDevice()||dirent.isFIFO()||dirent.isSocket()))continue;
58
- if(window.length>request.pageSize&&binaryCompare(name,window[window.length-1].name)>=0)continue;
59
- const entry=await directoryEntry(path.join(requestedPath,name),name);if(entry===null)continue;
60
- let index=window.findIndex(item=>binaryCompare(name,item.name)<0);if(index===-1)index=window.length;window.splice(index,0,entry);if(window.length>request.pageSize+1)window.pop();
61
- }
62
- const hasMore=window.length>request.pageSize;if(hasMore)window.pop();value={...before,entries:window,...hasMore?{nextAfter:window[window.length-1].name}:{}};
63
- }
64
- const result={protocolVersion:1,ok:true,value};
65
- return Buffer.byteLength(JSON.stringify(result)+'\n','utf8')>request.maxOutputBytes?error('HOST_DIRECTORY_PAGE_TOO_LARGE'):result;
66
- }catch(exception){return error(classify(exception),exception);}
67
- }
68
- async function main(){
69
- let input='';for await(const chunk of process.stdin)input+=chunk;
70
- let result;try{result=await execute(JSON.parse(input));}catch{result=error('PROJECT_PROTOCOL_INVALID');}
71
- process.stdout.write(JSON.stringify(result)+'\n');
72
- }
73
- // One remote Node process per browsing connection. Speculation is one level only,
74
- // shares the existing output budget, and never authorizes execution or selection.
75
- async function serve(maxBytes){
76
- const {StringDecoder}=require('node:string_decoder');const decoder=new StringDecoder('utf8');
77
- let buffer='',cache=new Map(),prefetchGeneration=0;
78
- const cacheKey=r=>JSON.stringify([r?.operation,r?.path??null,r?.after??null,r?.pageSize,r?.maxOutputBytes]);
79
- async function respond(frame){
80
- if(!frame||Object.keys(frame).sort().join(',')!=='id,request'||typeof frame.id!=='string')throw new Error('PROJECT_PROTOCOL_INVALID');
81
- const request=frame.request,key=cacheKey(request),saved=cache.get(key);
82
- let result=saved?await saved:await execute(request);
83
- // Re-observe a prefetched directory at click time: changed links, permissions,
84
- // or entries must not return an old canonical path or a stale listing.
85
- if(saved&&!result.ok)result=await execute(request);
86
- else if(saved&&result.ok){
87
- let current;try{current=await observe(request.path);}catch(exception){result=error(classify(exception),exception);}
88
- if(current){
89
- let changed=JSON.stringify(current)!==JSON.stringify((({entries,nextAfter,...info})=>info)(result.value));
90
- if(!changed)try{for(const entry of result.value.entries){if(JSON.stringify(await directoryEntry(entry.requestedPath,entry.name))!==JSON.stringify(entry)){changed=true;break;}}}catch{changed=true;}
91
- if(changed)result=await execute(request);
92
- }
93
- }
94
- const mine=++prefetchGeneration;cache=new Map();
95
- const line=JSON.stringify({id:frame.id,result})+'\n';
96
- process.stdout.write(Buffer.byteLength(line)>maxBytes?JSON.stringify({id:frame.id,result:error('HOST_DIRECTORY_PAGE_TOO_LARGE')})+'\n':line);
97
- if(request?.operation!=='browse'||!result.ok)return;
98
- const nextCache=cache;let bytes=0;
99
- // No recursion: execute() never calls serve() or starts another prefetch.
100
- void (async()=>{for(const entry of result.value.entries){
101
- if(mine!==prefetchGeneration)break;
102
- if(entry.errorCode||entry.permissions.read!==true||entry.permissions.execute!==true)continue;
103
- const child={...request,path:entry.requestedPath};delete child.after;
104
- const key=cacheKey(child),pending=execute(child);nextCache.set(key,pending);
105
- const value=await pending;bytes+=Buffer.byteLength(JSON.stringify(value));
106
- if(bytes>maxBytes){nextCache.delete(key);break;}
107
- }})().catch(()=>{prefetchGeneration++;cache.clear();process.exitCode=1;process.stdin.destroy();});
108
- }
109
- for await(const chunk of process.stdin){
110
- buffer+=decoder.write(chunk);if(Buffer.byteLength(buffer)>maxBytes)throw new Error('HOST_DIRECTORY_PAGE_TOO_LARGE');
111
- let end;while((end=buffer.indexOf('\n'))!==-1){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);await respond(JSON.parse(line));}
112
- }
113
- prefetchGeneration++;cache.clear();if(buffer||decoder.end())throw new Error('PROJECT_PROTOCOL_INVALID');
114
- }
115
- module.exports={execute,serve};
116
- if(require.main===module)void main();
@@ -1,9 +0,0 @@
1
- import type { RemoteConversationDetail, Result } from './api.ts';
2
- /** Best-effort local diagnostics. No receipt, admission, ordering or execution gate. */
3
- export declare function createConversationLog(o: {
4
- profileDir: string;
5
- diagnostic?: (line: string) => void;
6
- }): {
7
- append: (detail: RemoteConversationDetail) => void;
8
- read: () => Promise<Result<string>>;
9
- };
@@ -1,44 +0,0 @@
1
- import { constants } from 'node:fs';
2
- import { open } from 'node:fs/promises';
3
- import { join } from 'node:path';
4
- import { privateDirectory, readPrivate } from "./private-files.js";
5
- import { fail, ok } from "./needs.js";
6
- /** Best-effort local diagnostics. No receipt, admission, ordering or execution gate. */
7
- export function createConversationLog(o) {
8
- const root = join(o.profileDir, 'ai-workbench-connect'), file = join(root, 'conversation.log');
9
- let pending = Promise.resolve();
10
- const report = () => { try {
11
- (o.diagnostic ?? console.warn)('会话技术日志写入失败;本轮继续。');
12
- }
13
- catch { /* Diagnostics cannot stop a user turn. */ } };
14
- function append(detail) {
15
- let line;
16
- try {
17
- line = JSON.stringify({ time: new Date().toISOString(), detail }) + '\n';
18
- }
19
- catch {
20
- report();
21
- return;
22
- }
23
- pending = pending.then(async () => { await privateDirectory(root); const h = await open(file, constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); try {
24
- const stat = await h.stat();
25
- if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o177) !== 0)
26
- throw Error('PRIVATE_FILE_REQUIRED');
27
- await h.writeFile(line);
28
- }
29
- finally {
30
- await h.close();
31
- } }).catch(report);
32
- }
33
- async function read() {
34
- await pending;
35
- try {
36
- await privateDirectory(root);
37
- return ok(await readPrivate(file));
38
- }
39
- catch (e) {
40
- return e.code === 'ENOENT' ? ok('') : fail('REMOTE_DETAIL_STORAGE_FAILED');
41
- }
42
- }
43
- return { append, read };
44
- }
@@ -1,7 +0,0 @@
1
- import type { SshTarget } from './api.ts';
2
- export declare const DIRECTORY_CONTROL_PERSIST_SECONDS = 60;
3
- export declare function createDirectorySession(profileDir: string, maxBytes: number): {
4
- request(target: SshTarget, request: unknown, signal: AbortSignal): Promise<string>;
5
- reset(): Promise<void>;
6
- dispose(): Promise<void>;
7
- };
@@ -1,153 +0,0 @@
1
- import { spawn } from 'node:child_process';
2
- import { readFile, mkdtemp, realpath, rm, lstat } from 'node:fs/promises';
3
- import { join, relative } from 'node:path';
4
- import { randomUUID } from 'node:crypto';
5
- import { StringDecoder } from 'node:string_decoder';
6
- import { sshArgs } from "./ssh.js";
7
- import { privateDirectory } from "./private-files.js";
8
- import { AuthDiagnosticError } from "./auth-diagnostics.js";
9
- // B-class fixed transport policy, documented in README; not a business deadline.
10
- export const DIRECTORY_CONTROL_PERSIST_SECONDS = 60;
11
- export function createDirectorySession(profileDir, maxBytes) {
12
- let current;
13
- let tail = Promise.resolve(), generation = 0, disposed = false;
14
- const failure = (reason) => new AuthDiagnosticError({ stage: 'directory-stream', reason });
15
- async function close() {
16
- const old = current;
17
- if (!old)
18
- return;
19
- old.failure ??= failure('CONNECTION_LOST');
20
- old.pending?.reject(old.failure);
21
- old.pending = undefined;
22
- if (old.child.exitCode === null && old.child.signalCode === null)
23
- old.child.kill('SIGTERM');
24
- // Only this instance's private master, never another profile's connection.
25
- const exitCode = await new Promise((resolve, reject) => { const child = spawn('ssh', ['-O', 'exit', ...old.args], { cwd: profileDir, stdio: 'ignore', shell: false, env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined } }); child.once('error', () => reject(failure('MASTER_CLEANUP_FAILED'))); child.once('close', code => resolve(code)); });
26
- if (exitCode !== 0)
27
- try {
28
- await lstat(join(old.directory, 'c'));
29
- throw failure('MASTER_CLEANUP_FAILED');
30
- }
31
- catch (error) {
32
- if (error.code !== 'ENOENT')
33
- throw error;
34
- }
35
- await old.closed;
36
- try {
37
- await lstat(join(old.directory, 'c'));
38
- throw failure('MASTER_CLEANUP_FAILED');
39
- }
40
- catch (error) {
41
- if (error.code !== 'ENOENT')
42
- throw error;
43
- }
44
- await rm(old.directory, { recursive: true, force: true });
45
- if (current === old)
46
- current = undefined;
47
- }
48
- async function open(target) {
49
- const key = JSON.stringify(target);
50
- if (current?.target === key && !current.failure)
51
- return current;
52
- await close();
53
- if (await realpath(profileDir) !== profileDir)
54
- throw failure('PRIVATE_DIRECTORY_REQUIRED');
55
- const root = join(profileDir, 'ai-workbench-connect');
56
- await privateDirectory(root);
57
- if (await realpath(root) !== root)
58
- throw failure('PRIVATE_DIRECTORY_REQUIRED');
59
- const sockets = join(root, 'ssh');
60
- await privateDirectory(sockets);
61
- const directory = await mkdtemp(join(sockets, 'm-'));
62
- // A relative Unix socket path avoids macOS sun_path limits for long profile paths.
63
- const control = './' + relative(profileDir, join(directory, 'c'));
64
- const args = ['-o', 'ControlMaster=auto', '-o', 'ControlPath=' + JSON.stringify(control.replaceAll('%', '%%')), '-o', 'ControlPersist=' + DIRECTORY_CONTROL_PERSIST_SECONDS, ...sshArgs(target)];
65
- try {
66
- const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
67
- const command = 'node -e ' + "'" + (source + '\nserve(' + maxBytes + ');').replaceAll("'", "'\\''") + "'";
68
- const child = spawn('ssh', [...args, command], { cwd: profileDir, shell: false, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined } });
69
- let done = () => { };
70
- const closed = new Promise(resolve => done = resolve);
71
- const session = { target: key, child, closed, directory, args };
72
- current = session;
73
- const stop = (reason) => { session.failure ??= failure(reason); session.pending?.reject(session.failure); session.pending = undefined; if (child.exitCode === null && child.signalCode === null)
74
- child.kill('SIGTERM'); };
75
- const decoder = new StringDecoder('utf8');
76
- let buffer = '';
77
- child.stdout.on('data', (chunk) => {
78
- buffer += decoder.write(chunk);
79
- if (Buffer.byteLength(buffer) > maxBytes) {
80
- stop('OUTPUT_LIMIT_EXCEEDED');
81
- return;
82
- }
83
- let end;
84
- while ((end = buffer.indexOf('\n')) !== -1) {
85
- const line = buffer.slice(0, end);
86
- buffer = buffer.slice(end + 1);
87
- try {
88
- const frame = JSON.parse(line);
89
- if (!session.pending || !frame || Object.keys(frame).sort().join(',') !== 'id,result' || frame.id !== session.pending.id)
90
- throw Error();
91
- const pending = session.pending;
92
- session.pending = undefined;
93
- pending.resolve(JSON.stringify(frame.result));
94
- }
95
- catch {
96
- stop('PROJECT_PROTOCOL_INVALID');
97
- return;
98
- }
99
- }
100
- });
101
- child.stderr.on('data', () => stop('SSH_STDERR_NONEMPTY'));
102
- child.stdin.on('error', () => stop('STDIN_FAILED'));
103
- child.once('error', () => stop('SPAWN_FAILED'));
104
- child.once('close', () => { stop('CONNECTION_LOST'); done(); });
105
- return session;
106
- }
107
- catch (error) {
108
- await rm(directory, { recursive: true, force: true });
109
- throw error;
110
- }
111
- }
112
- return {
113
- request(target, request, signal) {
114
- const mine = generation;
115
- const task = tail.then(async () => {
116
- if (disposed || signal.aborted || mine !== generation)
117
- throw failure('CANCELLED');
118
- const session = await open(target);
119
- if (disposed || signal.aborted || mine !== generation) {
120
- await close();
121
- throw failure('CANCELLED');
122
- }
123
- if (session.failure)
124
- throw session.failure;
125
- const id = randomUUID(), line = JSON.stringify({ id, request }) + '\n';
126
- if (Buffer.byteLength(line) > maxBytes)
127
- throw failure('OUTPUT_LIMIT_EXCEEDED');
128
- const abort = () => { session.failure ??= failure('CANCELLED'); session.pending?.reject(session.failure); session.pending = undefined; session.child.kill('SIGTERM'); };
129
- signal.addEventListener('abort', abort, { once: true });
130
- try {
131
- return await new Promise((resolve, reject) => { session.pending = { id, resolve, reject }; if (signal.aborted)
132
- abort();
133
- else
134
- session.child.stdin.write(line); });
135
- }
136
- finally {
137
- signal.removeEventListener('abort', abort);
138
- if (session.failure)
139
- await close();
140
- }
141
- });
142
- tail = task.catch(() => { });
143
- return task;
144
- },
145
- reset() { generation++; const task = tail.then(close); tail = task.catch(() => { }); if (current) {
146
- current.failure ??= failure('CONNECTION_LOST');
147
- current.pending?.reject(current.failure);
148
- current.pending = undefined;
149
- current.child.kill('SIGTERM');
150
- } return task; },
151
- dispose() { disposed = true; return this.reset(); },
152
- };
153
- }
@@ -1,58 +0,0 @@
1
- import type { Result, SshTarget } from './api.ts';
2
- import type { Runner } from './ssh.ts';
3
- export interface HostDirectoryIdentity {
4
- device: string;
5
- inode: string;
6
- mtimeNs: string;
7
- ctimeNs: string;
8
- }
9
- export interface HostPermissions {
10
- read: boolean | null;
11
- write: boolean | null;
12
- execute: boolean | null;
13
- reason?: string;
14
- }
15
- export interface HostDirectoryInfo {
16
- requestedPath: string;
17
- path: string;
18
- parentPath: string | null;
19
- identity: HostDirectoryIdentity;
20
- entryIdentity: {
21
- device: string;
22
- inode: string;
23
- };
24
- isSymlink: boolean;
25
- permissions: HostPermissions;
26
- }
27
- export interface HostDirectoryEntry {
28
- name: string;
29
- requestedPath: string;
30
- path?: string;
31
- identity?: HostDirectoryIdentity;
32
- entryIdentity: {
33
- device: string;
34
- inode: string;
35
- };
36
- isSymlink: boolean;
37
- permissions: HostPermissions;
38
- errorCode?: string;
39
- }
40
- export interface HostDirectoryData extends HostDirectoryInfo {
41
- entries: HostDirectoryEntry[];
42
- nextAfter?: string;
43
- }
44
- export interface HostDirectoryRequest {
45
- path?: string;
46
- after?: string;
47
- pageSize: number;
48
- }
49
- export interface HostDirectories {
50
- reset?(): Promise<void>;
51
- dispose?(): Promise<void>;
52
- browse(target: SshTarget, data: HostDirectoryRequest, signal: AbortSignal): Promise<Result<HostDirectoryData>>;
53
- inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<Pick<HostDirectoryInfo, 'path'>>>;
54
- create?(target: SshTarget, path: string, name: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
55
- }
56
- export declare function createHostDirectories(runner: Runner, maxOutputBytes: number, options?: {
57
- profileDir: string;
58
- }): HostDirectories;
@@ -1,84 +0,0 @@
1
- import { createDirectorySession } from "./directory-session.js";
2
- import { readFile } from 'node:fs/promises';
3
- import { runRemote } from "./ssh.js";
4
- import { fail, ok } from "./needs.js";
5
- import { AuthDiagnosticError, authFailure } from "./auth-diagnostics.js";
6
- const codes = ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_PAGE_TOO_LARGE', 'PROJECT_PROTOCOL_INVALID', 'HOST_DIRECTORY_EXISTS'];
7
- const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
8
- const decimal = (value) => typeof value === 'string' && /^\d+$/.test(value);
9
- function validEntryIdentity(value) { return object(value) && decimal(value.device) && decimal(value.inode); }
10
- function validIdentity(value) { return object(value) && validEntryIdentity(value) && ['mtimeNs', 'ctimeNs'].every(key => typeof value[key] === 'string' && /^-?\d+$/.test(value[key])); }
11
- function validPermissions(value) { return object(value) && ['read', 'write', 'execute'].every(key => typeof value[key] === 'boolean' || value[key] === null) && ([value.read, value.write, value.execute].includes(null) ? value.reason === 'HOST_PERMISSION_UNKNOWN' : value.reason === undefined); }
12
- const validPath = (value) => typeof value === 'string' && value.startsWith('/') && !value.includes('\0');
13
- const validName = (value) => typeof value === 'string' && value !== '' && value !== '.' && value !== '..' && !value.includes('/') && !value.includes('\0');
14
- function validInfo(value) { return object(value) && validPath(value.requestedPath) && validPath(value.path) && (value.parentPath === null || validPath(value.parentPath)) && validIdentity(value.identity) && validEntryIdentity(value.entryIdentity) && typeof value.isSymlink === 'boolean' && validPermissions(value.permissions); }
15
- function validEntry(value, parent) {
16
- if (!object(value) || !validName(value.name) || value.requestedPath !== (parent.endsWith('/') ? parent : parent + '/') + value.name || !validEntryIdentity(value.entryIdentity) || typeof value.isSymlink !== 'boolean' || !validPermissions(value.permissions))
17
- return false;
18
- if (value.errorCode !== undefined && !['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE'].includes(value.errorCode))
19
- return false;
20
- if (value.path === undefined || value.identity === undefined)
21
- return value.path === undefined && value.identity === undefined && value.errorCode !== undefined;
22
- return validPath(value.path) && validIdentity(value.identity);
23
- }
24
- const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
25
- export function createHostDirectories(runner, maxOutputBytes, options) {
26
- const session = options ? createDirectorySession(options.profileDir, maxOutputBytes) : undefined;
27
- async function request(target, operation, data, signal) {
28
- if (signal.aborted)
29
- return fail('CONNECTION_LOST');
30
- if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name)) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.after !== undefined && (!validName(data.after))))
31
- return fail('HOST_DIRECTORY_INVALID');
32
- try {
33
- const payload = { protocolVersion: 1, operation, ...data, maxOutputBytes };
34
- // Inspect/create always perform a fresh check/mutation through the original path.
35
- if (operation === 'create')
36
- await session?.reset();
37
- const source = operation === 'browse' && session ? '' : await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
38
- const command = 'node -e ' + "'" + (source + '\nmain();').replaceAll("'", "'\\''") + "'";
39
- const raw = operation === 'browse' && session ? { exitCode: 0, stderr: '', stdout: await session.request(target, payload, signal) } : await runRemote(runner, target, command, signal, JSON.stringify(payload));
40
- if (signal.aborted)
41
- return fail('CONNECTION_LOST');
42
- if (raw.exitCode !== 0 || raw.stderr !== '')
43
- return authFailure('ssh-result', raw.exitCode !== 0 ? 'SSH_EXIT_NONZERO' : 'SSH_STDERR_NONEMPTY', { exitCode: raw.exitCode }, undefined, 'CONNECTION_LOST');
44
- if (Buffer.byteLength(raw.stdout, 'utf8') > maxOutputBytes)
45
- return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
46
- let result;
47
- try {
48
- result = JSON.parse(raw.stdout);
49
- }
50
- catch {
51
- return fail('PROJECT_PROTOCOL_INVALID');
52
- }
53
- if (!object(result) || result.protocolVersion !== 1 || typeof result.ok !== 'boolean')
54
- return fail('PROJECT_PROTOCOL_INVALID');
55
- if (!result.ok) {
56
- const error = result.error;
57
- const code = object(error) ? codes.find(code => code === error.code) : undefined;
58
- return authFailure('host-directory', 'REMOTE_DIRECTORY_ERROR', { ...(object(error) && ['ENOENT', 'ENOTDIR', 'EACCES', 'EPERM', 'EIO', 'ELOOP'].includes(String(error.systemCode)) ? { errorCode: error.systemCode } : {}) }, undefined, code ?? 'PROJECT_PROTOCOL_INVALID');
59
- }
60
- if (operation === 'inspect')
61
- return object(result.value) && result.value.path === data.path ? ok({ path: data.path }) : fail('PROJECT_PROTOCOL_INVALID');
62
- if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== (operation === 'create' ? (data.path.endsWith('/') ? data.path : data.path + '/') + data.name : data.path))
63
- return fail('PROJECT_PROTOCOL_INVALID');
64
- if (operation === 'browse') {
65
- const value = result.value;
66
- if (!Array.isArray(value.entries) || value.entries.length > data.pageSize || !value.entries.every(entry => validEntry(entry, value.requestedPath)) || value.entries.some((entry, index) => index > 0 && binaryCompare(value.entries[index - 1].name, entry.name) >= 0 || data.after !== undefined && binaryCompare(entry.name, data.after) <= 0) || value.nextAfter !== undefined && (value.entries.length !== data.pageSize || value.nextAfter !== value.entries[value.entries.length - 1]?.name))
67
- return fail('PROJECT_PROTOCOL_INVALID');
68
- }
69
- return ok(result.value);
70
- }
71
- catch (error) {
72
- if (signal.aborted)
73
- return fail('CONNECTION_LOST');
74
- if (error instanceof AuthDiagnosticError) {
75
- if (error.diagnostic.reason === 'OUTPUT_LIMIT_EXCEEDED')
76
- return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
77
- if (error.diagnostic.stage === 'remote-frame' || error.diagnostic.reason === 'PROJECT_PROTOCOL_INVALID')
78
- return fail('PROJECT_PROTOCOL_INVALID');
79
- }
80
- return authFailure('host-directory', 'DIRECTORY_CHECK_EXCEPTION', {}, error, 'CONNECTION_LOST');
81
- }
82
- }
83
- return { ...(session ? { reset: () => session.reset(), dispose: () => session.dispose() } : {}), create: (target, path, name, signal) => request(target, 'create', { path, name }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
84
- }
@@ -1,12 +0,0 @@
1
- import type { ConnectApi, HostSessionProjectTarget, Result, WorkspaceUse } from './api.ts';
2
- import type { HostWorkspaceResolveContext } from './workspace-location-types.ts';
3
- interface Options {
4
- guardEmployee?: (sessionId: string, target: import('./api.ts').SshTarget, source: HostWorkspaceResolveContext) => Promise<void>;
5
- api: Pick<ConnectApi, 'ensureReady' | 'appendRemoteConversationDetail'> & Partial<Pick<ConnectApi, 'getConnectionState'>>;
6
- hostDirectories?: import('./host-directories.ts').HostDirectories;
7
- }
8
- export declare function createHostSessionProjects(o: Options): {
9
- resolve: (id: string, use: WorkspaceUse, input: HostWorkspaceResolveContext) => Promise<Result<HostSessionProjectTarget>>;
10
- dispose(): void;
11
- };
12
- export {};
@@ -1,82 +0,0 @@
1
- import { basename, isAbsolute } from 'node:path';
2
- import { randomUUID } from 'node:crypto';
3
- import { exceptionSummary, outputSummary } from "./auth-diagnostics.js";
4
- import { ok, need, NeedError } from "./needs.js";
5
- const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
6
- function reject(code, reason) { throw new NeedError({ ...need(code), officialReason: reason }); }
7
- export function createHostSessionProjects(o) {
8
- const controllers = new Set();
9
- let disposed = false;
10
- async function resolve(id, use, input) {
11
- let stage = 'request';
12
- const failure = (error) => {
13
- let n = error instanceof NeedError ? error.need : need('PROJECT_BINDING_INVALID');
14
- if (n.code === 'HOST_DIRECTORY_UNREADABLE')
15
- n = { ...n, message: '暂时无法读取会话记录的主机目录,请查看技术详情,确认主机存储或权限恢复后再试。' };
16
- if (n.code === 'HOST_DIRECTORY_INVALID')
17
- n = { ...n, message: '会话记录的主机路径不存在或不是文件夹,请恢复该目录后再试。' };
18
- if (n.officialReason === 'SESSION_HOST_UNAVAILABLE')
19
- n = { ...n, message: '此会话使用的主机当前未连接,请连接原主机后再试;会话文件来源保持不变。' };
20
- const exception = exceptionSummary(error);
21
- const payload = { stage, reason: n.officialReason ?? (error instanceof NeedError ? 'DECLARED_NEED' : 'UNEXPECTED_EXCEPTION'), ...exception, ...(!(error instanceof NeedError) && error instanceof Error ? { exception: outputSummary(error.message) } : {}) };
22
- // 沿已有本机日志留一行;不记录异常原文/路径/凭据,也不让日志失败改写原失败。
23
- const line = { event: 'HOST_WORKSPACE_RESOLVE_FAILED', code: n.code, ...payload };
24
- try {
25
- if (!text(id) || !use || !['claude', 'codex'].includes(use.provider) || typeof o.api.appendRemoteConversationDetail !== 'function')
26
- throw Error('DIAGNOSTIC_CONTEXT_UNAVAILABLE');
27
- const connection = o.api.getConnectionState?.();
28
- o.api.appendRemoteConversationDetail({ version: 1, eventId: randomUUID(), instanceId: connection?.instanceId ?? 'unknown', epoch: connection?.epoch ?? 0, sessionId: id, provider: use.provider, turn: null, step: null, sequence: 0, kind: 'diagnostic', severity: 'action-required', code: n.code, summary: n.message, payload });
29
- }
30
- catch {
31
- try {
32
- console.warn(JSON.stringify(line));
33
- }
34
- catch { /* 日志不可用不改变本轮结果。 */ }
35
- }
36
- return { ok: false, error: n };
37
- };
38
- try {
39
- if (!text(id) || !use || Object.keys(use).sort().join(',') !== 'provider,purpose' || !['claude', 'codex'].includes(use.provider) || use.purpose !== 'user-turn')
40
- reject('PROJECT_BINDING_REQUIRED', 'SESSION_OR_REQUEST_UNAVAILABLE');
41
- const source = structuredClone(input);
42
- if (!source || source.source !== 'host' || !text(source.host) || !text(source.path) || !isAbsolute(source.path))
43
- reject('PROJECT_BINDING_REQUIRED', 'SESSION_HOST_PATH_REQUIRED');
44
- if (disposed)
45
- reject('DISPOSED', 'RUNTIME_DISPOSED');
46
- stage = 'login-ready';
47
- const before = o.api.getConnectionState?.();
48
- const ready = await o.api.ensureReady(use.provider);
49
- if (!ready.ok)
50
- return failure(new NeedError(ready.error));
51
- if (disposed)
52
- reject('DISPOSED', 'RUNTIME_DISPOSED');
53
- await o.guardEmployee?.(id, ready.value, source);
54
- if (ready.value.host !== source.host)
55
- reject('WORKSPACE_LOCATION_INVALID', 'SESSION_HOST_UNAVAILABLE');
56
- if (!o.hostDirectories)
57
- reject('DEPENDENCY_REQUIRED', 'HOST_DIRECTORY_SERVICE_REQUIRED');
58
- const controller = new AbortController();
59
- controllers.add(controller);
60
- try {
61
- stage = 'host-directory';
62
- const checked = await o.hostDirectories.inspect(ready.value, source.path, controller.signal);
63
- if (!checked.ok)
64
- return failure(new NeedError(checked.error));
65
- if (disposed)
66
- reject('DISPOSED', 'RUNTIME_DISPOSED');
67
- const now = o.api.getConnectionState?.();
68
- if (before && now && (now.phase !== 'connected' || now.epoch !== before.epoch || now.instanceId !== before.instanceId))
69
- reject('CONNECTION_LOST', 'CONNECTION_LOST');
70
- return ok({ sessionId: id, source: 'host', host: source.host, project: { name: basename(source.path) || '/', path: source.path }, target: structuredClone(ready.value) });
71
- }
72
- finally {
73
- controllers.delete(controller);
74
- }
75
- }
76
- catch (e) {
77
- return failure(e);
78
- }
79
- }
80
- return { resolve, dispose() { disposed = true; for (const controller of controllers)
81
- controller.abort(); } };
82
- }
@@ -1,46 +0,0 @@
1
- import type { Result } from './api.ts';
2
- /** Local metadata; neither OS consent nor an authenticated endpoint identity. */
3
- export interface LocalWorkspaceContextRequest {
4
- instanceId: string;
5
- epoch: number;
6
- workspaceId: string;
7
- expectedBindingId: string;
8
- }
9
- export interface LocalWorkspaceProcess {
10
- pid: number;
11
- ppid: number;
12
- platform: string;
13
- arch: string;
14
- executable: string;
15
- realUid: number;
16
- effectiveUid: number;
17
- realGid: number;
18
- effectiveGid: number;
19
- account: {
20
- name: string;
21
- home: string;
22
- shell: string | null;
23
- };
24
- environment: {
25
- HOME: string | null;
26
- PATH: string | null;
27
- SHELL: string | null;
28
- };
29
- }
30
- export interface LocalWorkspaceContext {
31
- version: 1;
32
- instanceId: string;
33
- epoch: number;
34
- workspaceId: string;
35
- bindingId: string;
36
- source: 'local';
37
- directory: {
38
- path: string;
39
- device: number;
40
- inode: number;
41
- };
42
- provenance: 'official-workspace-registry';
43
- process: LocalWorkspaceProcess;
44
- }
45
- /** Read the current backend's OS facts and three named variables. Never spawn a shell. */
46
- export declare function readLocalWorkspaceProcess(): Result<LocalWorkspaceProcess>;
@@ -1,17 +0,0 @@
1
- import { userInfo } from 'node:os';
2
- import { fail, ok } from "./needs.js";
3
- /** Read the current backend's OS facts and three named variables. Never spawn a shell. */
4
- export function readLocalWorkspaceProcess() {
5
- if (process.platform !== 'darwin')
6
- return fail('LOCAL_WORKSPACE_CONTEXT_UNSUPPORTED');
7
- try {
8
- const account = userInfo();
9
- return ok({ pid: process.pid, ppid: process.ppid, platform: process.platform, arch: process.arch, executable: process.execPath,
10
- realUid: process.getuid(), effectiveUid: process.geteuid(), realGid: process.getgid(), effectiveGid: process.getegid(),
11
- account: { name: account.username, home: account.homedir, shell: account.shell },
12
- environment: { HOME: process.env.HOME ?? null, PATH: process.env.PATH ?? null, SHELL: process.env.SHELL ?? null } });
13
- }
14
- catch {
15
- return fail('LOCAL_WORKSPACE_CONTEXT_UNAVAILABLE');
16
- }
17
- }