@ai-workbench/connect 0.7.22 → 0.7.26

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 (62) hide show
  1. package/README.md +20 -67
  2. package/client/index.cjs +93 -65
  3. package/helper/host-directories.cjs +8 -1
  4. package/lib/api.d.ts +21 -163
  5. package/lib/component-download.d.ts +1 -1
  6. package/lib/component-download.js +1 -1
  7. package/lib/component-source.d.ts +6 -27
  8. package/lib/component-source.js +10 -138
  9. package/lib/components.d.ts +1 -1
  10. package/lib/components.js +86 -98
  11. package/lib/connect.d.ts +0 -3
  12. package/lib/connect.js +15 -62
  13. package/lib/connection-messages.d.ts +2 -3
  14. package/lib/connection-messages.js +5 -4
  15. package/lib/conversation-log.d.ts +9 -0
  16. package/lib/conversation-log.js +44 -0
  17. package/lib/cordis.d.ts +1 -4
  18. package/lib/defaults.d.ts +0 -7
  19. package/lib/defaults.js +0 -2
  20. package/lib/enrollment.js +1 -8
  21. package/lib/host-directories.d.ts +6 -4
  22. package/lib/host-directories.js +4 -4
  23. package/lib/host-session-projects.d.ts +8 -58
  24. package/lib/host-session-projects.js +45 -270
  25. package/lib/index.d.ts +2 -11
  26. package/lib/index.js +11 -23
  27. package/lib/integration.d.ts +2 -2
  28. package/lib/integration.js +0 -2
  29. package/lib/native-workspace.d.ts +10 -0
  30. package/lib/needs.js +13 -25
  31. package/lib/ports.d.ts +1 -6
  32. package/lib/profile-runtime.js +59 -152
  33. package/lib/profile-settings.d.ts +6 -1
  34. package/lib/profile-settings.js +3 -5
  35. package/lib/startup.js +2 -2
  36. package/lib/workspace-directory-picker-types.d.ts +44 -0
  37. package/lib/workspace-directory-picker-types.js +1 -0
  38. package/lib/workspace-directory-picker.d.ts +30 -0
  39. package/lib/workspace-directory-picker.js +394 -0
  40. package/lib/workspace-location-types.d.ts +3 -7
  41. package/lib/workspace-locations.d.ts +6 -30
  42. package/lib/workspace-locations.js +83 -177
  43. package/package.json +3 -2
  44. package/helper/projects.cjs +0 -57
  45. package/lib/conversation-detail-settings.d.ts +0 -32
  46. package/lib/conversation-detail-settings.js +0 -119
  47. package/lib/conversation-details.d.ts +0 -30
  48. package/lib/conversation-details.js +0 -591
  49. package/lib/host-session-store.d.ts +0 -27
  50. package/lib/host-session-store.js +0 -130
  51. package/lib/local-acceptance-store.d.ts +0 -18
  52. package/lib/local-acceptance-store.js +0 -133
  53. package/lib/local-user-turn-acceptance.d.ts +0 -76
  54. package/lib/local-user-turn-acceptance.js +0 -289
  55. package/lib/local-user-turn-types.d.ts +0 -40
  56. package/lib/login-diagnostics.d.ts +0 -28
  57. package/lib/login-diagnostics.js +0 -57
  58. package/lib/projects.d.ts +0 -4
  59. package/lib/projects.js +0 -41
  60. package/lib/workspace-bindings.d.ts +0 -64
  61. package/lib/workspace-bindings.js +0 -379
  62. /package/lib/{local-user-turn-types.js → native-workspace.js} +0 -0
package/lib/components.js CHANGED
@@ -1,8 +1,7 @@
1
1
  import { connectionEmployeeMessage } from "./connection-messages.js";
2
- import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
3
- import { ComponentDownloadError } from "./component-download.js";
4
2
  import { L_DEFAULTS } from "./defaults.js";
5
- import { fail } from "./needs.js";
3
+ import { fail, ok } from "./needs.js";
4
+ import { isAbsolute } from 'node:path';
6
5
  import { employeeMessage } from "./startup.js";
7
6
  const record = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
8
7
  const text = (value) => typeof value === 'string' && value.length > 0 && !value.includes('\0');
@@ -21,20 +20,19 @@ function validLocationInput(operation, value) {
21
20
  return false;
22
21
  }
23
22
  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)
23
+ extra = value.source === 'local' ? ['source'] : value.source === 'host' ? ['source', 'selectionToken'] : [];
24
+ if (!extra.length || value.source === 'host' && !text(value.selectionToken))
26
25
  return false;
27
26
  }
28
27
  else
29
28
  return false;
30
29
  return Object.keys(value).every(key => [...context, ...extra].includes(key));
31
30
  }
