@ai-workbench/connect 0.7.19 → 0.7.21

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.
@@ -0,0 +1,71 @@
1
+ import type { ConnectApi, HostSessionProjectTarget, Provider, RemoteConversationDetail, Result, WorkspaceUse } from './api.ts';
2
+ import type { HostWorkspaceResolveContext, WorkspaceLocationState } from './workspace-location-types.ts';
3
+ import type { createWorkspaceLocations } from './workspace-locations.ts';
4
+ import type { NativeWorkspaceRegistry } from './workspace-bindings.ts';
5
+ interface Session {
6
+ header: Record<string, any>;
7
+ seq: number;
8
+ }
9
+ interface Event {
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 Event[];
28
+ }>;
29
+ close(): Promise<void>;
30
+ }>;
31
+ };
32
+ }
33
+ interface Options {
34
+ profileDir: string;
35
+ metadataMaxBytes: number;
36
+ api: ConnectApi;
37
+ registry: NativeWorkspaceRegistry;
38
+ services: () => Services;
39
+ readHeader: (id: string) => Promise<any>;
40
+ readLegacy: () => Promise<{
41
+ sessionIds: string[];
42
+ }[]>;
43
+ context: () => Promise<Result<{
44
+ identity: string;
45
+ guard?: () => void;
46
+ }>>;
47
+ withHostBinding: ReturnType<typeof createWorkspaceLocations>['withHostBinding'];
48
+ }
49
+ export declare function changedSessionBinding(): never;
50
+ export declare function createHostSessionProjects(o: Options): {
51
+ active: () => boolean;
52
+ observe: (session: Session, event: Event) => void;
53
+ observeLocations: (state: WorkspaceLocationState) => void;
54
+ observeSessionDisposed: (session: Session) => void;
55
+ resolve: (id: string, use: WorkspaceUse, input: HostWorkspaceResolveContext) => Promise<Result<HostSessionProjectTarget>>;
56
+ readScope: (sessionId: string, provider: Provider, ref?: string, detail?: Pick<RemoteConversationDetail, "sessionId" | "provider" | "instanceId" | "epoch">, expectedIdentity?: string) => Promise<Result<{
57
+ identity: string;
58
+ guard: () => void;
59
+ cacheGuard: () => void;
60
+ }>>;
61
+ withWrite: <T>(detail: RemoteConversationDetail, run: (proof: {
62
+ identity: string;
63
+ hostBindingRef: string;
64
+ guard: () => void;
65
+ }) => Promise<Result<T>>) => Promise<Result<T>>;
66
+ compatible: (id: string, header: any, source: "host" | "local" | "legacy-host", bindingId?: string) => void;
67
+ hasSession: (id: string) => boolean;
68
+ dispose(): void;
69
+ };
70
+ export type HostDetailsAdmission = ReturnType<typeof createHostSessionProjects>;
71
+ export {};
@@ -0,0 +1,291 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { basename } from 'node:path';
3
+ import { realpath } from 'node:fs/promises';
4
+ import { acceptanceStore, canonical, sameSessionHeader, validHeader } from "./local-acceptance-store.js";
5
+ import { hostProjectStore } from "./host-session-store.js";
6
+ import { fail, ok, need, NeedError } from "./needs.js";
7
+ const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
8
+ const int = (v) => Number.isSafeInteger(v) && v >= 0;
9
+ function reject(code) { throw new NeedError(need(code)); }
10
+ export function changedSessionBinding() { const n = need('PROJECT_BINDING_INVALID'); n.message = '文件来源已改,请新建会话继续'; n.actor = 'employee'; n.requires = '新会话与当前文件来源'; n.action = { id: 'new-session', label: '新建会话继续', available: false }; throw new NeedError(n); }
11
+ const resultError = (e) => e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_STORAGE_FAILED');
12
+ export function createHostSessionProjects(o) {
13
+ const store = hostProjectStore(o.profileDir, o.metadataMaxBytes), local = acceptanceStore(o.profileDir, o.metadataMaxBytes), runtimeId = randomUUID(), observed = new WeakMap(), revisions = new Map(), blocked = new Set(), persistenceIdentity = o.services().persistence.identity;
14
+ let disposed = false, uncertain = false, uncertainRecordId;
15
+ function active() { if (o.services().persistence.identity !== persistenceIdentity)
16
+ disposed = true; return !disposed; }
17
+ function life(c) { const now = o.api.getConnectionState(); if (!active() || now.phase === 'disposed')
18
+ reject('DISPOSED'); if (now.phase !== 'connected' || now.instanceId !== c.instanceId || now.epoch !== c.epoch)
19
+ reject('CONNECTION_LOST'); }
20
+ function mapping(id, workspaceId) { const list = o.registry.list().filter(w => w.sessionIds.includes(id)), registered = o.registry.get(workspaceId); if (list.length !== 1 || list[0].id !== workspaceId || !registered || registered.path !== list[0].path || !registered.sessionIds.includes(id)) {
21
+ for (const r of store.read())
22
+ if (r.sessionId === id)
23
+ blocked.add(r.id);
24
+ changedSessionBinding();
25
+ } }
26
+ function compatible(id, header, source, bindingId) {
27
+ const existing = store.read().filter(r => r.sessionId === id && sameSessionHeader(r.header, header));
28
+ if (existing.some(r => source !== 'host' || r.bindingId !== bindingId))
29
+ changedSessionBinding();
30
+ }
31
+ function observe(session, event) {
32
+ if (!active() || o.services().sessions.get(session.header.id) !== session)
33
+ return;
34
+ if (event.type === 'turn/start')
35
+ observed.set(session, new Map([[event.seq, { seq: event.seq, type: event.type, data: { turn: event.data.turn } }]]));
36
+ else if (event.type === 'turn/end')
37
+ observed.delete(session);
38
+ else if (event.type === 'user/message' && event.data?.source?.kind === 'user')
39
+ observed.get(session)?.set(event.seq, { seq: event.seq, type: event.type, data: { id: event.data.id } });
40
+ }
41
+ function capture(id, use, c) {
42
+ if (!text(id) || !use || Object.keys(use).sort().join(',') !== 'provider,purpose' || !['claude', 'codex'].includes(use.provider) || use.purpose !== 'user-turn')
43
+ reject('PROJECT_BINDING_REQUIRED');
44
+ if (!c || Object.keys(c).sort().join(',') !== 'epoch,expectedBindingId,instanceId,workspaceId' || !text(c.instanceId) || !int(c.epoch) || !text(c.workspaceId) || !text(c.expectedBindingId))
45
+ reject('WORKSPACE_LOCATION_INVALID');
46
+ life(c);
47
+ const services = o.services(), session = services.sessions.get(id);
48
+ if (!session || !int(session.seq) || !validHeader(session.header) || session.header.id !== id)
49
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
50
+ const header = structuredClone(session.header), watermark = session.seq, proof = observed.get(session);
51
+ if (!proof || ![...proof.values()].some(e => e.type === 'user/message'))
52
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
53
+ const guard = () => { life(c); mapping(id, c.workspaceId); if (o.services().sessions.get(id) !== session || canonical(session.header) !== canonical(header) || session.seq !== watermark)
54
+ reject('LOCAL_USER_TURN_CHANGED'); };
55
+ guard();
56
+ return { services, session, header, watermark, proof, guard };
57
+ }
58
+ async function verify(c, provider, path, guard) {
59
+ if (typeof c.header.cwd !== 'string' || await realpath(c.header.cwd) !== path)
60
+ reject('WORKSPACE_LOCATION_INVALID');
61
+ guard();
62
+ if (!await c.services.sessions.flush(c.session))
63
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
64
+ guard();
65
+ const handle = await c.services.persistence.open(c.header.id, 'read');
66
+ let events = [], inherited = 0;
67
+ try {
68
+ guard();
69
+ if (handle.id !== c.header.id || handle.access !== 'read' || !sameSessionHeader(handle.header, c.header) || !int(handle.inheritedEventCount))
70
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
71
+ inherited = handle.inheritedEventCount;
72
+ events = (await handle.read()).events;
73
+ guard();
74
+ }
75
+ finally {
76
+ await handle.close();
77
+ }
78
+ guard();
79
+ if (!Array.isArray(events) || events.length < c.watermark || events.some((e, i) => e.seq !== i))
80
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
81
+ let start, step, input, route, routeContext;
82
+ for (const e of events.slice(0, c.watermark)) {
83
+ if (e.type === 'turn/start') {
84
+ start = e;
85
+ step = undefined;
86
+ input = undefined;
87
+ route = undefined;
88
+ routeContext = undefined;
89
+ }
90
+ else if (e.type === 'turn/end') {
91
+ start = undefined;
92
+ step = undefined;
93
+ input = undefined;
94
+ route = undefined;
95
+ routeContext = undefined;
96
+ }
97
+ else if (e.type === 'step/start')
98
+ step = e;
99
+ else if (e.type === 'step/end')
100
+ step = undefined;
101
+ else if (e.type === 'user/message' && start && e.data?.source?.kind === 'user' && c.proof.has(e.seq))
102
+ input = e;
103
+ else if (e.type === 'request/header')
104
+ route = e.data?.header?.config?.provider;
105
+ else if (e.type === 'request/context')
106
+ routeContext = e.data?.provider;
107
+ }
108
+ const expected = provider === 'claude' ? 'claude-code-workbench' : 'codex-remote';
109
+ if (!start || !step || !input || !int(start.data.turn) || step.data.turn !== start.data.turn || [start.seq, step.seq, input.seq].some(n => n < inherited) || !c.proof.has(start.seq) || c.proof.get(start.seq)?.data.turn !== start.data.turn || !text(input.data.id) || !c.proof.has(input.seq) || c.proof.get(input.seq)?.data.id !== input.data.id || route !== expected || routeContext !== undefined && routeContext !== expected)
110
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
111
+ }
112
+ function revoke(bindingId) { const items = store.read(); let changed = false; for (const r of items)
113
+ if (r.bindingId === bindingId && !r.revoked) {
114
+ r.revoked = true;
115
+ changed = true;
116
+ } if (changed) {
117
+ try {
118
+ store.save(items, () => { });
119
+ }
120
+ catch (e) {
121
+ uncertain = true;
122
+ throw e;
123
+ }
124
+ } }
125
+ async function resolve(id, use, input) {
126
+ let c, location, provider;
127
+ try {
128
+ location = structuredClone(input);
129
+ provider = use?.provider;
130
+ c = capture(id, structuredClone(use), location);
131
+ }
132
+ catch (e) {
133
+ return resultError(e);
134
+ }
135
+ try {
136
+ let commit = () => { c.guard(); };
137
+ const result = await o.withHostBinding(location, async (value, bindingGuard) => {
138
+ const context = await o.context();
139
+ c.guard();
140
+ bindingGuard();
141
+ if (!context.ok)
142
+ return context;
143
+ const guard = () => { c.guard(); context.value.guard?.(); bindingGuard(); };
144
+ guard();
145
+ compatible(id, c.header, 'host', location.expectedBindingId);
146
+ if (local.read().some(r => r.acceptance.sessionId === id && sameSessionHeader(r.header, c.header)) || (await o.readLegacy()).some(r => r.sessionIds.includes(id)))
147
+ changedSessionBinding();
148
+ guard();
149
+ const ready = await o.api.ensureReady(provider);
150
+ guard();
151
+ if (!ready.ok)
152
+ return ready;
153
+ if (canonical(ready.value) !== canonical(value.target))
154
+ reject('CONNECTION_LOST');
155
+ await verify(c, provider, value.local.path, guard);
156
+ guard();
157
+ commit = () => {
158
+ guard();
159
+ const items = store.read();
160
+ if (items.some(r => r.bindingId === location.expectedBindingId && r.revoked))
161
+ reject('HOST_DIRECTORY_CHANGED');
162
+ const existing = items.find(r => r.sessionId === id && r.provider === provider && sameSessionHeader(r.header, c.header) && r.bindingId === location.expectedBindingId && r.instanceId === location.instanceId && r.epoch === location.epoch && r.runtimeId === runtimeId);
163
+ if (uncertain && (!existing || existing.id !== uncertainRecordId))
164
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
165
+ if (existing) {
166
+ if (blocked.has(existing.id))
167
+ changedSessionBinding();
168
+ if (canonical(existing.header) !== canonical(c.header) || existing.identity !== context.value.identity || canonical(existing.local) !== canonical(value.local))
169
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
170
+ store.verify(existing, guard);
171
+ uncertain = false;
172
+ uncertainRecordId = undefined;
173
+ }
174
+ else {
175
+ const record = { id: randomUUID(), sessionId: id, provider, header: c.header, identity: context.value.identity, workspaceId: location.workspaceId, bindingId: location.expectedBindingId, instanceId: location.instanceId, epoch: location.epoch, runtimeId, local: value.local, directory: value.directory, revoked: false, key: '' };
176
+ items.push(record);
177
+ try {
178
+ store.save(items, guard);
179
+ }
180
+ catch (e) {
181
+ if (e instanceof NeedError)
182
+ throw e;
183
+ uncertain = true;
184
+ uncertainRecordId = record.id;
185
+ throw new NeedError(need('REMOTE_DETAIL_STORAGE_FAILED'));
186
+ }
187
+ }
188
+ guard();
189
+ };
190
+ guard();
191
+ return ok({ instanceId: location.instanceId, epoch: location.epoch, sessionId: id, workspaceId: location.workspaceId, bindingId: location.expectedBindingId, bindingRevision: value.revision, source: 'host', directory: structuredClone(value.directory), project: { name: basename(value.directory.path) || '/', path: value.directory.path }, target: structuredClone(value.target) });
192
+ }, () => commit());
193
+ if (result.ok)
194
+ c.guard();
195
+ if (!result.ok && ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE', 'WORKSPACE_LOCATION_INVALID'].includes(result.error.code))
196
+ revoke(location.expectedBindingId);
197
+ return result;
198
+ }
199
+ catch (e) {
200
+ return resultError(e);
201
+ }
202
+ }
203
+ async function readScope(sessionId, provider, ref, detail, expectedIdentity) {
204
+ try {
205
+ const before = o.api.getConnectionState();
206
+ life(before);
207
+ const items = store.read(), context = await o.context();
208
+ life(before);
209
+ if (!context.ok)
210
+ return context;
211
+ const live = o.services().sessions.get(sessionId), revision = revisions.get(sessionId) ?? 0, rawHeader = await o.readHeader(sessionId), header = rawHeader && structuredClone(rawHeader);
212
+ life(before);
213
+ context.value.guard?.();
214
+ const record = ref ? items.find(r => r.id === ref) : undefined;
215
+ if (ref && !record)
216
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
217
+ if (record && detail && (record.sessionId !== detail.sessionId || record.provider !== detail.provider || record.instanceId !== detail.instanceId || record.epoch !== detail.epoch || expectedIdentity !== undefined && record.identity !== expectedIdentity))
218
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
219
+ const admitted = (record ? [record] : items).filter(r => r.identity === context.value.identity && r.sessionId === sessionId && r.provider === provider && sameSessionHeader(r.header, header));
220
+ if (!admitted.length)
221
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
222
+ const guard = () => { life(before); context.value.guard?.(); const current = o.services().sessions.get(sessionId); if (revision !== (revisions.get(sessionId) ?? 0) || live && current !== live || current && canonical(current.header) !== canonical(header))
223
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); const now = store.read(); for (const r of admitted) {
224
+ const same = now.find(n => n.id === r.id);
225
+ if (!same || canonical({ ...same, revoked: false, key: '' }) !== canonical({ ...r, revoked: false, key: '' }))
226
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
227
+ } };
228
+ guard();
229
+ return ok({ identity: context.value.identity, guard, cacheGuard: () => { guard(); if (!live || o.services().sessions.get(sessionId) !== live)
230
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); } });
231
+ }
232
+ catch (e) {
233
+ return resultError(e);
234
+ }
235
+ }
236
+ async function withWrite(detail, run) {
237
+ try {
238
+ const before = o.api.getConnectionState();
239
+ life(before);
240
+ if (uncertain)
241
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
242
+ const r = store.read().find(r => r.sessionId === detail.sessionId && r.provider === detail.provider && r.instanceId === before.instanceId && r.epoch === before.epoch && r.runtimeId === runtimeId && !r.revoked && !blocked.has(r.id));
243
+ if (!r)
244
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
245
+ if (detail.instanceId !== r.instanceId || detail.epoch !== r.epoch)
246
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
247
+ const header = await o.readHeader(r.sessionId);
248
+ life(before);
249
+ if (canonical(header) !== canonical(r.header))
250
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
251
+ let finalGuard = () => life(before);
252
+ const result = await o.withHostBinding({ instanceId: r.instanceId, epoch: r.epoch, workspaceId: r.workspaceId, expectedBindingId: r.bindingId }, async (value, bindingGuard) => {
253
+ const context = await o.context();
254
+ life(before);
255
+ if (!context.ok)
256
+ return context;
257
+ if (context.value.identity !== r.identity)
258
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
259
+ const guard = () => { life(before); context.value.guard?.(); bindingGuard(); mapping(r.sessionId, r.workspaceId); const current = o.services().sessions.get(r.sessionId); if (!current || canonical(current.header) !== canonical(r.header))
260
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); if (canonical(value.local) !== canonical(r.local))
261
+ reject('WORKSPACE_LOCATION_INVALID'); const same = store.read().find(n => n.id === r.id); if (!same || canonical(same) !== canonical(r) || same.revoked)
262
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); };
263
+ guard();
264
+ finalGuard = guard;
265
+ return run({ identity: r.identity, hostBindingRef: r.id, guard });
266
+ }, () => finalGuard());
267
+ if (result.ok)
268
+ finalGuard();
269
+ if (!result.ok && ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_UNREADABLE', 'WORKSPACE_LOCATION_INVALID'].includes(result.error.code))
270
+ revoke(r.bindingId);
271
+ return result;
272
+ }
273
+ catch (e) {
274
+ return resultError(e);
275
+ }
276
+ }
277
+ function observeLocations(state) { if (!active() || state.phase !== 'ready')
278
+ return; const items = store.read(), bindings = new Set(items.map(r => r.bindingId)); for (const binding of bindings) {
279
+ const r = items.find(r => r.bindingId === binding), item = state.items.find(i => i.workspaceId === r.workspaceId);
280
+ if (!item) {
281
+ if (!o.registry.get(r.workspaceId))
282
+ revoke(binding);
283
+ }
284
+ else if (item.bindingId !== binding || item.source !== 'host')
285
+ revoke(binding);
286
+ } }
287
+ function observeSessionDisposed(session) { for (const r of store.read())
288
+ if (r.sessionId === session.header.id && sameSessionHeader(r.header, session.header))
289
+ blocked.add(r.id); observed.delete(session); revisions.set(session.header.id, (revisions.get(session.header.id) ?? 0) + 1); }
290
+ return { active, observe, observeLocations, observeSessionDisposed, resolve, readScope, withWrite, compatible, hasSession: (id) => store.read().some(r => r.sessionId === id), dispose() { disposed = true; } };
291
+ }
@@ -0,0 +1,27 @@
1
+ import type { HostDirectoryInfo } from './host-directories.ts';
2
+ import type { Provider } from './api.ts';
3
+ export interface HostProjectRecord {
4
+ id: string;
5
+ sessionId: string;
6
+ provider: Provider;
7
+ header: Record<string, any>;
8
+ identity: string;
9
+ workspaceId: string;
10
+ bindingId: string;
11
+ instanceId: string;
12
+ epoch: number;
13
+ runtimeId: string;
14
+ local: {
15
+ path: string;
16
+ device: number;
17
+ inode: number;
18
+ };
19
+ directory: HostDirectoryInfo;
20
+ revoked: boolean;
21
+ key: string;
22
+ }
23
+ export declare function hostProjectStore(profile: string, maxBytes: number): {
24
+ read: () => HostProjectRecord[];
25
+ save: (items: HostProjectRecord[], guard: () => void) => void;
26
+ verify: (expected: HostProjectRecord, guard: () => void) => void;
27
+ };
@@ -0,0 +1,130 @@
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 { randomUUID } from 'node:crypto';
4
+ import { canonical, hash, validHeader } from "./local-acceptance-store.js";
5
+ const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
6
+ const int = (v) => Number.isSafeInteger(v) && v >= 0;
7
+ function validRecord(r) {
8
+ if (!r || Object.keys(r).sort().join(',') !== 'bindingId,directory,epoch,header,id,identity,instanceId,key,local,provider,revoked,runtimeId,sessionId,workspaceId' || !['id', 'sessionId', 'workspaceId', 'bindingId', 'instanceId', 'runtimeId'].every(k => text(r[k])) || !['claude', 'codex'].includes(r.provider) || !int(r.epoch) || !validHeader(r.header) || r.header.id !== r.sessionId || !/^[a-f0-9]{64}$/.test(r.identity) || typeof r.revoked !== 'boolean' || r.key !== hash({ ...r, key: '' }))
9
+ return false;
10
+ const d = r.directory, l = r.local;
11
+ return l && Object.keys(l).sort().join(',') === 'device,inode,path' && typeof l.path === 'string' && isAbsolute(l.path) && int(l.device) && int(l.inode) && d && Object.keys(d).sort().join(',') === 'entryIdentity,identity,isSymlink,parentPath,path,permissions,requestedPath' && (d.parentPath === null || typeof d.parentPath === 'string' && isAbsolute(d.parentPath)) && typeof d.path === 'string' && isAbsolute(d.path) && typeof d.requestedPath === 'string' && isAbsolute(d.requestedPath) && d.identity && Object.keys(d.identity).sort().join(',') === 'ctimeNs,device,inode,mtimeNs' && ['device', 'inode'].every(k => typeof d.identity[k] === 'string' && /^\d+$/.test(d.identity[k])) && ['mtimeNs', 'ctimeNs'].every(k => typeof d.identity[k] === 'string' && /^-?\d+$/.test(d.identity[k])) && d.entryIdentity && Object.keys(d.entryIdentity).sort().join(',') === 'device,inode' && ['device', 'inode'].every(k => typeof d.entryIdentity[k] === 'string' && /^\d+$/.test(d.entryIdentity[k])) && typeof d.isSymlink === 'boolean' && d.permissions && Object.keys(d.permissions).every(k => ['read', 'write', 'execute', 'reason'].includes(k)) && ([d.permissions.read, d.permissions.write, d.permissions.execute].includes(null) ? d.permissions.reason === 'HOST_PERMISSION_UNKNOWN' : d.permissions.reason === undefined) && ['read', 'write', 'execute'].every(k => [true, false, null].includes(d.permissions[k]));
12
+ }
13
+ export function hostProjectStore(profile, maxBytes) {
14
+ const root = join(profile, 'ai-workbench-connect'), file = join(root, 'host-session-projects.json');
15
+ const directory = (path) => { const st = lstatSync(path); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0 || realpathSync(path) !== path)
16
+ throw Error('HOST_SESSION_DIRECTORY_INVALID'); };
17
+ function read() {
18
+ if (realpathSync(profile) !== profile)
19
+ throw Error('HOST_SESSION_PROFILE_INVALID');
20
+ try {
21
+ directory(root);
22
+ }
23
+ catch (e) {
24
+ if (e.code === 'ENOENT')
25
+ return [];
26
+ throw e;
27
+ }
28
+ let fd;
29
+ try {
30
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
31
+ }
32
+ catch (e) {
33
+ if (e.code === 'ENOENT')
34
+ return [];
35
+ throw e;
36
+ }
37
+ try {
38
+ const st = fstatSync(fd);
39
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || st.size > maxBytes)
40
+ throw Error('HOST_SESSION_FILE_INVALID');
41
+ const bytes = readFileSync(fd);
42
+ if (bytes.length > maxBytes)
43
+ throw Error('HOST_SESSION_LIMIT');
44
+ const data = JSON.parse(bytes.toString('utf8'));
45
+ if (!data || Object.keys(data).sort().join(',') !== 'items,version' || data.version !== 1 || !Array.isArray(data.items))
46
+ throw Error('HOST_SESSION_FORMAT_INVALID');
47
+ const ids = new Set();
48
+ for (const r of data.items) {
49
+ if (!validRecord(r) || ids.has(r.id))
50
+ throw Error('HOST_SESSION_RECORD_INVALID');
51
+ ids.add(r.id);
52
+ }
53
+ return data.items;
54
+ }
55
+ finally {
56
+ closeSync(fd);
57
+ }
58
+ }
59
+ function save(items, guard) {
60
+ directory(root);
61
+ for (const r of items)
62
+ r.key = hash({ ...r, key: '' });
63
+ const bytes = JSON.stringify({ version: 1, items }) + '\n';
64
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || Buffer.byteLength(bytes) > maxBytes)
65
+ throw Error('HOST_SESSION_LIMIT');
66
+ const temp = join(root, '.host-session-' + randomUUID());
67
+ let created = false;
68
+ try {
69
+ const fd = openSync(temp, 'wx', 0o600);
70
+ created = true;
71
+ try {
72
+ writeFileSync(fd, bytes);
73
+ fsyncSync(fd);
74
+ }
75
+ finally {
76
+ closeSync(fd);
77
+ }
78
+ guard();
79
+ renameSync(temp, file);
80
+ created = false;
81
+ for (const path of [root, profile]) {
82
+ const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
83
+ try {
84
+ fsyncSync(d);
85
+ }
86
+ finally {
87
+ closeSync(d);
88
+ }
89
+ }
90
+ }
91
+ finally {
92
+ if (created)
93
+ unlinkSync(temp);
94
+ }
95
+ }
96
+ function verify(expected, guard) {
97
+ directory(root);
98
+ if (realpathSync(profile) !== profile)
99
+ throw Error('HOST_SESSION_PROFILE_INVALID');
100
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
101
+ try {
102
+ const st = fstatSync(fd);
103
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || st.size > maxBytes)
104
+ throw Error('HOST_SESSION_FILE_INVALID');
105
+ const bytes = readFileSync(fd);
106
+ if (bytes.length > maxBytes)
107
+ throw Error('HOST_SESSION_LIMIT');
108
+ const data = JSON.parse(bytes.toString('utf8'));
109
+ if (!Array.isArray(data.items) || !data.items.some((r) => canonical(r) === canonical(expected)))
110
+ throw Error('HOST_SESSION_CHANGED');
111
+ guard();
112
+ fsyncSync(fd);
113
+ }
114
+ finally {
115
+ closeSync(fd);
116
+ }
117
+ for (const path of [root, profile]) {
118
+ const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
119
+ try {
120
+ guard();
121
+ fsyncSync(d);
122
+ }
123
+ finally {
124
+ closeSync(d);
125
+ }
126
+ }
127
+ guard();
128
+ }
129
+ return { read, save, verify };
130
+ }
@@ -31,6 +31,8 @@ interface Services {
31
31
  };
