@ai-workbench/connect 0.7.28 → 0.7.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/NOTICE.md +2 -6
  2. package/README.md +8 -22
  3. package/client/index.cjs +17 -11
  4. package/helper/claude-callback.cjs +2 -13
  5. package/helper/host-directories.cjs +7 -12
  6. package/helper/remote-login.cjs +4 -11
  7. package/lib/api.d.ts +13 -7
  8. package/lib/auth-diagnostics.js +1 -1
  9. package/lib/browser-login.d.ts +10 -0
  10. package/lib/browser-login.js +70 -0
  11. package/lib/components.d.ts +1 -3
  12. package/lib/components.js +37 -15
  13. package/lib/connect.js +5 -1
  14. package/lib/defaults.d.ts +0 -10
  15. package/lib/defaults.js +1 -2
  16. package/lib/host-directories.d.ts +2 -3
  17. package/lib/host-directories.js +10 -8
  18. package/lib/host-session-projects.d.ts +2 -13
  19. package/lib/host-session-projects.js +65 -50
  20. package/lib/index.d.ts +0 -9
  21. package/lib/index.js +4 -13
  22. package/lib/integration.d.ts +1 -3
  23. package/lib/integration.js +8 -26
  24. package/lib/login.d.ts +2 -2
  25. package/lib/login.js +11 -9
  26. package/lib/needs.js +2 -2
  27. package/lib/ports.d.ts +1 -0
  28. package/lib/profile-runtime.js +5 -5
  29. package/lib/profile-settings.d.ts +2 -6
  30. package/lib/profile-settings.js +4 -8
  31. package/lib/remote-login.d.ts +1 -1
  32. package/lib/remote-login.js +2 -2
  33. package/lib/startup.js +19 -1
  34. package/lib/workspace-directory-picker.js +51 -95
  35. package/lib/workspace-location-types.d.ts +18 -11
  36. package/lib/workspace-locations.d.ts +2 -12
  37. package/lib/workspace-locations.js +81 -217
  38. package/package.json +3 -6
  39. package/helper/device-panel.cjs +0 -4
  40. package/helper/device-panel.css +0 -1
  41. package/helper/device-panel.html +0 -1
  42. package/helper/device-preload.cjs +0 -5
  43. package/helper/device-window.cjs +0 -60
  44. package/helper/main.cjs +0 -19
  45. package/helper/window.cjs +0 -46
  46. package/lib/archive.d.ts +0 -1
  47. package/lib/archive.js +0 -63
  48. package/lib/cache.d.ts +0 -21
  49. package/lib/cache.js +0 -156
  50. package/lib/component-download.d.ts +0 -34
  51. package/lib/component-download.js +0 -86
  52. package/lib/component-source.d.ts +0 -31
  53. package/lib/component-source.js +0 -18
  54. package/lib/electron.d.ts +0 -8
  55. package/lib/electron.js +0 -83
  56. package/lib/physical-fs.d.ts +0 -3
  57. package/lib/physical-fs.js +0 -7
  58. package/node_modules/pend/LICENSE +0 -23
  59. package/node_modules/pend/README.md +0 -41
  60. package/node_modules/pend/index.js +0 -55
  61. package/node_modules/pend/package.json +0 -18
  62. package/node_modules/pend/test.js +0 -137
  63. package/node_modules/yauzl/LICENSE +0 -21
  64. package/node_modules/yauzl/README.md +0 -1015
  65. package/node_modules/yauzl/crc32.js +0 -45
  66. package/node_modules/yauzl/fd-slicer.js +0 -188
  67. package/node_modules/yauzl/index.js +0 -1096
  68. package/node_modules/yauzl/package.json +0 -40
package/lib/components.js CHANGED
@@ -28,11 +28,11 @@ function validLocationInput(operation, value) {
28
28
  return false;
29
29
  return Object.keys(value).every(key => [...context, ...extra].includes(key));
30
30
  }
31
- export function registerComponents(ctx, inventory, temporaryDataParent, component, sources, observationIntervalMs = L_DEFAULTS.componentObservationIntervalMs, metadataMaxBytes = L_DEFAULTS.enrollmentMetadataMaxBytes) {
31
+ export function registerComponents(ctx, inventory, metadataMaxBytes = L_DEFAULTS.enrollmentMetadataMaxBytes) {
32
32
  const api = () => ctx.get('aiWorkbenchConnect');
33
33
  const getState = () => {
34
34
  const network = ctx.get('aiWorkbenchNetwork'), connect = api(), state = connect?.getState(), networkState = network?.getState();
35
- return { ...(typeof connect?.getWorkspaceDirectoryPickerSettings === 'function' ? { workspaceDirectoryPickerSettings: connect.getWorkspaceDirectoryPickerSettings() } : {}), workspaceLocations: connect?.getWorkspaceLocationState?.() ?? 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: '组件清单未装配' } };
35
+ return { ...(typeof connect?.getWorkspaceDirectoryPickerSettings === 'function' ? { workspaceDirectoryPickerSettings: connect.getWorkspaceDirectoryPickerSettings() } : {}), workspaceLocations: connect?.getWorkspaceLocationState?.() ?? null, browserLogin: connect?.getBrowserLoginState?.() ?? null, 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: '组件清单未装配' } };
36
36
  };
37
37
  ctx.provide('aiWorkbenchComponents', { getState });
