@ai-workbench/connect 0.7.23 → 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 -73
  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 +5 -29
  42. package/lib/workspace-locations.js +81 -204
  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 -595
  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
@@ -7,17 +7,16 @@ import { fail, ok, need, NeedError } from "./needs.js";
7
7
  import { readLocalWorkspaceProcess } from "./local-workspace-context.js";
8
8
  import { isDeepStrictEqual } from 'node:util';
9
9
  const queues = new Map();
10
- const detailQueues = new Map();
11
10
  const hash = (v) => createHash('sha256').update(JSON.stringify(v)).digest('hex');
12
11
  const token = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
13
12
  const obj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
14
- const checksum = (r) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, r.legacyBindingId, ...(r.revoked === undefined ? [] : [r.revoked])]);
13
+ const checksum = (r, historicalRevoked) => hash([r.workspaceId, r.localPath, r.localDev, r.localIno, r.bindingId, r.source, r.active, r.remote, r.identity, r.host, undefined, ...(historicalRevoked === undefined ? [] : [historicalRevoked])]);
15
14
  const sameNative = (a, b) => a.workspaceId === b.workspaceId && a.localPath === b.localPath && a.localDev === b.localDev && a.localIno === b.localIno;
16
15
  const sameDirectory = (a, b) => a.path === b.path && a.requestedPath === b.requestedPath && a.isSymlink === b.isSymlink && JSON.stringify(a.identity) === JSON.stringify(b.identity) && JSON.stringify(a.entryIdentity) === JSON.stringify(b.entryIdentity);
