@ai-workbench/connect 0.7.9 → 0.7.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/client/index.cjs +33 -13
- package/helper/host-directories.cjs +72 -0
- package/helper/remote-command.cjs +1 -1
- package/lib/api.d.ts +44 -1
- package/lib/api.js +1 -1
- package/lib/auth-diagnostics.d.ts +22 -0
- package/lib/auth-diagnostics.js +45 -0
- package/lib/auth-status.js +21 -8
- package/lib/components.d.ts +1 -1
- package/lib/components.js +106 -5
- package/lib/connect.d.ts +3 -0
- package/lib/connect.js +105 -23
- package/lib/connection-messages.d.ts +7 -0
- package/lib/connection-messages.js +6 -0
- package/lib/conversation-details.d.ts +3 -0
- package/lib/conversation-details.js +8 -7
- package/lib/cordis.d.ts +3 -1
- package/lib/defaults.d.ts +6 -0
- package/lib/defaults.js +2 -0
- package/lib/host-directories.d.ts +53 -0
- package/lib/host-directories.js +76 -0
- package/lib/index.d.ts +8 -1
- package/lib/index.js +9 -4
- package/lib/integration.js +6 -3
- package/lib/local-workspace-context.d.ts +46 -0
- package/lib/local-workspace-context.js +17 -0
- package/lib/login-diagnostics.d.ts +26 -0
- package/lib/login-diagnostics.js +42 -0
- package/lib/needs.js +12 -0
- package/lib/ports.d.ts +2 -0
- package/lib/processes.js +6 -5
- package/lib/profile-runtime.js +53 -22
- package/lib/ssh.js +37 -14
- package/lib/startup.d.ts +23 -2
- package/lib/startup.js +152 -41
- package/lib/workspace-bindings.d.ts +30 -1
- package/lib/workspace-bindings.js +1 -0
- package/lib/workspace-location-types.d.ts +65 -0
- package/lib/workspace-location-types.js +1 -0
- package/lib/workspace-locations.d.ts +45 -0
- package/lib/workspace-locations.js +427 -0
- package/node_modules/argparse/CHANGELOG.md +216 -0
- package/package.json +4 -3
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { runRemote } from "./ssh.js";
|
|
3
|
+
import { fail, ok } from "./needs.js";
|
|
4
|
+
import { AuthDiagnosticError } from "./auth-diagnostics.js";
|
|
5
|
+
const codes = ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_PAGE_TOO_LARGE', 'PROJECT_PROTOCOL_INVALID'];
|
|
6
|
+
const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
7
|
+
const decimal = (value) => typeof value === 'string' && /^\d+$/.test(value);
|
|
8
|
+
function validEntryIdentity(value) { return object(value) && decimal(value.device) && decimal(value.inode); }
|
|
9
|
+
function validIdentity(value) { return object(value) && validEntryIdentity(value) && ['mtimeNs', 'ctimeNs'].every(key => typeof value[key] === 'string' && /^-?\d+$/.test(value[key])); }
|
|
10
|
+
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); }
|
|
11
|
+
const validPath = (value) => typeof value === 'string' && value.startsWith('/') && !value.includes('\0');
|
|
12
|
+
const validName = (value) => typeof value === 'string' && value !== '' && value !== '.' && value !== '..' && !value.includes('/') && !value.includes('\0');
|
|
13
|
+
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); }
|
|
14
|
+
function validEntry(value, parent) {
|
|
15
|
+
if (!object(value) || !validName(value.name) || value.requestedPath !== (parent.endsWith('/') ? parent : parent + '/') + value.name || !validEntryIdentity(value.entryIdentity) || typeof value.isSymlink !== 'boolean' || !validPermissions(value.permissions))
|
|
16
|
+
return false;
|
|
17
|
+
if (value.errorCode !== undefined && !['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE'].includes(value.errorCode))
|
|
18
|
+
return false;
|
|
19
|
+
if (value.path === undefined || value.identity === undefined)
|
|
20
|
+
return value.path === undefined && value.identity === undefined && value.errorCode !== undefined;
|
|
21
|
+
return validPath(value.path) && validIdentity(value.identity) && (value.errorCode !== undefined || value.permissions.read === true && value.permissions.execute === true);
|
|
22
|
+
}
|
|
23
|
+
const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
24
|
+
export function createHostDirectories(runner, maxOutputBytes) {
|
|
25
|
+
async function request(target, operation, data, signal) {
|
|
26
|
+
if (signal.aborted)
|
|
27
|
+
return fail('CONNECTION_LOST');
|
|
28
|
+
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.expected !== undefined && !validIdentity(data.expected) || data.after !== undefined && (!validName(data.after) || !validIdentity(data.expected))))
|
|
29
|
+
return fail('HOST_DIRECTORY_INVALID');
|
|
30
|
+
try {
|
|
31
|
+
const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
|
|
32
|
+
const command = 'node -e ' + "'" + (source + '\nmain();').replaceAll("'", "'\\''") + "'";
|
|
33
|
+
const raw = await runRemote(runner, target, command, signal, JSON.stringify({ protocolVersion: 1, operation, ...data, maxOutputBytes }));
|
|
34
|
+
if (signal.aborted)
|
|
35
|
+
return fail('CONNECTION_LOST');
|
|
36
|
+
if (raw.exitCode !== 0 || raw.stderr !== '')
|
|
37
|
+
return fail('HOST_DIRECTORY_UNREADABLE');
|
|
38
|
+
if (Buffer.byteLength(raw.stdout, 'utf8') > maxOutputBytes)
|
|
39
|
+
return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
40
|
+
let result;
|
|
41
|
+
try {
|
|
42
|
+
result = JSON.parse(raw.stdout);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
46
|
+
}
|
|
47
|
+
if (!object(result) || result.protocolVersion !== 1 || typeof result.ok !== 'boolean')
|
|
48
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
49
|
+
if (!result.ok) {
|
|
50
|
+
const error = result.error;
|
|
51
|
+
const code = object(error) ? codes.find(code => code === error.code) : undefined;
|
|
52
|
+
return fail(code ?? 'PROJECT_PROTOCOL_INVALID');
|
|
53
|
+
}
|
|
54
|
+
if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== data.path)
|
|
55
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
56
|
+
if (operation === 'browse') {
|
|
57
|
+
const value = result.value;
|
|
58
|
+
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) || data.expected !== undefined && ['device', 'inode', 'mtimeNs', 'ctimeNs'].some(key => value.identity[key] !== data.expected[key]))
|
|
59
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
60
|
+
}
|
|
61
|
+
return ok(result.value);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (signal.aborted)
|
|
65
|
+
return fail('CONNECTION_LOST');
|
|
66
|
+
if (error instanceof AuthDiagnosticError) {
|
|
67
|
+
if (error.diagnostic.reason === 'OUTPUT_LIMIT_EXCEEDED')
|
|
68
|
+
return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
69
|
+
if (error.diagnostic.stage === 'remote-frame')
|
|
70
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
71
|
+
}
|
|
72
|
+
return fail('HOST_DIRECTORY_UNREADABLE');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
|
|
76
|
+
}
|
package/lib/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from './connection-messages.ts';
|
|
1
2
|
import type { Context } from '@deepseek-ai/cordis';
|
|
2
3
|
import z from '@deepseek-ai/schemastery';
|
|
3
4
|
export type * from './cordis.ts';
|
|
@@ -12,6 +13,12 @@ export { sshArgs } from './ssh.ts';
|
|
|
12
13
|
export declare const name = "ai-workbench-connect";
|
|
13
14
|
export declare const inject: string[];
|
|
14
15
|
export interface Config {
|
|
16
|
+
connectionMessages?: {
|
|
17
|
+
administratorAfterMs?: number;
|
|
18
|
+
};
|
|
19
|
+
workspaceLocations?: {
|
|
20
|
+
pageSize?: number;
|
|
21
|
+
};
|
|
15
22
|
conversationDetails?: {
|
|
16
23
|
maxEventBytes?: number;
|
|
17
24
|
pageSize?: number;
|
|
@@ -39,7 +46,7 @@ export interface Config {
|
|
|
39
46
|
};
|
|
40
47
|
}
|
|
41
48
|
export declare const Config: z<Config>;
|
|
42
|
-
export declare function register(ctx: Context, ports: Ports, _inventory?: ComponentInventory, extend?: (api: import('./api.ts').ConnectApi) => void): void;
|
|
49
|
+
export declare function register(ctx: Context, ports: Ports, _inventory?: ComponentInventory, extend?: (api: import('./api.ts').ConnectApi) => void, connectionMessages?: Config['connectionMessages']): void;
|
|
43
50
|
export declare function apply(ctx: Context, config?: Config): void;
|
|
44
51
|
export { createProfileEnrollment } from './profile-enrollment.ts';
|
|
45
52
|
export { createWorkspaceBindings } from './workspace-bindings.ts';
|
package/lib/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from "./connection-messages.js";
|
|
2
|
+
import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
|
|
3
|
+
import { WORKSPACE_LOCATION_DEFAULTS } from "./defaults.js";
|
|
1
4
|
import z from '@deepseek-ai/schemastery';
|
|
2
5
|
import { createConversationDetailSettings } from "./conversation-detail-settings.js";
|
|
3
6
|
import { createConnect } from "./connect.js";
|
|
@@ -18,6 +21,8 @@ const positive = () => z.number().step(1).min(1);
|
|
|
18
21
|
// aiWorkbenchNetwork itself is a required Cordis injection; missing N holds this module from loading.
|
|
19
22
|
// Own technical defaults use the approved settings record; no global DSH policy is changed.
|
|
20
23
|
export const Config = z.object({
|
|
24
|
+
connectionMessages: z.object({ administratorAfterMs: positive().max(2147483647).default(CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs).description('connectionMessages.administratorAfterMs:持续断线多久改为“请联系管理员”;默认30000毫秒,范围1至2147483647整数,可修改。改大延后提示、改小提前;只改变提示,不改重连/SSH超时,不重放请求。') }),
|
|
25
|
+
workspaceLocations: z.object({ pageSize: positive().max(Number.MAX_SAFE_INTEGER).default(WORKSPACE_LOCATION_DEFAULTS.pageSize).description('workspaceLocations.pageSize:主机目录每页条数,默认100,可修改;改大增加元数据与内存,超过commandOutputMaxBytes会明确拒绝整页。') }),
|
|
21
26
|
conversationDetails: z.object({
|
|
22
27
|
maxEventBytes: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.maxEventBytes).description('conversationDetails.maxEventBytes:完整UTF-8 JSON事件的字节上限;默认1048576,范围1至9007199254740991整数。改大增加单事件存储与内存;改小会拒收超过新值的新事件,不裁剪或删除旧记录。'),
|
|
23
28
|
pageSize: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.pageSize).description('conversationDetails.pageSize:每页条数;默认100,范围1至9007199254740991整数。改大增加一次读取与界面负担,改小增加继续加载次数,不减少完整快照总数。'),
|
|
@@ -39,9 +44,9 @@ export const Config = z.object({
|
|
|
39
44
|
executable: z.string().description('darwin-arm64默认Electron.app/Contents/MacOS/Electron;其他平台无默认,管理员可改'), loginOutputMaxBytes: positive().default(L_DEFAULTS.loginOutputMaxBytes).description('登录进程输出字节上限;默认1048576,管理员可改'), ipcMaxBytes: positive().default(L_DEFAULTS.ipcMaxBytes).description('私有IPC字节上限;默认1048576,管理员可改'),
|
|
40
45
|
}),
|
|
41
46
|
});
|
|
42
|
-
export function register(ctx, ports, _inventory, extend) {
|
|
47
|
+
export function register(ctx, ports, _inventory, extend, connectionMessages) {
|
|
43
48
|
// 当前独立插件始终检查两品牌;保留旧inventory参数兼容调用,但不以交付清单开关能力。
|
|
44
|
-
const api = createConnect(ports, state => ctx.emit('ai-workbench/connect-state', state), { onConnectionState: state => ctx.emit('ai-workbench/connection-state', state), onPromptState: state => ctx.emit('ai-workbench/login-prompt-state', state), onPromptResult: result => ctx.emit('ai-workbench/login-prompt-result', result) });
|
|
49
|
+
const api = createConnect(ports, state => ctx.emit('ai-workbench/connect-state', state), { connectionMessages, onConnectionState: state => ctx.emit('ai-workbench/connection-state', state), onPromptState: state => ctx.emit('ai-workbench/login-prompt-state', state), onPromptResult: result => ctx.emit('ai-workbench/login-prompt-result', result) });
|
|
45
50
|
extend?.(api);
|
|
46
51
|
ctx.provide('aiWorkbenchConnect', api);
|
|
47
52
|
ctx.effect(() => { void api.refreshLoginPrompts(); return () => api.dispose(); });
|
|
@@ -56,8 +61,8 @@ export function apply(ctx, config = {}) {
|
|
|
56
61
|
const sources = createComponentSources({ profileDir: ctx.get('profileContext')?.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, source: config.helper?.source, sha256: config.helper?.sha256, reason: sourceReason, busy: () => ['downloading', 'verifying', 'unpacking'].includes(component.getState().phase) || ctx.get('aiWorkbenchConnect')?.getLoginPromptState().phase === 'authorizing' });
|
|
57
62
|
ctx.effect(() => () => sources.dispose());
|
|
58
63
|
const ports = configuredPorts(config, network, component, sources);
|
|
59
|
-
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network));
|
|
60
|
-
registerComponents(ctx, config.inventory, config.helper?.cacheDir, component, sources, config.helper?.componentObservationIntervalMs, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
64
|
+
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network), config.connectionMessages);
|
|
65
|
+
registerComponents(ctx, config.inventory, config.helper?.cacheDir, component, sources, config.helper?.componentObservationIntervalMs, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, config.connectionMessages?.administratorAfterMs ?? CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs);
|
|
61
66
|
}
|
|
62
67
|
export { createProfileEnrollment } from "./profile-enrollment.js";
|
|
63
68
|
export { createWorkspaceBindings } from "./workspace-bindings.js";
|
package/lib/integration.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHostDirectories } from "./host-directories.js";
|
|
1
2
|
import { ComponentDownloadError } from "./component-download.js";
|
|
2
3
|
import { fileURLToPath } from 'node:url';
|
|
3
4
|
import { readEnrollment } from "./enrollment.js";
|
|
@@ -10,6 +11,7 @@ import { runLogin } from "./login.js";
|
|
|
10
11
|
import { ensureHelper } from "./cache.js";
|
|
11
12
|
import { launchElectron } from "./electron.js";
|
|
12
13
|
import { parseLoginStatus } from "./auth-status.js";
|
|
14
|
+
import { authFailure } from "./auth-diagnostics.js";
|
|
13
15
|
import { need, fail, ok } from "./needs.js";
|
|
14
16
|
import { createComponentProgress, downloadComponent } from "./component-download.js";
|
|
15
17
|
export function configuredPorts(config, provider, component = createComponentProgress(), sources) {
|
|
@@ -23,6 +25,7 @@ export function configuredPorts(config, provider, component = createComponentPro
|
|
|
23
25
|
const runner = createRunner(config.commandOutputMaxBytes);
|
|
24
26
|
ports.ssh = createSsh(runner, config.commandOutputMaxBytes);
|
|
25
27
|
ports.projects = createProjects(runner);
|
|
28
|
+
ports.hostDirectories = createHostDirectories(runner, config.commandOutputMaxBytes);
|
|
26
29
|
}
|
|
27
30
|
else if (provider)
|
|
28
31
|
ports.ssh = { verify: async () => fail('SETTINGS_REQUIRED'), status: async () => fail('SETTINGS_REQUIRED') };
|
|
@@ -48,7 +51,7 @@ export function configuredPorts(config, provider, component = createComponentPro
|
|
|
48
51
|
return fail('LOGIN_FAILED');
|
|
49
52
|
// Component preparation may outlive another device's completed login. Recheck immediately before any destructive CLI authorization.
|
|
50
53
|
if (!ports.ssh)
|
|
51
|
-
return
|
|
54
|
+
return authFailure('integration-pre-login', 'SSH_PORT_MISSING');
|
|
52
55
|
try {
|
|
53
56
|
const raw = await ports.ssh.status(target, provider, signal);
|
|
54
57
|
if (signal.aborted)
|
|
@@ -61,8 +64,8 @@ export function configuredPorts(config, provider, component = createComponentPro
|
|
|
61
64
|
if (current.value.loggedIn)
|
|
62
65
|
return ok(undefined);
|
|
63
66
|
}
|
|
64
|
-
catch {
|
|
65
|
-
return
|
|
67
|
+
catch (error) {
|
|
68
|
+
return authFailure('integration-pre-login', 'STATUS_EXCEPTION', {}, error);
|
|
66
69
|
}
|
|
67
70
|
return runLogin(target, provider, {
|
|
68
71
|
start: (t, p, s) => createRemoteLogin('ssh', [...sshArgs(t), remoteLoginCommand(p, h.remoteKillGraceMs)], p, h.loginOutputMaxBytes, s, 'remote-control'),
|
|
@@ -0,0 +1,46 @@
|
|
|
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>;
|
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { RemoteConversationDetail } from './api.ts';
|
|
2
|
+
import { type ConversationDetailOptions } from './conversation-details.ts';
|
|
3
|
+
export declare function validLoginDiagnostic(detail: RemoteConversationDetail): boolean;
|
|
4
|
+
export declare function createLoginDiagnostics(options: Omit<ConversationDetailOptions, 'storageName' | 'validate' | 'knownKinds'>): {
|
|
5
|
+
appendLoginDiagnostic: (detail: RemoteConversationDetail) => Promise<import("./api.ts").Result<{
|
|
6
|
+
eventId: string;
|
|
7
|
+
recorded: true;
|
|
8
|
+
}>>;
|
|
9
|
+
getLoginDiagnosticReceipt: (query: {
|
|
10
|
+
eventId: string;
|
|
11
|
+
sessionId: string;
|
|
12
|
+
provider: import("./api.ts").Provider;
|
|
13
|
+
}) => Promise<import("./api.ts").Result<{
|
|
14
|
+
eventId: string;
|
|
15
|
+
recorded: false;
|
|
16
|
+
} | {
|
|
17
|
+
eventId: string;
|
|
18
|
+
recorded: true;
|
|
19
|
+
detail: RemoteConversationDetail;
|
|
20
|
+
}>>;
|
|
21
|
+
listLoginDiagnostics: (query: import("./api.ts").RemoteDetailQuery) => Promise<import("./api.ts").Result<import("./api.ts").RemoteDetailPage>>;
|
|
22
|
+
getLoginDiagnosticState: () => import("./api.ts").RemoteConversationDetailState;
|
|
23
|
+
onLoginDiagnosticState: (listener: (state: import("./api.ts").RemoteConversationDetailState) => void) => () => void;
|
|
24
|
+
observeConnection: (state: import("./api.ts").ConnectionState) => void;
|
|
25
|
+
dispose: () => Promise<void>;
|
|
26
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createConversationDetails, validRemoteConversationDetail } from "./conversation-details.js";
|
|
2
|
+
import { validAuthDiagnosticReason } from "./auth-diagnostics.js";
|
|
3
|
+
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
4
|
+
const keys = (value, required, optional = []) => required.every(key => Object.hasOwn(value, key)) && Object.keys(value).every(key => required.includes(key) || optional.includes(key));
|
|
5
|
+
const providers = (value) => Array.isArray(value) && value.every(provider => provider === 'claude' || provider === 'codex') && new Set(value).size === value.length;
|
|
6
|
+
// Only structured status facts belong here. Ordinary user-turn payloads retain D19's scope.
|
|
7
|
+
export function validLoginDiagnostic(detail) {
|
|
8
|
+
if (!validRemoteConversationDetail(detail) || detail.kind !== 'login-check')
|
|
9
|
+
return false;
|
|
10
|
+
const p = detail.payload;
|
|
11
|
+
if (!object(p) || !keys(p, ['reason', 'connection', 'login'], ['observedLoginInstanceId', 'officialReason', 'officialReasonRejected']))
|
|
12
|
+
return false;
|
|
13
|
+
const c = p.connection, l = p.login;
|
|
14
|
+
if (typeof p.reason !== 'string' || !/^[A-Z][A-Z0-9_]*$/.test(p.reason) || !object(c) || !object(l))
|
|
15
|
+
return false;
|
|
16
|
+
if (!keys(c, ['phase', 'instanceId', 'epoch']) || !['connecting', 'connected', 'unavailable', 'disposed'].includes(c.phase) || c.instanceId !== detail.instanceId || c.epoch !== detail.epoch)
|
|
17
|
+
return false;
|
|
18
|
+
if (!keys(l, ['phase', 'instanceId', 'logins', 'queuedProviders', 'checkingProviders']) || !['checking', 'blocked', 'login-required', 'authorizing', 'idle', 'disposed'].includes(l.phase) || !object(l.logins))
|
|
19
|
+
return false;
|
|
20
|
+
// The observed ID is diagnostic evidence only. Event/connection scope remains current.
|
|
21
|
+
if (Object.hasOwn(p, 'observedLoginInstanceId')) {
|
|
22
|
+
const observed = p.observedLoginInstanceId;
|
|
23
|
+
if (p.reason !== 'LOGIN_INSTANCE_MISMATCH' || typeof observed !== 'string' || !observed.length || /[\x00-\x1f\x7f]/.test(observed) || observed === detail.instanceId || l.instanceId !== observed)
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
else if (l.instanceId !== detail.instanceId)
|
|
27
|
+
return false;
|
|
28
|
+
if (!keys(l.logins, [], ['claude', 'codex']) || !Object.values(l.logins).every(value => typeof value === 'boolean' || value === 'absent') || !providers(l.queuedProviders) || !providers(l.checkingProviders))
|
|
29
|
+
return false;
|
|
30
|
+
if (p.officialReasonRejected !== undefined) {
|
|
31
|
+
const rejected = p.officialReasonRejected;
|
|
32
|
+
if (p.reason !== 'OFFICIAL_REASON_UNSUPPORTED' || p.officialReason !== undefined || !object(rejected) || !keys(rejected, ['bytes', 'sha256']) || !Number.isSafeInteger(rejected.bytes) || Number(rejected.bytes) < 0 || typeof rejected.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(rejected.sha256))
|
|
33
|
+
return false;
|
|
34
|
+
}
|
|
35
|
+
if (p.reason === 'OFFICIAL_REASON_UNSUPPORTED' && p.officialReasonRejected === undefined)
|
|
36
|
+
return false;
|
|
37
|
+
return p.officialReason === undefined || validAuthDiagnosticReason(p.officialReason);
|
|
38
|
+
}
|
|
39
|
+
export function createLoginDiagnostics(options) {
|
|
40
|
+
const details = createConversationDetails({ ...options, get maxEventBytes() { return options.maxEventBytes; }, get pageSize() { return options.pageSize; }, context: () => options.context(), scope: (sessionId, provider) => options.scope(sessionId, provider), storageName: 'login-diagnostics', knownKinds: ['login-check'], validate: validLoginDiagnostic });
|
|
41
|
+
return { appendLoginDiagnostic: details.appendRemoteConversationDetail, getLoginDiagnosticReceipt: details.getRemoteConversationDetailReceipt, listLoginDiagnostics: details.listRemoteConversationDetails, getLoginDiagnosticState: details.getRemoteConversationDetailState, onLoginDiagnosticState: details.onRemoteConversationDetailState, observeConnection: details.observeConnection, dispose: details.dispose };
|
|
42
|
+
}
|
package/lib/needs.js
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
const entries = {
|
|
2
|
+
LOCAL_WORKSPACE_CONTEXT_UNSUPPORTED: { layer: 'integration', message: '当前平台尚未接入本地工作区进程环境交接。', requires: '已接入平台的本机后端上下文', actor: 'plugin', action: { id: 'inspect-local-workspace-context', label: '查看技术详情', available: false } },
|
|
3
|
+
LOCAL_WORKSPACE_CONTEXT_UNAVAILABLE: { layer: 'integration', message: '本机进程环境无法确认,已停止交接;根因未查明。', requires: '当前进程的真实操作系统账户与环境', actor: 'plugin', action: { id: 'inspect-local-workspace-context', label: '查看技术详情', available: false } },
|
|
4
|
+
HOST_DIRECTORY_INVALID: { layer: 'projects', message: '目录不存在或不是文件夹,请重新选择。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
5
|
+
HOST_DIRECTORY_UNREADABLE: { layer: 'projects', message: '主机目录无法列出,请查看目录权限或连接状态。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
6
|
+
HOST_DIRECTORY_CHANGED: { layer: 'projects', message: '目录内容或位置已变化,请重新浏览后选择。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
7
|
+
HOST_DIRECTORY_PAGE_TOO_LARGE: { layer: 'projects', message: '本页目录元数据超过 commandOutputMaxBytes,请减小每页条数或联系管理员调整。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
8
|
+
WORKSPACE_LOCATION_REQUIRED: { layer: 'projects', message: '请先在远程主机连接设置中选择此工作区的文件来源;旧关联需要确认。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
9
|
+
WORKSPACE_LOCATION_INVALID: { layer: 'projects', message: '工作区位置与当前目录或主机身份不符,请重新选择。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
10
|
+
WORKSPACE_LOCATION_CONFLICT: { layer: 'projects', message: '工作区或连接已变化,请刷新位置后重选。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
11
|
+
WORKSPACE_LOCATION_PROVIDER_REQUIRED: { layer: 'projects', message: '主机文件夹已记录,等待远程提供方接入位置合同后才能执行。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
12
|
+
WORKSPACE_EXECUTION_UNAVAILABLE: { layer: 'projects', message: '本地文件夹已记录,按需远程文件与命令执行尚未接通。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
13
|
+
WORKSPACE_LOCATION_STORAGE_FAILED: { layer: 'projects', message: '工作区位置记录无法读取或保存,已停止操作,请联系管理员。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
|
|
2
14
|
REMOTE_DETAIL_INVALID: { layer: 'integration', message: '诊断内容格式无效或含未脱敏认证材料,已拒绝保存。', requires: '有效且已脱敏的诊断与可信连接', actor: 'plugin', action: { id: 'inspect-remote-details', label: '查看技术详情', available: false } },
|
|
3
15
|
REMOTE_DETAIL_SCOPE_INVALID: { layer: 'integration', message: '诊断内容与当前连接、原生会话或已核验品牌关联不符,已拒绝保存。', requires: '有效且已脱敏的诊断与可信连接', actor: 'plugin', action: { id: 'inspect-remote-details', label: '查看技术详情', available: false } },
|
|
4
16
|
REMOTE_DETAIL_STORAGE_FAILED: { layer: 'integration', message: '诊断记录无法持久保存或读取,结果无法确认,请联系管理员。', requires: '有效且已脱敏的诊断与可信连接', actor: 'plugin', action: { id: 'inspect-remote-details', label: '查看技术详情', available: false } },
|
package/lib/ports.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Provider, Result, SshTarget, SessionTarget, HostContext, Project, ProjectList } from './api.ts';
|
|
2
|
+
import type { createHostDirectories } from './host-directories.ts';
|
|
2
3
|
export interface Enrollment {
|
|
3
4
|
authKeyFile?: string;
|
|
4
5
|
hostContext?: HostContext;
|
|
@@ -20,6 +21,7 @@ export type NetworkEvent = {
|
|
|
20
21
|
kind: 'restored';
|
|
21
22
|
};
|
|
22
23
|
export interface Ports {
|
|
24
|
+
hostDirectories?: ReturnType<typeof createHostDirectories>;
|
|
23
25
|
enrollment?: {
|
|
24
26
|
read(signal: AbortSignal): Promise<Result<Enrollment>>;
|
|
25
27
|
};
|
package/lib/processes.js
CHANGED
|
@@ -2,6 +2,7 @@ import { spawn } from 'node:child_process';
|
|
|
2
2
|
import { StringDecoder } from 'node:string_decoder';
|
|
3
3
|
import { extractLoginUrl } from "./login.js";
|
|
4
4
|
import { fail, ok } from "./needs.js";
|
|
5
|
+
import { AuthDiagnosticError, exceptionSummary, outputSummary } from "./auth-diagnostics.js";
|
|
5
6
|
function limit(n) { if (!Number.isSafeInteger(n) || n < 1)
|
|
6
7
|
throw new Error('OUTPUT_SETTING_REQUIRED'); }
|
|
7
8
|
function start(command, args, signal) {
|
|
@@ -18,15 +19,15 @@ export function createRunner(maxBytes) {
|
|
|
18
19
|
limit(maxBytes);
|
|
19
20
|
return { run: async (command, args, signal, input) => {
|
|
20
21
|
const child = start(command, args, signal);
|
|
21
|
-
let stdout = '', stderr = '', size = 0,
|
|
22
|
-
child.stdin.on('error',
|
|
22
|
+
let stdout = '', stderr = '', size = 0, failure;
|
|
23
|
+
child.stdin.on('error', error => { failure ??= { stage: 'process-stdin', reason: 'STDIN_FAILED', ...exceptionSummary(error) }; child.kill('SIGTERM'); });
|
|
23
24
|
child.stdin.end(input);
|
|
24
25
|
const finished = new Promise((resolve, reject) => {
|
|
25
|
-
child.once('error',
|
|
26
|
+
child.once('error', error => { failure = { stage: 'process-spawn', reason: 'SPAWN_FAILED', ...exceptionSummary(error) }; });
|
|
26
27
|
for (const [stream, channel] of [[child.stdout, 'out'], [child.stderr, 'err']]) {
|
|
27
28
|
const decoder = new StringDecoder('utf8');
|
|
28
29
|
stream.on('data', (chunk) => { size += chunk.length; if (size > maxBytes) {
|
|
29
|
-
|
|
30
|
+
failure ??= { stage: 'process-output', reason: 'OUTPUT_LIMIT_EXCEEDED', maxOutputBytes: maxBytes, observedBytes: size };
|
|
30
31
|
child.kill('SIGTERM');
|
|
31
32
|
return;
|
|
32
33
|
} if (channel === 'out')
|
|
@@ -34,7 +35,7 @@ export function createRunner(maxBytes) {
|
|
|
34
35
|
else
|
|
35
36
|
stderr += decoder.write(chunk); });
|
|
36
37
|
}
|
|
37
|
-
child.once('close', code =>
|
|
38
|
+
child.once('close', (code, processSignal) => failure || signal.aborted || processSignal !== null ? reject(new AuthDiagnosticError(failure ?? { stage: 'process-runner', reason: signal.aborted ? 'CANCELLED' : 'PROCESS_SIGNAL', exitCode: code, signal: ['SIGTERM', 'SIGKILL', 'SIGABRT', 'SIGHUP', 'SIGINT', 'SIGSEGV'].includes(processSignal ?? '') ? processSignal : 'OTHER', stderr: outputSummary(stderr) }, 'COMMAND_FAILED')) : resolve({ exitCode: code, stdout, stderr }));
|
|
38
39
|
});
|
|
39
40
|
const abort = () => child.kill('SIGTERM');
|
|
40
41
|
signal.addEventListener('abort', abort, { once: true });
|
package/lib/profile-runtime.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { WORKSPACE_LOCATION_DEFAULTS } from "./defaults.js";
|
|
2
|
+
import { createWorkspaceLocations } from "./workspace-locations.js";
|
|
1
3
|
import { mapNetworkNeed } from "./provider.js";
|
|
2
4
|
import { createProfileEnrollment } from "./profile-enrollment.js";
|
|
3
5
|
import { createWorkspaceBindings } from "./workspace-bindings.js";
|
|
@@ -6,6 +8,7 @@ import { createNativeImportPicker } from "./native-import-picker.js";
|
|
|
6
8
|
import { createHash } from 'node:crypto';
|
|
7
9
|
import { readPrivate } from "./private-files.js";
|
|
8
10
|
import { createConversationDetails } from "./conversation-details.js";
|
|
11
|
+
import { createLoginDiagnostics } from "./login-diagnostics.js";
|
|
9
12
|
import { CONVERSATION_DETAIL_DEFAULTS, L_DEFAULTS } from "./defaults.js";
|
|
10
13
|
import { createProfileActivation } from "./profile-activation.js";
|
|
11
14
|
// Composition only: consume official services; never provide replacements or alter default entries.
|
|
@@ -24,32 +27,49 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
|
|
|
24
27
|
api.importEnrollment = async () => { const result = await manager.importEnrollment(); if (result.ok && result.value.outcome === 'imported')
|
|
25
28
|
await api.refreshLoginPrompts(); return result; };
|
|
26
29
|
ctx.effect(() => () => manager.dispose());
|
|
30
|
+
let locationRevision = 0;
|
|
27
31
|
let workspaceRevision = 0;
|
|
28
32
|
let lastWorkspaceError;
|
|
29
33
|
ctx.provide('aiWorkbenchWorkspaceDiagnostics', { getLatest: () => lastWorkspaceError });
|
|
30
|
-
ctx.inject(['workspaceRegistry', 'sessions', 'sessionPersistence'], native => {
|
|
34
|
+
ctx.inject(['profileContext', 'workspaceRegistry', 'sessions', 'sessionPersistence'], native => {
|
|
35
|
+
const profile = native.get('profileContext');
|
|
36
|
+
if (!profile || typeof profile.dir !== 'string')
|
|
37
|
+
return;
|
|
31
38
|
const registry = native.get('workspaceRegistry');
|
|
39
|
+
const readHeader = async (id) => {
|
|
40
|
+
const live = native.get('sessions');
|
|
41
|
+
const session = live?.get(id);
|
|
42
|
+
if (session)
|
|
43
|
+
return session.header;
|
|
44
|
+
const persistence = native.get('sessionPersistence');
|
|
45
|
+
if (!persistence)
|
|
46
|
+
throw new NeedError(need('DEPENDENCY_REQUIRED'));
|
|
47
|
+
return (await persistence.list()).find(s => s.header.id === id)?.header;
|
|
48
|
+
};
|
|
32
49
|
const bindings = createWorkspaceBindings({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, api, registry,
|
|
33
|
-
readHeader:
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
50
|
+
readHeader, nextRevision: () => ++workspaceRevision, onState: state => ctx.emit('ai-workbench/workspace-binding-state', state), diagnostic: error => { lastWorkspaceError = error; ctx.emit('ai-workbench/workspace-diagnostic', error); } });
|
|
51
|
+
const locations = createWorkspaceLocations({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, pageSize: config.workspaceLocations?.pageSize ?? WORKSPACE_LOCATION_DEFAULTS.pageSize, nextRevision: () => ++locationRevision, api, registry, readLegacy: bindings.readLegacyLocations, hostDirectories: ports.hostDirectories, onState: state => ctx.emit('ai-workbench/workspace-location-state', state) });
|
|
52
|
+
if (process.platform === 'darwin')
|
|
53
|
+
api.getLocalWorkspaceContext = locations.getLocalWorkspaceContext;
|
|
54
|
+
api.getWorkspaceLocationState = locations.getWorkspaceLocationState;
|
|
55
|
+
api.onWorkspaceLocationState = locations.onWorkspaceLocationState;
|
|
56
|
+
api.refreshWorkspaceLocations = locations.refreshWorkspaceLocations;
|
|
57
|
+
api.browseWorkspaceHostDirectories = locations.browseWorkspaceHostDirectories;
|
|
58
|
+
api.selectWorkspaceLocation = locations.selectWorkspaceLocation;
|
|
59
|
+
native.effect(() => { void locations.refreshWorkspaceLocations(); return api.onConnectionState(() => locations.observeConnection()); });
|
|
60
|
+
native.effect(() => () => { if (api.getLocalWorkspaceContext === locations.getLocalWorkspaceContext)
|
|
61
|
+
delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; return locations.dispose(); });
|
|
43
62
|
const settings = ctx.get('aiWorkbenchConversationDetailSettings');
|
|
63
|
+
const context = async () => { const current = api.getModelCatalogTarget('codex'); if (!current.ok)
|
|
64
|
+
return current; const t = current.value.target; try {
|
|
65
|
+
const trust = await readPrivate(t.knownHostsFile, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
66
|
+
return { ok: true, value: { identity: createHash('sha256').update(JSON.stringify([t.host, t.username, t.port, trust])).digest('hex') } };
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
70
|
+
} };
|
|
44
71
|
const details = createConversationDetails({ profileDir: profile.dir, get maxEventBytes() { return settings ? settings.values()?.maxEventBytes ?? 0 : config.conversationDetails?.maxEventBytes ?? CONVERSATION_DETAIL_DEFAULTS.maxEventBytes; }, get pageSize() { return settings ? settings.values()?.pageSize ?? 0 : config.conversationDetails?.pageSize ?? CONVERSATION_DETAIL_DEFAULTS.pageSize; }, getConnectionState: api.getConnectionState,
|
|
45
|
-
context
|
|
46
|
-
return current; const t = current.value.target; try {
|
|
47
|
-
const trust = await readPrivate(t.knownHostsFile, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
48
|
-
return { ok: true, value: { identity: createHash('sha256').update(JSON.stringify([t.host, t.username, t.port, trust])).digest('hex') } };
|
|
49
|
-
}
|
|
50
|
-
catch {
|
|
51
|
-
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
52
|
-
} },
|
|
72
|
+
context,
|
|
53
73
|
scope: async (sessionId, provider) => { const current = api.getModelCatalogTarget(provider); if (!current.ok)
|
|
54
74
|
return current; return bindings.verifyRemoteConversationScope(sessionId, provider, current.value.target); },
|
|
55
75
|
onState: state => ctx.emit('ai-workbench/remote-conversation-detail-state', state) });
|
|
@@ -58,16 +78,27 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
|
|
|
58
78
|
api.getRemoteConversationDetailState = details.getRemoteConversationDetailState;
|
|
59
79
|
api.onRemoteConversationDetailState = details.onRemoteConversationDetailState;
|
|
60
80
|
api.listRemoteConversationDetails = details.listRemoteConversationDetails;
|
|
61
|
-
const
|
|
81
|
+
const loginDiagnostics = createLoginDiagnostics({ profileDir: profile.dir, get maxEventBytes() { return settings ? settings.values()?.maxEventBytes ?? 0 : config.conversationDetails?.maxEventBytes ?? CONVERSATION_DETAIL_DEFAULTS.maxEventBytes; }, get pageSize() { return settings ? settings.values()?.pageSize ?? 0 : config.conversationDetails?.pageSize ?? CONVERSATION_DETAIL_DEFAULTS.pageSize; }, getConnectionState: api.getConnectionState, context,
|
|
82
|
+
scope: async (sessionId, provider) => { const current = api.getModelCatalogTarget(provider); if (!current.ok)
|
|
83
|
+
return current; const header = await readHeader(sessionId); if (!header || header.id !== sessionId)
|
|
84
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID'); return context(); },
|
|
85
|
+
onState: state => ctx.emit('ai-workbench/login-diagnostic-state', state) });
|
|
86
|
+
api.appendLoginDiagnostic = loginDiagnostics.appendLoginDiagnostic;
|
|
87
|
+
api.getLoginDiagnosticReceipt = loginDiagnostics.getLoginDiagnosticReceipt;
|
|
88
|
+
api.listLoginDiagnostics = loginDiagnostics.listLoginDiagnostics;
|
|
89
|
+
api.getLoginDiagnosticState = loginDiagnostics.getLoginDiagnosticState;
|
|
90
|
+
api.onLoginDiagnosticState = loginDiagnostics.onLoginDiagnosticState;
|
|
91
|
+
const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1, workspaceLocations: 1, ...(process.platform === 'darwin' && api.getConnectionState().phase !== 'disposed' ? { localWorkspaceContext: 1 } : {}) });
|
|
62
92
|
api.getContractInfo = detailContractInfo;
|
|
63
93
|
native.effect(() => { details.observeConnection(api.getConnectionState()); return api.onConnectionState(details.observeConnection); });
|
|
94
|
+
native.effect(() => { loginDiagnostics.observeConnection(api.getConnectionState()); return api.onConnectionState(loginDiagnostics.observeConnection); });
|
|
64
95
|
native.effect(() => () => { if (api.getContractInfo === detailContractInfo)
|
|
65
|
-
api.getContractInfo = previousContractInfo; return details.dispose(); });
|
|
96
|
+
api.getContractInfo = previousContractInfo; return Promise.all([details.dispose(), loginDiagnostics.dispose()]); });
|
|
66
97
|
native.effect(() => api.onConnectionState(bindings.observeConnection));
|
|
67
98
|
api.getWorkspaceBindingState = bindings.getWorkspaceBindingState;
|
|
68
99
|
api.onWorkspaceBindingState = bindings.onWorkspaceBindingState;
|
|
69
100
|
api.acknowledgeWorkspaceNotice = bindings.acknowledgeWorkspaceNotice;
|
|
70
|
-
api.resolveSessionProject = bindings.resolveSessionProject;
|
|
101
|
+
api.resolveSessionProject = (sessionId, use) => locations.resolveLegacySession(sessionId, () => bindings.resolveSessionProject(sessionId, use));
|
|
71
102
|
native.effect(() => () => { api.resolveSessionProject = async () => fail('DEPENDENCY_REQUIRED'); api.acknowledgeWorkspaceNotice = async () => fail('DEPENDENCY_REQUIRED'); return bindings.dispose(); });
|
|
72
103
|
});
|
|
73
104
|
}
|
package/lib/ssh.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { fail, ok } from "./needs.js";
|
|
4
|
+
import { AuthDiagnosticError, authFailure, outputSummary } from "./auth-diagnostics.js";
|
|
4
5
|
export function shellQuote(s) {
|
|
5
6
|
if (/[\x00-\x1f\x7f%]/.test(s))
|
|
6
7
|
throw new Error('INVALID_PROXY_PATH');
|
|
@@ -18,28 +19,46 @@ export async function runRemote(runner, t, command, signal, input) {
|
|
|
18
19
|
const nonce = randomUUID(), source = await readFile(new URL('../helper/remote-command.cjs', import.meta.url), 'utf8');
|
|
19
20
|
const remote = 'node -e ' + "'" + source.replaceAll("'", "'\\''") + "'";
|
|
20
21
|
const raw = await runner.run('ssh', [...sshArgs(t), remote], signal, JSON.stringify({ protocolVersion: 1, nonce, command, ...input === undefined ? {} : { input } }));
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
const bad = (stage, reason, details = {}) => { throw new AuthDiagnosticError({ stage, reason, ...details }); };
|
|
23
|
+
if (signal.aborted)
|
|
24
|
+
bad('ssh-result', 'CANCELLED');
|
|
25
|
+
if (raw.exitCode !== 0 || raw.stderr !== '')
|
|
26
|
+
bad('ssh-result', raw.exitCode !== 0 ? 'SSH_EXIT_NONZERO' : 'SSH_STDERR_NONEMPTY', { exitCode: raw.exitCode, stderr: outputSummary(raw.stderr) });
|
|
23
27
|
const lines = raw.stdout.split('\n');
|
|
24
28
|
if (lines.pop() !== '')
|
|
25
|
-
|
|
29
|
+
bad('remote-frame', 'FRAME_TRUNCATED');
|
|
26
30
|
let started = false, ended = false, exitCode = null;
|
|
27
31
|
const out = [], err = [];
|
|
28
|
-
for (const line of lines) {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
+
for (const [index, line] of lines.entries()) {
|
|
33
|
+
let v;
|
|
34
|
+
try {
|
|
35
|
+
v = JSON.parse(line);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
bad('remote-frame', 'FRAME_JSON_INVALID', { index, errorName: 'SyntaxError', output: outputSummary(line) });
|
|
39
|
+
}
|
|
40
|
+
if (!v || typeof v !== 'object' || Array.isArray(v))
|
|
41
|
+
bad('remote-frame', 'FRAME_OBJECT_INVALID', { index });
|
|
42
|
+
if (v.protocolVersion !== 1)
|
|
43
|
+
bad('remote-frame', 'FRAME_VERSION_INVALID', { index });
|
|
44
|
+
if (v.nonce !== nonce)
|
|
45
|
+
bad('remote-frame', 'FRAME_NONCE_INVALID', { index });
|
|
46
|
+
if (ended)
|
|
47
|
+
bad('remote-frame', 'FRAME_AFTER_END', { index });
|
|
32
48
|
const keys = Object.keys(v).sort().join(',');
|
|
33
49
|
if (v.type === 'start' && !started && keys === 'nonce,protocolVersion,type') {
|
|
34
50
|
started = true;
|
|
35
51
|
continue;
|
|
36
52
|
}
|
|
53
|
+
const expected = v.type === 'start' ? 'nonce,protocolVersion,type' : v.type === 'end' ? 'exitCode,nonce,protocolVersion,signal,type' : v.type === 'stdout' || v.type === 'stderr' ? 'data,nonce,protocolVersion,type' : undefined;
|
|
54
|
+
if (expected && keys !== expected)
|
|
55
|
+
bad('remote-frame', 'FRAME_KEYS_INVALID', { index, missing: expected.split(',').filter(key => !Object.hasOwn(v, key)), unexpectedCount: Object.keys(v).filter(key => !expected.split(',').includes(key)).length });
|
|
37
56
|
if (!started)
|
|
38
|
-
|
|
57
|
+
bad('remote-frame', 'FRAME_START_MISSING', { index });
|
|
39
58
|
if ((v.type === 'stdout' || v.type === 'stderr') && keys === 'data,nonce,protocolVersion,type' && typeof v.data === 'string') {
|
|
40
59
|
const bytes = Buffer.from(v.data, 'base64');
|
|
41
60
|
if (bytes.toString('base64') !== v.data)
|
|
42
|
-
|
|
61
|
+
bad('remote-frame', 'FRAME_BASE64_INVALID', { index });
|
|
43
62
|
(v.type === 'stdout' ? out : err).push(bytes);
|
|
44
63
|
continue;
|
|
45
64
|
}
|
|
@@ -48,10 +67,14 @@ export async function runRemote(runner, t, command, signal, input) {
|
|
|
48
67
|
exitCode = v.exitCode;
|
|
49
68
|
continue;
|
|
50
69
|
}
|
|
51
|
-
|
|
70
|
+
if (v.type === 'end' && v.signal !== null)
|
|
71
|
+
bad('remote-frame', 'REMOTE_COMMAND_SIGNAL', { index, signal: ['SIGTERM', 'SIGKILL', 'SIGABRT', 'SIGHUP', 'SIGINT', 'SIGSEGV'].includes(v.signal) ? v.signal : 'OTHER' });
|
|
72
|
+
if (v.type === 'end')
|
|
73
|
+
bad('remote-frame', 'FRAME_END_EXIT_INVALID', { index, exitCodeType: typeof v.exitCode, ...(typeof v.exitCode === 'number' && Number.isFinite(v.exitCode) && Number.isInteger(v.exitCode) ? { exitCode: v.exitCode } : {}) });
|
|
74
|
+
bad('remote-frame', 'FRAME_SEQUENCE_OR_VALUE_INVALID', { index });
|
|
52
75
|
}
|
|
53
76
|
if (!ended || exitCode === null)
|
|
54
|
-
|
|
77
|
+
bad('remote-frame', 'FRAME_END_MISSING');
|
|
55
78
|
return { exitCode, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8') };
|
|
56
79
|
}
|
|
57
80
|
export function createSsh(runner, maxOutputBytes) {
|
|
@@ -66,12 +89,12 @@ export function createSsh(runner, maxOutputBytes) {
|
|
|
66
89
|
status: async (t, p, signal) => {
|
|
67
90
|
try {
|
|
68
91
|
if (!['codex', 'claude'].includes(p) || !Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1)
|
|
69
|
-
return
|
|
92
|
+
return authFailure('ssh-status', 'STATUS_ARGUMENT_INVALID');
|
|
70
93
|
const source = await readFile(new URL('../helper/auth-status.cjs', import.meta.url), 'utf8');
|
|
71
94
|
return ok(await runRemote(runner, t, 'node -e ' + "'" + source.replaceAll("'", "'\\''") + "' -- " + p + ' ' + maxOutputBytes, signal));
|
|
72
95
|
}
|
|
73
|
-
catch {
|
|
74
|
-
return
|
|
96
|
+
catch (error) {
|
|
97
|
+
return authFailure('ssh-status', 'STATUS_EXECUTION_FAILED', {}, error);
|
|
75
98
|
}
|
|
76
99
|
},
|
|
77
100
|
};
|