38
38
  ctx.inject(['webServer', 'connection'], host => {
@@ -53,9 +53,9 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
53
53
  res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
54
54
  res.statusCode = 200;
55
55
  let closed = false;
56
- let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, undownload = () => { }, unsource = () => { }, unlocations = () => { };
56
+ let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, unbrowser = () => { }, unlocations = () => { };
57
57
  const close = () => { if (closed)
58
- return; closed = true; unprompt(); unconnection(); unenrollment(); undownload(); unsource(); unlocations(); streams.delete(close); res.end(); };
58
+ return; closed = true; unprompt(); unconnection(); unenrollment(); unbrowser(); unlocations(); streams.delete(close); res.end(); };
59
59
  const send = () => { if (closed)
60
60
  return; try {
61
61
  if (!res.write('data: ' + JSON.stringify(getState()) + '\n\n'))
@@ -67,8 +67,7 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
67
67
  unprompt = service.onLoginPromptState(send);
68
68
  unconnection = service.onConnectionState(send);
69
69
  unenrollment = service.onEnrollmentState?.(send) ?? (() => { });
70
- undownload = component?.onState(send) ?? (() => { });
71
- unsource = sources?.onState(send) ?? (() => { });
70
+ unbrowser = service.onBrowserLoginState?.(send) ?? (() => { });
72
71
  unlocations = service.onWorkspaceLocationState?.(send) ?? (() => { });
73
72
  streams.add(close);
74
73
  res.once('close', close);
@@ -207,16 +206,39 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
207
206
  res.end(JSON.stringify(result));
208
207
  return;
209
208
  }
210
- if (req.method === 'POST' && /^\/ai-workbench-connect\/component-download\/cancel\/[a-zA-Z0-9-]+$/.test(path) && component) {
209
+ if (req.method === 'POST' && /^\/ai-workbench-connect\/(login-code|cancel-login)\/[a-zA-Z0-9-]+$/.test(path)) {
211
210
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
212
- if (Number(req.headers?.['content-length'] ?? 0) > 0 || req.headers?.['transfer-encoding']) {
211
+ const id = path.split('/').at(-1);
212
+ let code;
213
+ try {
214
+ if (!Number.isSafeInteger(metadataMaxBytes) || metadataMaxBytes < 1)
215
+ throw Error();
216
+ const chunks = [];
217
+ let bytes = 0;
218
+ for await (const chunk of req) {
219
+ const part = Buffer.from(chunk);
220
+ bytes += part.length;
221
+ if (bytes > metadataMaxBytes)
222
+ throw Error();
223
+ chunks.push(part);
224
+ }
225
+ if (path.includes('/login-code/')) {
226
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
227
+ if (!record(body) || Object.keys(body).length !== 1 || typeof body.code !== 'string')
228
+ throw Error();
229
+ code = body.code;
230
+ }
231
+ else if (bytes)
232
+ throw Error();
233
+ }
234
+ catch {
213
235
  res.statusCode = 400;
214
- res.end(JSON.stringify({ error: 'no-input-accepted' }));
236
+ res.end(JSON.stringify(fail('LOGIN_PROMPT_INVALID')));
215
237
  return;
216
238
  }
217
- const cancelled = component.cancel(path.split('/').at(-1));
218
- res.statusCode = cancelled ? 200 : 409;
219
- res.end(JSON.stringify({ ...getState(), ...(!cancelled ? { actionErrorCode: 'COMPONENT_DOWNLOAD_NOT_ACTIVE', actionError: '该组件下载已经结束或更新,请使用当前状态。' } : {}) }));
239
+ const result = typeof code === 'string' ? await service?.submitLoginCode?.(id, code) : service?.cancelBrowserLogin?.(id);
240
+ res.statusCode = result?.ok ? 200 : 409;
241
+ res.end(JSON.stringify({ ...getState(), ...(!result?.ok ? { actionErrorCode: result?.error.code ?? 'LOGIN_PROMPT_INVALID', actionError: result && !result.ok ? result.error.message : '本次登录已结束,请重新发起。' } : {}) }));
220
242
  return;
221
243
  }
222
244
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
@@ -235,12 +257,12 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
235
257
  result = await service.refreshLoginPrompts();
236
258
  else if (/^\/ai-workbench-connect\/start-login\/(claude|codex)\/[a-zA-Z0-9-]+\/\d+$/.test(path)) {
237
259
  const [, provider, instance, revision] = /\/start-login\/(claude|codex)\/([a-zA-Z0-9-]+)\/(\d+)$/.exec(path);
238
- const brand = provider, shown = service.getLoginPromptState(), before = service.getConnectionState();
239
- if (before.phase !== 'connected' || shown.instanceId !== instance || shown.revision !== Number(revision) || shown.phase === 'authorizing' || shown.logins[brand] !== false || shown.checkingProviders.includes(brand) || shown.providerNeeds[brand])
260
+ const brand = provider, shown = service.getLoginPromptState(), before = service.getConnectionState(), claudeUnknown = brand === 'claude' && shown.logins.claude === undefined;
261
+ if ((before.phase !== 'connected' && !claudeUnknown) || shown.instanceId !== instance || shown.revision !== Number(revision) || ['authorizing', 'disposed'].includes(shown.phase) || !claudeUnknown && (shown.logins[brand] !== false || shown.providerNeeds[brand]) || shown.checkingProviders.includes(brand))
240
262
  result = fail('LOGIN_PROMPT_INVALID');
241
263
  else {
242
264
  const requested = await service.requestLoginPrompt(brand, 'user'), after = service.getConnectionState();
243
- if (after.phase !== 'connected' || after.instanceId !== before.instanceId || after.epoch !== before.epoch)
265
+ if (after.phase !== 'connected' || after.instanceId !== before.instanceId || before.phase === 'connected' && after.epoch !== before.epoch)
244
266
  result = fail('LOGIN_PROMPT_INVALID');
245
267
  else if (!requested.ok)
246
268
  result = requested;
package/lib/connect.js CHANGED
@@ -200,7 +200,7 @@ export function createConnect(ports, emit, options = {}) {
200
200
  if (!connected.ok)
201
201
  return connected;
202
202
  if (!ports.login)
203
- return block(dependency('Electron 登录助手及已确认设置'));
203
+ return block(dependency('系统浏览器及已确认设置'));
204
204
  const owner = startup.captureCheck(provider), signal = controller.signal;
205
205
  publish({ phase: 'login', target: connected.value, provider });
206
206
  const stalePublish = invalid(g);
@@ -264,6 +264,10 @@ export function createConnect(ports, emit, options = {}) {
264
264
  startup = createStartup({ ...operations, connect: () => connect(true), checkLogin: provider => track(checkLogin(provider, true)) }, options.providers ?? ['codex', 'claude'], options.onPromptState, options.onPromptResult, instanceId);
265
265
  return {
266
266
  ...operations,
267
+ getBrowserLoginState: () => ports.login?.interaction?.getState() ?? null,
268
+ onBrowserLoginState: fn => ports.login?.interaction?.onState(fn) ?? (() => { }),
269
+ submitLoginCode: async (id, code) => disposed ? fail('DISPOSED') : ports.login?.interaction?.submit(id, code) ?? fail('LOGIN_PROMPT_INVALID'),
270
+ cancelBrowserLogin: id => ports.login?.interaction?.cancel(id) ?? fail('LOGIN_PROMPT_INVALID'),
267
271
  getModelCatalogTarget: provider => {
268
272
  if (disposed)
269
273
  return fail('DISPOSED');
package/lib/defaults.d.ts CHANGED
@@ -2,17 +2,7 @@ export declare const L_DEFAULTS: Readonly<{
2
2
  enrollmentMetadataMaxBytes: 1048576;
3
3
  commandOutputMaxBytes: 1048576;
4
4
  remoteKillGraceMs: 1000;
5
- componentDownloadMaxRedirects: 3;
6
- componentObservationIntervalMs: 1000;
7
- maxDownloadBytes: 200000000;
8
- maxExtractedBytes: 600000000;
9
5
  loginOutputMaxBytes: 1048576;
10
- ipcMaxBytes: 1048576;
11
- }>;
12
- export declare const ELECTRON_PIN: Readonly<{
13
- source: "https://github.com/electron/electron/releases/download/v44.0.0/electron-v44.0.0-darwin-arm64.zip";
14
- sha256: "076d79742986e1b100b69ebecc691cb07368045e54c9087cef631b8622b76a80";
15
- executable: "Electron.app/Contents/MacOS/Electron";
16
6
  }>;
17
7
  export declare const NETWORK_DEFAULTS: Readonly<{
18
8
  logUpload: false;
package/lib/defaults.js CHANGED
@@ -1,5 +1,4 @@
1
1
  // Owner-approved technical settings (2026-10-20, part two). One source for schema and composition.
2
- export const L_DEFAULTS = Object.freeze({ enrollmentMetadataMaxBytes: 1048576, commandOutputMaxBytes: 1048576, remoteKillGraceMs: 1000, componentDownloadMaxRedirects: 3, componentObservationIntervalMs: 1000, maxDownloadBytes: 200000000, maxExtractedBytes: 600000000, loginOutputMaxBytes: 1048576, ipcMaxBytes: 1048576 });
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' });
2
+ export const L_DEFAULTS = Object.freeze({ enrollmentMetadataMaxBytes: 1048576, commandOutputMaxBytes: 1048576, remoteKillGraceMs: 1000, loginOutputMaxBytes: 1048576 });
4
3
  export const NETWORK_DEFAULTS = Object.freeze({ logUpload: false, statusRefreshIntervalSeconds: 2, dialTimeoutSeconds: 20, headerTimeoutSeconds: 10, enrollmentObservationSeconds: 30, httpMaxHeaderBytes: 1048576, startupObservationSeconds: 35, shutdownObservationSeconds: 10, controlResponseMaxBytes: 65536 });
5
4
  export const WORKSPACE_LOCATION_DEFAULTS = { pageSize: 100 };
@@ -45,11 +45,10 @@ export interface HostDirectoryRequest {
45
45
  path?: string;
46
46
  after?: string;
47
47
  pageSize: number;
48
- expected?: HostDirectoryIdentity;
49
48
  }
50
49
  export interface HostDirectories {
51
50
  browse(target: SshTarget, data: HostDirectoryRequest, signal: AbortSignal): Promise<Result<HostDirectoryData>>;
52
- inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
53
- create?(target: SshTarget, path: string, name: string, expected: HostDirectoryIdentity, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
51
+ inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<Pick<HostDirectoryInfo, 'path'>>>;
52
+ create?(target: SshTarget, path: string, name: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
54
53
  }
55
54
  export declare function createHostDirectories(runner: Runner, maxOutputBytes: number): HostDirectories;
@@ -1,7 +1,7 @@
1
1
  import { readFile } from 'node:fs/promises';
2
2
  import { runRemote } from "./ssh.js";
3
3
  import { fail, ok } from "./needs.js";
4
- import { AuthDiagnosticError } from "./auth-diagnostics.js";
4
+ import { AuthDiagnosticError, authFailure } from "./auth-diagnostics.js";
5
5
  const codes = ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_PAGE_TOO_LARGE', 'PROJECT_PROTOCOL_INVALID', 'HOST_DIRECTORY_EXISTS'];
6
6
  const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
7
7
  const decimal = (value) => typeof value === 'string' && /^\d+$/.test(value);
@@ -18,14 +18,14 @@ function validEntry(value, parent) {
18
18
  return false;
19
19
  if (value.path === undefined || value.identity === undefined)
20
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);
21
+ return validPath(value.path) && validIdentity(value.identity);
22
22
  }
23
23
  const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
24
24
  export function createHostDirectories(runner, maxOutputBytes) {
25
25
  async function request(target, operation, data, signal) {
26
26
  if (signal.aborted)
27
27
  return fail('CONNECTION_LOST');
28
- if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name) || !validIdentity(data.expected)) || 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))))
28
+ 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))))
29
29
  return fail('HOST_DIRECTORY_INVALID');
30
30
  try {
31
31
  const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
@@ -34,7 +34,7 @@ export function createHostDirectories(runner, maxOutputBytes) {
34
34
  if (signal.aborted)
35
35
  return fail('CONNECTION_LOST');
36
36
  if (raw.exitCode !== 0 || raw.stderr !== '')
37
- return fail('CONNECTION_LOST');
37
+ return authFailure('ssh-result', raw.exitCode !== 0 ? 'SSH_EXIT_NONZERO' : 'SSH_STDERR_NONEMPTY', { exitCode: raw.exitCode }, undefined, 'CONNECTION_LOST');
38
38
  if (Buffer.byteLength(raw.stdout, 'utf8') > maxOutputBytes)
39
39
  return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
40
40
  let result;
@@ -49,13 +49,15 @@ export function createHostDirectories(runner, maxOutputBytes) {
49
49
  if (!result.ok) {
50
50
  const error = result.error;
51
51
  const code = object(error) ? codes.find(code => code === error.code) : undefined;
52
- return fail(code ?? 'PROJECT_PROTOCOL_INVALID');
52
+ 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');
53
53
  }
54
+ if (operation === 'inspect')
55
+ return object(result.value) && result.value.path === data.path ? ok({ path: data.path }) : fail('PROJECT_PROTOCOL_INVALID');
54
56
  if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== (operation === 'create' ? (data.path.endsWith('/') ? data.path : data.path + '/') + data.name : data.path))
55
57
  return fail('PROJECT_PROTOCOL_INVALID');
56
58
  if (operation === 'browse') {
57
59
  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]))
60
+ 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))
59
61
  return fail('PROJECT_PROTOCOL_INVALID');
60
62
  }
61
63
  return ok(result.value);
@@ -69,8 +71,8 @@ export function createHostDirectories(runner, maxOutputBytes) {
69
71
  if (error.diagnostic.stage === 'remote-frame')
70
72
  return fail('PROJECT_PROTOCOL_INVALID');
71
73
  }
72
- return fail('CONNECTION_LOST');
74
+ return authFailure('host-directory', 'DIRECTORY_CHECK_EXCEPTION', {}, error, 'CONNECTION_LOST');
73
75
  }