17
16
  export function createWorkspaceLocations(o) {
18
- const controllers = new Set(), revokedBindings = new Map();
17
+ const controllers = new Set();
19
18
  const root = join(o.profileDir, 'ai-workbench-connect'), file = join(root, 'locations.json'), secret = randomBytes(32), listeners = new Set();
20
- let disposed = false, revision = 0, tail = Promise.resolve(), detailTail = Promise.resolve();
19
+ let disposed = false, revision = 0, tail = Promise.resolve();
21
20
  let snapshot = { ...connection(), host: currentHost(), revision: 0, phase: 'loading', pageSize: o.pageSize, items: [] };
22
21
  function connection() { const c = o.api.getConnectionState(); return { instanceId: c.instanceId, epoch: c.epoch }; }
23
22
  function currentHost() { const c = o.api.getConnectionState(); if (c.phase !== 'connected')
@@ -31,7 +30,6 @@ export function createWorkspaceLocations(o) {
31
30
  }
32
31
  function publish(items, error) {
33
32
  snapshot = { ...connection(), host: currentHost(), revision: (revision = o.nextRevision?.() ?? revision + 1), phase: disposed ? 'disposed' : error ? 'failed' : 'ready', pageSize: o.pageSize, items, ...(error ? { need: need(error) } : {}) };
34
- // An internal durability failure must not hide invalidation from settings.
35
33
  let failed = false, firstError;
36
34
  const notify = (listener) => { try {
37
35
  listener(structuredClone(snapshot));
@@ -49,8 +47,8 @@ export function createWorkspaceLocations(o) {
49
47
  if (failed)
50
48
  throw firstError;
51
49
  }
52
- function serial(fn, detailWrite = false) {
53
- const queue = detailWrite ? detailQueues : queues, before = queue.get(file) ?? Promise.resolve();
50
+ function serial(fn) {
51
+ const before = queues.get(file) ?? Promise.resolve();
54
52
  const task = before.then(async () => {
55
53
  if (disposed)
56
54
  return fail('DISPOSED');
@@ -62,14 +60,11 @@ export function createWorkspaceLocations(o) {
62
60
  }
63
61
  });
64
62
  const settled = task.then(() => { }, () => { });
65
- if (detailWrite)
66
- detailTail = settled;
67
- else
68
- tail = settled;
69
- queue.set(file, settled);
63
+ tail = settled;
64
+ queues.set(file, settled);
70
65
  void settled.then(() => {
71
- if (queue.get(file) === settled)
72
- queue.delete(file);
66
+ if (queues.get(file) === settled)
67
+ queues.delete(file);
73
68
  });
74
69
  return task;
75
70
  }
@@ -98,26 +93,22 @@ export function createWorkspaceLocations(o) {
98
93
  const data = JSON.parse(raw);
99
94
  if (!obj(data) || data.schemaVersion !== 1 || !Array.isArray(data.items))
100
95
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
96
+ const items = data.items.filter(r => !obj(r) || r.source !== 'legacy-host');
101
97
  const ids = new Set(), active = new Set();
102
- for (const r of data.items) {
103
- if (!obj(r) || !token(r.bindingId) || !token(r.workspaceId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || !['local', 'host', 'legacy-host'].includes(r.source) || typeof r.active !== 'boolean' || r.source === 'legacy-host' && !token(r.legacyBindingId) || r.source !== 'legacy-host' && r.legacyBindingId !== undefined || r.revoked !== undefined && (r.source !== 'host' || !['HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE'].includes(r.revoked)) || r.key !== checksum(r) || ids.has(r.bindingId) || r.active && active.has(r.workspaceId) || r.source !== 'local' && (!obj(r.remote) || !isAbsolute(r.remote.path) || !isAbsolute(r.remote.requestedPath) || !obj(r.remote.identity) || !obj(r.remote.entryIdentity) || !obj(r.remote.permissions) || !obj(r.host) || !token(r.host.host) || !token(r.host.username) || !Number.isSafeInteger(r.host.port) || !(/^[a-f0-9]{64}$/.test(r.identity))))
98
+ for (const r of items) {
99
+ if (!obj(r) || !token(r.bindingId) || !token(r.workspaceId) || !isAbsolute(r.localPath) || !Number.isSafeInteger(r.localDev) || !Number.isSafeInteger(r.localIno) || !['local', 'host'].includes(r.source) || typeof r.active !== 'boolean' || r.legacyBindingId !== undefined || r.revoked !== undefined && (r.source !== 'host' || !['HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE'].includes(r.revoked)) || r.key !== checksum(r, r.revoked) || ids.has(r.bindingId) || r.active && active.has(r.workspaceId) || r.source !== 'local' && (!obj(r.remote) || !isAbsolute(r.remote.path) || !isAbsolute(r.remote.requestedPath) || !obj(r.remote.identity) || !obj(r.remote.entryIdentity) || !obj(r.remote.permissions) || !obj(r.host) || !token(r.host.host) || !token(r.host.username) || !Number.isSafeInteger(r.host.port) || !(/^[a-f0-9]{64}$/.test(r.identity))))
104
100
  reject('WORKSPACE_LOCATION_STORAGE_FAILED');
105
101
  ids.add(r.bindingId);
106
102
  if (r.active)
107
103
  active.add(r.workspaceId);
104
+ delete r.revoked;
108
105
  }
109
- return data.items;
106
+ return items;
110
107
  }
111
- // Detail writes may overlap selection/resolve. Revalidate all storage, then
112
- // bind the guard to this exact active record, not a later read of new bytes.
113
- // An unrelated workspace's valid selection does not change this authority.
114
108
  function guardStoredBinding(expected) {
115
109
  const current = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === expected.workspaceId);
116
110
  if (!current)
117
111
  reject('WORKSPACE_LOCATION_CONFLICT');
118
- const invalid = bindingNeed(current);
119
- if (invalid)
120
- reject(invalid);
121
112
  if (!isDeepStrictEqual(current, expected))
122
113
  reject('WORKSPACE_LOCATION_CONFLICT');
123
114
  }
@@ -174,14 +165,14 @@ export function createWorkspaceLocations(o) {
174
165
  reject('WORKSPACE_LOCATION_INVALID');
175
166
  check(c);
176
167
  await prepare();
177
- const stored = await records(), legacy = await o.readLegacy(), n = await native(c.workspaceId);
168
+ const stored = await records(), n = await native(c.workspaceId);
178
169
  check(c);
179
- const current = stored.find(r => r.active && r.workspaceId === c.workspaceId), old = legacy.find(r => r.workspaceId === c.workspaceId);
180
- if ((current?.bindingId ?? old?.bindingId ?? null) !== c.expectedBindingId)
170
+ const current = stored.find(r => r.active && r.workspaceId === c.workspaceId);
171
+ if ((current?.bindingId ?? null) !== c.expectedBindingId)
181
172
  reject('WORKSPACE_LOCATION_CONFLICT');
182
- if (current && !sameNative(current, n) || !current && old && !sameNative(old, n))
173
+ if (current && !sameNative(current, n))
183
174
  reject('WORKSPACE_LOCATION_INVALID');
184
- return { stored, legacy, n, current, old };
175
+ return { stored, n, current };
185
176
  }
186
177
  async function remote(c, run) {
187
178
  check(c);
@@ -220,8 +211,6 @@ export function createWorkspaceLocations(o) {
220
211
  reject('WORKSPACE_LOCATION_CONFLICT');
221
212
  }
222
213
  }
223
- function bindingNeed(r) { const code = r.revoked ?? revokedBindings.get(r.bindingId) ?? (o.isHostBindingRevoked?.(r.bindingId) ? 'HOST_DIRECTORY_CHANGED' : undefined); if (code)
224
- revokedBindings.set(r.bindingId, code); return code; }
225
214
  function directoryChange(a, b) {
226
215
  if (a.path !== b.path || a.requestedPath !== b.requestedPath || a.identity.device !== b.identity.device || a.identity.inode !== b.identity.inode || a.entryIdentity.device !== b.entryIdentity.device || a.entryIdentity.inode !== b.entryIdentity.inode || a.isSymlink !== b.isSymlink)
227
216
  return 'HOST_DIRECTORY_CHANGED';
@@ -230,22 +219,7 @@ export function createWorkspaceLocations(o) {
230
219
  if (['read', 'write', 'execute'].some(k => typeof a.permissions[k] === 'boolean' && typeof b.permissions[k] === 'boolean' && a.permissions[k] !== b.permissions[k]))
231
220
  return 'HOST_DIRECTORY_CHANGED';
232
221
  }
233
- async function invalidate(stored, r, code, c) {
234
- // Confirmed observation cannot be forgotten if durable publication fails.
235
- revokedBindings.set(r.bindingId, code);
236
- r.revoked = code;
237
- try {
238
- await save(stored, async () => { check(c); if (!sameNative(r, await native(r.workspaceId)))
239
- reject('WORKSPACE_LOCATION_INVALID'); }, c);
240
- check(c);
241
- }
242
- catch (e) {
243
- if (exact(c))
244
- publish(snapshot.items.map(i => i.bindingId === r.bindingId ? { ...i, status: 'invalid', need: need(code) } : i));
245
- throw e;
246
- }
247
- }
248
- async function items(stored, legacy, inspectHost = false, c = connection()) {
222
+ async function items(stored, inspectHost = false, c = connection()) {
249
223
  const result = [];
250
224
  for (const w of o.registry.list()) {
251
225
  let n;
@@ -256,16 +230,14 @@ export function createWorkspaceLocations(o) {
256
230
  result.push({ workspaceId: w.id, workspaceName: w.title, localPath: w.path, bindingId: null, source: null, status: 'invalid', execution: 'not-selected', need: need('WORKSPACE_LOCATION_INVALID') });
257
231
  continue;
258
232
  }
259
- const r = stored.find(r => r.active && r.workspaceId === w.id), old = legacy.find(r => r.workspaceId === w.id);
260
- const base = { workspaceId: w.id, workspaceName: w.title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? old?.bindingId ?? null };
233
+ const r = stored.find(r => r.active && r.workspaceId === w.id);
234
+ const base = { workspaceId: w.id, workspaceName: w.title || w.id, localPath: n.localPath, bindingId: r?.bindingId ?? null };
261
235
  if (r) {
262
236
  let valid = sameNative(r, n), error;
263
- if (r.source === 'host')
264
- error = bindingNeed(r);
265
237
  if (valid && r.source !== 'local') {
266
238
  try {
267
239
  valid = (await target(c)).identity === r.identity;
268
- if (valid && !error && inspectHost && r.source === 'host') {
240
+ if (valid && inspectHost && r.source === 'host') {
269
241
  const t = await target(c);
270
242
  check(c);
271
243
  const inspected = o.hostDirectories ? await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal)) : fail('DEPENDENCY_REQUIRED');
@@ -275,7 +247,6 @@ export function createWorkspaceLocations(o) {
275
247
  else {
276
248
  const changed = directoryChange(r.remote, inspected.value);
277
249
  if (changed) {
278
- await invalidate(stored, r, changed, c);
279
250
  error = changed;
280
251
  }
281
252
  else if (Object.values(inspected.value.permissions).includes(null))
@@ -289,10 +260,7 @@ export function createWorkspaceLocations(o) {
289
260
  error = e instanceof NeedError ? e.need.code : 'WORKSPACE_LOCATION_STORAGE_FAILED';
290
261
  }
291
262
  }
292
- result.push({ ...base, source: r.source, status: valid && !error ? 'selected' : 'invalid', execution: r.source === 'local' ? 'local-pending' : r.source === 'host' ? 'host-pending' : 'legacy-confirmed', ...(r.remote ? { remote: r.remote, host: r.host } : {}), ...(!valid || error ? { need: need(error ?? 'WORKSPACE_LOCATION_INVALID') } : {}) });
293
- }
294
- else if (old) {
295
- result.push({ ...base, source: 'legacy-host', status: 'legacy-confirmation-required', execution: 'not-selected', legacyPath: old.project.path, ...(!sameNative(old, n) ? { need: need('WORKSPACE_LOCATION_INVALID') } : {}) });
263
+ result.push({ ...base, source: r.source, status: valid && !error ? 'selected' : 'invalid', execution: r.source === 'local' ? 'local-pending' : 'host-pending', ...(r.remote ? { remote: r.remote, host: r.host } : {}), ...(!valid || error ? { need: need(error ?? 'WORKSPACE_LOCATION_INVALID') } : {}) });
296
264
  }
297
265
  else
298
266
  result.push({ ...base, source: null, status: 'unselected', execution: 'not-selected' });
@@ -303,8 +271,8 @@ export function createWorkspaceLocations(o) {
303
271
  try {
304
272
  check(c);
305
273
  await prepare();
306
- const stored = await records(), legacy = await o.readLegacy();
307
- const next = await items(stored, legacy, true, c);
274
+ const stored = await records();
275
+ const next = await items(stored, true, c);
308
276
  check(c);
309
277
  publish(next);
310
278
  return ok(structuredClone(snapshot));
@@ -348,8 +316,8 @@ export function createWorkspaceLocations(o) {
348
316
  async function select(c) {
349
317
  if (!obj(c))
350
318
  reject('WORKSPACE_LOCATION_INVALID');
351
- strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source', ...(c.source === 'host' ? ['selectionToken'] : c.source === 'legacy-host' ? ['confirmLegacy'] : [])]);
352
- if (!['local', 'host', 'legacy-host'].includes(c.source))
319
+ strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId', 'source', ...(c.source === 'host' ? ['selectionToken'] : [])]);
320
+ if (!['local', 'host'].includes(c.source))
353
321
  reject('WORKSPACE_LOCATION_INVALID');
354
322
  const x = await context(c);
355
323
  let r = { ...x.n, bindingId: randomUUID(), source: c.source, active: true, key: '' };
@@ -357,28 +325,15 @@ export function createWorkspaceLocations(o) {
357
325
  const t = await target(c);
358
326
  if (!o.hostDirectories)
359
327
  reject('DEPENDENCY_REQUIRED');
360
- let selected;
361
- if (c.source === 'host') {
362
- const s = unseal(c.selectionToken);
363
- if (s.kind !== 'selection' || !sameNative(s.native, x.n) || s.identity !== t.identity || JSON.stringify(s.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }))
364
- reject('WORKSPACE_LOCATION_CONFLICT');
365
- selected = s.info;
366
- }
367
- else {
368
- if (c.confirmLegacy !== true || !x.old || x.old.phase !== 'bound' || x.old.identity !== t.identity || !sameNative(x.old, x.n))
369
- reject('WORKSPACE_LOCATION_INVALID');
370
- const inspected = await remote(c, signal => o.hostDirectories.inspect(t.value, x.old.project.path, signal));
371
- check(c);
372
- if (!inspected.ok)
373
- return inspected;
374
- selected = inspected.value;
375
- r.legacyBindingId = x.old.bindingId;
376
- }
377
- const inspected = await remote(c, signal => o.hostDirectories.inspect(t.value, selected.requestedPath, signal));
328
+ const selected = unseal(c.selectionToken);
329
+ if (selected.kind !== 'selection' || !sameNative(selected.native, x.n) || selected.identity !== t.identity || JSON.stringify(selected.context) !== JSON.stringify({ instanceId: c.instanceId, epoch: c.epoch, workspaceId: c.workspaceId, expectedBindingId: c.expectedBindingId }))
330
+ reject('WORKSPACE_LOCATION_CONFLICT');
331
+ const selectedInfo = selected.info;
332
+ const inspected = await remote(c, signal => o.hostDirectories.inspect(t.value, selectedInfo.requestedPath, signal));
378
333
  check(c);
379
334
  if (!inspected.ok)
380
335
  return inspected;
381
- if (!sameDirectory(selected, inspected.value))
336
+ if (!sameDirectory(selectedInfo, inspected.value))
382
337
  reject('HOST_DIRECTORY_CHANGED');
383
338
  if (inspected.value.permissions.read !== true || inspected.value.permissions.execute !== true)
384
339
  reject('HOST_DIRECTORY_UNREADABLE');
@@ -387,7 +342,7 @@ export function createWorkspaceLocations(o) {
387
342
  if (!sameNative(await native(c.workspaceId), x.n))
388
343
  reject('WORKSPACE_LOCATION_CONFLICT');
389
344
  check(c);
390
- if (x.current && !bindingNeed(x.current) && x.current.source === r.source && JSON.stringify(x.current.remote) === JSON.stringify(r.remote) && x.current.identity === r.identity)
345
+ if (x.current && x.current.source === r.source && JSON.stringify(x.current.remote) === JSON.stringify(r.remote) && x.current.identity === r.identity)
391
346
  return ok(structuredClone(snapshot));
392
347
  for (const old of x.stored)
393
348
  if (old.active && old.workspaceId === c.workspaceId)
@@ -400,11 +355,14 @@ export function createWorkspaceLocations(o) {
400
355
  reject('WORKSPACE_LOCATION_CONFLICT');
401
356
  check(c);
402
357
  }, c);
403
- publish(await items(x.stored, x.legacy));
358
+ publish(await items(x.stored));
404
359
  check(c);
405
360
  return ok(structuredClone(snapshot));
406
361
  }
362
+ function checkPending(id) { if (o.isWorkspacePending?.(id))
363
+ reject('WORKSPACE_PICKER_ROLLBACK_FAILED'); }
407
364
  function checkLocalContext(c) {
365
+ checkPending(c.workspaceId);
408
366
  const current = o.api.getConnectionState();
409
367
  if (disposed || current.phase === 'disposed')
410
368
  reject('DISPOSED');
@@ -421,7 +379,6 @@ export function createWorkspaceLocations(o) {
421
379
  checkLocalContext(c);
422
380
  await prepare();
423
381
  const stored = await records();
424
- checkLocalContext(c);
425
382
  const record = stored.find(r => r.active && r.workspaceId === c.workspaceId);
426
383
  if (!record || record.bindingId !== c.expectedBindingId)
427
384
  reject('WORKSPACE_LOCATION_CONFLICT');
@@ -429,18 +386,15 @@ export function createWorkspaceLocations(o) {
429
386
  reject('WORKSPACE_LOCATION_INVALID');
430
387
  const registeredPath = registeredLocalPath(c.workspaceId);
431
388
  const first = await native(c.workspaceId);
432
- checkLocalContext(c);
433
389
  if (!sameNative(record, first))
434
390
  reject('WORKSPACE_LOCATION_INVALID');
435
391
  const facts = readLocalWorkspaceProcess();
436
392
  if (!facts.ok)
437
393
  return facts;
438
394
  const latest = (await records()).find(r => r.active && r.workspaceId === c.workspaceId);
439
- checkLocalContext(c);
440
395
  if (!latest || latest.bindingId !== record.bindingId || latest.source !== 'local' || !sameNative(record, latest))
441
396
  reject('WORKSPACE_LOCATION_CONFLICT');
442
397
  const last = await native(c.workspaceId);
443
- checkLocalContext(c);
444
398
  if (!sameNative(record, last))
445
399
  reject('WORKSPACE_LOCATION_INVALID');
446
400
  // Final synchronous registry check closes changes during the preceding filesystem awaits.
@@ -455,64 +409,30 @@ export function createWorkspaceLocations(o) {
455
409
  return Promise.resolve(fail('DISPOSED'));
456
410
  if (!obj(request) || Object.keys(request).sort().join(',') !== 'epoch,expectedBindingId,instanceId,workspaceId' || !token(request.instanceId) || !Number.isSafeInteger(request.epoch) || request.epoch < 0 || !token(request.workspaceId) || !token(request.expectedBindingId))
457
411
  return Promise.resolve(fail('WORKSPACE_LOCATION_INVALID'));
412
+ if (o.isWorkspacePending?.(request.workspaceId))
413
+ return Promise.resolve(fail('WORKSPACE_PICKER_ROLLBACK_FAILED'));
458
414
  // Copy before queueing: retaining the caller's input cannot change this operation's scope.
459
415
  const c = { instanceId: request.instanceId, epoch: request.epoch, workspaceId: request.workspaceId, expectedBindingId: request.expectedBindingId };
460
416
  return serial(() => localContext(c));
461
417
  }
462
- async function guard(sessionId) {
463
- const c = connection();
464
- check(c);
465
- await prepare();
466
- check(c);
467
- const workspaces = o.registry.list().filter(w => w.sessionIds.includes(sessionId));
468
- if (workspaces.length !== 1)
469
- return fail('WORKSPACE_LOCATION_REQUIRED');
470
- const stored = await records();
471
- check(c);
472
- const r = stored.find(r => r.active && r.workspaceId === workspaces[0].id);
473
- if (!r)
474
- return fail('WORKSPACE_LOCATION_REQUIRED');
475
- if (!sameNative(r, await native(r.workspaceId)))
476
- return fail('WORKSPACE_LOCATION_INVALID');
477
- check(c);
478
- if (r.source === 'local')
479
- return fail('WORKSPACE_EXECUTION_UNAVAILABLE');
480
- if (r.source === 'host')
481
- return fail('WORKSPACE_LOCATION_PROVIDER_REQUIRED');
482
- const t = await target(c), legacy = (await o.readLegacy()).find(old => old.bindingId === r.legacyBindingId);
483
- check(c);
484
- if (!legacy || r.identity !== t.identity || legacy.identity !== t.identity || legacy.project.path !== r.remote?.path)
485
- return fail('WORKSPACE_LOCATION_INVALID');
486
- const current = o.hostDirectories ? await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal)) : undefined;
487
- check(c);
488
- if (!current?.ok || r.remote.path !== current.value.path || r.remote.requestedPath !== current.value.requestedPath || r.remote.identity.device !== current.value.identity.device || r.remote.identity.inode !== current.value.identity.inode || JSON.stringify(r.remote.entryIdentity) !== JSON.stringify(current.value.entryIdentity))
489
- return fail('WORKSPACE_LOCATION_INVALID');
490
- return ok(undefined);
491
- }
492
- // Resolves remain serialized with selection. Already-admitted detail writes
493
- // use their own queue and revalidate the original binding at every guard.
494
- function withHostBinding(input, run, finalize = () => { }, inspectRemote = true) {
418
+ function withHostBinding(input, run, finalize = () => { }) {
495
419
  const c = structuredClone(input);
496
420
  return serial(async () => {
497
421
  strict(c, ['instanceId', 'epoch', 'workspaceId', 'expectedBindingId']);
498
422
  if (!token(c.expectedBindingId))
499
423
  reject('WORKSPACE_LOCATION_INVALID');
424
+ checkPending(c.workspaceId);
500
425
  const x = await context(c), r = x.current;
501
426
  if (!r || r.source !== 'host' || !r.remote)
502
427
  reject('WORKSPACE_LOCATION_CONFLICT');
503
- const invalid = bindingNeed(r);
504
- if (invalid)
505
- reject(invalid);
506
428
  const t = await target(c);
507
429
  check(c);
508
430
  if (t.identity !== r.identity)
509
431
  reject('WORKSPACE_LOCATION_INVALID');
510
- const bytes = inspectRemote ? await readPrivate(file, o.metadataMaxBytes) : undefined, registeredPath = registeredLocalPath(c.workspaceId);
432
+ const bytes = await readPrivate(file, o.metadataMaxBytes), registeredPath = registeredLocalPath(c.workspaceId);
511
433
  const guard = () => {
434
+ checkPending(c.workspaceId);
512
435
  check(c);
513
- const invalid = bindingNeed(r);
514
- if (invalid)
515
- reject(invalid);
516
436
  const now = o.api.getConnectionState();
517
437
  if (now.phase !== 'connected')
518
438
  reject('CONNECTION_LOST');
@@ -522,12 +442,8 @@ export function createWorkspaceLocations(o) {
522
442
  const v = latest.value.target;
523
443
  if (hash([v.host, v.username, v.port, v.projectRoot, v.session, readPrivateSync(v.knownHostsFile, o.metadataMaxBytes)]) !== t.identity)
524
444
  reject('WORKSPACE_LOCATION_INVALID');
525
- if (inspectRemote) {
526
- if (readPrivateSync(file, o.metadataMaxBytes) !== bytes)
527
- reject('WORKSPACE_LOCATION_CONFLICT');
528
- }
529
- else
530
- guardStoredBinding(r);
445
+ if (readPrivateSync(file, o.metadataMaxBytes) !== bytes)
446
+ reject('WORKSPACE_LOCATION_CONFLICT');
531
447
  if (registeredLocalPath(c.workspaceId) !== registeredPath)
532
448
  reject('WORKSPACE_LOCATION_INVALID');
533
449
  try {
@@ -541,95 +457,56 @@ export function createWorkspaceLocations(o) {
541
457
  reject('WORKSPACE_LOCATION_INVALID');
542
458
  }
543
459
  };
544
- const inspect = async () => {
545
- guard();
546
- if (!o.hostDirectories)
547
- reject('DEPENDENCY_REQUIRED');
548
- const current = await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal));
549
- guard();
550
- if (!current.ok)
551
- throw new NeedError(current.error);
552
- const a = r.remote, b = current.value;
553
- const changed = directoryChange(a, b);
554
- if (changed) {
555
- await invalidate(x.stored, r, changed, c);
556
- const next = await items(x.stored, x.legacy, false, c);
557
- check(c);
558
- publish(next);
559
- reject(changed);
560
- }
561
- if (Object.values(b.permissions).includes(null))
562
- reject('HOST_DIRECTORY_UNREADABLE');
563
- return b;
564
- };
565
- const directory = inspectRemote ? await inspect() : structuredClone(r.remote), value = { directory, target: structuredClone(t.value), local: { path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, revision: snapshot.revision };
566
- const result = await run(value, guard);
567
460
  guard();
461
+ if (!o.hostDirectories)
462
+ reject('DEPENDENCY_REQUIRED');
463
+ const current = await remote(c, signal => o.hostDirectories.inspect(t.value, r.remote.requestedPath, signal));
464
+ if (!current.ok)
465
+ throw new NeedError(current.error);
466
+ const changed = directoryChange(r.remote, current.value);
467
+ if (changed)
468
+ reject(changed);
469
+ if (Object.values(current.value.permissions).includes(null))
470
+ reject('HOST_DIRECTORY_UNREADABLE');
471
+ const value = { directory: current.value, target: structuredClone(t.value), local: { path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, revision: snapshot.revision };
472
+ const result = await run(value, guard);
568
473
  if (!result.ok)
569
474
  return result;
570
- // Do not treat directory content timestamps as identity changes.
571
475
  guard();
572
476
  finalize();
573
- guard();
574
477
  return result;
575
- }, !inspectRemote);
478
+ });
576
479
  }
577
- // Admission remains with source selection; only existing detail authority
578
- // uses the independent queue. Neither path is a public execution API.
579
- function withLocalBinding(c, run, queue) {
580
- return serial(async () => {
581
- const x = await context(c);
582
- checkLocalContext(c);
583
- if (!x.current || x.current.source !== 'local')
584
- reject('WORKSPACE_LOCATION_INVALID');
585
- const registeredPath = registeredLocalPath(c.workspaceId);
586
- const guard = () => {
587
- checkLocalContext(c);
588
- if (queue === 'detail-write')
589
- guardStoredBinding(x.current);
590
- if (registeredLocalPath(c.workspaceId) !== registeredPath)
591
- reject('WORKSPACE_LOCATION_INVALID');
592
- try {
593
- const path = realpathSync(registeredPath), st = lstatSync(path);
594
- if (path !== x.n.localPath || !st.isDirectory() || st.isSymbolicLink() || st.dev !== x.n.localDev || st.ino !== x.n.localIno)
595
- reject('WORKSPACE_LOCATION_INVALID');
596
- }
597
- catch (e) {
598
- if (e instanceof NeedError)
599
- throw e;
600
- reject('WORKSPACE_LOCATION_INVALID');
601
- }
602
- checkLocalContext(c);
603
- };
604
- guard();
605
- return run({ path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, guard);
606
- }, queue === 'detail-write');
480
+ function captureWorkspacePickerGuard(workspaceId, expectedBindingId) {
481
+ const original = parseRecords(readPrivateSync(file, o.metadataMaxBytes)).find(r => r.active && r.workspaceId === workspaceId);
482
+ if (!original || original.bindingId !== expectedBindingId)
483
+ reject('WORKSPACE_LOCATION_CONFLICT');
484
+ const registeredPath = registeredLocalPath(workspaceId);
485
+ return () => { guardStoredBinding(original); if (registeredLocalPath(workspaceId) !== registeredPath)
486
+ reject('WORKSPACE_LOCATION_INVALID'); };
607
487
  }
608
- return { withHostBinding, isHostBindingRevoked: (id) => revokedBindings.has(id) || !!o.isHostBindingRevoked?.(id), withLocalBinding, getLocalWorkspaceContext, getWorkspaceLocationState: () => ({ ...structuredClone(snapshot), host: currentHost() }), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), guardLegacySession: (id) => serial(() => guard(id)), resolveLegacySession: (id, resolve) => serial(async () => {
609
- const c = connection(), before = await guard(id);
610
- if (!before.ok)
611
- return before;
612
- check(c);
613
- const result = await resolve();
614
- check(c);
615
- const after = await guard(id);
616
- check(c);
617
- return after.ok ? result : after;
618
- }), observeConnection() {
488
+ return { captureWorkspacePickerGuard, withHostBinding, getLocalWorkspaceContext, getWorkspaceLocationState: () => ({ ...structuredClone(snapshot), host: currentHost() }), onWorkspaceLocationState(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; }, refreshWorkspaceLocations: () => serial(refresh), browseWorkspaceHostDirectories: (c) => serial(() => browse(c)), selectWorkspaceLocation: (c) => serial(() => select(c)), observeConnection() {
619
489
  if (disposed)
620
490
  return;
621
491
  for (const controller of controllers)
622
492
  controller.abort();
623
- publish(snapshot.items.map(i => i.source === 'host' || i.source === 'legacy-host' ? { ...i, status: i.status === 'legacy-confirmation-required' ? i.status : 'invalid', need: need('WORKSPACE_LOCATION_CONFLICT') } : i));
624
- if (o.api.getConnectionState().phase === 'connected') {
625
- const c = connection();
626
- return serial(() => refresh(c));
627
- }
493
+ const connected = o.api.getConnectionState().phase === 'connected';
494
+ publish(snapshot.items.map(item => {
495
+ if (item.source !== 'host')
496
+ return item;
497
+ if (!connected)
498
+ return { ...item, need: need('CONNECTION_LOST') };
499
+ if (item.need?.code === 'CONNECTION_LOST' || item.need?.code === 'WORKSPACE_LOCATION_CONFLICT') {
500
+ const { need: _, ...selected } = item;
501
+ return selected;
502
+ }
503
+ return item;
504
+ }));
628
505
  }, dispose() {
629
506
  disposed = true;
630
507
  for (const controller of controllers)
631
508
  controller.abort();
632
509
  listeners.clear();
633
- return Promise.all([tail, detailTail]).then(() => { });
510
+ return tail.then(() => { });
634
511
  } };
635
512
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.23",
3
+ "version": "0.7.26",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1"
@@ -69,7 +69,8 @@
69
69
  "@deepseek-ai/dsh-client-runtime",
70
70
  "@deepseek-ai/dsh-client-ui-settings",
71
71
  "@deepseek-ai/dsh-client-ui-slots",
72
- "@deepseek-ai/dsh-client-locale"
72
+ "@deepseek-ai/dsh-client-locale",
73
+ "@deepseek-ai/dsh-client-ui-workspace"
73
74
  ]
74
75
  },
75
76
  "bundle": {
@@ -1,57 +0,0 @@
1
- const fs=require('node:fs/promises');
2
- const path=require('node:path');
3
- const {spawnSync}=require('node:child_process');
4
- function validName(name){return typeof name==='string'&&name!==''&&name!=='.'&&name!=='..'&&!/[\\/\x00-\x1f\x7f]/.test(name);}
5
- // Repository selection must come solely from trusted root, never the remote shell's Git overrides.
6
- const gitEnvironment=()=>Object.fromEntries(Object.entries(process.env).filter(([key])=>!key.startsWith('GIT_')));
7
- const outputPath=text=>text.endsWith('\n')?text.slice(0,-1):text;
8
- const error=code=>({protocolVersion:1,ok:false,error:{code}});
9
- async function execute(request){
10
- if(request?.protocolVersion!==1||!['list','create'].includes(request.operation))return error('PROJECT_PROTOCOL_INVALID');
11
- if(request.operation==='create'&&!validName(request.name))return error('PROJECT_NAME_INVALID');
12
- const root=request.root;
13
- try{
14
- if(typeof root!=='string'||!path.isAbsolute(root))return error('PROJECT_ROOT_INVALID');
15
- const st=await fs.lstat(root);
16
- if(!st.isDirectory()||st.isSymbolicLink()||st.uid!==process.getuid()||(st.mode&0o077)!==0||await fs.realpath(root)!==root)return error('PROJECT_ROOT_INVALID');
17
- }catch{return error('PROJECT_ROOT_INVALID');}
18
- if(request.operation==='create'){
19
- const destination=path.join(root,request.name);let created=false;
20
- try{
21
- await fs.mkdir(destination,{mode:0o700});created=true;
22
- const result=spawnSync('git',['-c','init.templateDir=','init','--quiet','--',destination],{encoding:'utf8',stdio:['ignore','pipe','pipe'],env:gitEnvironment()});
23
- if(result.status!==0)return error('PROJECT_INIT_FAILED');
24
- const verified=spawnSync('git',['-C',destination,'rev-parse','--show-toplevel'],{encoding:'utf8',stdio:['ignore','pipe','pipe'],env:gitEnvironment()});
25
- if(verified.status!==0||outputPath(verified.stdout)!==destination)return error('PROJECT_INIT_FAILED');
26
- return {protocolVersion:1,ok:true,value:{name:request.name,path:destination}};
27
- }catch(e){return error(!created&&e.code==='EEXIST'?'PROJECT_EXISTS':'PROJECT_CREATE_FAILED');}
28
- }
29
- try{
30
- const projects=[],unavailable=[];
31
- for(const name of (await fs.readdir(root)).sort()){
32
- const directory=path.join(root,name),st=await fs.lstat(directory);let reason;
33
- if(!validName(name))reason='invalid-name';
34
- else if(st.isSymbolicLink())reason='symlink';
35
- else if(!st.isDirectory())reason='not-directory';
36
- else if(st.uid!==process.getuid()||(st.mode&0o077)!==0)reason='permissions';
37
- else{
38
- let metadata=false;try{await fs.lstat(path.join(directory,'.git'));metadata=true;}catch(e){if(e.code!=='ENOENT')throw e;}
39
- if(!metadata)reason='not-git';
40
- else{
41
- const git=spawnSync('git',['-C',directory,'rev-parse','--show-toplevel'],{encoding:'utf8',stdio:['ignore','pipe','pipe'],env:gitEnvironment()});
42
- if(git.status!==0)reason='invalid-git';
43
- else if(outputPath(git.stdout)!==directory)reason='outside-root';
44
- }
45
- }
46
- if(reason)unavailable.push({name,reason});else projects.push({name,path:directory});
47
- }
48
- return {protocolVersion:1,ok:true,value:{projects,unavailable}};
49
- }catch{return error('PROJECT_LIST_FAILED');}
50
- }
51
- async function main(){
52
- let input='';for await(const chunk of process.stdin)input+=chunk;
53
- let result;try{result=await execute(JSON.parse(input));}catch{result=error('PROJECT_PROTOCOL_INVALID');}
54
- process.stdout.write(JSON.stringify(result)+'\n');
55
- }
56
- module.exports={execute,validName};
57
- if(require.main===module)void main();
@@ -1,32 +0,0 @@
1
- export interface ConversationDetailSettingsValues {
2
- maxEventBytes: number;
3
- pageSize: number;
4
- }
5
- export interface ConversationDetailSettingsState {
6
- instanceId: string;
7
- revision: number;
8
- phase: 'loading' | 'ready' | 'saving' | 'failed' | 'disposed';
9
- values?: ConversationDetailSettingsValues;
10
- source: 'config' | 'saved';
11
- errorCode?: 'SETTINGS_REQUIRED' | 'REMOTE_DETAIL_STORAGE_FAILED';
12
- }
13
- export declare function validDetailSettings(v: any): v is ConversationDetailSettingsValues;
14
- export declare function createConversationDetailSettings(options: {
15
- profileDir?: string;
16
- initial?: Partial<ConversationDetailSettingsValues>;
17
- metadataMaxBytes?: number;
18
- }): {
19
- ready: Promise<void>;
20
- getState: () => ConversationDetailSettingsState;
21
- values: () => ConversationDetailSettingsValues | undefined;
22
- onState(fn: () => void): () => void;
23
- save: (input: ConversationDetailSettingsValues) => Promise<{
24
- ok: false;
25
- error: import("./api.ts").ConnectNeed;
26
- } | {
27
- ok: true;
28
- value: undefined;
29
- }>;
30
- dispose(): Promise<void>;
31
- };
32
- export type ConversationDetailSettings = ReturnType<typeof createConversationDetailSettings>;