@ai-workbench/connect 0.7.11 → 0.7.17
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 +34 -3
- package/client/index.cjs +29 -9
- package/helper/host-directories.cjs +72 -0
- package/lib/api.d.ts +31 -2
- package/lib/api.js +1 -1
- package/lib/cache.js +2 -2
- package/lib/component-download.d.ts +2 -0
- package/lib/component-download.js +13 -3
- package/lib/components.d.ts +1 -1
- package/lib/components.js +80 -5
- package/lib/connect.d.ts +3 -0
- package/lib/connect.js +53 -11
- package/lib/connection-messages.d.ts +7 -0
- package/lib/connection-messages.js +6 -0
- package/lib/conversation-details.d.ts +2 -0
- package/lib/conversation-details.js +158 -51
- package/lib/cordis.d.ts +2 -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 +10 -5
- package/lib/integration.js +2 -0
- package/lib/local-acceptance-store.d.ts +17 -0
- package/lib/local-acceptance-store.js +129 -0
- package/lib/local-user-turn-acceptance.d.ts +74 -0
- package/lib/local-user-turn-acceptance.js +281 -0
- package/lib/local-user-turn-types.d.ts +40 -0
- package/lib/local-user-turn-types.js +1 -0
- package/lib/local-workspace-context.d.ts +46 -0
- package/lib/local-workspace-context.js +17 -0
- package/lib/login-diagnostics.d.ts +3 -1
- package/lib/needs.js +13 -0
- package/lib/ports.d.ts +2 -0
- package/lib/private-files.d.ts +2 -0
- package/lib/private-files.js +17 -1
- package/lib/profile-runtime.js +62 -12
- package/lib/startup.d.ts +1 -1
- package/lib/startup.js +33 -13
- 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 +50 -0
- package/lib/workspace-locations.js +455 -0
- package/node_modules/argparse/CHANGELOG.md +216 -0
- package/package.json +4 -3
package/lib/connect.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
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";
|
|
@@ -20,41 +22,81 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
20
22
|
let connection = { instanceId, phase: 'unavailable', epoch: 0 };
|
|
21
23
|
const connectionListeners = new Set();
|
|
22
24
|
let startup;
|
|
23
|
-
const
|
|
24
|
-
|
|
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) } : {}) };
|
|
25
52
|
if (JSON.stringify(next) === JSON.stringify(connection))
|
|
26
53
|
return;
|
|
27
54
|
if (phase !== 'connected')
|
|
28
55
|
trustedTarget = undefined;
|
|
29
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 } };
|
|
30
63
|
startup?.connectionChanged(next);
|
|
64
|
+
if (connection !== publication)
|
|
65
|
+
return;
|
|
31
66
|
options.onConnectionState?.(structuredClone(next));
|
|
32
|
-
|
|
67
|
+
if (connection !== publication)
|
|
68
|
+
return;
|
|
69
|
+
for (const listener of connectionListeners) {
|
|
70
|
+
if (connection !== publication)
|
|
71
|
+
return;
|
|
33
72
|
listener(structuredClone(next));
|
|
73
|
+
}
|
|
34
74
|
};
|
|
35
75
|
let controller = new AbortController();
|
|
36
76
|
const loginFlights = new Map();
|
|
37
77
|
const pending = new Set();
|
|
38
78
|
let disposal;
|
|
39
79
|
const track = (promise) => { pending.add(promise); void promise.then(() => pending.delete(promise), () => pending.delete(promise)); return promise; };
|
|
40
|
-
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)); };
|
|
41
81
|
const invalid = (g) => disposed ? fail('DISPOSED') : g !== generation ? fail('CONNECTION_LOST') : undefined;
|
|
42
82
|
const block = (r) => { if (!r.ok && !disposed) {
|
|
43
|
-
publish({ phase: 'blocked', need: r.error });
|
|
44
83
|
if (connection.phase !== 'connected')
|
|
45
84
|
setConnection('unavailable', r.error);
|
|
46
|
-
|
|
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; };
|
|
47
87
|
const transportBlock = (r) => { if (!r.ok && !disposed && connection.phase === 'connected') {
|
|
48
88
|
generation++;
|
|
49
89
|
controller.abort();
|
|
50
90
|
controller = new AbortController();
|
|
51
91
|
flight = undefined;
|
|
52
92
|
loginFlights.clear();
|
|
53
|
-
}
|
|
54
|
-
setConnection('unavailable', r.error); return
|
|
93
|
+
} if (!r.ok && !disposed)
|
|
94
|
+
setConnection('unavailable', r.error); return block(r); };
|
|
55
95
|
const connect = (reuseTrusted = false) => {
|
|
56
96
|
if (disposed)
|
|
57
97
|
return Promise.resolve(fail('DISPOSED'));
|
|
98
|
+
if (!validMessageSettings)
|
|
99
|
+
return Promise.resolve(block(fail('SETTINGS_REQUIRED')));
|
|
58
100
|
if ((state.target || reuseTrusted) && connection.phase === 'connected' && trustedTarget)
|
|
59
101
|
return Promise.resolve(ok(structuredClone(trustedTarget)));
|
|
60
102
|
if (flight)
|
|
@@ -251,8 +293,8 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
251
293
|
controller = new AbortController();
|
|
252
294
|
flight = undefined;
|
|
253
295
|
loginFlights.clear();
|
|
254
|
-
block(fail('CONNECTION_LOST'));
|
|
255
296
|
setConnection('unavailable', need('CONNECTION_LOST'));
|
|
297
|
+
block(fail('CONNECTION_LOST'));
|
|
256
298
|
}
|
|
257
299
|
else {
|
|
258
300
|
void connect();
|
|
@@ -280,7 +322,7 @@ export function createConnect(ports, emit, options = {}) {
|
|
|
280
322
|
getRemoteConversationDetailReceipt: async () => dependency('官方会话存储与持久诊断记录'),
|
|
281
323
|
getRemoteConversationDetailState: () => ({ instanceId, epoch: connection.epoch, revision: 0, phase: disposed ? 'disposed' : 'unavailable', sessions: [], need: need(disposed ? 'DISPOSED' : 'DEPENDENCY_REQUIRED') }),
|
|
282
324
|
onRemoteConversationDetailState: () => () => { }, listRemoteConversationDetails: async () => dependency('官方会话存储与持久诊断记录'),
|
|
283
|
-
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, modelCatalogTarget: 1 }),
|
|
284
326
|
getEnrollmentState: () => ({ instanceId, revision: 0, phase: 'blocked', need: need('DEPENDENCY_REQUIRED') }), onEnrollmentState: () => () => { },
|
|
285
327
|
importEnrollment: async () => dependency('官方profileContext与原生目录选择服务'),
|
|
286
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);
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import type { LocalDetailsAdmission } from './local-user-turn-acceptance.ts';
|
|
1
2
|
import type { ConnectApi, ConnectionState, Provider, RemoteConversationDetail, RemoteConversationDetailState, Result } from './api.ts';
|
|
2
3
|
export interface ConversationDetailOptions {
|
|
3
4
|
profileDir: string;
|
|
4
5
|
maxEventBytes: number;
|
|
5
6
|
pageSize: number;
|
|
7
|
+
localAcceptance?: LocalDetailsAdmission;
|
|
6
8
|
storageName?: 'conversation-details' | 'login-diagnostics';
|
|
7
9
|
validate?: (detail: RemoteConversationDetail) => boolean;
|
|
8
10
|
knownKinds?: readonly string[];
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { lstat, open, readdir, realpath, rename, rm } from 'node:fs/promises';
|
|
3
|
-
import { constants } from 'node:fs';
|
|
4
|
-
import { isAbsolute, join } from 'node:path';
|
|
3
|
+
import { constants, renameSync } from 'node:fs';
|
|
4
|
+
import { isAbsolute, join, basename } from 'node:path';
|
|
5
5
|
import { fail, need, NeedError, ok } from "./needs.js";
|
|
6
6
|
import { privateDirectory, readPrivate } from "./private-files.js";
|
|
7
7
|
const queues = new Map();
|
|
@@ -53,12 +53,16 @@ export function createConversationDetails(options) {
|
|
|
53
53
|
const parent = join(options.profileDir, 'ai-workbench-connect'), root = join(parent, options.storageName ?? 'conversation-details');
|
|
54
54
|
const valid = (detail) => validRemoteConversationDetail(detail) && (!options.validate || options.validate(detail));
|
|
55
55
|
let disposed = false, uncertain = false, revision = 0, tail = Promise.resolve();
|
|
56
|
+
const localRefs = new WeakMap();
|
|
57
|
+
let writeGuard, finalReadGuard;
|
|
58
|
+
const recordGuards = new WeakMap();
|
|
59
|
+
let snapshotGuards = [];
|
|
56
60
|
let snapshot = { ...connectionIds(), revision, phase: 'unavailable', sessions: [] };
|
|
57
61
|
const listeners = new Set();
|
|
58
62
|
function connectionIds() { const c = options.getConnectionState(); return { instanceId: c.instanceId, epoch: c.epoch }; }
|
|
59
63
|
function check(before) { const c = options.getConnectionState(); if (disposed || c.phase === 'disposed')
|
|
60
64
|
throw new NeedError(need('DISPOSED')); if (c.phase !== 'connected' || c.instanceId !== before.instanceId || c.epoch !== before.epoch)
|
|
61
|
-
throw new NeedError(need('CONNECTION_LOST')); }
|
|
65
|
+
throw new NeedError(need('CONNECTION_LOST')); writeGuard?.(); }
|
|
62
66
|
function start() { const c = options.getConnectionState(); check(c); return c; }
|
|
63
67
|
async function checked(p, before) { const value = await p; check(before); return value; }
|
|
64
68
|
function publish(phase, sessions = [], code) {
|
|
@@ -145,7 +149,12 @@ export function createConversationDetails(options) {
|
|
|
145
149
|
if (e.code !== 'ENOENT')
|
|
146
150
|
throw e;
|
|
147
151
|
}
|
|
148
|
-
|
|
152
|
+
if (writeGuard) {
|
|
153
|
+
check(before);
|
|
154
|
+
renameSync(temp, file);
|
|
155
|
+
}
|
|
156
|
+
else
|
|
157
|
+
await checked(rename(temp, file), before);
|
|
149
158
|
await syncDir(join(file, '..'), before);
|
|
150
159
|
}
|
|
151
160
|
finally {
|
|
@@ -163,7 +172,7 @@ export function createConversationDetails(options) {
|
|
|
163
172
|
if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || (st.mode & 0o777) !== 0o600)
|
|
164
173
|
throw Error('DETAIL_RECORD_INVALID');
|
|
165
174
|
const record = JSON.parse(await checked(h.readFile('utf8'), before));
|
|
166
|
-
if (record
|
|
175
|
+
if (!validStored(record) || canonical(record.detail) !== canonical(detail) || (record.localAcceptanceId ?? undefined) !== localRefs.get(detail))
|
|
167
176
|
throw Error('DETAIL_RECORD_INVALID');
|
|
168
177
|
await checked(h.sync(), before);
|
|
169
178
|
}
|
|
@@ -195,14 +204,29 @@ export function createConversationDetails(options) {
|
|
|
195
204
|
await durable(path, value, before);
|
|
196
205
|
return value;
|
|
197
206
|
}
|
|
207
|
+
function validStored(raw) {
|
|
208
|
+
if (!raw || !valid(raw.detail) || raw.digest !== digest(canonical(raw.detail)))
|
|
209
|
+
return false;
|
|
210
|
+
if (raw.version === 1)
|
|
211
|
+
return Object.keys(raw).sort().join(',') === 'detail,digest,version';
|
|
212
|
+
return raw.version === 2 && Object.keys(raw).sort().join(',') === 'detail,digest,localAcceptanceId,scopeDigest,version' && text(raw.localAcceptanceId) && raw.scopeDigest === digest(canonical([raw.localAcceptanceId, raw.detail]));
|
|
213
|
+
}
|
|
198
214
|
async function rows(domain, before) {
|
|
199
215
|
const items = [], ids = new Set(), sequences = new Set();
|
|
200
216
|
for (const name of await checked(readdir(domain), before)) {
|
|
201
217
|
if (!/^[a-f0-9]{64}\.json$/.test(name))
|
|
202
218
|
throw Error('DETAIL_RECORD_INVALID');
|
|
203
219
|
const raw = JSON.parse(await checked(privateRead(join(domain, name), before), before)), d = raw.detail;
|
|
204
|
-
if (
|
|
220
|
+
if (!validStored(raw) || name !== digest(d.eventId) + '.json' || ids.has(d.eventId) || sequences.has(canonical([d.sessionId, d.provider, d.sequence])))
|
|
205
221
|
throw Error('DETAIL_RECORD_INVALID');
|
|
222
|
+
if (raw.version === 2) {
|
|
223
|
+
if (!options.localAcceptance)
|
|
224
|
+
throw Error('DETAIL_LOCAL_CONTEXT_REQUIRED');
|
|
225
|
+
localRefs.set(d, raw.localAcceptanceId);
|
|
226
|
+
const r = await checked(options.localAcceptance.readScope(d.sessionId, d.provider, raw.localAcceptanceId, d, basename(domain)), before);
|
|
227
|
+
if (!r.ok && r.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
|
|
228
|
+
throw new NeedError(r.error);
|
|
229
|
+
}
|
|
206
230
|
ids.add(d.eventId);
|
|
207
231
|
sequences.add(canonical([d.sessionId, d.provider, d.sequence]));
|
|
208
232
|
items.push(d);
|
|
@@ -217,20 +241,67 @@ export function createConversationDetails(options) {
|
|
|
217
241
|
throw new NeedError(result.error);
|
|
218
242
|
return result.value.identity;
|
|
219
243
|
}
|
|
244
|
+
async function readScope(sessionId, provider, before) {
|
|
245
|
+
if (!text(sessionId) || !brand(provider))
|
|
246
|
+
throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID'));
|
|
247
|
+
const legacy = await checked(options.scope(sessionId, provider), before);
|
|
248
|
+
const local = options.localAcceptance ? await checked(options.localAcceptance.readScope(sessionId, provider), before) : undefined;
|
|
249
|
+
if (local && !local.ok && local.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
|
|
250
|
+
throw new NeedError(local.error);
|
|
251
|
+
if (local?.ok) {
|
|
252
|
+
finalReadGuard = local.value.guard;
|
|
253
|
+
return local.value.identity;
|
|
254
|
+
}
|
|
255
|
+
finalReadGuard = undefined;
|
|
256
|
+
if (legacy.ok)
|
|
257
|
+
return legacy.value.identity;
|
|
258
|
+
throw new NeedError(legacy.error);
|
|
259
|
+
}
|
|
260
|
+
async function authorized(items, identity, sessionId, provider, before) {
|
|
261
|
+
const selected = items.filter(d => d.sessionId === sessionId && d.provider === provider), result = [];
|
|
262
|
+
const legacy = selected.some(d => !localRefs.has(d)) ? await checked(options.scope(sessionId, provider), before) : undefined;
|
|
263
|
+
for (const d of selected) {
|
|
264
|
+
const ref = localRefs.get(d);
|
|
265
|
+
if (ref) {
|
|
266
|
+
const r = await checked(options.localAcceptance.readScope(sessionId, provider, ref, d, identity), before);
|
|
267
|
+
if (r.ok && r.value.identity === identity) {
|
|
268
|
+
recordGuards.set(d, { guard: r.value.guard, cacheGuard: r.value.cacheGuard });
|
|
269
|
+
result.push(d);
|
|
270
|
+
}
|
|
271
|
+
else if (!r.ok && r.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
|
|
272
|
+
throw new NeedError(r.error);
|
|
273
|
+
}
|
|
274
|
+
else if (legacy?.ok && legacy.value.identity === identity)
|
|
275
|
+
result.push(d);
|
|
276
|
+
}
|
|
277
|
+
return result;
|
|
278
|
+
}
|
|
220
279
|
async function stateRows(items, identity, before) {
|
|
221
|
-
const sessions = [];
|
|
280
|
+
const sessions = [], seen = new Set(), guards = [], cacheGuards = [];
|
|
222
281
|
let excluded = false;
|
|
223
282
|
for (const d of items) {
|
|
224
|
-
|
|
283
|
+
const pair = canonical([d.sessionId, d.provider]);
|
|
284
|
+
if (seen.has(pair))
|
|
225
285
|
continue;
|
|
226
|
-
|
|
227
|
-
|
|
286
|
+
seen.add(pair);
|
|
287
|
+
const accessible = await authorized(items, identity, d.sessionId, d.provider, before);
|
|
288
|
+
if (!accessible.length) {
|
|
228
289
|
excluded = true;
|
|
229
290
|
continue;
|
|
230
291
|
}
|
|
231
|
-
|
|
292
|
+
for (const item of accessible) {
|
|
293
|
+
const guard = recordGuards.get(item);
|
|
294
|
+
if (guard) {
|
|
295
|
+
guards.push(guard.guard);
|
|
296
|
+
cacheGuards.push(guard.cacheGuard);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
sessions.push({ sessionId: d.sessionId, provider: d.provider, ...counts(accessible, options.knownKinds) });
|
|
232
300
|
}
|
|
233
301
|
check(before);
|
|
302
|
+
for (const guard of guards)
|
|
303
|
+
guard();
|
|
304
|
+
snapshotGuards = cacheGuards;
|
|
234
305
|
publish('ready', sessions, excluded ? 'REMOTE_DETAIL_SCOPE_INVALID' : undefined);
|
|
235
306
|
}
|
|
236
307
|
function cursor(value, secret) { const payload = Buffer.from(canonical(value)).toString('base64url'); return payload + '.' + createHmac('sha256', secret).update(payload).digest('hex'); }
|
|
@@ -248,12 +319,17 @@ export function createConversationDetails(options) {
|
|
|
248
319
|
}
|
|
249
320
|
}
|
|
250
321
|
const api = {
|
|
251
|
-
appendRemoteConversationDetail(input) {
|
|
252
|
-
let detail;
|
|
322
|
+
appendRemoteConversationDetail(input, scopeInput) {
|
|
323
|
+
let detail, localId;
|
|
253
324
|
try {
|
|
254
325
|
if (!valid(input))
|
|
255
326
|
return Promise.resolve(fail('REMOTE_DETAIL_INVALID'));
|
|
256
327
|
detail = structuredClone(input);
|
|
328
|
+
if (scopeInput !== undefined) {
|
|
329
|
+
if (!scopeInput || Object.keys(scopeInput).join(',') !== 'localAcceptanceId' || !text(scopeInput.localAcceptanceId))
|
|
330
|
+
return Promise.resolve(fail('REMOTE_DETAIL_SCOPE_INVALID'));
|
|
331
|
+
localId = scopeInput.localAcceptanceId;
|
|
332
|
+
}
|
|
257
333
|
}
|
|
258
334
|
catch {
|
|
259
335
|
return Promise.resolve(fail('REMOTE_DETAIL_INVALID'));
|
|
@@ -262,41 +338,60 @@ export function createConversationDetails(options) {
|
|
|
262
338
|
const before = start();
|
|
263
339
|
if (detail.instanceId !== before.instanceId || detail.epoch !== before.epoch)
|
|
264
340
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
const identity = await scope(detail.sessionId, detail.provider, before), domain = (await prepare(identity, before, true)), items = await rows(domain, before), existing = items.find(d => d.eventId === detail.eventId);
|
|
268
|
-
if (existing && canonical(existing) !== canonical(detail))
|
|
269
|
-
return fail('REMOTE_DETAIL_CONFLICT');
|
|
270
|
-
if (!existing && Buffer.byteLength(JSON.stringify(detail), 'utf8') > options.maxEventBytes)
|
|
271
|
-
return fail('REMOTE_DETAIL_TOO_LARGE');
|
|
272
|
-
if (!existing && items.some(d => d.sessionId === detail.sessionId && d.provider === detail.provider && d.sequence >= detail.sequence))
|
|
273
|
-
return fail('REMOTE_DETAIL_SEQUENCE_INVALID');
|
|
274
|
-
// Recheck native ownership after all storage reads and before writing or acknowledging.
|
|
275
|
-
if (await scope(detail.sessionId, detail.provider, before) !== identity)
|
|
276
|
-
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
277
|
-
const file = join(domain, digest(detail.eventId) + '.json');
|
|
278
|
-
await key(before, true);
|
|
279
|
-
if (!existing) {
|
|
280
|
-
await durable(file, JSON.stringify({ version: 1, digest: digest(canonical(detail)), detail }) + '\n', before);
|
|
281
|
-
items.push(detail);
|
|
282
|
-
}
|
|
283
|
-
else {
|
|
284
|
-
const h = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
341
|
+
const write = async (proof) => {
|
|
342
|
+
writeGuard = proof?.guard;
|
|
285
343
|
try {
|
|
286
344
|
check(before);
|
|
287
|
-
|
|
345
|
+
if (!Number.isSafeInteger(options.maxEventBytes) || options.maxEventBytes < 1)
|
|
346
|
+
return fail('SETTINGS_REQUIRED');
|
|
347
|
+
const identity = proof?.identity ?? await scope(detail.sessionId, detail.provider, before), domain = (await prepare(identity, before, true)), items = await rows(domain, before), existing = items.find(d => d.eventId === detail.eventId);
|
|
348
|
+
if (existing && (canonical(existing) !== canonical(detail) || localRefs.get(existing) !== localId))
|
|
349
|
+
return fail('REMOTE_DETAIL_CONFLICT');
|
|
350
|
+
if (!existing && Buffer.byteLength(JSON.stringify(detail), 'utf8') > options.maxEventBytes)
|
|
351
|
+
return fail('REMOTE_DETAIL_TOO_LARGE');
|
|
352
|
+
if (!existing && items.some(d => d.sessionId === detail.sessionId && d.provider === detail.provider && d.sequence >= detail.sequence))
|
|
353
|
+
return fail('REMOTE_DETAIL_SEQUENCE_INVALID');
|
|
354
|
+
if (!proof && await scope(detail.sessionId, detail.provider, before) !== identity)
|
|
355
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
356
|
+
check(before);
|
|
357
|
+
const file = join(domain, digest(detail.eventId) + '.json');
|
|
358
|
+
await key(before, true);
|
|
359
|
+
if (!existing) {
|
|
360
|
+
const envelope = localId ? { version: 2, localAcceptanceId: localId, scopeDigest: digest(canonical([localId, detail])) } : { version: 1 };
|
|
361
|
+
await durable(file, JSON.stringify({ ...envelope, digest: digest(canonical(detail)), detail }) + '\n', before);
|
|
362
|
+
if (localId)
|
|
363
|
+
localRefs.set(detail, localId);
|
|
364
|
+
items.push(detail);
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
const h = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
368
|
+
try {
|
|
369
|
+
check(before);
|
|
370
|
+
await checked(h.sync(), before);
|
|
371
|
+
}
|
|
372
|
+
finally {
|
|
373
|
+
await h.close();
|
|
374
|
+
}
|
|
375
|
+
await syncDir(domain, before);
|
|
376
|
+
}
|
|
377
|
+
await stateRows(items, identity, before);
|
|
378
|
+
if (!proof && await scope(detail.sessionId, detail.provider, before) !== identity)
|
|
379
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
380
|
+
check(before);
|
|
381
|
+
uncertain = false;
|
|
382
|
+
return ok({ eventId: detail.eventId, recorded: true });
|
|
288
383
|
}
|
|
289
384
|
finally {
|
|
290
|
-
|
|
385
|
+
writeGuard = undefined;
|
|
291
386
|
}
|
|
292
|
-
|
|
387
|
+
};
|
|
388
|
+
if (localId) {
|
|
389
|
+
if (!options.localAcceptance)
|
|
390
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
391
|
+
const result = await options.localAcceptance.withWrite(localId, detail, write);
|
|
392
|
+
return !result.ok && result.error.code === 'REMOTE_DETAIL_STORAGE_FAILED' ? error(new NeedError(result.error)) : result;
|
|
293
393
|
}
|
|
294
|
-
|
|
295
|
-
if (await scope(detail.sessionId, detail.provider, before) !== identity)
|
|
296
|
-
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
297
|
-
check(before);
|
|
298
|
-
uncertain = false;
|
|
299
|
-
return ok({ eventId: detail.eventId, recorded: true });
|
|
394
|
+
return write();
|
|
300
395
|
});
|
|
301
396
|
},
|
|
302
397
|
getRemoteConversationDetailReceipt(query) {
|
|
@@ -311,17 +406,19 @@ export function createConversationDetails(options) {
|
|
|
311
406
|
const before = start();
|
|
312
407
|
if (!q || !text(q.eventId) || Object.keys(q).sort().join(',') !== 'eventId,provider,sessionId')
|
|
313
408
|
return fail('REMOTE_DETAIL_INVALID');
|
|
314
|
-
const identity = await
|
|
315
|
-
if (d && (d.sessionId !== q.sessionId || d.provider !== q.provider))
|
|
409
|
+
const identity = await readScope(q.sessionId, q.provider, before), domain = await prepare(identity, before), items = domain ? await rows(domain, before) : [], d = items.find(r => r.eventId === q.eventId);
|
|
410
|
+
if (d && (d.sessionId !== q.sessionId || d.provider !== q.provider || !(await authorized([d], identity, q.sessionId, q.provider, before)).length))
|
|
316
411
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
317
412
|
if (d)
|
|
318
413
|
await verifyReceipt(domain, d, before);
|
|
319
414
|
else if (uncertain)
|
|
320
415
|
return fail('REMOTE_DETAIL_STORAGE_FAILED');
|
|
321
|
-
if (await
|
|
416
|
+
if (await readScope(q.sessionId, q.provider, before) !== identity)
|
|
322
417
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
323
418
|
if (d)
|
|
324
419
|
uncertain = false;
|
|
420
|
+
finalReadGuard?.();
|
|
421
|
+
check(before);
|
|
325
422
|
return ok(d ? { eventId: q.eventId, recorded: true, detail: structuredClone(d) } : { eventId: q.eventId, recorded: false });
|
|
326
423
|
});
|
|
327
424
|
},
|
|
@@ -341,7 +438,7 @@ export function createConversationDetails(options) {
|
|
|
341
438
|
return fail('REMOTE_DETAIL_INVALID');
|
|
342
439
|
if (!Number.isSafeInteger(options.pageSize) || options.pageSize < 1)
|
|
343
440
|
return fail('SETTINGS_REQUIRED');
|
|
344
|
-
const identity = await
|
|
441
|
+
const identity = await readScope(q.sessionId, q.provider, before), domain = await prepare(identity, before), items = domain ? await rows(domain, before) : [], all = (await authorized(items, identity, q.sessionId, q.provider, before)).sort((a, b) => a.sequence - b.sequence);
|
|
345
442
|
const secret = all.length ? await key(before) : '';
|
|
346
443
|
if (q.cursor !== undefined && !all.length)
|
|
347
444
|
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
@@ -350,24 +447,34 @@ export function createConversationDetails(options) {
|
|
|
350
447
|
if (typeof q.cursor !== 'string')
|
|
351
448
|
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
352
449
|
const c = readCursor(q.cursor, secret);
|
|
353
|
-
if (!c || typeof c !== 'object' || Array.isArray(c) || Object.keys(c).sort().join(',')
|
|
450
|
+
if (!c || typeof c !== 'object' || Array.isArray(c) || !['after,authorization,identity,provider,sessionId,upper,version', 'after,identity,provider,sessionId,upper,version'].includes(Object.keys(c).sort().join(',')) || c.version !== 1 || c.identity !== identity || c.sessionId !== q.sessionId || c.provider !== q.provider || !integer(c.upper) || !integer(c.after) || c.after > c.upper || !all.some(d => d.sequence === c.upper) || !all.some(d => d.sequence === c.after))
|
|
451
|
+
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
452
|
+
if (c.authorization === undefined ? all.some(d => d.sequence <= c.upper && localRefs.has(d)) : c.authorization !== digest(canonical(all.filter(d => d.sequence <= c.upper).map(d => [d.eventId, localRefs.get(d) ?? null]))))
|
|
354
453
|
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
355
454
|
upper = c.upper;
|
|
356
455
|
after = c.after;
|
|
357
456
|
}
|
|
358
457
|
const bounded = all.filter(d => d.sequence <= upper), remaining = bounded.filter(d => d.sequence > after), page = remaining.slice(0, options.pageSize);
|
|
359
|
-
if (await
|
|
458
|
+
if (await readScope(q.sessionId, q.provider, before) !== identity)
|
|
360
459
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
361
460
|
await stateRows(items, identity, before);
|
|
362
|
-
if (await
|
|
461
|
+
if (await readScope(q.sessionId, q.provider, before) !== identity)
|
|
363
462
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
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) } : {}) };
|
|
463
|
+
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, authorization: digest(canonical(bounded.map(d => [d.eventId, localRefs.get(d) ?? null]))) }, secret) } : {}) };
|
|
464
|
+
finalReadGuard?.();
|
|
465
|
+
check(before);
|
|
365
466
|
return ok(value);
|
|
366
467
|
});
|
|
367
468
|
},
|
|
368
469
|
getRemoteConversationDetailState() { const c = options.getConnectionState(); if (disposed || c.phase === 'disposed')
|
|
369
470
|
return { ...connectionIds(), revision, phase: 'disposed', sessions: [], need: need('DISPOSED') }; if (c.phase !== 'connected' || snapshot.instanceId !== c.instanceId || snapshot.epoch !== c.epoch)
|
|
370
|
-
return { ...connectionIds(), revision, phase: 'unavailable', sessions: [], need: need('CONNECTION_LOST') };
|
|
471
|
+
return { ...connectionIds(), revision, phase: 'unavailable', sessions: [], need: need('CONNECTION_LOST') }; try {
|
|
472
|
+
for (const guard of snapshotGuards)
|
|
473
|
+
guard();
|
|
474
|
+
}
|
|
475
|
+
catch (e) {
|
|
476
|
+
return { ...connectionIds(), revision, phase: 'unavailable', sessions: [], need: need(e instanceof NeedError ? e.need.code : 'REMOTE_DETAIL_STORAGE_FAILED') };
|
|
477
|
+
} return structuredClone(snapshot); },
|
|
371
478
|
onRemoteConversationDetailState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
372
479
|
};
|
|
373
480
|
return { ...api, observeConnection(c) { if (disposed)
|
package/lib/cordis.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
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;
|
|
7
8
|
'ai-workbench/login-diagnostic-state': (state: RemoteConversationDetailState) => void;
|
|
8
9
|
'ai-workbench/remote-conversation-detail-state': (state: RemoteConversationDetailState) => void;
|
|
9
10
|
'ai-workbench/enrollment-state': (state: EnrollmentState) => 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
|
+
};
|