74
76
  }
75
- return { create: (target, path, name, expected, signal) => request(target, 'create', { path, name, expected }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
77
+ return { 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) };
76
78
  }
@@ -1,19 +1,8 @@
1
1
  import type { ConnectApi, HostSessionProjectTarget, Result, WorkspaceUse } from './api.ts';
2
2
  import type { HostWorkspaceResolveContext } from './workspace-location-types.ts';
3
- import type { createWorkspaceLocations } from './workspace-locations.ts';
4
- import type { NativeWorkspaceRegistry } from './native-workspace.ts';
5
- interface Session {
6
- header: Record<string, any>;
7
- }
8
3
  interface Options {
9
- api: ConnectApi;
10
- registry: NativeWorkspaceRegistry;
11
- services: () => {
12
- sessions: {
13
- get(id: string): Session | undefined;
14
- };
15
- };
16
- withHostBinding: ReturnType<typeof createWorkspaceLocations>['withHostBinding'];
4
+ api: Pick<ConnectApi, 'ensureReady' | 'appendRemoteConversationDetail'> & Partial<Pick<ConnectApi, 'getConnectionState'>>;
5
+ hostDirectories?: import('./host-directories.ts').HostDirectories;
17
6
  }
18
7
  export declare function createHostSessionProjects(o: Options): {
19
8
  resolve: (id: string, use: WorkspaceUse, input: HostWorkspaceResolveContext) => Promise<Result<HostSessionProjectTarget>>;
@@ -1,62 +1,77 @@
1
1
  import { basename, isAbsolute } from 'node:path';
2
- import { realpath } from 'node:fs/promises';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import { fail, ok, need, NeedError } from "./needs.js";
2
+ import { randomUUID } from 'node:crypto';
3
+ import { exceptionSummary, outputSummary } from "./auth-diagnostics.js";
4
+ import { ok, need, NeedError } from "./needs.js";
5
5
  const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
6
- function reject(code) { throw new NeedError(need(code)); }
7
- function changedSessionBinding() {
8
- const n = need('PROJECT_BINDING_INVALID');
9
- n.message = '文件来源已改,请新建会话继续';
10
- n.actor = 'employee';
11
- n.requires = '新会话与当前文件来源';
12
- n.action = { id: 'new-session', label: '新建会话继续', available: false };
13
- throw new NeedError(n);
14
- }
6
+ function reject(code, reason) { throw new NeedError({ ...need(code), officialReason: reason }); }
15
7
  export function createHostSessionProjects(o) {
16
- // 同一运行期的重连保留来源选择;不迁移旧测试会话。
17
- const sources = new Map();
8
+ const controllers = new Set();
18
9
  let disposed = false;
19
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
+ };
20
38
  try {
21
39
  if (!text(id) || !use || Object.keys(use).sort().join(',') !== 'provider,purpose' || !['claude', 'codex'].includes(use.provider) || use.purpose !== 'user-turn')
22
- reject('PROJECT_BINDING_REQUIRED');
23
- const provider = use.provider, c = structuredClone(input);
24
- if (!c || Object.keys(c).sort().join(',') !== 'epoch,expectedBindingId,instanceId,workspaceId' || !text(c.instanceId) || !Number.isSafeInteger(c.epoch) || c.epoch < 0 || !text(c.workspaceId) || !text(c.expectedBindingId))
25
- reject('WORKSPACE_LOCATION_INVALID');
26
- const session = o.services().sessions.get(id);
27
- if (!session || session.header.id !== id || !text(session.header.cwd) || !isAbsolute(session.header.cwd))
28
- reject('PROJECT_BINDING_REQUIRED');
29
- const header = structuredClone(session.header), source = { workspaceId: c.workspaceId, bindingId: c.expectedBindingId, source: 'host' };
30
- const guard = () => {
31
- const now = o.api.getConnectionState();
32
- if (disposed || now.phase === 'disposed')
33
- reject('DISPOSED');
34
- if (now.phase !== 'connected' || now.instanceId !== c.instanceId || now.epoch !== c.epoch)
35
- reject('CONNECTION_LOST');
36
- const matches = o.registry.list().filter(w => w.sessionIds.includes(id)), registered = o.registry.get(c.workspaceId);
37
- if (matches.length !== 1 || matches[0].id !== c.workspaceId || !registered || registered.path !== matches[0].path || !registered.sessionIds.includes(id))
38
- changedSessionBinding();
39
- if (o.services().sessions.get(id) !== session || !isDeepStrictEqual(session.header, header))
40
- reject('PROJECT_BINDING_INVALID');
41
- const previous = sources.get(id);
42
- if (previous && !isDeepStrictEqual(previous, source))
43
- changedSessionBinding();
44
- };
45
- guard();
46
- return await o.withHostBinding(c, async (value) => {
47
- if (await realpath(header.cwd) !== value.local.path)
48
- reject('WORKSPACE_LOCATION_INVALID');
49
- const ready = await o.api.ensureReady(provider);
50
- if (!ready.ok)
51
- return ready;
52
- if (!isDeepStrictEqual(ready.value, value.target))
53
- reject('CONNECTION_LOST');
54
- return ok({ instanceId: c.instanceId, epoch: c.epoch, sessionId: id, workspaceId: c.workspaceId, bindingId: c.expectedBindingId, bindingRevision: value.revision, source: 'host', directory: structuredClone(value.directory), project: { name: basename(value.directory.path) || '/', path: value.directory.path }, target: structuredClone(value.target) });
55
- }, () => { guard(); sources.set(id, source); });
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 ready = await o.api.ensureReady(use.provider);
48
+ if (!ready.ok)
49
+ return failure(new NeedError(ready.error));
50
+ if (disposed)
51
+ reject('DISPOSED', 'RUNTIME_DISPOSED');
52
+ if (ready.value.host !== source.host)
53
+ reject('WORKSPACE_LOCATION_INVALID', 'SESSION_HOST_UNAVAILABLE');
54
+ if (!o.hostDirectories)
55
+ reject('DEPENDENCY_REQUIRED', 'HOST_DIRECTORY_SERVICE_REQUIRED');
56
+ const controller = new AbortController();
57
+ controllers.add(controller);
58
+ try {
59
+ stage = 'host-directory';
60
+ const checked = await o.hostDirectories.inspect(ready.value, source.path, controller.signal);
61
+ if (!checked.ok)
62
+ return failure(new NeedError(checked.error));
63
+ if (disposed)
64
+ reject('DISPOSED', 'RUNTIME_DISPOSED');
65
+ return ok({ sessionId: id, source: 'host', host: source.host, project: { name: basename(source.path) || '/', path: source.path }, target: structuredClone(ready.value) });
66
+ }
67
+ finally {
68
+ controllers.delete(controller);
69
+ }
56
70
  }
57
71
  catch (e) {
58
- return e instanceof NeedError ? { ok: false, error: e.need } : fail('PROJECT_BINDING_INVALID');
72
+ return failure(e);
59
73
  }
60
74
  }