32
- export function registerComponents(ctx, inventory, temporaryDataParent, component, sources, observationIntervalMs = L_DEFAULTS.componentObservationIntervalMs, metadataMaxBytes = L_DEFAULTS.enrollmentMetadataMaxBytes, administratorAfterMs = CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs) {
33
- const detailSettings = () => ctx.get('aiWorkbenchConversationDetailSettings');
31
+ export function registerComponents(ctx, inventory, temporaryDataParent, component, sources, observationIntervalMs = L_DEFAULTS.componentObservationIntervalMs, metadataMaxBytes = L_DEFAULTS.enrollmentMetadataMaxBytes) {
34
32
  const api = () => ctx.get('aiWorkbenchConnect');
35
33
  const getState = () => {
36
34
  const network = ctx.get('aiWorkbenchNetwork'), connect = api(), state = connect?.getState(), networkState = network?.getState();
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: '组件清单未装配' } };
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: '组件清单未装配' } };
38
36
  };
39
37
  ctx.provide('aiWorkbenchComponents', { getState });
40
38
  ctx.inject(['webServer', 'connection'], host => {
@@ -55,9 +53,9 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
55
53
  res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
56
54
  res.statusCode = 200;
57
55
  let closed = false;
58
- let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, unnative = () => { }, undownload = () => { }, unsource = () => { }, undetails = () => { }, unloginDetails = () => { }, undetailsettings = () => { }, unlocations = () => { };
56
+ let unprompt = () => { }, unconnection = () => { }, unenrollment = () => { }, undownload = () => { }, unsource = () => { }, unlocations = () => { };
59
57
  const close = () => { if (closed)
60
- return; closed = true; unprompt(); unconnection(); unenrollment(); unnative(); undownload(); unsource(); undetails(); unloginDetails(); undetailsettings(); unlocations(); streams.delete(close); res.end(); };
58
+ return; closed = true; unprompt(); unconnection(); unenrollment(); undownload(); unsource(); unlocations(); streams.delete(close); res.end(); };
61
59
  const send = () => { if (closed)
62
60
  return; try {
63
61
  if (!res.write('data: ' + JSON.stringify(getState()) + '\n\n'))
@@ -69,18 +67,87 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
69
67
  unprompt = service.onLoginPromptState(send);
70
68
  unconnection = service.onConnectionState(send);
71
69
  unenrollment = service.onEnrollmentState?.(send) ?? (() => { });
72
- unnative = service.onWorkspaceBindingState?.(send) ?? (() => { });
73
70
  undownload = component?.onState(send) ?? (() => { });
74
71
  unsource = sources?.onState(send) ?? (() => { });
75
- undetails = service.onRemoteConversationDetailState?.(send) ?? (() => { });
76
- unloginDetails = service.onLoginDiagnosticState?.(send) ?? (() => { });
77
- undetailsettings = detailSettings()?.onState(send) ?? (() => { });
78
72
  unlocations = service.onWorkspaceLocationState?.(send) ?? (() => { });
79
73
  streams.add(close);
80
74
  res.once('close', close);
81
75
  send();
82
76
  return;
83
77
  }
78
+ if (/^\/ai-workbench-connect\/directory-picker\/(config|browse|select|create)$/.test(path)) {
79
+ res.setHeader('Content-Type', 'application/json; charset=utf-8');
80
+ const operation = path.split('/').at(-1);
81
+ const respond = (status, value) => { res.statusCode = status; res.end(JSON.stringify(value)); };
82
+ const invalid = () => respond(400, fail('WORKSPACE_PICKER_INVALID'));
83
+ if (operation === 'config' ? req.method !== 'GET' : req.method !== 'POST') {
84
+ invalid();
85
+ return;
86
+ }
87
+ let body = {};
88
+ if (operation !== 'config') {
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 part = Buffer.from(chunk);
98
+ bytes += part.length;
99
+ if (bytes > metadataMaxBytes) {
100
+ invalid();
101
+ return;
102
+ }
103
+ chunks.push(part);
104
+ }
105
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
106
+ if (!record(parsed)) {
107
+ invalid();
108
+ return;
109
+ }
110
+ body = parsed;
111
+ }
112
+ catch {
113
+ invalid();
114
+ return;
115
+ }
116
+ const keys = Object.keys(body);
117
+ if (operation === 'create') {
118
+ if (keys.length !== 2 || keys.some(k => !['selectionToken', 'name'].includes(k)) || !text(body.selectionToken) || !text(body.name)) {
119
+ invalid();
120
+ return;
121
+ }
122
+ }
123
+ else if (operation === 'select') {
124
+ if (keys.length !== 1 || keys[0] !== 'selectionToken' || !text(body.selectionToken)) {
125
+ invalid();
126
+ return;
127
+ }
128
+ }
129
+ else if (keys.some(k => !['target', 'path', 'cursor'].includes(k)) || body.target !== undefined && !['local', 'host'].includes(body.target) || body.path !== undefined && (!text(body.path) || !isAbsolute(body.path)) || body.cursor !== undefined && !text(body.cursor) || body.path !== undefined && body.cursor !== undefined) {
130
+ invalid();
131
+ return;
132
+ }
133
+ }
134
+ if (!service || service.getContractInfo?.().workspaceDirectoryPicker !== 1 || typeof service.getWorkspaceDirectoryPickerSettings !== 'function' || typeof service.browseWorkspaceDirectories !== 'function' || typeof service.selectWorkspaceDirectory !== 'function') {
135
+ respond(503, fail('DEPENDENCY_REQUIRED'));
136
+ return;
137
+ }
138
+ if (operation === 'create' && typeof service.createWorkspaceDirectory !== 'function') {
139
+ respond(503, fail('DEPENDENCY_REQUIRED'));
140
+ return;
141
+ }
142
+ try {
143
+ const result = operation === 'create' ? await service.createWorkspaceDirectory(body) : operation === 'config' ? ok(service.getWorkspaceDirectoryPickerSettings()) : operation === 'browse' ? await service.browseWorkspaceDirectories(body) : await service.selectWorkspaceDirectory(body);
144
+ respond(result.ok ? 200 : 409, result);
145
+ }
146
+ catch {
147
+ respond(503, fail('WORKSPACE_PICKER_STORAGE_FAILED'));
148
+ }
149
+ return;
150
+ }
84
151
  if (req.method === 'POST' && /^\/ai-workbench-connect\/workspace-locations\/(refresh|browse|select)$/.test(path)) {
85
152
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
86
153
  const invalid = () => { res.statusCode = 400; res.end(JSON.stringify(fail('WORKSPACE_LOCATION_INVALID'))); };
@@ -128,70 +195,18 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
128
195
  }
