@ai-workbench/connect 0.7.14 → 0.7.18
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 +43 -4
- package/client/index.cjs +3 -3
- package/lib/api.d.ts +10 -2
- package/lib/cache.js +2 -2
- package/lib/component-download.d.ts +2 -0
- package/lib/component-download.js +13 -3
- package/lib/connect.js +1 -1
- package/lib/conversation-details.d.ts +4 -0
- package/lib/conversation-details.js +168 -55
- package/lib/index.js +1 -1
- 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/login-diagnostics.d.ts +3 -1
- package/lib/login-diagnostics.js +17 -2
- package/lib/needs.js +1 -0
- package/lib/private-files.d.ts +2 -0
- package/lib/private-files.js +17 -1
- package/lib/profile-runtime.js +62 -10
- package/lib/workspace-locations.d.ts +5 -0
- package/lib/workspace-locations.js +30 -2
- package/package.json +1 -1
|
@@ -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,20 +53,34 @@ 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) {
|
|
65
69
|
snapshot = { ...connectionIds(), revision: ++revision, phase, sessions, ...(code ? { need: need(code) } : {}) };
|
|
66
|
-
options.
|
|
70
|
+
const visible = () => options.cacheContext || options.publicationRevision ? currentSnapshot() : structuredClone(snapshot);
|
|
71
|
+
options.onState?.(visible());
|
|
67
72
|
for (const listener of listeners)
|
|
68
|
-
listener(
|
|
73
|
+
listener(visible());
|
|
69
74
|
}
|
|
75
|
+
function currentSnapshot() { const c = options.getConnectionState(); if (disposed || c.phase === 'disposed')
|
|
76
|
+
return { ...connectionIds(), revision, phase: 'disposed', sessions: [], need: need('DISPOSED') }; if (c.phase !== 'connected' || snapshot.instanceId !== c.instanceId || snapshot.epoch !== c.epoch)
|
|
77
|
+
return { ...connectionIds(), revision, phase: 'unavailable', sessions: [], need: need('CONNECTION_LOST') }; try {
|
|
78
|
+
for (const guard of snapshotGuards)
|
|
79
|
+
guard();
|
|
80
|
+
}
|
|
81
|
+
catch (e) {
|
|
82
|
+
return { ...connectionIds(), revision, phase: 'unavailable', sessions: [], need: need(e instanceof NeedError ? e.need.code : 'REMOTE_DETAIL_STORAGE_FAILED') };
|
|
83
|
+
} return structuredClone(snapshot); }
|
|
70
84
|
function error(e) { const code = e instanceof NeedError ? e.need.code : 'REMOTE_DETAIL_STORAGE_FAILED'; if (code === 'REMOTE_DETAIL_STORAGE_FAILED') {
|
|
71
85
|
uncertain = true;
|
|
72
86
|
publish('failed', [], code);
|
|
@@ -145,7 +159,12 @@ export function createConversationDetails(options) {
|
|
|
145
159
|
if (e.code !== 'ENOENT')
|
|
146
160
|
throw e;
|
|
147
161
|
}
|
|
148
|
-
|
|
162
|
+
if (writeGuard) {
|
|
163
|
+
check(before);
|
|
164
|
+
renameSync(temp, file);
|
|
165
|
+
}
|
|
166
|
+
else
|
|
167
|
+
await checked(rename(temp, file), before);
|
|
149
168
|
await syncDir(join(file, '..'), before);
|
|
150
169
|
}
|
|
151
170
|
finally {
|
|
@@ -163,7 +182,7 @@ export function createConversationDetails(options) {
|
|
|
163
182
|
if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || (st.mode & 0o777) !== 0o600)
|
|
164
183
|
throw Error('DETAIL_RECORD_INVALID');
|
|
165
184
|
const record = JSON.parse(await checked(h.readFile('utf8'), before));
|
|
166
|
-
if (record
|
|
185
|
+
if (!validStored(record) || canonical(record.detail) !== canonical(detail) || (record.localAcceptanceId ?? undefined) !== localRefs.get(detail))
|
|
167
186
|
throw Error('DETAIL_RECORD_INVALID');
|
|
168
187
|
await checked(h.sync(), before);
|
|
169
188
|
}
|
|
@@ -195,14 +214,29 @@ export function createConversationDetails(options) {
|
|
|
195
214
|
await durable(path, value, before);
|
|
196
215
|
return value;
|
|
197
216
|
}
|
|
217
|
+
function validStored(raw) {
|
|
218
|
+
if (!raw || !valid(raw.detail) || raw.digest !== digest(canonical(raw.detail)))
|
|
219
|
+
return false;
|
|
220
|
+
if (raw.version === 1)
|
|
221
|
+
return Object.keys(raw).sort().join(',') === 'detail,digest,version';
|
|
222
|
+
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]));
|
|
223
|
+
}
|
|
198
224
|
async function rows(domain, before) {
|
|
199
225
|
const items = [], ids = new Set(), sequences = new Set();
|
|
200
226
|
for (const name of await checked(readdir(domain), before)) {
|
|
201
227
|
if (!/^[a-f0-9]{64}\.json$/.test(name))
|
|
202
228
|
throw Error('DETAIL_RECORD_INVALID');
|
|
203
229
|
const raw = JSON.parse(await checked(privateRead(join(domain, name), before), before)), d = raw.detail;
|
|
204
|
-
if (
|
|
230
|
+
if (!validStored(raw) || name !== digest(d.eventId) + '.json' || ids.has(d.eventId) || sequences.has(canonical([d.sessionId, d.provider, d.sequence])))
|
|
205
231
|
throw Error('DETAIL_RECORD_INVALID');
|
|
232
|
+
if (raw.version === 2) {
|
|
233
|
+
if (!options.localAcceptance)
|
|
234
|
+
throw Error('DETAIL_LOCAL_CONTEXT_REQUIRED');
|
|
235
|
+
localRefs.set(d, raw.localAcceptanceId);
|
|
236
|
+
const r = await checked(options.localAcceptance.readScope(d.sessionId, d.provider, raw.localAcceptanceId, d, basename(domain)), before);
|
|
237
|
+
if (!r.ok && r.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
|
|
238
|
+
throw new NeedError(r.error);
|
|
239
|
+
}
|
|
206
240
|
ids.add(d.eventId);
|
|
207
241
|
sequences.add(canonical([d.sessionId, d.provider, d.sequence]));
|
|
208
242
|
items.push(d);
|
|
@@ -217,20 +251,71 @@ export function createConversationDetails(options) {
|
|
|
217
251
|
throw new NeedError(result.error);
|
|
218
252
|
return result.value.identity;
|
|
219
253
|
}
|
|
254
|
+
async function readScope(sessionId, provider, before) {
|
|
255
|
+
if (!text(sessionId) || !brand(provider))
|
|
256
|
+
throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID'));
|
|
257
|
+
const legacy = await checked(options.scope(sessionId, provider), before);
|
|
258
|
+
const local = options.localAcceptance ? await checked(options.localAcceptance.readScope(sessionId, provider), before) : undefined;
|
|
259
|
+
if (local && !local.ok && local.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
|
|
260
|
+
throw new NeedError(local.error);
|
|
261
|
+
if (local?.ok) {
|
|
262
|
+
finalReadGuard = local.value.guard;
|
|
263
|
+
return local.value.identity;
|
|
264
|
+
}
|
|
265
|
+
finalReadGuard = undefined;
|
|
266
|
+
if (legacy.ok)
|
|
267
|
+
return legacy.value.identity;
|
|
268
|
+
throw new NeedError(legacy.error);
|
|
269
|
+
}
|
|
270
|
+
async function authorized(items, identity, sessionId, provider, before) {
|
|
271
|
+
const selected = items.filter(d => d.sessionId === sessionId && d.provider === provider), result = [];
|
|
272
|
+
const legacy = selected.some(d => !localRefs.has(d)) ? await checked(options.scope(sessionId, provider), before) : undefined;
|
|
273
|
+
for (const d of selected) {
|
|
274
|
+
const ref = localRefs.get(d);
|
|
275
|
+
if (ref) {
|
|
276
|
+
const r = await checked(options.localAcceptance.readScope(sessionId, provider, ref, d, identity), before);
|
|
277
|
+
if (r.ok && r.value.identity === identity) {
|
|
278
|
+
recordGuards.set(d, { guard: r.value.guard, cacheGuard: r.value.cacheGuard });
|
|
279
|
+
result.push(d);
|
|
280
|
+
}
|
|
281
|
+
else if (!r.ok && r.error.code !== 'REMOTE_DETAIL_SCOPE_INVALID')
|
|
282
|
+
throw new NeedError(r.error);
|
|
283
|
+
}
|
|
284
|
+
else if (legacy?.ok && legacy.value.identity === identity)
|
|
285
|
+
result.push(d);
|
|
286
|
+
}
|
|
287
|
+
return result;
|
|
288
|
+
}
|
|
220
289
|
async function stateRows(items, identity, before) {
|
|
221
|
-
const
|
|
290
|
+
const publicationRevision = options.publicationRevision?.(), publicationCurrent = () => !options.publicationRevision || options.publicationRevision() === publicationRevision, publicationGuard = () => { if (!publicationCurrent())
|
|
291
|
+
throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID')); };
|
|
292
|
+
const sessions = [], seen = new Set(), guards = [], cacheGuards = [];
|
|
222
293
|
let excluded = false;
|
|
223
294
|
for (const d of items) {
|
|
224
|
-
|
|
295
|
+
const pair = canonical([d.sessionId, d.provider]);
|
|
296
|
+
if (seen.has(pair))
|
|
225
297
|
continue;
|
|
226
|
-
|
|
227
|
-
|
|
298
|
+
seen.add(pair);
|
|
299
|
+
const accessible = await authorized(items, identity, d.sessionId, d.provider, before);
|
|
300
|
+
if (!accessible.length) {
|
|
228
301
|
excluded = true;
|
|
229
302
|
continue;
|
|
230
303
|
}
|
|
231
|
-
|
|
304
|
+
for (const item of accessible) {
|
|
305
|
+
const guard = recordGuards.get(item);
|
|
306
|
+
if (guard) {
|
|
307
|
+
guards.push(guard.guard);
|
|
308
|
+
cacheGuards.push(guard.cacheGuard);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
sessions.push({ sessionId: d.sessionId, provider: d.provider, ...counts(accessible, options.knownKinds) });
|
|
232
312
|
}
|
|
233
313
|
check(before);
|
|
314
|
+
for (const guard of guards)
|
|
315
|
+
guard();
|
|
316
|
+
if (!publicationCurrent())
|
|
317
|
+
return;
|
|
318
|
+
snapshotGuards = [...cacheGuards, ...(options.cacheContext ? [() => options.cacheContext(identity)] : []), ...(options.publicationRevision ? [publicationGuard] : [])];
|
|
234
319
|
publish('ready', sessions, excluded ? 'REMOTE_DETAIL_SCOPE_INVALID' : undefined);
|
|
235
320
|
}
|
|
236
321
|
function cursor(value, secret) { const payload = Buffer.from(canonical(value)).toString('base64url'); return payload + '.' + createHmac('sha256', secret).update(payload).digest('hex'); }
|
|
@@ -248,12 +333,17 @@ export function createConversationDetails(options) {
|
|
|
248
333
|
}
|
|
249
334
|
}
|
|
250
335
|
const api = {
|
|
251
|
-
appendRemoteConversationDetail(input) {
|
|
252
|
-
let detail;
|
|
336
|
+
appendRemoteConversationDetail(input, scopeInput) {
|
|
337
|
+
let detail, localId;
|
|
253
338
|
try {
|
|
254
339
|
if (!valid(input))
|
|
255
340
|
return Promise.resolve(fail('REMOTE_DETAIL_INVALID'));
|
|
256
341
|
detail = structuredClone(input);
|
|
342
|
+
if (scopeInput !== undefined) {
|
|
343
|
+
if (!scopeInput || Object.keys(scopeInput).join(',') !== 'localAcceptanceId' || !text(scopeInput.localAcceptanceId))
|
|
344
|
+
return Promise.resolve(fail('REMOTE_DETAIL_SCOPE_INVALID'));
|
|
345
|
+
localId = scopeInput.localAcceptanceId;
|
|
346
|
+
}
|
|
257
347
|
}
|
|
258
348
|
catch {
|
|
259
349
|
return Promise.resolve(fail('REMOTE_DETAIL_INVALID'));
|
|
@@ -262,41 +352,60 @@ export function createConversationDetails(options) {
|
|
|
262
352
|
const before = start();
|
|
263
353
|
if (detail.instanceId !== before.instanceId || detail.epoch !== before.epoch)
|
|
264
354
|
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);
|
|
355
|
+
const write = async (proof) => {
|
|
356
|
+
writeGuard = proof?.guard;
|
|
285
357
|
try {
|
|
286
358
|
check(before);
|
|
287
|
-
|
|
359
|
+
if (!Number.isSafeInteger(options.maxEventBytes) || options.maxEventBytes < 1)
|
|
360
|
+
return fail('SETTINGS_REQUIRED');
|
|
361
|
+
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);
|
|
362
|
+
if (existing && (canonical(existing) !== canonical(detail) || localRefs.get(existing) !== localId))
|
|
363
|
+
return fail('REMOTE_DETAIL_CONFLICT');
|
|
364
|
+
if (!existing && Buffer.byteLength(JSON.stringify(detail), 'utf8') > options.maxEventBytes)
|
|
365
|
+
return fail('REMOTE_DETAIL_TOO_LARGE');
|
|
366
|
+
if (!existing && items.some(d => d.sessionId === detail.sessionId && d.provider === detail.provider && d.sequence >= detail.sequence))
|
|
367
|
+
return fail('REMOTE_DETAIL_SEQUENCE_INVALID');
|
|
368
|
+
if (!proof && await scope(detail.sessionId, detail.provider, before) !== identity)
|
|
369
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
370
|
+
check(before);
|
|
371
|
+
const file = join(domain, digest(detail.eventId) + '.json');
|
|
372
|
+
await key(before, true);
|
|
373
|
+
if (!existing) {
|
|
374
|
+
const envelope = localId ? { version: 2, localAcceptanceId: localId, scopeDigest: digest(canonical([localId, detail])) } : { version: 1 };
|
|
375
|
+
await durable(file, JSON.stringify({ ...envelope, digest: digest(canonical(detail)), detail }) + '\n', before);
|
|
376
|
+
if (localId)
|
|
377
|
+
localRefs.set(detail, localId);
|
|
378
|
+
items.push(detail);
|
|
379
|
+
}
|
|
380
|
+
else {
|
|
381
|
+
const h = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
382
|
+
try {
|
|
383
|
+
check(before);
|
|
384
|
+
await checked(h.sync(), before);
|
|
385
|
+
}
|
|
386
|
+
finally {
|
|
387
|
+
await h.close();
|
|
388
|
+
}
|
|
389
|
+
await syncDir(domain, before);
|
|
390
|
+
}
|
|
391
|
+
await stateRows(items, identity, before);
|
|
392
|
+
if (!proof && await scope(detail.sessionId, detail.provider, before) !== identity)
|
|
393
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
394
|
+
check(before);
|
|
395
|
+
uncertain = false;
|
|
396
|
+
return ok({ eventId: detail.eventId, recorded: true });
|
|
288
397
|
}
|
|
289
398
|
finally {
|
|
290
|
-
|
|
399
|
+
writeGuard = undefined;
|
|
291
400
|
}
|
|
292
|
-
|
|
401
|
+
};
|
|
402
|
+
if (localId) {
|
|
403
|
+
if (!options.localAcceptance)
|
|
404
|
+
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
405
|
+
const result = await options.localAcceptance.withWrite(localId, detail, write);
|
|
406
|
+
return !result.ok && result.error.code === 'REMOTE_DETAIL_STORAGE_FAILED' ? error(new NeedError(result.error)) : result;
|
|
293
407
|
}
|
|
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 });
|
|
408
|
+
return write();
|
|
300
409
|
});
|
|
301
410
|
},
|
|
302
411
|
getRemoteConversationDetailReceipt(query) {
|
|
@@ -311,17 +420,19 @@ export function createConversationDetails(options) {
|
|
|
311
420
|
const before = start();
|
|
312
421
|
if (!q || !text(q.eventId) || Object.keys(q).sort().join(',') !== 'eventId,provider,sessionId')
|
|
313
422
|
return fail('REMOTE_DETAIL_INVALID');
|
|
314
|
-
const identity = await
|
|
315
|
-
if (d && (d.sessionId !== q.sessionId || d.provider !== q.provider))
|
|
423
|
+
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);
|
|
424
|
+
if (d && (d.sessionId !== q.sessionId || d.provider !== q.provider || !(await authorized([d], identity, q.sessionId, q.provider, before)).length))
|
|
316
425
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
317
426
|
if (d)
|
|
318
427
|
await verifyReceipt(domain, d, before);
|
|
319
428
|
else if (uncertain)
|
|
320
429
|
return fail('REMOTE_DETAIL_STORAGE_FAILED');
|
|
321
|
-
if (await
|
|
430
|
+
if (await readScope(q.sessionId, q.provider, before) !== identity)
|
|
322
431
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
323
432
|
if (d)
|
|
324
433
|
uncertain = false;
|
|
434
|
+
finalReadGuard?.();
|
|
435
|
+
check(before);
|
|
325
436
|
return ok(d ? { eventId: q.eventId, recorded: true, detail: structuredClone(d) } : { eventId: q.eventId, recorded: false });
|
|
326
437
|
});
|
|
327
438
|
},
|
|
@@ -341,7 +452,7 @@ export function createConversationDetails(options) {
|
|
|
341
452
|
return fail('REMOTE_DETAIL_INVALID');
|
|
342
453
|
if (!Number.isSafeInteger(options.pageSize) || options.pageSize < 1)
|
|
343
454
|
return fail('SETTINGS_REQUIRED');
|
|
344
|
-
const identity = await
|
|
455
|
+
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
456
|
const secret = all.length ? await key(before) : '';
|
|
346
457
|
if (q.cursor !== undefined && !all.length)
|
|
347
458
|
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
@@ -350,24 +461,26 @@ export function createConversationDetails(options) {
|
|
|
350
461
|
if (typeof q.cursor !== 'string')
|
|
351
462
|
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
352
463
|
const c = readCursor(q.cursor, secret);
|
|
353
|
-
if (!c || typeof c !== 'object' || Array.isArray(c) || Object.keys(c).sort().join(',')
|
|
464
|
+
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))
|
|
465
|
+
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
466
|
+
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
467
|
return fail('REMOTE_DETAIL_CURSOR_INVALID');
|
|
355
468
|
upper = c.upper;
|
|
356
469
|
after = c.after;
|
|
357
470
|
}
|
|
358
471
|
const bounded = all.filter(d => d.sequence <= upper), remaining = bounded.filter(d => d.sequence > after), page = remaining.slice(0, options.pageSize);
|
|
359
|
-
if (await
|
|
472
|
+
if (await readScope(q.sessionId, q.provider, before) !== identity)
|
|
360
473
|
return fail('REMOTE_DETAIL_SCOPE_INVALID');
|
|
361
474
|
await stateRows(items, identity, before);
|
|
362
|
-
if (await
|
|
475
|
+
if (await readScope(q.sessionId, q.provider, before) !== identity)
|
|
363
476
|
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) } : {}) };
|
|
477
|
+
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) } : {}) };
|
|
478
|
+
finalReadGuard?.();
|
|
479
|
+
check(before);
|
|
365
480
|
return ok(value);
|
|
366
481
|
});
|
|
367
482
|
},
|
|
368
|
-
getRemoteConversationDetailState
|
|
369
|
-
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') }; return structuredClone(snapshot); },
|
|
483
|
+
getRemoteConversationDetailState: currentSnapshot,
|
|
371
484
|
onRemoteConversationDetailState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
|
|
372
485
|
};
|
|
373
486
|
return { ...api, observeConnection(c) { if (disposed)
|
package/lib/index.js
CHANGED
|
@@ -27,7 +27,7 @@ export const Config = z.object({
|
|
|
27
27
|
maxEventBytes: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.maxEventBytes).description('conversationDetails.maxEventBytes:完整UTF-8 JSON事件的字节上限;默认1048576,范围1至9007199254740991整数。改大增加单事件存储与内存;改小会拒收超过新值的新事件,不裁剪或删除旧记录。'),
|
|
28
28
|
pageSize: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.pageSize).description('conversationDetails.pageSize:每页条数;默认100,范围1至9007199254740991整数。改大增加一次读取与界面负担,改小增加继续加载次数,不减少完整快照总数。'),
|
|
29
29
|
}).description('管理员诊断记录设置:不自动过期、不按条数淘汰、没有隐藏总条数上限,本版没有清除入口。'),
|
|
30
|
-
enrollmentMetadataMaxBytes: positive().max(2147483647).default(L_DEFAULTS.enrollmentMetadataMaxBytes).description('
|
|
30
|
+
enrollmentMetadataMaxBytes: positive().max(2147483647).default(L_DEFAULTS.enrollmentMetadataMaxBytes).description('开通元数据、工作区关联文件、本地接纳关系文件、诊断设置文件及设置提交JSON各单份文件的字节上限;默认1048576,可由管理员修改;改小可能拒绝设置读取/提交,不读取key内容'),
|
|
31
31
|
inventory: z.object({ network: z.string(), connect: z.string(), claude: z.string(), codex: z.string() }).description('由已安装组件的实际版本自动生成,只读信息,不作为功能开关'),
|
|
32
32
|
enrollmentPackageDir: z.string().description('连接资料目录:由管理员安装时配置,员工无需手填'),
|
|
33
33
|
trustDir: z.string().description('主机信任缓存目录:由管理员安装时配置'),
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { LocalUserTurnAcceptance } from './local-user-turn-types.ts';
|
|
2
|
+
export declare const canonical: (v: any) => string;
|
|
3
|
+
export declare const hash: (v: unknown) => string;
|
|
4
|
+
export interface AcceptanceRecord {
|
|
5
|
+
acceptance: LocalUserTurnAcceptance;
|
|
6
|
+
identity: string;
|
|
7
|
+
header: Record<string, unknown>;
|
|
8
|
+
retired: boolean;
|
|
9
|
+
runtimeId: string;
|
|
10
|
+
key: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function validHeader(h: any): boolean;
|
|
13
|
+
export declare function acceptanceStore(profile: string, maxBytes: number): {
|
|
14
|
+
read: () => AcceptanceRecord[];
|
|
15
|
+
save: (items: AcceptanceRecord[], guard: () => void) => void;
|
|
16
|
+
verify: (expected: AcceptanceRecord, guard: () => void) => void;
|
|
17
|
+
};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { constants, openSync, closeSync, fstatSync, lstatSync, readFileSync, writeFileSync, fsyncSync, renameSync, unlinkSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { join, isAbsolute } from 'node:path';
|
|
3
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
4
|
+
export const canonical = (v) => v === null || typeof v !== 'object' ? JSON.stringify(v) : Array.isArray(v) ? '[' + v.map(canonical).join(',') + ']' : '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}';
|
|
5
|
+
export const hash = (v) => createHash('sha256').update(canonical(v)).digest('hex');
|
|
6
|
+
const exact = (v, fields) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).sort().join(',') === fields;
|
|
7
|
+
const text = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
|
|
8
|
+
const int = (v) => Number.isSafeInteger(v) && v >= 0;
|
|
9
|
+
export function validHeader(h) { return !!h && typeof h === 'object' && !Array.isArray(h) && h.version === 4 && text(h.id) && int(h.createdAt) && typeof h.isSeeded === 'boolean' && typeof h.cwd === 'string' && isAbsolute(h.cwd) && Object.keys(h).every(k => ['version', 'id', 'createdAt', 'cwd', 'parentSession', 'isSeeded', 'origin', 'delegationDepth', 'agentPreset'].includes(k)); }
|
|
10
|
+
function validAcceptance(a) { return exact(a, 'acceptanceId,bindingId,directory,epoch,instanceId,provider,sessionId,source,userTurn,version,workspaceId') && a.version === 1 && ['acceptanceId', 'bindingId', 'instanceId', 'sessionId', 'workspaceId'].every(k => text(a[k])) && int(a.epoch) && ['claude', 'codex'].includes(a.provider) && a.source === 'local' && exact(a.directory, 'device,inode,path') && isAbsolute(a.directory.path) && int(a.directory.device) && int(a.directory.inode) && exact(a.userTurn, 'startSequence,turn,userMessageId,userMessageSequence') && int(a.userTurn.turn) && int(a.userTurn.startSequence) && int(a.userTurn.userMessageSequence) && a.userTurn.userMessageSequence > a.userTurn.startSequence && text(a.userTurn.userMessageId); }
|
|
11
|
+
export function acceptanceStore(profile, maxBytes) {
|
|
12
|
+
const root = join(profile, 'ai-workbench-connect'), file = join(root, 'local-user-turn-acceptances.json');
|
|
13
|
+
const directory = (path) => { const st = lstatSync(path); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0 || realpathSync(path) !== path)
|
|
14
|
+
throw Error('ACCEPTANCE_DIRECTORY_INVALID'); };
|
|
15
|
+
function read() {
|
|
16
|
+
if (realpathSync(profile) !== profile)
|
|
17
|
+
throw Error('ACCEPTANCE_PROFILE_INVALID');
|
|
18
|
+
try {
|
|
19
|
+
directory(root);
|
|
20
|
+
}
|
|
21
|
+
catch (e) {
|
|
22
|
+
if (e.code === 'ENOENT')
|
|
23
|
+
return [];
|
|
24
|
+
throw e;
|
|
25
|
+
}
|
|
26
|
+
let fd;
|
|
27
|
+
try {
|
|
28
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
if (e.code === 'ENOENT')
|
|
32
|
+
return [];
|
|
33
|
+
throw e;
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
const st = fstatSync(fd);
|
|
37
|
+
if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || st.size > maxBytes)
|
|
38
|
+
throw Error('ACCEPTANCE_FILE_INVALID');
|
|
39
|
+
const bytes = readFileSync(fd);
|
|
40
|
+
if (bytes.length > maxBytes)
|
|
41
|
+
throw Error('ACCEPTANCE_LIMIT');
|
|
42
|
+
const data = JSON.parse(bytes.toString('utf8'));
|
|
43
|
+
if (!data || Object.keys(data).sort().join(',') !== 'items,version' || data.version !== 1 || !Array.isArray(data.items))
|
|
44
|
+
throw Error('ACCEPTANCE_FORMAT_INVALID');
|
|
45
|
+
const ids = new Set();
|
|
46
|
+
for (const r of data.items) {
|
|
47
|
+
const a = r?.acceptance;
|
|
48
|
+
if (!r || Object.keys(r).sort().join(',') !== 'acceptance,header,identity,key,retired,runtimeId' || !a || a.version !== 1 || typeof a.acceptanceId !== 'string' || !a.acceptanceId || ids.has(a.acceptanceId) || !['claude', 'codex'].includes(a.provider) || a.source !== 'local' || !a.directory || !a.userTurn || !r.header || typeof r.retired !== 'boolean' || !/^[a-f0-9]{64}$/.test(r.identity) || !validAcceptance(a) || !validHeader(r.header) || r.header.id !== a.sessionId || typeof r.runtimeId !== 'string' || !r.runtimeId || r.key !== hash({ acceptance: a, identity: r.identity, header: r.header, retired: r.retired, runtimeId: r.runtimeId }))
|
|
49
|
+
throw Error('ACCEPTANCE_RECORD_INVALID');
|
|
50
|
+
ids.add(a.acceptanceId);
|
|
51
|
+
}
|
|
52
|
+
return data.items;
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
closeSync(fd);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
function save(items, guard) {
|
|
59
|
+
directory(root);
|
|
60
|
+
for (const r of items)
|
|
61
|
+
r.key = hash({ acceptance: r.acceptance, identity: r.identity, header: r.header, retired: r.retired, runtimeId: r.runtimeId });
|
|
62
|
+
const bytes = JSON.stringify({ version: 1, items }) + '\n';
|
|
63
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || Buffer.byteLength(bytes) > maxBytes)
|
|
64
|
+
throw Error('ACCEPTANCE_LIMIT');
|
|
65
|
+
const temp = join(root, '.local-acceptance-' + randomUUID());
|
|
66
|
+
let created = false;
|
|
67
|
+
try {
|
|
68
|
+
const fd = openSync(temp, 'wx', 0o600);
|
|
69
|
+
created = true;
|
|
70
|
+
try {
|
|
71
|
+
writeFileSync(fd, bytes);
|
|
72
|
+
fsyncSync(fd);
|
|
73
|
+
}
|
|
74
|
+
finally {
|
|
75
|
+
closeSync(fd);
|
|
76
|
+
}
|
|
77
|
+
guard();
|
|
78
|
+
renameSync(temp, file);
|
|
79
|
+
created = false;
|
|
80
|
+
for (const path of [root, profile]) {
|
|
81
|
+
const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
82
|
+
try {
|
|
83
|
+
fsyncSync(d);
|
|
84
|
+
}
|
|
85
|
+
finally {
|
|
86
|
+
closeSync(d);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
if (created)
|
|
92
|
+
unlinkSync(temp);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function verify(expected, guard) {
|
|
96
|
+
directory(root);
|
|
97
|
+
if (realpathSync(profile) !== profile)
|
|
98
|
+
throw Error('ACCEPTANCE_PROFILE_INVALID');
|
|
99
|
+
const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
100
|
+
try {
|
|
101
|
+
const st = fstatSync(fd);
|
|
102
|
+
if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || st.size > maxBytes)
|
|
103
|
+
throw Error('ACCEPTANCE_FILE_INVALID');
|
|
104
|
+
const bytes = readFileSync(fd);
|
|
105
|
+
if (bytes.length > maxBytes)
|
|
106
|
+
throw Error('ACCEPTANCE_LIMIT');
|
|
107
|
+
const data = JSON.parse(bytes.toString('utf8'));
|
|
108
|
+
if (!Array.isArray(data.items) || !data.items.some((r) => canonical(r) === canonical(expected)))
|
|
109
|
+
throw Error('ACCEPTANCE_CHANGED');
|
|
110
|
+
guard();
|
|
111
|
+
fsyncSync(fd);
|
|
112
|
+
}
|
|
113
|
+
finally {
|
|
114
|
+
closeSync(fd);
|
|
115
|
+
}
|
|
116
|
+
for (const path of [root, profile]) {
|
|
117
|
+
const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
118
|
+
try {
|
|
119
|
+
guard();
|
|
120
|
+
fsyncSync(d);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
closeSync(d);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
guard();
|
|
127
|
+
}
|
|
128
|
+
return { read, save, verify };
|
|
129
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { ConnectionState, Provider, RemoteConversationDetail, Result } from './api.ts';
|
|
2
|
+
import type { LocalUserTurnAcceptance, LocalUserTurnAcceptanceRequest } from './local-user-turn-types.ts';
|
|
3
|
+
import type { WorkspaceLocationState } from './workspace-location-types.ts';
|
|
4
|
+
import type { NativeWorkspaceRegistry } from './workspace-bindings.ts';
|
|
5
|
+
interface Session {
|
|
6
|
+
header: Record<string, any>;
|
|
7
|
+
seq: number;
|
|
8
|
+
}
|
|
9
|
+
interface SessionEvent {
|
|
10
|
+
seq: number;
|
|
11
|
+
type: string;
|
|
12
|
+
data: any;
|
|
13
|
+
}
|
|
14
|
+
interface Services {
|
|
15
|
+
sessions: {
|
|
16
|
+
get(id: string): Session | undefined;
|
|
17
|
+
flush(session: Session): Promise<boolean>;
|
|
18
|
+
};
|
|
19
|
+
persistence: {
|
|
20
|
+
identity?: symbol;
|
|
21
|
+
open(id: string, access: 'read'): Promise<{
|
|
22
|
+
id: string;
|
|
23
|
+
access: string;
|
|
24
|
+
header: Record<string, any>;
|
|
25
|
+
inheritedEventCount: number;
|
|
26
|
+
read(): Promise<{
|
|
27
|
+
events: readonly SessionEvent[];
|
|
28
|
+
}>;
|
|
29
|
+
close(): Promise<void>;
|
|
30
|
+
}>;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
interface Options {
|
|
34
|
+
profileDir: string;
|
|
35
|
+
metadataMaxBytes: number;
|
|
36
|
+
registry: NativeWorkspaceRegistry;
|
|
37
|
+
getConnectionState: () => ConnectionState;
|
|
38
|
+
services: () => Services;
|
|
39
|
+
readHeader: (id: string) => Promise<Record<string, any> | undefined>;
|
|
40
|
+
context: () => Promise<Result<{
|
|
41
|
+
identity: string;
|
|
42
|
+
guard?: () => void;
|
|
43
|
+
}>>;
|
|
44
|
+
withLocalBinding: <T>(c: {
|
|
45
|
+
instanceId: string;
|
|
46
|
+
epoch: number;
|
|
47
|
+
workspaceId: string;
|
|
48
|
+
expectedBindingId: string;
|
|
49
|
+
}, run: (directory: {
|
|
50
|
+
path: string;
|
|
51
|
+
device: number;
|
|
52
|
+
inode: number;
|
|
53
|
+
}, guard: () => void) => Promise<Result<T>>) => Promise<Result<T>>;
|
|
54
|
+
}
|
|
55
|
+
export declare function createLocalUserTurnAcceptance(o: Options): {
|
|
56
|
+
active: () => boolean;
|
|
57
|
+
observe: (session: Session, event: SessionEvent) => void;
|
|
58
|
+
observeLocations: (state: WorkspaceLocationState) => void;
|
|
59
|
+
observeSessionDisposed: (session: Session) => void;
|
|
60
|
+
readScope: (sessionId: string, provider: Provider, acceptanceId?: string, detail?: RemoteConversationDetail, expectedIdentity?: string) => Promise<Result<{
|
|
61
|
+
identity: string;
|
|
62
|
+
guard: () => void;
|
|
63
|
+
cacheGuard: () => void;
|
|
64
|
+
}>>;
|
|
65
|
+
withWrite: <T>(acceptanceId: string, detail: RemoteConversationDetail, run: (proof: {
|
|
66
|
+
identity: string;
|
|
67
|
+
acceptanceId: string;
|
|
68
|
+
guard: () => void;
|
|
69
|
+
}) => Promise<Result<T>>) => Promise<Result<T>>;
|
|
70
|
+
acceptLocalWorkspaceUserTurn(request: LocalUserTurnAcceptanceRequest): Promise<Result<LocalUserTurnAcceptance>>;
|
|
71
|
+
dispose(): void;
|
|
72
|
+
};
|
|
73
|
+
export type LocalDetailsAdmission = ReturnType<typeof createLocalUserTurnAcceptance>;
|
|
74
|
+
export {};
|