32
32
  }
33
33
  interface Options {
34
+ assertPriorBinding?: (sessionId: string, header: Record<string, any>, bindingId: string) => Promise<void>;
35
+ assertSessionBinding?: (sessionId: string, header: Record<string, any>, source: 'local', bindingId: string) => void;
34
36
  profileDir: string;
35
37
  metadataMaxBytes: number;
36
38
  registry: NativeWorkspaceRegistry;
@@ -57,7 +59,7 @@ export declare function createLocalUserTurnAcceptance(o: Options): {
57
59
  observe: (session: Session, event: SessionEvent) => void;
58
60
  observeLocations: (state: WorkspaceLocationState) => void;
59
61
  observeSessionDisposed: (session: Session) => void;
60
- readScope: (sessionId: string, provider: Provider, acceptanceId?: string, detail?: RemoteConversationDetail, expectedIdentity?: string) => Promise<Result<{
62
+ readScope: (sessionId: string, provider: Provider, acceptanceId?: string, detail?: Pick<RemoteConversationDetail, "sessionId" | "provider" | "instanceId" | "epoch">, expectedIdentity?: string) => Promise<Result<{
61
63
  identity: string;
62
64
  guard: () => void;
63
65
  cacheGuard: () => void;
@@ -1,5 +1,6 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { acceptanceStore, canonical, validHeader, sameSessionHeader } from "./local-acceptance-store.js";
3
+ import { changedSessionBinding } from "./host-session-projects.js";
3
4
  import { fail, ok, need, NeedError } from "./needs.js";
4
5
  const text = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
5
6
  const int = (v) => Number.isSafeInteger(v) && v >= 0;
@@ -65,9 +66,14 @@ export function createLocalUserTurnAcceptance(o) {
65
66
  let items = [];
66
67
  try {
67
68
  c.guard();
69
+ await o.assertPriorBinding?.(r.sessionId, c.header, r.expectedBindingId);
70
+ c.guard();
71
+ o.assertSessionBinding?.(r.sessionId, c.header, 'local', r.expectedBindingId);
68
72
  if (uncertain)
69
73
  reject('REMOTE_DETAIL_STORAGE_FAILED');
70
74
  items = store.read();
75
+ if (items.some(v => v.acceptance.sessionId === r.sessionId && sameSessionHeader(v.header, c.header) && v.acceptance.bindingId !== r.expectedBindingId))
76
+ changedSessionBinding();
71
77
  const context = await o.context();
72
78
  c.guard();
73
79
  if (!context.ok)
@@ -75,7 +81,7 @@ export function createLocalUserTurnAcceptance(o) {
75
81
  const identity = context.value.identity;
76
82
  const result = await o.withLocalBinding(r, async (directory, bindingGuard) => {
77
83
  try {
78
- const guard = () => { c.guard(); context.value.guard?.(); bindingGuard(); if (canonical(directory) !== canonical({ ...r.expectedDirectory, path: directory.path }))
84
+ const guard = () => { c.guard(); o.assertSessionBinding?.(r.sessionId, c.header, 'local', r.expectedBindingId); context.value.guard?.(); bindingGuard(); if (canonical(directory) !== canonical({ ...r.expectedDirectory, path: directory.path }))
79
85
  reject('REMOTE_DETAIL_SCOPE_INVALID'); };
80
86
  guard();
81
87
  // Canonical session cwd must be the selected official directory; no basename/host mapping.
@@ -7,6 +7,9 @@ import { NeedError, need, fail } from "./needs.js";
7
7
  import { createNativeImportPicker } from "./native-import-picker.js";
8
8
  import { createHash } from 'node:crypto';
9
9
  import { readPrivate, readPrivateSync } from "./private-files.js";
10
+ import { hostProjectStore } from "./host-session-store.js";
11
+ import { acceptanceStore, sameSessionHeader } from "./local-acceptance-store.js";
12
+ import { createHostSessionProjects, changedSessionBinding } from "./host-session-projects.js";
10
13
  import { createLocalUserTurnAcceptance } from "./local-user-turn-acceptance.js";
11
14
  import { createConversationDetails } from "./conversation-details.js";
12
15
  import { createLoginDiagnostics } from "./login-diagnostics.js";
@@ -92,7 +95,19 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
92
95
  }
93
96
  };
94
97
  const nativeSessions = native.get('sessions'), nativePersistence = native.get('sessionPersistence');
95
- const localAcceptance = process.platform === 'darwin' && typeof nativeSessions?.flush === 'function' && typeof nativePersistence?.open === 'function' && typeof nativePersistence?.identity === 'symbol' ? createLocalUserTurnAcceptance({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, registry, getConnectionState: api.getConnectionState, readHeader, context, withLocalBinding: locations.withLocalBinding,
98
+ const hostLedger = hostProjectStore(profile.dir, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes), localLedger = acceptanceStore(profile.dir, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
99
+ const assertHostBinding = (id, header) => { if (hostLedger.read().some(r => r.sessionId === id && sameSessionHeader(r.header, header)))
100
+ changedSessionBinding(); };
101
+ const officialServices = () => ({ sessions: native.get('sessions'), persistence: native.get('sessionPersistence') });
102
+ const hostAcceptance = typeof ports.hostDirectories?.inspect === 'function' && typeof ports.hostDirectories?.browse === 'function' && typeof nativeSessions?.flush === 'function' && typeof nativePersistence?.open === 'function' && typeof nativePersistence?.identity === 'symbol' ? createHostSessionProjects({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, api, registry, services: officialServices, readHeader, readLegacy: bindings.readLegacyLocations, context, withHostBinding: locations.withHostBinding }) : undefined;
103
+ if (hostAcceptance) {
104
+ native.on('session/event', (session, event) => hostAcceptance.observe(session, event));
105
+ native.on('session/disposed', (session) => hostAcceptance.observeSessionDisposed(session));
106
+ native.effect(() => locations.onWorkspaceLocationState(hostAcceptance.observeLocations));
107
+ native.effect(() => () => hostAcceptance.dispose());
108
+ }
109
+ const localAcceptance = process.platform === 'darwin' && typeof nativeSessions?.flush === 'function' && typeof nativePersistence?.open === 'function' && typeof nativePersistence?.identity === 'symbol' ? createLocalUserTurnAcceptance({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, registry, getConnectionState: api.getConnectionState, readHeader, context, assertSessionBinding: assertHostBinding, assertPriorBinding: async (id) => { if ((await bindings.readLegacyLocations()).some(r => r.sessionIds.includes(id)))
110
+ changedSessionBinding(); }, withLocalBinding: locations.withLocalBinding,
96
111
  // SessionStore proxies are not instance IDs. Check the exact live Session and
97
112
  // SessionPersistence's public stable identity, plus the injected lifetime.
98
113
  services: () => ({ sessions: native.get('sessions'), persistence: native.get('sessionPersistence') }) }) : undefined;
@@ -105,7 +120,7 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
105
120
  delete api.acceptLocalWorkspaceUserTurn; });
106
121
  }
107
122
  const details = createConversationDetails({ profileDir: profile.dir, get maxEventBytes() { return settings ? settings.values()?.maxEventBytes ?? 0 : config.conversationDetails?.maxEventBytes ?? CONVERSATION_DETAIL_DEFAULTS.maxEventBytes; }, get pageSize() { return settings ? settings.values()?.pageSize ?? 0 : config.conversationDetails?.pageSize ?? CONVERSATION_DETAIL_DEFAULTS.pageSize; }, getConnectionState: api.getConnectionState,
108
- context, localAcceptance,
123
+ context, localAcceptance, hostAcceptance,
109
124
  scope: async (sessionId, provider) => { const current = api.getModelCatalogTarget(provider); if (!current.ok)
110
125
  return current; return bindings.verifyRemoteConversationScope(sessionId, provider, current.value.target); },
111
126
  onState: state => ctx.emit('ai-workbench/remote-conversation-detail-state', state) });
@@ -140,7 +155,7 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
140
155
  api.listLoginDiagnostics = loginDiagnostics.listLoginDiagnostics;
141
156
  api.getLoginDiagnosticState = loginDiagnostics.getLoginDiagnosticState;
142
157
  api.onLoginDiagnosticState = loginDiagnostics.onLoginDiagnosticState;
143
- const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1, workspaceLocations: 1, ...(api.getConnectionState().phase !== 'disposed' ? { preflightDiagnostics: 1 } : {}), ...(process.platform === 'darwin' && api.getConnectionState().phase !== 'disposed' ? { localWorkspaceContext: 1, ...(localAcceptance?.active() ? { localUserTurnAcceptance: 1 } : {}) } : {}) });
158
+ const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1, workspaceLocations: 1, ...(hostAcceptance?.active() && api.getConnectionState().phase !== 'disposed' ? { hostWorkspaceResolution: 1 } : {}), ...(api.getConnectionState().phase !== 'disposed' ? { preflightDiagnostics: 1 } : {}), ...(process.platform === 'darwin' && api.getConnectionState().phase !== 'disposed' ? { localWorkspaceContext: 1, ...(localAcceptance?.active() ? { localUserTurnAcceptance: 1 } : {}) } : {}) });
144
159
  api.getContractInfo = detailContractInfo;
145
160
  native.effect(() => { details.observeConnection(api.getConnectionState()); return api.onConnectionState(details.observeConnection); });
146
161
  native.effect(() => { loginDiagnostics.observeConnection(api.getConnectionState()); return api.onConnectionState(loginDiagnostics.observeConnection); });
@@ -150,7 +165,17 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
150
165
  api.getWorkspaceBindingState = bindings.getWorkspaceBindingState;
151
166
  api.onWorkspaceBindingState = bindings.onWorkspaceBindingState;
152
167
  api.acknowledgeWorkspaceNotice = bindings.acknowledgeWorkspaceNotice;
153
- api.resolveSessionProject = (sessionId, use) => locations.resolveLegacySession(sessionId, () => bindings.resolveSessionProject(sessionId, use));
168
+ api.resolveSessionProject = (sessionId, use, location) => { if (location !== undefined)
169
+ return hostAcceptance ? hostAcceptance.resolve(sessionId, use, location) : Promise.resolve(fail('DEPENDENCY_REQUIRED')); return locations.resolveLegacySession(sessionId, async () => { try {
170
+ const header = await readHeader(sessionId);
171
+ assertHostBinding(sessionId, header);
172
+ if (localLedger.read().some(r => r.acceptance.sessionId === sessionId && sameSessionHeader(r.header, header)))
173
+ changedSessionBinding();
174
+ return bindings.resolveSessionProject(sessionId, use);
175
+ }
176
+ catch (e) {
177
+ return e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_STORAGE_FAILED');
178
+ } }); };
154
179
  native.effect(() => () => { api.resolveSessionProject = async () => fail('DEPENDENCY_REQUIRED'); api.acknowledgeWorkspaceNotice = async () => fail('DEPENDENCY_REQUIRED'); return bindings.dispose(); });
155
180
  });
156
181
  }