129
196
  return;
130
197
  }
131
- if (req.method === 'GET' && ['/ai-workbench-connect/login-diagnostics', '/ai-workbench-connect/login-diagnostic-receipt'].includes(path)) {
198
+ if (req.method === 'GET' && path === '/ai-workbench-connect/conversation-log') {
132
199
  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
- }
156
- if (req.method === 'GET' && ['/ai-workbench-connect/conversation-details', '/ai-workbench-connect/conversation-detail-receipt'].includes(path) && service) {
157
- const params = new URL(req.url ?? '/', 'http://dsh').searchParams, isReceipt = path.endsWith('/conversation-detail-receipt'), allowed = isReceipt ? ['sessionId', 'provider', 'eventId'] : ['sessionId', 'provider', 'cursor'];
158
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
159
- if ([...params.keys()].some(k => !allowed.includes(k) || params.getAll(k).length !== 1)) {
160
- res.statusCode = 400;
161
- res.end(JSON.stringify(fail('REMOTE_DETAIL_INVALID')));
200
+ if (!service || typeof service.readConversationLog !== 'function') {
201
+ res.statusCode = 503;
202
+ res.end(JSON.stringify(fail('DEPENDENCY_REQUIRED')));
162
203
  return;
163
204
  }
164
- const query = { sessionId: params.get('sessionId') ?? '', provider: params.get('provider') };
165
- const result = isReceipt ? await service.getRemoteConversationDetailReceipt({ ...query, eventId: params.get('eventId') ?? '' }) : await service.listRemoteConversationDetails({ ...query, ...(params.has('cursor') ? { cursor: params.get('cursor') } : {}) });
205
+ const result = await service.readConversationLog();
166
206
  res.statusCode = result.ok ? 200 : 409;
167
207
  res.end(JSON.stringify(result));
168
208
  return;
169
209
  }
170
- if (req.method === 'POST' && path === '/ai-workbench-connect/conversation-detail-settings' && detailSettings()) {
171
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
172
- try {
173
- const chunks = [];
174
- let bytes = 0;
175
- for await (const chunk of req) {
176
- const data = Buffer.from(chunk);
177
- bytes += data.length;
178
- if (!Number.isSafeInteger(metadataMaxBytes) || metadataMaxBytes < 1 || bytes > metadataMaxBytes) {
179
- res.statusCode = 400;
180
- res.end(JSON.stringify({ ...getState(), actionErrorCode: 'SETTINGS_REQUIRED', actionError: '设置未保存:输入超出 enrollmentMetadataMaxBytes,请仅提交两项正安全整数。' }));
181
- return;
182
- }
183
- chunks.push(data);
184
- }
185
- const result = await detailSettings().save(JSON.parse(Buffer.concat(chunks).toString('utf8')));
186
- res.statusCode = result.ok ? 200 : 409;
187
- res.end(JSON.stringify({ ...getState(), ...(!result.ok ? { actionErrorCode: result.error.code, actionError: result.error.message } : {}) }));
188
- }
189
- catch {
190
- res.statusCode = 400;
191
- res.end(JSON.stringify({ ...getState(), actionErrorCode: 'SETTINGS_REQUIRED', actionError: '设置未保存:请输入两项正安全整数。' }));
192
- }
193
- return;
194
- }
195
210
  if (req.method === 'POST' && /^\/ai-workbench-connect\/component-download\/cancel\/[a-zA-Z0-9-]+$/.test(path) && component) {
196
211
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
197
212
  if (Number(req.headers?.['content-length'] ?? 0) > 0 || req.headers?.['transfer-encoding']) {
@@ -204,24 +219,6 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
204
219
  res.end(JSON.stringify({ ...getState(), ...(!cancelled ? { actionErrorCode: 'COMPONENT_DOWNLOAD_NOT_ACTIVE', actionError: '该组件下载已经结束或更新,请使用当前状态。' } : {}) }));
205
220
  return;
206
221
  }
207
- if (req.method === 'POST' && /^\/ai-workbench-connect\/component-source\/(github|npmmirror)$/.test(path) && sources) {
208
- res.setHeader('Content-Type', 'application/json; charset=utf-8');
209
- if (Number(req.headers?.['content-length'] ?? 0) > 0 || req.headers?.['transfer-encoding']) {
210
- res.statusCode = 400;
211
- res.end(JSON.stringify({ error: 'no-input-accepted' }));
212
- return;
213
- }
214
- try {
215
- await sources.select(path.split('/').at(-1));
216
- res.statusCode = 200;
217
- res.end(JSON.stringify(getState()));
218
- }
219
- catch (e) {
220
- res.statusCode = 409;
221
- res.end(JSON.stringify({ ...getState(), actionErrorCode: e instanceof ComponentDownloadError ? e.message : 'COMPONENT_SOURCE_STATE_INVALID', actionError: '下载源未更改;请结束当前下载或授权后重选,或检查技术详情。' }));
222
- }
223
- return;
224
- }
225
222
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
226
223
  let actionError, actionErrorCode;
227
224
  if (req.method === 'POST' && service) {
@@ -234,15 +231,6 @@ export function registerComponents(ctx, inventory, temporaryDataParent, componen
234
231
  }
235
232
  result = await service.importEnrollment();
236
233
  }
237
- else if (/^\/ai-workbench-connect\/workspace-notice\/[a-zA-Z0-9-]+\/displayed$/.test(path)) {
238
- if (Number(req.headers?.['content-length'] ?? 0) > 0 || req.headers?.['transfer-encoding']) {
239
- res.statusCode = 400;
240
- res.end(JSON.stringify({ error: 'no-input-accepted' }));
241
- return;
242
- }
243
- const id = /\/workspace-notice\/([a-zA-Z0-9-]+)\/displayed$/.exec(path)[1];
244
- result = await service.acknowledgeWorkspaceNotice({ noticeId: id, surface: 'settings', outcome: 'displayed' });
245
- }
246
234
  else if (path === '/ai-workbench-connect/check')
247
235
  result = await service.refreshLoginPrompts();
248
236
  else if (/^\/ai-workbench-connect\/start-login\/(claude|codex)\/[a-zA-Z0-9-]+\/\d+$/.test(path)) {
package/lib/connect.d.ts CHANGED
@@ -2,9 +2,6 @@ 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
- };
8
5
  providers?: Provider[];
9
6
  onConnectionState?: (s: ConnectionState) => void;
10
7
  onPromptState?: (s: LoginPromptState) => void;
package/lib/connect.js CHANGED
@@ -1,8 +1,6 @@
1
- import { CONNECTION_MESSAGES, connectionEmployeeMessage, isConnectionInterruption } from "./connection-messages.js";
2
- import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
1
+ import { connectionEmployeeMessage, isConnectionInterruption } from "./connection-messages.js";
3
2
  import { randomUUID } from 'node:crypto';
4
3
  import { dependency, fail as baseFail, ok, need } from "./needs.js";
5
- import { isProjectName } from "./projects.js";
6
4
  import { createStartup } from "./startup.js";
7
5
  import { parseLoginStatus } from "./auth-status.js";
8
6
  import { authFailure } from "./auth-diagnostics.js";
@@ -24,29 +22,13 @@ export function createConnect(ports, emit, options = {}) {
24
22
  let startup;
25
23
  const fail = (code) => { const result = baseFail(code), message = connectionEmployeeMessage(connection); if (!result.ok && message && isConnectionInterruption(code))
26
24
  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; };
25
+ let recovery;
26
+ const stopRecovery = () => { recovery = undefined; };
33
27
  const setConnection = (phase, sourceNeed) => {
34
28
  if (phase === 'connected' || phase === 'disposed' || phase === 'unavailable' && sourceNeed && !isConnectionInterruption(sourceNeed.code))
35
29
  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
- }
30
+ else if (phase === 'unavailable' && sourceNeed && isConnectionInterruption(sourceNeed.code) && !recovery)
31
+ recovery = { version: 1, phase: 'reconnecting', startedAt: Date.now() };
50
32
  const message = connectionEmployeeMessage({ recovery });
51
33
  const next = { instanceId, phase, epoch: generation, ...(sourceNeed ? { need: { ...sourceNeed, ...(message ? { message } : {}) } } : {}), ...(recovery ? { recovery: structuredClone(recovery) } : {}) };
52
34
  if (JSON.stringify(next) === JSON.stringify(connection))
@@ -95,8 +77,6 @@ export function createConnect(ports, emit, options = {}) {
95
77
  const connect = (reuseTrusted = false) => {
96
78
  if (disposed)
97
79
  return Promise.resolve(fail('DISPOSED'));
98
- if (!validMessageSettings)
99
- return Promise.resolve(block(fail('SETTINGS_REQUIRED')));
100
80
  if ((state.target || reuseTrusted) && connection.phase === 'connected' && trustedTarget)
101
81
  return Promise.resolve(ok(structuredClone(trustedTarget)));
102
82
  if (flight)
@@ -136,8 +116,8 @@ export function createConnect(ports, emit, options = {}) {
136
116
  return transportBlock(n);
137
117
  if (typeof n.value.proxyCommand !== 'string' || n.value.proxyCommand.length === 0 || /[\r\n\x00]/.test(n.value.proxyCommand))
138
118
  return transportBlock(dependency('有效的远程网络连接通道'));
139
- const { host, username, port, projectRoot, knownHostsFile, session, hostContext } = e.value;
140
- const target = { host, username, port, projectRoot, knownHostsFile, session, ...(hostContext ? { hostContext } : {}), proxyCommand: n.value.proxyCommand };
119
+ const { host, username, port, projectRoot, knownHostsFile, session } = e.value;
120
+ const target = { host, username, port, projectRoot, knownHostsFile, session, proxyCommand: n.value.proxyCommand };
141
121
  publish({ phase: 'ssh' });
142
122
  const verified = await ports.ssh.verify(target, signal);
143
123
  stale = invalid(g);
@@ -263,27 +243,6 @@ export function createConnect(ports, emit, options = {}) {
263
243
  void promise.then(clear, clear);
264
244
  return promise;
265
245
  };
266
- const projectOperation = (operation, name) => track((async () => {
267
- if (disposed)
268
- return fail('DISPOSED');
269
- if (operation === 'create' && !isProjectName(name))
270
- return fail('PROJECT_NAME_INVALID');
271
- const connecting = connect(), g = generation, connected = await connecting;
272
- const stale = invalid(g);
273
- if (stale)
274
- return stale;
275
- if (!connected.ok)
276
- return connected;
277
- if (!ports.projects)
278
- return dependency('L 主机项目接口适配器');
279
- try {
280
- const r = operation === 'list' ? await ports.projects.list(connected.value, controller.signal) : await ports.projects.create(connected.value, name, controller.signal);
281
- return invalid(g) ?? r;
282
- }
283
- catch {
284
- return invalid(g) ?? fail(operation === 'list' ? 'PROJECT_LIST_FAILED' : 'PROJECT_CREATE_FAILED');
285
- }
286
- })());
287
246
  const unsubscribe = ports.network?.onState(event => {
288
247
  if (disposed)
289
248
  return;
@@ -300,7 +259,8 @@ export function createConnect(ports, emit, options = {}) {
300
259
  void connect();
301
260
  }
302
261
  });
303
- const operations = { getState: () => structuredClone(state), connect, checkLogin: provider => track(checkLogin(provider)), login };
262
+ const operations = { getState: () => { const copy = structuredClone(state), message = connectionEmployeeMessage(connection); if (message && copy.need)
263
+ copy.need.message = message; return copy; }, connect, checkLogin: provider => track(checkLogin(provider)), login };
304
264
  startup = createStartup({ ...operations, connect: () => connect(true), checkLogin: provider => track(checkLogin(provider, true)) }, options.providers ?? ['codex', 'claude'], options.onPromptState, options.onPromptResult, instanceId);
305
265
  return {
306
266
  ...operations,
@@ -313,21 +273,14 @@ export function createConnect(ports, emit, options = {}) {
313
273
  return fail('CONNECTION_LOST');
314
274
  return ok({ version: 1, purpose: 'model-catalog', scope: 'host-user', instanceId, epoch: connection.epoch, provider, target: structuredClone(trustedTarget) });
315
275
  },
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: () => () => { },
322
- getRemoteConversationDetailReceipt: async () => dependency('官方会话存储与持久诊断记录'),
323
- getRemoteConversationDetailState: () => ({ instanceId, epoch: connection.epoch, revision: 0, phase: disposed ? 'disposed' : 'unavailable', sessions: [], need: need(disposed ? 'DISPOSED' : 'DEPENDENCY_REQUIRED') }),
324
- onRemoteConversationDetailState: () => () => { }, listRemoteConversationDetails: async () => dependency('官方会话存储与持久诊断记录'),
325
- getContractInfo: () => ({ apiVersion: '0.7.0', status: 'implemented', workspaceBinding: 'native-local-v1', connectionMessages: 1, modelCatalogTarget: 1 }),
276
+ appendRemoteConversationDetail: () => { console.warn('会话技术日志未就绪;本轮继续。'); },
277
+ readConversationLog: async () => dependency('本机日志服务'),
278
+ getContractInfo: () => ({ apiVersion: '0.7.0', status: 'implemented', connectionMessages: 1, modelCatalogTarget: 1 }),
326
279
  getEnrollmentState: () => ({ instanceId, revision: 0, phase: 'blocked', need: need('DEPENDENCY_REQUIRED') }), onEnrollmentState: () => () => { },
327
280
  importEnrollment: async () => dependency('官方profileContext与原生目录选择服务'),
328
- getWorkspaceBindingState: () => ({ instanceId, revision: 0, items: [] }), onWorkspaceBindingState: () => () => { }, acknowledgeWorkspaceNotice: async () => dependency('官方工作区说明回执'), resolveSessionProject: async () => dependency('官方会话存储与L可信工作区关联'),
329
- listProjects: () => projectOperation('list'), createProject: name => projectOperation('create', name), getSshTarget: connect,
330
- getConnectionState: () => structuredClone(connection), onConnectionState: listener => { connectionListeners.add(listener); return () => { connectionListeners.delete(listener); }; },
281
+ resolveSessionProject: async () => dependency('当前工作区文件来源'), getSshTarget: connect,
282
+ getConnectionState: () => { const copy = structuredClone(connection), message = connectionEmployeeMessage(copy); if (message && copy.need)
283
+ copy.need.message = message; return copy; }, onConnectionState: listener => { connectionListeners.add(listener); return () => { connectionListeners.delete(listener); }; },
331
284
  getLoginPromptState: startup.getState, onLoginPromptState: startup.subscribe,
332
285
  requestLoginPrompt: startup.request, respondLoginPrompt: startup.respond,
333
286
  refreshLoginPrompts: async () => { await startup.check(); const s = startup.getState(); return s.phase === 'disposed' ? fail('DISPOSED') : s.phase === 'blocked' ? fail(s.technicalDetails.code ?? 'AUTH_STATUS_INVALID') : ok(s); },
@@ -1,7 +1,6 @@
1
1
  import type { ConnectionState, NeedCode } from './api.ts';
2
2
  export declare const CONNECTION_MESSAGES: Readonly<{
3
- readonly reconnecting: "正在自动重连";
4
- readonly administratorRequired: "请联系管理员";
3
+ readonly reconnecting: "与主机的连接已中断,网络恢复后会自动重连;你可以先检查本机网络";
5
4
  }>;
6
- export declare function connectionEmployeeMessage(state: Pick<ConnectionState, 'recovery'> | undefined): string | undefined;
5
+ export declare function connectionEmployeeMessage(state: Pick<ConnectionState, 'recovery'> | undefined, now?: number): string | undefined;
7
6
  export declare const isConnectionInterruption: (code: NeedCode) => boolean;
@@ -1,6 +1,7 @@
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;
1
+ export const CONNECTION_MESSAGES = Object.freeze({ reconnecting: '与主机的连接已中断,网络恢复后会自动重连;你可以先检查本机网络' });
2
+ export function connectionEmployeeMessage(state, now = Date.now()) {
3
+ if (!state?.recovery)
4
+ return undefined;
5
+ return '与主机的连接已中断(已持续 ' + Math.max(0, Math.floor((now - state.recovery.startedAt) / 60000)) + ' 分钟),网络恢复后会自动重连;你可以先检查本机网络';
5
6
  }
6
7
  export const isConnectionInterruption = (code) => ['CONNECTION_LOST', 'HOST_OFFLINE', 'SSH_FAILED'].includes(code);
@@ -0,0 +1,9 @@
1
+ import type { RemoteConversationDetail, Result } from './api.ts';
2
+ /** Best-effort local diagnostics. No receipt, admission, ordering or execution gate. */
3
+ export declare function createConversationLog(o: {
4
+ profileDir: string;
5
+ diagnostic?: (line: string) => void;
6
+ }): {
7
+ append: (detail: RemoteConversationDetail) => void;
8
+ read: () => Promise<Result<string>>;
9
+ };
@@ -0,0 +1,44 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { privateDirectory, readPrivate } from "./private-files.js";
5
+ import { fail, ok } from "./needs.js";
6
+ /** Best-effort local diagnostics. No receipt, admission, ordering or execution gate. */
7
+ export function createConversationLog(o) {
8
+ const root = join(o.profileDir, 'ai-workbench-connect'), file = join(root, 'conversation.log');
9
+ let pending = Promise.resolve();
10
+ const report = () => { try {
11
+ (o.diagnostic ?? console.warn)('会话技术日志写入失败;本轮继续。');
12
+ }
13
+ catch { /* Diagnostics cannot stop a user turn. */ } };
14
+ function append(detail) {
15
+ let line;
16
+ try {
17
+ line = JSON.stringify({ time: new Date().toISOString(), detail }) + '\n';
18
+ }
19
+ catch {
20
+ report();
21
+ return;
22
+ }
23
+ pending = pending.then(async () => { await privateDirectory(root); const h = await open(file, constants.O_APPEND | constants.O_CREAT | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600); try {
24
+ const stat = await h.stat();
25
+ if (!stat.isFile() || stat.uid !== process.getuid() || (stat.mode & 0o177) !== 0)
26
+ throw Error('PRIVATE_FILE_REQUIRED');
27
+ await h.writeFile(line);
28
+ }
29
+ finally {
30
+ await h.close();
31
+ } }).catch(report);
32
+ }
33
+ async function read() {
34
+ await pending;
35
+ try {
36
+ await privateDirectory(root);
37
+ return ok(await readPrivate(file));
38
+ }
39
+ catch (e) {
40
+ return e.code === 'ENOENT' ? ok('') : fail('REMOTE_DETAIL_STORAGE_FAILED');
41
+ }
42
+ }
43
+ return { append, read };
44
+ }
package/lib/cordis.d.ts CHANGED
@@ -1,14 +1,11 @@
1
- import type { ConnectApi, ConnectState, ConnectionState, LoginPromptState, LoginPromptResult, EnrollmentState, WorkspaceBindingState, RemoteConversationDetailState, WorkspaceLocationState } from './api.ts';
1
+ import type { ConnectApi, ConnectState, ConnectionState, LoginPromptState, LoginPromptResult, EnrollmentState, 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
7
  'ai-workbench/workspace-location-state': (state: WorkspaceLocationState) => void;
8
- 'ai-workbench/login-diagnostic-state': (state: RemoteConversationDetailState) => void;
9
- 'ai-workbench/remote-conversation-detail-state': (state: RemoteConversationDetailState) => void;
10
8
  'ai-workbench/enrollment-state': (state: EnrollmentState) => void;
11
- 'ai-workbench/workspace-binding-state': (state: WorkspaceBindingState) => void;
12
9
  'ai-workbench/workspace-diagnostic': (error: unknown) => void;
13
10
  'ai-workbench/connect-state': (state: ConnectState) => void;
14
11
  'ai-workbench/connection-state': (state: ConnectionState) => void;
package/lib/defaults.d.ts CHANGED
@@ -28,13 +28,6 @@ export declare const NETWORK_DEFAULTS: Readonly<{
28
28
  controlResponseMaxBytes: 65536;
29
29
  downloadMaxRedirects: 3;
30
30
  }>;
31
- export declare const CONVERSATION_DETAIL_DEFAULTS: Readonly<{
32
- maxEventBytes: 1048576;
33
- pageSize: 100;
34
- }>;
35
31
  export declare const WORKSPACE_LOCATION_DEFAULTS: {
36
32
  readonly pageSize: 100;
37
33
  };
38
- export declare const CONNECTION_MESSAGE_DEFAULTS: Readonly<{
39
- administratorAfterMs: 30000;
40
- }>;
package/lib/defaults.js CHANGED
@@ -2,6 +2,4 @@
2
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
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
- export const CONVERSATION_DETAIL_DEFAULTS = Object.freeze({ maxEventBytes: 1048576, pageSize: 100 });
6
5
  export const WORKSPACE_LOCATION_DEFAULTS = { pageSize: 100 };
7
- export const CONNECTION_MESSAGE_DEFAULTS = Object.freeze({ administratorAfterMs: 30000 });
package/lib/enrollment.js CHANGED
@@ -14,13 +14,6 @@ export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
14
14
  if (wire.schemaVersion !== 1 || !/^emp-[a-z0-9][a-z0-9-]*$/.test(wire.employee?.username) || wire.employee.username.length > 32)
15
15
  return fail('ENROLLMENT_INVALID');
16
16
  const user = wire.employee.username, home = '/Users/' + user;
17
- const rows = (v) => Array.isArray(v) && v.every(r => r && typeof r.id === 'string' && typeof r.status === 'string' && !/[\x00-\x1f\x7f]/.test(r.id + r.status));
18
- if (!['production', 'test'].includes(wire.hostEnforcement) || wire.host?.enforcement !== wire.hostEnforcement || ![0, 1].includes(wire.checkExitCode) || !rows(wire.failedChecks) || !rows(wire.unverifiedChecks))
19
- return fail('ENROLLMENT_INVALID');
20
- const hasIssues = wire.failedChecks.length + wire.unverifiedChecks.length > 0;
21
- if ((wire.checkExitCode === 0 && hasIssues) || (wire.checkExitCode === 1 && !hasIssues) || (wire.hostEnforcement === 'production' && (hasIssues || wire.checkExitCode !== 0)))
22
- return fail('ENROLLMENT_INVALID');
23
- const hostContext = { enforcement: wire.hostEnforcement, checkExitCode: wire.checkExitCode, failedChecks: wire.failedChecks.map(({ id, status }) => ({ id, status })), unverifiedChecks: wire.unverifiedChecks.map(({ id, status }) => ({ id, status })) };
24
17
  if (wire.employee.home !== home || wire.employee.projectsRoot !== home + '/projects' || wire.employee.tag !== 'tag:aw-' + user || wire.host?.tag !== 'tag:aw-host' || !Number.isInteger(wire.host?.sshPort) || wire.host.sshPort < 1 || wire.host.sshPort > 65535 || !(/^[a-zA-Z0-9][a-zA-Z0-9.-]*$/).test(wire.host?.name))
25
18
  return fail('ENROLLMENT_INVALID');
26
19
  if (wire.session?.protocolVersion !== 1 || typeof wire.session.command !== 'string' || !wire.session.command.startsWith('/') || typeof wire.session.settingsPath !== 'string' || !wire.session.settingsPath.startsWith('/') || wire.session.root !== home + '/.aw/s' || [wire.session.command, wire.session.settingsPath].some((v) => /[\x00-\x1f\x7f]/.test(v)) || wire.authKeyDelivery?.mode !== 'file' || wire.authKeyDelivery.source !== 'administrator-stdin' || typeof wire.authKeyDelivery.path !== 'string' || !(/^[a-zA-Z0-9._-]+$/).test(wire.authKeyDelivery.path) || ['.', '..'].includes(wire.authKeyDelivery.path))
@@ -70,7 +63,7 @@ export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
70
63
  await rm(temp, { force: true });
71
64
  }
72
65
  }
73
- return ok({ authKeyFile, hostContext, host: wire.host.name, username: user, port: wire.host.sshPort, projectRoot: wire.employee.projectsRoot, knownHostsFile: destination, session: { command: wire.session.command, root: wire.session.root, settingsPath: wire.session.settingsPath, protocolVersion: 1 } });
66
+ return ok({ authKeyFile, host: wire.host.name, username: user, port: wire.host.sshPort, projectRoot: wire.employee.projectsRoot, knownHostsFile: destination, session: { command: wire.session.command, root: wire.session.root, settingsPath: wire.session.settingsPath, protocolVersion: 1 } });
74
67
  }
75
68
  catch {
76
69
  return fail('ENROLLMENT_INVALID');
@@ -47,7 +47,9 @@ export interface HostDirectoryRequest {
47
47
  pageSize: number;
48
48
  expected?: HostDirectoryIdentity;
49
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
- };
50
+ export interface HostDirectories {
51
+ 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>>;
54
+ }
55
+ export declare function createHostDirectories(runner: Runner, maxOutputBytes: number): HostDirectories;
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
2
2
  import { runRemote } from "./ssh.js";
3
3
  import { fail, ok } from "./needs.js";
4
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'];
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);
8
8
  function validEntryIdentity(value) { return object(value) && decimal(value.device) && decimal(value.inode); }
@@ -25,7 +25,7 @@ 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 === '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) || !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))))
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');
@@ -51,7 +51,7 @@ export function createHostDirectories(runner, maxOutputBytes) {
51
51
  const code = object(error) ? codes.find(code => code === error.code) : undefined;
52
52
  return fail(code ?? 'PROJECT_PROTOCOL_INVALID');
53
53
  }
54
- if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== data.path)
54
+ if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== (operation === 'create' ? (data.path.endsWith('/') ? data.path : data.path + '/') + data.name : data.path))
55
55
  return fail('PROJECT_PROTOCOL_INVALID');
56
56
  if (operation === 'browse') {
57
57
  const value = result.value;
@@ -72,5 +72,5 @@ export function createHostDirectories(runner, maxOutputBytes) {
72
72
  return fail('CONNECTION_LOST');
73
73
  }
74
74
  }
75
- return { browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
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) };
76
76
  }