61
- return { resolve, dispose() { disposed = true; } };
75
+ return { resolve, dispose() { disposed = true; for (const controller of controllers)
76
+ controller.abort(); } };
62
77
  }
package/lib/index.d.ts CHANGED
@@ -24,17 +24,8 @@ export interface Config {
24
24
  commandOutputMaxBytes?: number;
25
25
  network?: (NetworkSettings & AssemblySettings);
26
26
  helper?: {
27
- componentObservationIntervalMs?: number;
28
- componentDownloadMaxRedirects?: number;
29
27
  remoteKillGraceMs?: number;
30
- maxRedirects?: number;
31
- sha256?: string;
32
- cacheDir?: string;
33
- maxDownloadBytes?: number;
34
- maxExtractedBytes?: number;
35
- executable?: string;
36
28
  loginOutputMaxBytes?: number;
37
- ipcMaxBytes?: number;
38
29
  };
39
30
  }
40
31
  export declare const Config: z<Config>;
package/lib/index.js CHANGED
@@ -5,8 +5,6 @@ import { createConnect } from "./connect.js";
5
5
  import { configuredPorts } from "./integration.js";
6
6
  import { attachProfileRuntime } from "./profile-runtime.js";
7
7
  import { profileSettings } from "./profile-settings.js";
8
- import { createComponentSources } from "./component-source.js";
9
- import { createComponentProgress } from "./component-download.js";
10
8
  import { L_DEFAULTS, NETWORK_DEFAULTS } from "./defaults.js";
