@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
package/lib/components.js
CHANGED
|
@@ -1,13 +1,40 @@
|
|
|
1
|
+
import { connectionEmployeeMessage } from "./connection-messages.js";
|
|
2
|
+
import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
|
|
1
3
|
import { ComponentDownloadError } from "./component-download.js";
|
|
2
4
|
import { L_DEFAULTS } from "./defaults.js";
|
|
3
5
|
import { fail } from "./needs.js";
|
|
4
6
|
import { employeeMessage } from "./startup.js";
|
|
5
|
-
|
|
7
|
+
const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
8
|
+
const text = (value) => typeof value === 'string' && value.length > 0 && !value.includes('\0');
|
|
9
|
+
function validLocationInput(operation, value) {
|
|
10
|
+
if (!record(value))
|
|
11
|
+
return false;
|
|
12
|
+
if (operation === 'refresh')
|
|
13
|
+
return Object.keys(value).length === 0;
|
|
14
|
+
const context = ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId'];
|
|
15
|
+
if (!text(value.instanceId) || !Number.isSafeInteger(value.epoch) || value.epoch < 0 || !text(value.workspaceId) || !(value.expectedBindingId === null || text(value.expectedBindingId)))
|
|
16
|
+
return false;
|
|
17
|
+
let extra;
|
|
18
|
+
if (operation === 'browse') {
|
|
19
|
+
extra = ['path', 'cursor', 'pageSize'];
|
|
20
|
+
if (value.path !== undefined && (!text(value.path) || !value.path.startsWith('/')) || value.cursor !== undefined && !text(value.cursor) || value.path !== undefined && value.cursor !== undefined || value.pageSize !== undefined && (!Number.isSafeInteger(value.pageSize) || value.pageSize < 1))
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
else if (operation === 'select') {
|
|
24
|
+
extra = value.source === 'local' ? ['source'] : value.source === 'host' ? ['source', 'selectionToken'] : value.source === 'legacy-host' ? ['source', 'confirmLegacy'] : [];
|
|
25
|
+
if (!extra.length || value.source === 'host' && !text(value.selectionToken) || value.source === 'legacy-host' && value.confirmLegacy !== true)
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
else
|
|
29
|
+
return false;
|
|
30
|
+
return Object.keys(value).every(key => [...context, ...extra].includes(key));
|
|
31
|
+
}
|
|
32
|
+
export function registerComponents(ctx, inventory, temporaryDataParent, component, sources, observationIntervalMs = L_DEFAULTS.componentObservationIntervalMs, metadataMaxBytes = L_DEFAULTS.enrollmentMetadataMaxBytes, administratorAfterMs = CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs) {
|
|
6
33
|
const detailSettings = () => ctx.get('aiWorkbenchConversationDetailSettings');
|
|
7
34
|
const api = () => ctx.get('aiWorkbenchConnect');
|
|
8
35
|
const getState = () => {
|
|
9
36
|
const network = ctx.get('aiWorkbenchNetwork'), connect = api(), state = connect?.getState(), networkState = network?.getState();
|
|
10
|
-
return { conversationDetails: connect?.getRemoteConversationDetailState?.() ?? null, conversationDetailSettings: detailSettings() ? { ...detailSettings().getState(), metadataMaxBytes } : null, workspaceBindings: connect?.getWorkspaceBindingState?.() ?? null, loginComponent: { temporaryDataParent: temporaryDataParent ?? null, download: component?.getState() ?? null, source: sources?.getState() ?? null, observationIntervalMs }, startup: connect?.getLoginPromptState?.() ?? null, inventory: inventory ?? null, network: { serviceProvided: !!network, phase: networkState?.phase ?? 'missing', needCode: networkState?.error?.code ?? networkState?.need?.code }, enrollment: connect?.getEnrollmentState?.() ?? null, connection: connect?.getConnectionState?.() ?? null, connect: { serviceProvided: !!connect, phase: state?.phase ?? 'missing', message: state?.need ? employeeMessage(state.need.code) : '连接服务等待就绪' }, codex: inventory?.codex ? { installed: true, message: 'Codex 组件已安装' } : { installed: null, message: '组件清单未装配' } };
|
|
37
|
+
return { connectionMessageSettings: { administratorAfterMs }, workspaceLocations: connect?.getWorkspaceLocationState?.() ?? null, loginDiagnostics: connect?.getLoginDiagnosticState?.() ?? null, conversationDetails: connect?.getRemoteConversationDetailState?.() ?? null, conversationDetailSettings: detailSettings() ? { ...detailSettings().getState(), metadataMaxBytes } : null, workspaceBindings: connect?.getWorkspaceBindingState?.() ?? null, loginComponent: { temporaryDataParent: temporaryDataParent ?? null, download: component?.getState() ?? null, source: sources?.getState() ?? null, observationIntervalMs }, startup: connect?.getLoginPromptState?.() ?? null, inventory: inventory ?? null, network: { serviceProvided: !!network, phase: networkState?.phase ?? 'missing', needCode: networkState?.error?.code ?? networkState?.need?.code }, enrollment: connect?.getEnrollmentState?.() ?? null, connection: connect?.getConnectionState?.() ?? null, connect: { serviceProvided: !!connect, phase: state?.phase ?? 'missing', message: connectionEmployeeMessage(connect?.getConnectionState?.()) ?? (state?.need ? employeeMessage(state.need.code) : '连接服务等待就绪') }, codex: inventory?.codex ? { installed: true, message: 'Codex 组件已安装' } : { installed: null, message: '组件清单未装配' } };
|
|
11
38
|
};
|
|
12
39
|
ctx.provide('aiWorkbenchComponents', { getState });
|
|
13
40
|
ctx.inject(['webServer', 'connection'], host => {
|
|
@@ -28,9 +55,9 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
|
|
|
28
55
|
res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
|
|
29
56
|
res.statusCode = 200;
|
|
30
57
|
let closed = false;
|
|
31
|
-
let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, unnative = () => { }, undownload = () => { }, unsource = () => { }, undetails = () => { }, undetailsettings = () => { };
|
|
58
|
+
let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, unnative = () => { }, undownload = () => { }, unsource = () => { }, undetails = () => { }, unloginDetails = () => { }, undetailsettings = () => { }, unlocations = () => { };
|
|
32
59
|
const close = () => { if (closed)
|
|
33
|
-
return; closed = true; unprompt(); unconnection(); unenrollment(); unnative(); undownload(); unsource(); undetails(); undetailsettings(); streams.delete(close); res.end(); };
|
|
60
|
+
return; closed = true; unprompt(); unconnection(); unenrollment(); unnative(); undownload(); unsource(); undetails(); unloginDetails(); undetailsettings(); unlocations(); streams.delete(close); res.end(); };
|
|
34
61
|
const send = () => { if (closed)
|
|
35
62
|
return; try {
|
|
36
63
|
if (!res.write('data: ' + JSON.stringify(getState()) + '\n\n'))
|
|
@@ -46,12 +73,86 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
|
|
|
46
73
|
undownload = component?.onState(send) ?? (() => { });
|
|
47
74
|
unsource = sources?.onState(send) ?? (() => { });
|
|
48
75
|
undetails = service.onRemoteConversationDetailState?.(send) ?? (() => { });
|
|
76
|
+
unloginDetails = service.onLoginDiagnosticState?.(send) ?? (() => { });
|
|
49
77
|
undetailsettings = detailSettings()?.onState(send) ?? (() => { });
|
|
78
|
+
unlocations = service.onWorkspaceLocationState?.(send) ?? (() => { });
|
|
50
79
|
streams.add(close);
|
|
51
80
|
res.once('close', close);
|
|
52
81
|
send();
|
|
53
82
|
return;
|
|
54
83
|
}
|
|
84
|
+
if (req.method === 'POST' && /^\/ai-workbench-connect\/workspace-locations\/(refresh|browse|select)$/.test(path)) {
|
|
85
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
86
|
+
const invalid = () => { res.statusCode = 400; res.end(JSON.stringify(fail('WORKSPACE_LOCATION_INVALID'))); };
|
|
87
|
+
const operation = path.split('/').at(-1);
|
|
88
|
+
let body;
|
|
89
|
+
try {
|
|
90
|
+
const chunks = [];
|
|
91
|
+
let bytes = 0;
|
|
92
|
+
if (!Number.isSafeInteger(metadataMaxBytes) || metadataMaxBytes < 1) {
|
|
93
|
+
invalid();
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
for await (const chunk of req) {
|
|
97
|
+
const data = Buffer.from(chunk);
|
|
98
|
+
bytes += data.length;
|
|
99
|
+
if (bytes > metadataMaxBytes) {
|
|
100
|
+
invalid();
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
chunks.push(data);
|
|
104
|
+
}
|
|
105
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
106
|
+
}
|
|
107
|
+
catch {
|
|
108
|
+
invalid();
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (!validLocationInput(operation, body)) {
|
|
112
|
+
invalid();
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (!service || service.getContractInfo?.().workspaceLocations !== 1 || typeof service.refreshWorkspaceLocations !== 'function' || typeof service.browseWorkspaceHostDirectories !== 'function' || typeof service.selectWorkspaceLocation !== 'function') {
|
|
116
|
+
res.statusCode = 503;
|
|
117
|
+
res.end(JSON.stringify(fail('DEPENDENCY_REQUIRED')));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const result = operation === 'refresh' ? await service.refreshWorkspaceLocations() : operation === 'browse' ? await service.browseWorkspaceHostDirectories(body) : await service.selectWorkspaceLocation(body);
|
|
122
|
+
res.statusCode = result.ok ? 200 : 409;
|
|
123
|
+
res.end(JSON.stringify(result));
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
res.statusCode = 503;
|
|
127
|
+
res.end(JSON.stringify(fail('DEPENDENCY_REQUIRED')));
|
|
128
|
+
}
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (req.method === 'GET' && ['/ai-workbench-connect/login-diagnostics', '/ai-workbench-connect/login-diagnostic-receipt'].includes(path)) {
|
|
132
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
133
|
+
const unavailable = () => { res.statusCode = 503; res.end(JSON.stringify(fail('DEPENDENCY_REQUIRED'))); };
|
|
134
|
+
try {
|
|
135
|
+
const isReceipt = path.endsWith('-receipt');
|
|
136
|
+
if (!service || typeof service.getContractInfo !== 'function' || service.getContractInfo()?.loginDiagnostics !== 1 || typeof (isReceipt ? service.getLoginDiagnosticReceipt : service.listLoginDiagnostics) !== 'function') {
|
|
137
|
+
unavailable();
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const params = new URL(req.url ?? '/', 'http://dsh').searchParams, allowed = isReceipt ? ['sessionId', 'provider', 'eventId'] : ['sessionId', 'provider', 'cursor'];
|
|
141
|
+
if ([...params.keys()].some(k => !allowed.includes(k) || params.getAll(k).length !== 1)) {
|
|
142
|
+
res.statusCode = 400;
|
|
143
|
+
res.end(JSON.stringify(fail('REMOTE_DETAIL_INVALID')));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const query = { sessionId: params.get('sessionId') ?? '', provider: params.get('provider') };
|
|
147
|
+
const result = isReceipt ? await service.getLoginDiagnosticReceipt({ ...query, eventId: params.get('eventId') ?? '' }) : await service.listLoginDiagnostics({ ...query, ...(params.has('cursor') ? { cursor: params.get('cursor') } : {}) });
|
|
148
|
+
res.statusCode = result.ok ? 200 : 409;
|
|
149
|
+
res.end(JSON.stringify(result));
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
unavailable();
|
|
153
|
+
}
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
55
156
|
if (req.method === 'GET' && ['/ai-workbench-connect/conversation-details', '/ai-workbench-connect/conversation-detail-receipt'].includes(path) && service) {
|
|
56
157
|
const params = new URL(req.url ?? '/', 'http://dsh').searchParams, isReceipt = path.endsWith('/conversation-detail-receipt'), allowed = isReceipt ? ['sessionId', 'provider', 'eventId'] : ['sessionId', 'provider', 'cursor'];
|
|
57
158
|
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
@@ -177,7 +278,7 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
|
|
|
177
278
|
if (!result.ok) {
|
|
178
279
|
res.statusCode = 409;
|
|
179
280
|
actionErrorCode = result.error.code;
|
|
180
|
-
actionError = result.error.code === 'LOGIN_PROMPT_INVALID' ? result.error.message : employeeMessage(result.error.code);
|
|
281
|
+
actionError = result.error.code === 'LOGIN_PROMPT_INVALID' ? result.error.message : employeeMessage(result.error.code, service.getConnectionState());
|
|
181
282
|
}
|
|
182
283
|
}
|
|
183
284
|
else if (req.method !== 'GET' || path !== '/ai-workbench-connect/status') {
|
package/lib/connect.d.ts
CHANGED
|
@@ -2,6 +2,9 @@ import type { ConnectApi, ConnectState, Provider, ConnectionState, LoginPromptSt
|
|
|
2
2
|
import type { Enrollment, Ports } from './ports.ts';
|
|
3
3
|
export declare function validEnrollment(e: Enrollment): boolean;
|
|
4
4
|
export interface ConnectOptions {
|
|
5
|
+
connectionMessages?: {
|
|
6
|
+
administratorAfterMs?: number;
|
|
7
|
+
};
|
|
5
8
|
providers?: Provider[];
|
|
6
9
|
onConnectionState?: (s: ConnectionState) => void;
|
|
7
10
|
onPromptState?: (s: LoginPromptState) => void;
|
package/lib/connect.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
import { CONNECTION_MESSAGES, connectionEmployeeMessage, isConnectionInterruption } from "./connection-messages.js";
|
|
2
|
+
import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
|
|
1
3
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { dependency, fail, ok, need } from "./needs.js";
|
|
4
|
+
import { dependency, fail as baseFail, ok, need } from "./needs.js";
|
|
3
5
|
import { isProjectName } from "./projects.js";
|
|
4
6
|
import { createStartup } from "./startup.js";
|
|
5
7
|
import { parseLoginStatus } from "./auth-status.js";
|
|
8
|
+
import { authFailure } from "./auth-diagnostics.js";
|
|
6
9
|
export function validEnrollment(e) {
|
|
7
10
|
return typeof e === 'object' && e !== null && typeof e.host === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9.-]*$/.test(e.host)
|
|
8
11
|
&& typeof e.username === 'string' && /^emp-[a-z0-9][a-z0-9-]*$/.test(e.username)
|
|
@@ -19,42 +22,82 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
19
22
|
let connection = { instanceId, phase: 'unavailable', epoch: 0 };
|
|
20
23
|
const connectionListeners = new Set();
|
|
21
24
|
let startup;
|
|
22
|
-
const
|
|
23
|
-
|
|
25
|
+
const fail = (code) => { const result = baseFail(code), message = connectionEmployeeMessage(connection); if (!result.ok && message && isConnectionInterruption(code))
|
|
26
|
+
result.error.message = message; return result; };
|
|
27
|
+
const configuredAfterMs = options.connectionMessages?.administratorAfterMs;
|
|
28
|
+
const administratorAfterMs = configuredAfterMs === undefined ? CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs : configuredAfterMs;
|
|
29
|
+
const validMessageSettings = Number.isSafeInteger(administratorAfterMs) && administratorAfterMs >= 1 && administratorAfterMs <= 2147483647;
|
|
30
|
+
let recovery, recoveryTimer, recoverySerial = 0;
|
|
31
|
+
const stopRecovery = () => { recoverySerial++; if (recoveryTimer !== undefined)
|
|
32
|
+
clearTimeout(recoveryTimer); recoveryTimer = undefined; recovery = undefined; };
|
|
33
|
+
const setConnection = (phase, sourceNeed) => {
|
|
34
|
+
if (phase === 'connected' || phase === 'disposed' || phase === 'unavailable' && sourceNeed && !isConnectionInterruption(sourceNeed.code))
|
|
35
|
+
stopRecovery();
|
|
36
|
+
else if (phase === 'unavailable' && sourceNeed && isConnectionInterruption(sourceNeed.code) && !recovery && validMessageSettings) {
|
|
37
|
+
const mine = ++recoverySerial;
|
|
38
|
+
recovery = { version: 1, phase: 'reconnecting', message: CONNECTION_MESSAGES.reconnecting, startedAt: Date.now(), administratorAfterMs };
|
|
39
|
+
recoveryTimer = setTimeout(() => {
|
|
40
|
+
if (disposed || mine !== recoverySerial || !recovery)
|
|
41
|
+
return;
|
|
42
|
+
recoveryTimer = undefined;
|
|
43
|
+
recovery = { ...recovery, phase: 'administrator-required', message: CONNECTION_MESSAGES.administratorRequired };
|
|
44
|
+
setConnection(connection.phase, connection.need);
|
|
45
|
+
if (state.need && isConnectionInterruption(state.need.code))
|
|
46
|
+
publish({ ...state, need: { ...state.need, message: CONNECTION_MESSAGES.administratorRequired } });
|
|
47
|
+
}, administratorAfterMs);
|
|
48
|
+
recoveryTimer.unref?.();
|
|
49
|
+
}
|
|
50
|
+
const message = connectionEmployeeMessage({ recovery });
|
|
51
|
+
const next = { instanceId, phase, epoch: generation, ...(sourceNeed ? { need: { ...sourceNeed, ...(message ? { message } : {}) } } : {}), ...(recovery ? { recovery: structuredClone(recovery) } : {}) };
|
|
24
52
|
if (JSON.stringify(next) === JSON.stringify(connection))
|
|
25
53
|
return;
|
|
26
54
|
if (phase !== 'connected')
|
|
27
55
|
trustedTarget = undefined;
|
|
28
56
|
connection = structuredClone(next);
|
|
57
|
+
const publication = connection;
|
|
58
|
+
// 同步读取者在事件回调里也必须看到同一份员工话。
|
|
59
|
+
if (phase === 'unavailable' && next.need)
|
|
60
|
+
state = { phase: 'blocked', need: structuredClone(next.need) };
|
|
61
|
+
else if (message && state.need && isConnectionInterruption(state.need.code))
|
|
62
|
+
state = { ...state, need: { ...state.need, message } };
|
|
29
63
|
startup?.connectionChanged(next);
|
|
64
|
+
if (connection !== publication)
|
|
65
|
+
return;
|
|
30
66
|
options.onConnectionState?.(structuredClone(next));
|
|
31
|
-
|
|
67
|
+
if (connection !== publication)
|
|
68
|
+
return;
|
|
69
|
+
for (const listener of connectionListeners) {
|
|
70
|
+
if (connection !== publication)
|
|
71
|
+
return;
|
|
32
72
|
listener(structuredClone(next));
|
|
73
|
+
}
|
|
33
74
|
};
|
|
34
75
|
let controller = new AbortController();
|
|
35
76
|
const loginFlights = new Map();
|
|
36
77
|
const pending = new Set();
|
|
37
78
|
let disposal;
|
|
38
79
|
const track = (promise) => { pending.add(promise); void promise.then(() => pending.delete(promise), () => pending.delete(promise)); return promise; };
|
|
39
|
-
const publish = (s) => { state = structuredClone(s); emit(structuredClone(state)); };
|
|
80
|
+
const publish = (s) => { const message = connectionEmployeeMessage(connection); state = structuredClone(s.need && isConnectionInterruption(s.need.code) && message ? { ...s, need: { ...s.need, message } } : s); emit(structuredClone(state)); };
|
|
40
81
|
const invalid = (g) => disposed ? fail('DISPOSED') : g !== generation ? fail('CONNECTION_LOST') : undefined;
|
|
41
82
|
const block = (r) => { if (!r.ok && !disposed) {
|
|
42
|
-
publish({ phase: 'blocked', need: r.error });
|
|
43
83
|
if (connection.phase !== 'connected')
|
|
44
84
|
setConnection('unavailable', r.error);
|
|
45
|
-
|
|
85
|
+
publish({ phase: 'blocked', need: r.error });
|
|
86
|
+
} const message = connectionEmployeeMessage(connection); return !r.ok && message && isConnectionInterruption(r.error.code) ? { ok: false, error: { ...r.error, message } } : r; };
|
|
46
87
|
const transportBlock = (r) => { if (!r.ok && !disposed && connection.phase === 'connected') {
|
|
47
88
|
generation++;
|
|
48
89
|
controller.abort();
|
|
49
90
|
controller = new AbortController();
|
|
50
91
|
flight = undefined;
|
|
51
92
|
loginFlights.clear();
|
|
52
|
-
}
|
|
53
|
-
setConnection('unavailable', r.error); return
|
|
54
|
-
const connect = () => {
|
|
93
|
+
} if (!r.ok && !disposed)
|
|
94
|
+
setConnection('unavailable', r.error); return block(r); };
|
|
95
|
+
const connect = (reuseTrusted = false) => {
|
|
55
96
|
if (disposed)
|
|
56
97
|
return Promise.resolve(fail('DISPOSED'));
|
|
57
|
-
if (
|
|
98
|
+
if (!validMessageSettings)
|
|
99
|
+
return Promise.resolve(block(fail('SETTINGS_REQUIRED')));
|
|
100
|
+
if ((state.target || reuseTrusted) && connection.phase === 'connected' && trustedTarget)
|
|
58
101
|
return Promise.resolve(ok(structuredClone(trustedTarget)));
|
|
59
102
|
if (flight)
|
|
60
103
|
return flight;
|
|
@@ -118,30 +161,46 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
118
161
|
void promise.then(clear, clear);
|
|
119
162
|
return promise;
|
|
120
163
|
};
|
|
121
|
-
const checkLogin = async (provider) => {
|
|
164
|
+
const checkLogin = async (provider, reuseTrusted = false) => {
|
|
122
165
|
if (provider !== 'claude' && provider !== 'codex')
|
|
123
166
|
return fail('AUTH_STATUS_INVALID');
|
|
124
|
-
const connecting = connect(), g = generation;
|
|
167
|
+
const connecting = connect(reuseTrusted), g = generation;
|
|
125
168
|
const connected = await connecting;
|
|
126
169
|
const staleConnection = invalid(g);
|
|
127
170
|
if (staleConnection)
|
|
128
171
|
return staleConnection;
|
|
129
172
|
if (!connected.ok)
|
|
130
173
|
return connected;
|
|
174
|
+
const signal = controller.signal;
|
|
131
175
|
publish({ phase: 'checking-login', target: connected.value, provider });
|
|
176
|
+
const stalePublish = invalid(g);
|
|
177
|
+
if (stalePublish)
|
|
178
|
+
return stalePublish;
|
|
179
|
+
const ticket = startup.beginCheck(provider);
|
|
180
|
+
const staleTicket = invalid(g);
|
|
181
|
+
if (staleTicket)
|
|
182
|
+
return staleTicket;
|
|
132
183
|
try {
|
|
133
|
-
const raw = await ports.ssh.status(connected.value, provider,
|
|
184
|
+
const raw = await ports.ssh.status(connected.value, provider, signal);
|
|
134
185
|
const stale = invalid(g);
|
|
135
186
|
if (stale)
|
|
136
187
|
return stale;
|
|
137
188
|
const status = raw.ok ? parseLoginStatus(provider, raw.value) : raw;
|
|
189
|
+
if (!startup.finishCheck(ticket, status))
|
|
190
|
+
return invalid(g) ?? authFailure('connect-check-login', 'STATUS_SUPERSEDED');
|
|
138
191
|
if (!status.ok)
|
|
139
192
|
return ['network', 'ssh', 'enrollment'].includes(status.error.layer) ? transportBlock(status) : block(status);
|
|
140
193
|
publish(status.value.loggedIn ? { phase: 'ready', target: connected.value, provider } : { phase: 'connected', target: connected.value, provider });
|
|
141
|
-
return status;
|
|
194
|
+
return invalid(g) ?? status;
|
|
142
195
|
}
|
|
143
|
-
catch {
|
|
144
|
-
|
|
196
|
+
catch (error) {
|
|
197
|
+
const stale = invalid(g);
|
|
198
|
+
if (stale)
|
|
199
|
+
return stale;
|
|
200
|
+
const failure = authFailure('connect-check-login', 'STATUS_EXCEPTION', {}, error);
|
|
201
|
+
if (!startup.finishCheck(ticket, failure))
|
|
202
|
+
return authFailure('connect-check-login', 'STATUS_SUPERSEDED');
|
|
203
|
+
return block(failure);
|
|
145
204
|
}
|
|
146
205
|
};
|
|
147
206
|
const login = (provider) => {
|
|
@@ -162,21 +221,39 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
162
221
|
return connected;
|
|
163
222
|
if (!ports.login)
|
|
164
223
|
return block(dependency('Electron 登录助手及已确认设置'));
|
|
224
|
+
const owner = startup.captureCheck(provider), signal = controller.signal;
|
|
165
225
|
publish({ phase: 'login', target: connected.value, provider });
|
|
226
|
+
const stalePublish = invalid(g);
|
|
227
|
+
if (stalePublish)
|
|
228
|
+
return stalePublish;
|
|
229
|
+
if (!startup.currentTicket(owner))
|
|
230
|
+
return authFailure('connect-check-login', 'STATUS_SUPERSEDED');
|
|
166
231
|
try {
|
|
167
|
-
const r = await ports.login.run(connected.value, provider,
|
|
232
|
+
const r = await ports.login.run(connected.value, provider, signal);
|
|
168
233
|
const stale = invalid(g);
|
|
169
234
|
if (stale)
|
|
170
235
|
return stale;
|
|
236
|
+
if (!startup.currentTicket(owner))
|
|
237
|
+
return authFailure('connect-check-login', 'STATUS_SUPERSEDED');
|
|
171
238
|
if (!r.ok)
|
|
172
239
|
return ['network', 'ssh', 'enrollment'].includes(r.error.layer) ? transportBlock(r) : block(r);
|
|
173
240
|
const checked = await checkLogin(provider), staleChecked = invalid(g);
|
|
174
241
|
if (staleChecked)
|
|
175
242
|
return staleChecked;
|
|
176
|
-
|
|
243
|
+
if (checked.ok && !checked.value.loggedIn) {
|
|
244
|
+
const failed = block(fail('LOGIN_FAILED'));
|
|
245
|
+
startup.inheritCheck(checked, failed);
|
|
246
|
+
return failed;
|
|
247
|
+
}
|
|
248
|
+
return checked;
|
|
177
249
|
}
|
|
178
250
|
catch {
|
|
179
|
-
|
|
251
|
+
const stale = invalid(g);
|
|
252
|
+
if (stale)
|
|
253
|
+
return stale;
|
|
254
|
+
if (!startup.currentTicket(owner))
|
|
255
|
+
return authFailure('connect-check-login', 'STATUS_SUPERSEDED');
|
|
256
|
+
return block(fail('LOGIN_FAILED'));
|
|
180
257
|
}
|
|
181
258
|
};
|
|
182
259
|
const promise = track(run());
|
|
@@ -216,15 +293,15 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
216
293
|
controller = new AbortController();
|
|
217
294
|
flight = undefined;
|
|
218
295
|
loginFlights.clear();
|
|
219
|
-
block(fail('CONNECTION_LOST'));
|
|
220
296
|
setConnection('unavailable', need('CONNECTION_LOST'));
|
|
297
|
+
block(fail('CONNECTION_LOST'));
|
|
221
298
|
}
|
|
222
299
|
else {
|
|
223
300
|
void connect();
|
|
224
301
|
}
|
|
225
302
|
});
|
|
226
303
|
const operations = { getState: () => structuredClone(state), connect, checkLogin: provider => track(checkLogin(provider)), login };
|
|
227
|
-
startup = createStartup(operations, options.providers ?? ['codex', 'claude'], options.onPromptState, options.onPromptResult, instanceId);
|
|
304
|
+
startup = createStartup({ ...operations, connect: () => connect(true), checkLogin: provider => track(checkLogin(provider, true)) }, options.providers ?? ['codex', 'claude'], options.onPromptState, options.onPromptResult, instanceId);
|
|
228
305
|
return {
|
|
229
306
|
...operations,
|
|
230
307
|
getModelCatalogTarget: provider => {
|
|
@@ -237,10 +314,15 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
237
314
|
return ok({ version: 1, purpose: 'model-catalog', scope: 'host-user', instanceId, epoch: connection.epoch, provider, target: structuredClone(trustedTarget) });
|
|
238
315
|
},
|
|
239
316
|
appendRemoteConversationDetail: async () => dependency('官方会话存储与持久诊断记录'),
|
|
317
|
+
appendLoginDiagnostic: async () => dependency('官方会话存储与持久登录诊断记录'),
|
|
318
|
+
getLoginDiagnosticReceipt: async () => dependency('官方会话存储与持久登录诊断记录'),
|
|
319
|
+
listLoginDiagnostics: async () => dependency('官方会话存储与持久登录诊断记录'),
|
|
320
|
+
getLoginDiagnosticState: () => ({ instanceId, epoch: connection.epoch, revision: 0, phase: disposed ? 'disposed' : 'unavailable', sessions: [], need: need(disposed ? 'DISPOSED' : 'DEPENDENCY_REQUIRED') }),
|
|
321
|
+
onLoginDiagnosticState: () => () => { },
|
|
240
322
|
getRemoteConversationDetailReceipt: async () => dependency('官方会话存储与持久诊断记录'),
|
|
241
323
|
getRemoteConversationDetailState: () => ({ instanceId, epoch: connection.epoch, revision: 0, phase: disposed ? 'disposed' : 'unavailable', sessions: [], need: need(disposed ? 'DISPOSED' : 'DEPENDENCY_REQUIRED') }),
|
|
242
324
|
onRemoteConversationDetailState: () => () => { }, listRemoteConversationDetails: async () => dependency('官方会话存储与持久诊断记录'),
|
|
243
|
-
getContractInfo: () => ({ apiVersion: '0.7.0', status: 'implemented', workspaceBinding: 'native-local-v1' }),
|
|
325
|
+
getContractInfo: () => ({ apiVersion: '0.7.0', status: 'implemented', workspaceBinding: 'native-local-v1', connectionMessages: 1 }),
|
|
244
326
|
getEnrollmentState: () => ({ instanceId, revision: 0, phase: 'blocked', need: need('DEPENDENCY_REQUIRED') }), onEnrollmentState: () => () => { },
|
|
245
327
|
importEnrollment: async () => dependency('官方profileContext与原生目录选择服务'),
|
|
246
328
|
getWorkspaceBindingState: () => ({ instanceId, revision: 0, items: [] }), onWorkspaceBindingState: () => () => { }, acknowledgeWorkspaceNotice: async () => dependency('官方工作区说明回执'), resolveSessionProject: async () => dependency('官方会话存储与L可信工作区关联'),
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { ConnectionState, NeedCode } from './api.ts';
|
|
2
|
+
export declare const CONNECTION_MESSAGES: Readonly<{
|
|
3
|
+
readonly reconnecting: "正在自动重连";
|
|
4
|
+
readonly administratorRequired: "请联系管理员";
|
|
5
|
+
}>;
|
|
6
|
+
export declare function connectionEmployeeMessage(state: Pick<ConnectionState, 'recovery'> | undefined): string | undefined;
|
|
7
|
+
export declare const isConnectionInterruption: (code: NeedCode) => boolean;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export const CONNECTION_MESSAGES = Object.freeze({ reconnecting: '正在自动重连', administratorRequired: '请联系管理员' });
|
|
2
|
+
// 状态由L计时;消费方不按自己的时钟/品牌推断阶段。
|
|
3
|
+
export function connectionEmployeeMessage(state) {
|
|
4
|
+
return state?.recovery?.phase === 'reconnecting' ? CONNECTION_MESSAGES.reconnecting : state?.recovery?.phase === 'administrator-required' ? CONNECTION_MESSAGES.administratorRequired : undefined;
|
|
5
|
+
}
|
|
6
|
+
export const isConnectionInterruption = (code) => ['CONNECTION_LOST', 'HOST_OFFLINE', 'SSH_FAILED'].includes(code);
|
|
@@ -3,6 +3,9 @@ export interface ConversationDetailOptions {
|
|
|
3
3
|
profileDir: string;
|
|
4
4
|
maxEventBytes: number;
|
|
5
5
|
pageSize: number;
|
|
6
|
+
storageName?: 'conversation-details' | 'login-diagnostics';
|
|
7
|
+
validate?: (detail: RemoteConversationDetail) => boolean;
|
|
8
|
+
knownKinds?: readonly string[];
|
|
6
9
|
getConnectionState: () => ConnectionState;
|
|
7
10
|
context: () => Promise<Result<{
|
|
8
11
|
identity: string;
|
|
@@ -48,9 +48,10 @@ export function validRemoteConversationDetail(v) {
|
|
|
48
48
|
return false;
|
|
49
49
|
return v.version === 1 && text(v.eventId) && text(v.instanceId) && integer(v.epoch) && text(v.sessionId) && brand(v.provider) && integer(v.sequence) && [v.turn, v.step].every(x => x === null || text(x) || integer(x)) && text(v.kind) && ['info', 'warning', 'action-required'].includes(v.severity) && text(v.code) && typeof v.summary === 'string' && (v.method === undefined || text(v.method));
|
|
50
50
|
}
|
|
51
|
-
const counts = (items
|
|
51
|
+
const counts = (items, knownKinds = ['extensions', 'commands', 'tools', 'usage', 'action-required']) => ({ total: items.length, unknownCount: items.filter(d => !knownKinds.includes(d.kind)).length, actionRequiredCount: items.filter(d => d.severity === 'action-required' || d.kind === 'action-required').length });
|
|
52
52
|
export function createConversationDetails(options) {
|
|
53
|
-
const parent = join(options.profileDir, 'ai-workbench-connect'), root = join(parent, 'conversation-details');
|
|
53
|
+
const parent = join(options.profileDir, 'ai-workbench-connect'), root = join(parent, options.storageName ?? 'conversation-details');
|
|
54
|
+
const valid = (detail) => validRemoteConversationDetail(detail) && (!options.validate || options.validate(detail));
|
|
54
55
|
let disposed = false, uncertain = false, revision = 0, tail = Promise.resolve();
|
|
55
56
|
let snapshot = { ...connectionIds(), revision, phase: 'unavailable', sessions: [] };
|
|
56
57
|
const listeners = new Set();
|
|
@@ -162,7 +163,7 @@ export function createConversationDetails(options) {
|
|
|
162
163
|
if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || (st.mode & 0o777) !== 0o600)
|
|
163
164
|
throw Error('DETAIL_RECORD_INVALID');
|
|
164
165
|
const record = JSON.parse(await checked(h.readFile('utf8'), before));
|
|
165
|
-
if (record.version !== 1 || !
|
|
166
|
+
if (record.version !== 1 || !valid(record.detail) || record.digest !== digest(canonical(record.detail)) || canonical(record.detail) !== canonical(detail))
|
|
166
167
|
throw Error('DETAIL_RECORD_INVALID');
|
|
167
168
|
await checked(h.sync(), before);
|
|
168
169
|
}
|
|
@@ -200,7 +201,7 @@ export function createConversationDetails(options) {
|
|
|
200
201
|
if (!/^[a-f0-9]{64}\.json$/.test(name))
|
|
201
202
|
throw Error('DETAIL_RECORD_INVALID');
|
|
202
203
|
const raw = JSON.parse(await checked(privateRead(join(domain, name), before), before)), d = raw.detail;
|
|
203
|
-
if (raw.version !== 1 || !
|
|
204
|
+
if (raw.version !== 1 || !valid(d) || raw.digest !== digest(canonical(d)) || name !== digest(d.eventId) + '.json' || ids.has(d.eventId) || sequences.has(canonical([d.sessionId, d.provider, d.sequence])))
|
|
204
205
|
throw Error('DETAIL_RECORD_INVALID');
|
|
205
206
|
ids.add(d.eventId);
|
|
206
207
|
sequences.add(canonical([d.sessionId, d.provider, d.sequence]));
|
|
@@ -227,7 +228,7 @@ export function createConversationDetails(options) {
|
|
|
227
228
|
excluded = true;
|
|
228
229
|
continue;
|
|
229
230
|
}
|
|
230
|
-
sessions.push({ sessionId: d.sessionId, provider: d.provider, ...counts(items.filter(r => r.sessionId === d.sessionId && r.provider === d.provider)) });
|
|
231
|
+
sessions.push({ sessionId: d.sessionId, provider: d.provider, ...counts(items.filter(r => r.sessionId === d.sessionId && r.provider === d.provider), options.knownKinds) });
|
|
231
232
|
}
|
|
232
233
|
check(before);
|
|
233
234
|
publish('ready', sessions, excluded ? 'REMOTE_DETAIL_SCOPE_INVALID' : undefined);
|
|
@@ -250,7 +251,7 @@ export function createConversationDetails(options) {
|
|
|
250
251
|
appendRemoteConversationDetail(input) {
|
|
251
252
|
let detail;
|
|
252
253
|
try {
|
|
253
|
-
if (!
|
|
254
|
+
if (!valid(input))
|
|
254
255
|
return Promise.resolve(fail('REMOTE_DETAIL_INVALID'));
|
|
255
256
|
detail = structuredClone(input);
|
|
256
257
|
}
|
|
@@ -360,7 +361,7 @@ export function createConversationDetails(options) {
|
|
|
360
361
|
await stateRows(items, identity, before);
|
|
361
362
|
if (await scope(q.sessionId, q.provider, before) !== identity)
|
|
362
363
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
363
|
-
const value = { items: structuredClone(page), ...counts(bounded), ...(page.length < remaining.length ? { nextCursor: cursor({ version: 1, identity, sessionId: q.sessionId, provider: q.provider, upper, after: page.at(-1).sequence }, secret) } : {}) };
|
|
364
|
+
const value = { items: structuredClone(page), ...counts(bounded, options.knownKinds), ...(page.length < remaining.length ? { nextCursor: cursor({ version: 1, identity, sessionId: q.sessionId, provider: q.provider, upper, after: page.at(-1).sequence }, secret) } : {}) };
|
|
364
365
|
return ok(value);
|
|
365
366
|
});
|
|
366
367
|
},
|
package/lib/cordis.d.ts
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
-
import type { ConnectApi, ConnectState, ConnectionState, LoginPromptState, LoginPromptResult, EnrollmentState, WorkspaceBindingState, RemoteConversationDetailState } from './api.ts';
|
|
1
|
+
import type { ConnectApi, ConnectState, ConnectionState, LoginPromptState, LoginPromptResult, EnrollmentState, WorkspaceBindingState, RemoteConversationDetailState, WorkspaceLocationState } from './api.ts';
|
|
2
2
|
declare module '@deepseek-ai/cordis' {
|
|
3
3
|
interface Context {
|
|
4
4
|
aiWorkbenchConnect: ConnectApi;
|
|
5
5
|
}
|
|
6
6
|
interface Events {
|
|
7
|
+
'ai-workbench/workspace-location-state': (state: WorkspaceLocationState) => void;
|
|
8
|
+
'ai-workbench/login-diagnostic-state': (state: RemoteConversationDetailState) => void;
|
|
7
9
|
'ai-workbench/remote-conversation-detail-state': (state: RemoteConversationDetailState) => void;
|
|
8
10
|
'ai-workbench/enrollment-state': (state: EnrollmentState) => void;
|
|
9
11
|
'ai-workbench/workspace-binding-state': (state: WorkspaceBindingState) => void;
|
package/lib/defaults.d.ts
CHANGED
|
@@ -32,3 +32,9 @@ export declare const CONVERSATION_DETAIL_DEFAULTS: Readonly<{
|
|
|
32
32
|
maxEventBytes: 1048576;
|
|
33
33
|
pageSize: 100;
|
|
34
34
|
}>;
|
|
35
|
+
export declare const WORKSPACE_LOCATION_DEFAULTS: {
|
|
36
|
+
readonly pageSize: 100;
|
|
37
|
+
};
|
|
38
|
+
export declare const CONNECTION_MESSAGE_DEFAULTS: Readonly<{
|
|
39
|
+
administratorAfterMs: 30000;
|
|
40
|
+
}>;
|
package/lib/defaults.js
CHANGED
|
@@ -3,3 +3,5 @@ export const L_DEFAULTS = Object.freeze({ enrollmentMetadataMaxBytes: 1048576, c
|
|
|
3
3
|
export const ELECTRON_PIN = Object.freeze({ source: 'https://github.com/electron/electron/releases/download/v44.0.0/electron-v44.0.0-darwin-arm64.zip', sha256: '076d79742986e1b100b69ebecc691cb07368045e54c9087cef631b8622b76a80', executable: 'Electron.app/Contents/MacOS/Electron' });
|
|
4
4
|
export const NETWORK_DEFAULTS = Object.freeze({ proxyListen: '127.0.0.1:0', logUpload: false, statusRefreshIntervalSeconds: 2, dialTimeoutSeconds: 20, headerTimeoutSeconds: 10, enrollmentObservationSeconds: 30, httpMaxHeaderBytes: 1048576, httpMaxResponseHeaderBytes: 1048576, startupObservationSeconds: 35, shutdownObservationSeconds: 10, controlResponseMaxBytes: 65536, downloadMaxRedirects: 3 });
|
|
5
5
|
export const CONVERSATION_DETAIL_DEFAULTS = Object.freeze({ maxEventBytes: 1048576, pageSize: 100 });
|
|
6
|
+
export const WORKSPACE_LOCATION_DEFAULTS = { pageSize: 100 };
|
|
7
|
+
export const CONNECTION_MESSAGE_DEFAULTS = Object.freeze({ administratorAfterMs: 30000 });
|
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
expected?: HostDirectoryIdentity;
|
|
49
|
+
}
|
|
50
|
+
export declare function createHostDirectories(runner: Runner, maxOutputBytes: number): {
|
|
51
|
+
browse: (target: SshTarget, data: HostDirectoryRequest, signal: AbortSignal) => Promise<Result<HostDirectoryData>>;
|
|
52
|
+
inspect: (target: SshTarget, path: string, signal: AbortSignal) => Promise<Result<HostDirectoryInfo>>;
|
|
53
|
+
};
|