@ai-workbench/connect 0.7.18 → 0.7.20
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 +7 -3
- package/client/index.cjs +16 -10
- package/lib/api.d.ts +16 -2
- package/lib/conversation-details.d.ts +2 -0
- package/lib/conversation-details.js +50 -7
- package/lib/host-session-projects.d.ts +71 -0
- package/lib/host-session-projects.js +291 -0
- package/lib/host-session-store.d.ts +27 -0
- package/lib/host-session-store.js +130 -0
- package/lib/local-acceptance-store.d.ts +1 -0
- package/lib/local-acceptance-store.js +5 -1
- package/lib/local-user-turn-acceptance.d.ts +2 -0
- package/lib/local-user-turn-acceptance.js +16 -8
- package/lib/profile-runtime.js +29 -4
- package/lib/workspace-location-types.d.ts +8 -0
- package/lib/workspace-locations.d.ts +27 -4
- package/lib/workspace-locations.js +78 -4
- package/package.json +1 -1
|
@@ -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
|
+
}
|
|
@@ -10,6 +10,7 @@ export interface AcceptanceRecord {
|
|
|
10
10
|
key: string;
|
|
11
11
|
}
|
|
12
12
|
export declare function validHeader(h: any): boolean;
|
|
13
|
+
export declare function sameSessionHeader(a: any, b: any): boolean;
|
|
13
14
|
export declare function acceptanceStore(profile: string, maxBytes: number): {
|
|
14
15
|
read: () => AcceptanceRecord[];
|
|
15
16
|
save: (items: AcceptanceRecord[], guard: () => void) => void;
|
|
@@ -6,7 +6,11 @@ export const hash = (v) => createHash('sha256').update(canonical(v)).digest('hex
|
|
|
6
6
|
const exact = (v, fields) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).sort().join(',') === fields;
|
|
7
7
|
const text = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
|
|
8
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)); }
|
|
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.hasOwn(h, 'delegationDepth') || int(h.delegationDepth) && !Object.is(h.delegationDepth, -0)) && Object.keys(h).every(k => ['version', 'id', 'createdAt', 'cwd', 'parentSession', 'isSeeded', 'origin', 'delegationDepth', 'agentPreset'].includes(k)); }
|
|
10
|
+
// Official rc.2 JSONL encodes an omitted delegationDepth as 0. Compare only
|
|
11
|
+
// those two native representations as equivalent; retain every other field.
|
|
12
|
+
// Stored headers and integrity hashes stay byte-for-byte in their original form.
|
|
13
|
+
export function sameSessionHeader(a, b) { return validHeader(a) && validHeader(b) && canonical({ ...a, delegationDepth: a.delegationDepth ?? 0 }) === canonical({ ...b, delegationDepth: b.delegationDepth ?? 0 }); }
|
|
10
14
|
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
15
|
export function acceptanceStore(profile, maxBytes) {
|
|
12
16
|
const root = join(profile, 'ai-workbench-connect'), file = join(root, 'local-user-turn-acceptances.json');
|
|
@@ -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;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
-
import { acceptanceStore, canonical, validHeader } from "./local-acceptance-store.js";
|
|
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.
|
|
@@ -92,7 +98,7 @@ export function createLocalUserTurnAcceptance(o) {
|
|
|
92
98
|
let inherited = 0;
|
|
93
99
|
try {
|
|
94
100
|
guard();
|
|
95
|
-
if (handle.id !== r.sessionId || handle.access !== 'read' ||
|
|
101
|
+
if (handle.id !== r.sessionId || handle.access !== 'read' || !sameSessionHeader(handle.header, c.header) || !int(handle.inheritedEventCount))
|
|
96
102
|
reject('REMOTE_DETAIL_SCOPE_INVALID');
|
|
97
103
|
inherited = handle.inheritedEventCount;
|
|
98
104
|
events = (await handle.read()).events;
|
|
@@ -133,12 +139,14 @@ export function createLocalUserTurnAcceptance(o) {
|
|
|
133
139
|
const a = { version: 1, acceptanceId: randomUUID(), instanceId: r.instanceId, epoch: r.epoch, sessionId: r.sessionId, provider: r.provider, workspaceId: r.workspaceId, bindingId: r.expectedBindingId, source: 'local', directory, userTurn: { turn: start.data.turn, startSequence: start.seq, userMessageId: input.data.id, userMessageSequence: input.seq } };
|
|
134
140
|
// Re-read inside the location queue; another acceptance may have committed while awaiting it.
|
|
135
141
|
items = store.read();
|
|
136
|
-
const same = items.find(v => v.identity === identity &&
|
|
137
|
-
const oldInput = items.find(v => v.acceptance.sessionId === r.sessionId &&
|
|
142
|
+
const same = items.find(v => v.identity === identity && sameSessionHeader(v.header, c.header) && sameProof(v.acceptance, a));
|
|
143
|
+
const oldInput = items.find(v => v.acceptance.sessionId === r.sessionId && sameSessionHeader(v.header, c.header) && v.acceptance.provider === r.provider && canonical(v.acceptance.userTurn) === canonical(a.userTurn) && !sameProof(v.acceptance, a));
|
|
138
144
|
if (oldInput || same && (same.retired || same.runtimeId !== runtimeId || blocked.has(same.acceptance.acceptanceId)))
|
|
139
145
|
reject('REMOTE_DETAIL_SCOPE_INVALID');
|
|
140
146
|
guard();
|
|
141
147
|
if (same) {
|
|
148
|
+
if (canonical(same.header) !== canonical(c.header))
|
|
149
|
+
reject('REMOTE_DETAIL_SCOPE_INVALID');
|
|
142
150
|
store.verify(same, guard);
|
|
143
151
|
return ok(structuredClone(same.acceptance));
|
|
144
152
|
}
|
|
@@ -176,9 +184,9 @@ export function createLocalUserTurnAcceptance(o) {
|
|
|
176
184
|
if (record && detail && (record.acceptance.sessionId !== detail.sessionId || record.acceptance.provider !== detail.provider || record.acceptance.instanceId !== detail.instanceId || record.acceptance.epoch !== detail.epoch || expectedIdentity !== undefined && record.identity !== expectedIdentity))
|
|
177
185
|
reject('REMOTE_DETAIL_STORAGE_FAILED');
|
|
178
186
|
const matches = acceptanceId ? [record] : items;
|
|
179
|
-
if (!header || !matches.some(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider &&
|
|
187
|
+
if (!header || !matches.some(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider && sameSessionHeader(r.header, header) && (!detail || (r.acceptance.instanceId === detail.instanceId && r.acceptance.epoch === detail.epoch))))
|
|
180
188
|
reject('REMOTE_DETAIL_SCOPE_INVALID');
|
|
181
|
-
const admitted = matches.filter(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider &&
|
|
189
|
+
const admitted = matches.filter(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider && sameSessionHeader(r.header, header));
|
|
182
190
|
const guard = () => {
|
|
183
191
|
life(before);
|
|
184
192
|
context.value.guard?.();
|
|
@@ -262,7 +270,7 @@ export function createLocalUserTurnAcceptance(o) {
|
|
|
262
270
|
return;
|
|
263
271
|
observed.delete(session);
|
|
264
272
|
sessionRevisions.set(session.header.id, (sessionRevisions.get(session.header.id) ?? 0) + 1);
|
|
265
|
-
retire(store.read(), r => r.acceptance.sessionId === session.header.id &&
|
|
273
|
+
retire(store.read(), r => r.acceptance.sessionId === session.header.id && sameSessionHeader(r.header, session.header));
|
|
266
274
|
}
|
|
267
275
|
return { active, observe, observeLocations, observeSessionDisposed, readScope, withWrite, acceptLocalWorkspaceUserTurn(request) {
|
|
268
276
|
try {
|
package/lib/profile-runtime.js
CHANGED
|
@@ -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
|
|
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) =>
|
|
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
|
}
|