11
9
  import { registerComponents } from "./components.js";
12
10
  export { writeNetworkConfig } from "./network.js";
@@ -28,13 +26,8 @@ export const Config = z.object({
28
26
  commandOutputMaxBytes: positive().default(L_DEFAULTS.commandOutputMaxBytes).description('远程命令输出内存上限(字节),默认1048576,管理员可修改'),
29
27
  network: z.object({ executable: z.string(), runtimeDir: z.string(), stateDir: z.string(), configFile: z.string(), helperLogFile: z.string(), nodeName: z.string(), startupObservationSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.startupObservationSeconds), shutdownObservationSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.shutdownObservationSeconds), controlResponseMaxBytes: positive().default(NETWORK_DEFAULTS.controlResponseMaxBytes), logUpload: z.boolean().default(NETWORK_DEFAULTS.logUpload), statusRefreshIntervalSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.statusRefreshIntervalSeconds), dialTimeoutSeconds: z.number().min(1e-9).default(NETWORK_DEFAULTS.dialTimeoutSeconds), headerTimeoutSeconds: z.number().min(0.001).max(2147483.647).default(NETWORK_DEFAULTS.headerTimeoutSeconds), enrollmentObservationSeconds: z.number().min(1e-9).default(NETWORK_DEFAULTS.enrollmentObservationSeconds), httpMaxHeaderBytes: positive().default(NETWORK_DEFAULTS.httpMaxHeaderBytes), controlMaxBytes: positive() }).description('远程网络连接设置:使用默认技术参数,管理员可修改;路径根据当前用户和应用配置目录生成,员工无需填写'),
30
28
  helper: z.object({
31
- componentObservationIntervalMs: z.number().step(1).min(1).max(2147483647).default(L_DEFAULTS.componentObservationIntervalMs).description('无进展观察刷新间隔毫秒,默认1000;只刷新秒数,不超时/重试/换源'),
32
- componentDownloadMaxRedirects: z.number().step(1).min(0).default(L_DEFAULTS.componentDownloadMaxRedirects).description('组件直接HTTPS下载的重定向次数上限;默认3,0拒绝重定向;管理员可改,不改变网页登录网络'),
33
29
  remoteKillGraceMs: z.number().step(1).min(0).max(2147483647).default(L_DEFAULTS.remoteKillGraceMs).description('远端本轮登录进程组结束宽限毫秒;默认1000,0立即KILL,管理员可改'),
34
- maxRedirects: z.number().step(1).min(0).description('兼容旧配置;此项不再生效'),
35
- sha256: z.string().description('darwin-arm64默认使用Electron 44.0.0对应的下载SHA256;管理员可改,必须校验'),
36
- cacheDir: z.string().description('默认从当前profile自动派生ai-workbench-connect/login-component-cache;管理员可改,员工不填路径'), maxDownloadBytes: positive().default(L_DEFAULTS.maxDownloadBytes).description('下载字节上限;默认200000000,管理员可改'), maxExtractedBytes: positive().default(L_DEFAULTS.maxExtractedBytes).description('解压字节上限;默认600000000,管理员可改'),
37
- 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,管理员可改'),
30
+ loginOutputMaxBytes: positive().default(L_DEFAULTS.loginOutputMaxBytes).description('登录进程输出字节上限;默认1048576,管理员可改'),
38
31
  }),
39
32
  });
40
33
  export function register(ctx, ports, _inventory, extend, autoStart = true) {
@@ -47,12 +40,10 @@ export function register(ctx, ports, _inventory, extend, autoStart = true) {
47
40
  }
48
41
  export function apply(ctx, config = {}) {
49
42
  config = profileSettings(config, ctx.get('profileContext')?.dir);
50
- const network = ctx.get('aiWorkbenchNetwork'), component = createComponentProgress();
51
- const sources = createComponentSources({ sha256: config.helper?.sha256 });
52
- ctx.effect(() => () => sources.dispose());
53
- const ports = configuredPorts(config, network, component, sources);
43
+ const network = ctx.get('aiWorkbenchNetwork');
44
+ const ports = configuredPorts(config, network);
54
45
  register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network, true), false);
55
- registerComponents(ctx, config.inventory, config.helper?.cacheDir, component, sources, config.helper?.componentObservationIntervalMs, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
46
+ registerComponents(ctx, config.inventory, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
56
47
  }
57
48
  export { createProfileEnrollment } from "./profile-enrollment.js";
58
49
  export { profileSettings } from "./profile-settings.js";
@@ -1,6 +1,4 @@
1
- import type { ComponentSources } from './component-source.ts';
2
1
  import type { RuntimeConfig } from './profile-settings.ts';
3
2
  import type { Ports } from './ports.ts';
4
3
  import { type NetworkProvider } from './provider.ts';
5
- import { type ComponentProgressStore } from './component-download.ts';
6
- export declare function configuredPorts(config: RuntimeConfig, provider?: NetworkProvider, component?: ComponentProgressStore, sources?: ComponentSources): Ports;
4
+ export declare function configuredPorts(config: RuntimeConfig, provider?: NetworkProvider): Ports;
@@ -1,19 +1,15 @@
1
+ import { createBrowserLogin } from "./browser-login.js";
1
2
  import { createHostDirectories } from "./host-directories.js";
2
- import { ComponentDownloadError } from "./component-download.js";
3
- import { fileURLToPath } from 'node:url';
4
3
  import { readEnrollment } from "./enrollment.js";
5
4
  import { adaptNetwork } from "./provider.js";
6
5
  import { createRunner, createRemoteLogin } from "./processes.js";
7
6
  import { createSsh, sshArgs } from "./ssh.js";
8
7
  import { remoteLoginCommand } from "./remote-login.js";
9
8
  import { runLogin } from "./login.js";
10
- import { ensureHelper } from "./cache.js";
11
- import { launchElectron } from "./electron.js";
12
9
  import { parseLoginStatus } from "./auth-status.js";
13
10
  import { authFailure } from "./auth-diagnostics.js";
14
- import { need, fail, ok } from "./needs.js";
15
- import { createComponentProgress, downloadComponent } from "./component-download.js";
16
- export function configuredPorts(config, provider, component = createComponentProgress(), sources) {
11
+ import { fail, ok } from "./needs.js";
12
+ export function configuredPorts(config, provider) {
17
13
  const ports = {};
18
14
  const network = provider ? adaptNetwork(provider) : undefined;
19
15
  if (config.enrollmentPackageDir && config.trustDir)
@@ -29,25 +25,11 @@ export function configuredPorts(config, provider, component = createComponentPro
29
25
  ports.ssh = { verify: async () => fail('SETTINGS_REQUIRED'), status: async () => fail('SETTINGS_REQUIRED') };
30
26
  if (network) {
31
27
  ports.network = network;
32
- ports.login = { run: async (target, provider, signal) => {
28
+ ports.login = { interaction: createBrowserLogin(), run: async (target, provider, signal) => {
33
29
  const h = config.helper;
34
- if (!h || !Number.isSafeInteger(h.remoteKillGraceMs) || h.remoteKillGraceMs < 0 || h.remoteKillGraceMs > 2147483647 || ![h.source, h.sha256, h.cacheDir, h.executable].every(x => typeof x === 'string' && x) || !Number.isSafeInteger(h.componentDownloadMaxRedirects) || h.componentDownloadMaxRedirects < 0 || ![h.maxDownloadBytes, h.maxExtractedBytes, h.loginOutputMaxBytes, h.ipcMaxBytes].every(x => Number.isSafeInteger(x) && x > 0))
35
- return { ok: false, error: need('SETTINGS_REQUIRED') };
36
- let selection;
37
- try {
38
- selection = await sources?.resolve();
39
- }
40
- catch (e) {
41
- return { ok: false, error: { ...need('SETTINGS_REQUIRED'), officialReason: e instanceof ComponentDownloadError ? e.message : 'COMPONENT_SOURCE_STATE_INVALID' } };
42
- }
43
- const cancellation = new AbortController(), downloadSignal = AbortSignal.any([signal, cancellation.signal]);
44
- const attempt = component.begin(selection, () => cancellation.abort());
45
- const result = await ensureHelper({ ...h, source: selection?.source ?? h.source }, { download: source => downloadComponent(source, downloadSignal, h.componentDownloadMaxRedirects), signal: downloadSignal, onProgress: attempt.update });
46
- if (!result.ok)
47
- return result;
48
- if (signal.aborted)
49
- return fail('LOGIN_FAILED');
50
- // Component preparation may outlive another device's completed login. Recheck immediately before any destructive CLI authorization.
30
+ if (!h || !Number.isSafeInteger(h.remoteKillGraceMs) || h.remoteKillGraceMs < 0 || h.remoteKillGraceMs > 2147483647 || !Number.isSafeInteger(h.loginOutputMaxBytes) || h.loginOutputMaxBytes < 1)
31
+ return fail('SETTINGS_REQUIRED');
32
+ // Another device may already have completed login: check before starting the CLI.
51
33
  if (!ports.ssh)
52
34
  return authFailure('integration-pre-login', 'SSH_PORT_MISSING');
53
35
  try {
@@ -67,7 +49,7 @@ export function configuredPorts(config, provider, component = createComponentPro
67
49
  }
68
50
  return runLogin(target, provider, {
69
51
  start: (t, p, s) => createRemoteLogin('ssh', [...sshArgs(t), remoteLoginCommand(p, h.remoteKillGraceMs)], p, h.loginOutputMaxBytes, s, 'remote-control'),
70
- open: (boot, onCode, s) => launchElectron({ executable: result.value, entry: fileURLToPath(new URL('../helper/main.cjs', import.meta.url)), cacheDir: h.cacheDir, ipcMaxBytes: h.ipcMaxBytes }, boot, onCode, s),
52
+ open: (boot, onCode, s) => ports.login.interaction.open(boot, onCode, s),
71
53
  }, signal);
72
54
  } };
73
55
  }
package/lib/login.d.ts CHANGED
@@ -19,13 +19,13 @@ export interface RemoteLogin {
19
19
  writeCode(code: string): Promise<void>;
20
20
  close(): Promise<void>;
21
21
  }
22
- export interface LoginWindow {
22
+ export interface LoginInteraction {
23
23
  closed: Promise<void>;
24
24
  close(): Promise<void>;
25
25
  }
26
26
  export interface LoginPorts {
27
27
  start(t: SshTarget, p: Provider, s: AbortSignal): Promise<RemoteLogin>;
28
- open(boot: LoginBoot, onCode: (code: string) => Promise<void>, s: AbortSignal): Promise<LoginWindow>;
28
+ open(boot: LoginBoot, onCode: (code: string) => Promise<void>, s: AbortSignal): Promise<LoginInteraction>;
29
29
  }
30
30
  export declare function extractLoginUrl(provider: Provider, text: string): string | undefined;
31
31
  export declare function runLogin(t: SshTarget, p: Provider, ports: LoginPorts, parentSignal: AbortSignal): Promise<Result<void>>;
package/lib/login.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createRequire } from 'node:module';
2
- const { isClaudeAuthorizeUrl, validateClaudePaste } = createRequire(import.meta.url)('../helper/claude-callback.cjs');
3
- import { fail, NeedError } from "./needs.js";
2
+ const { isClaudeAuthorizeUrl, isClaudeManualAuthorizeUrl, validateClaudePaste } = createRequire(import.meta.url)('../helper/claude-callback.cjs');
3
+ import { fail, need, NeedError } from "./needs.js";
4
4
  export function extractLoginUrl(provider, text) {
5
5
  for (const match of text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '').matchAll(/https:\/\/[^\s<>"']+/g)) {
6
6
  try {
@@ -18,8 +18,9 @@ export async function runLogin(t, p, ports, parentSignal) {
18
18
  parentSignal.addEventListener('abort', parentAbort, { once: true });
19
19
  if (parentSignal.aborted)
20
20
  controller.abort();
21
- let remote, window, remove = () => { };
21
+ let remote, interaction, remove = () => { };
22
22
  let result = fail('LOGIN_FAILED');
23
+ const codeFailure = (message) => ({ ok: false, error: { ...need('LOGIN_FAILED'), message } });
23
24
  try {
24
25
  if (signal.aborted)
25
26
  return result;
@@ -28,7 +29,7 @@ export async function runLogin(t, p, ports, parentSignal) {
28
29
  const url = await Promise.race([remote.url, cancelled]);
29
30
  if (!url.ok)
30
31
  return url;
31
- if (typeof url.value !== 'string' || extractLoginUrl(p, url.value) !== url.value)
32
+ if (typeof url.value !== 'string' || extractLoginUrl(p, url.value) !== url.value || p === 'claude' && !isClaudeManualAuthorizeUrl(url.value))
32
33
  return result;
33
34
  let deviceCode;
34
35
  if (p === 'codex') {
@@ -42,10 +43,10 @@ export async function runLogin(t, p, ports, parentSignal) {
42
43
  let codeSent = false, codeError = () => { };
43
44
  const failedCode = new Promise(r => codeError = r);
44
45
  const boot = p === 'claude' ? { provider: p, url: url.value } : { provider: p, url: url.value, deviceCode: deviceCode };
45
- window = await ports.open(boot, async (code) => {
46
+ interaction = await ports.open(boot, async (code) => {
46
47
  if (p !== 'claude' || codeSent || signal.aborted || !validateClaudePaste(url.value, code)) {
47
- codeError(fail('LOGIN_FAILED'));
48
- return;
48
+ codeError(codeFailure('授权码格式不正确或不属于本次登录,请重新发起登录。'));
49
+ throw Error('LOGIN_CODE_REJECTED');
49
50
  }
50
51
  codeSent = true;
51
52
  try {
@@ -53,9 +54,10 @@ export async function runLogin(t, p, ports, parentSignal) {
53
54
  }
54
55
  catch {
55
56
  codeError(fail('LOGIN_FAILED'));
57
+ throw Error('LOGIN_STDIN_FAILED');
56
58
  }
57
59
  }, signal);
58
- result = await Promise.race([remote.completion, window.closed.then(() => fail('LOGIN_FAILED')), failedCode, cancelled]);
60
+ result = await Promise.race([remote.completion.then(r => !r.ok && p === 'claude' ? codeFailure('本次 Claude 登录未完成,主机未确认成功。请重新发起登录。') : r), interaction.closed.then(() => fail('LOGIN_FAILED')), failedCode, cancelled]);
59
61
  }
60
62
  catch (error) {
61
63
  result = error instanceof NeedError ? { ok: false, error: error.need } : fail('LOGIN_FAILED');
@@ -64,7 +66,7 @@ export async function runLogin(t, p, ports, parentSignal) {
64
66
  remove();
65
67
  parentSignal.removeEventListener('abort', parentAbort);
66
68
  // Attempt every cleanup even when one resource fails; surface failure instead of success.
67
- const cleanup = await Promise.allSettled([window?.close(), remote?.close()]);
69
+ const cleanup = await Promise.allSettled([interaction?.close(), remote?.close()]);
68
70
  if (cleanup.some(r => r.status === 'rejected'))
69
71
  result = fail('LOGIN_FAILED');
70
72
  }