@ai-workbench/connect 0.7.14 → 0.7.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,281 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { acceptanceStore, canonical, validHeader } from "./local-acceptance-store.js";
3
+ import { fail, ok, need, NeedError } from "./needs.js";
4
+ const text = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
5
+ const int = (v) => Number.isSafeInteger(v) && v >= 0;
6
+ const keys = (v, k) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).sort().join(',') === k;
7
+ function reject(code) { throw new NeedError(need(code)); }
8
+ const resultError = (e) => e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_STORAGE_FAILED');
9
+ export function createLocalUserTurnAcceptance(o) {
10
+ const store = acceptanceStore(o.profileDir, o.metadataMaxBytes), observed = new WeakMap(), blocked = new Set(), sessionRevisions = new Map(), runtimeId = randomUUID(), persistenceIdentity = o.services().persistence.identity;
11
+ let disposed = false, uncertain = false;
12
+ function active() { if (o.services().persistence?.identity !== persistenceIdentity)
13
+ disposed = true; return !disposed; }
14
+ function life(c) { const now = o.getConnectionState(); if (!active() || now.phase === 'disposed')
15
+ reject('DISPOSED'); if (now.phase !== 'connected' || now.instanceId !== c.instanceId || now.epoch !== c.epoch)
16
+ reject('CONNECTION_LOST'); }
17
+ function mapping(sessionId, workspaceId) { const list = o.registry.list().filter(w => w.sessionIds.includes(sessionId)); if (list.length !== 1 || list[0].id !== workspaceId || o.registry.get(workspaceId)?.path !== list[0].path)
18
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); }
19
+ function retire(items, matching) { const changed = items.filter(r => !r.retired && matching(r)); for (const r of changed) {
20
+ blocked.add(r.acceptance.acceptanceId);
21
+ r.retired = true;
22
+ } if (changed.length) {
23
+ try {
24
+ store.save(items, () => { });
25
+ }
26
+ catch (e) {
27
+ uncertain = true;
28
+ throw e;
29
+ }
30
+ } }
31
+ function retireFailed(items, workspaceId, bindingId, result) { if (!result.ok && ['WORKSPACE_LOCATION_INVALID', 'WORKSPACE_LOCATION_CONFLICT'].includes(result.error.code))
32
+ retire(items, r => r.acceptance.workspaceId === workspaceId && r.acceptance.bindingId === bindingId); }
33
+ const sameProof = (a, b) => canonical({ ...a, acceptanceId: '' }) === canonical({ ...b, acceptanceId: '' });
34
+ function validRequest(r) { return keys(r, 'epoch,expectedBindingId,expectedDirectory,expectedUserTurn,instanceId,provider,purpose,sessionId,workspaceId') && text(r.instanceId) && int(r.epoch) && text(r.sessionId) && ['claude', 'codex'].includes(r.provider) && r.purpose === 'user-turn' && text(r.workspaceId) && text(r.expectedBindingId) && keys(r.expectedDirectory, 'device,inode') && int(r.expectedDirectory.device) && int(r.expectedDirectory.inode) && keys(r.expectedUserTurn, 'turn,userMessageId') && int(r.expectedUserTurn.turn) && text(r.expectedUserTurn.userMessageId); }
35
+ function observe(session, event) {
36
+ if (disposed || o.services().sessions.get(session.header.id) !== session)
37
+ return;
38
+ // Keep only current turn's proof metadata, never prompt/headers/whole events.
39
+ if (event.type === 'turn/start')
40
+ observed.set(session, new Map([[event.seq, { seq: event.seq, type: event.type, data: { turn: event.data.turn } }]]));
41
+ else if (event.type === 'turn/end')
42
+ observed.delete(session);
43
+ else if (event.type === 'user/message' && event.data?.source?.kind === 'user')
44
+ observed.get(session)?.set(event.seq, { seq: event.seq, type: event.type, data: { id: event.data.id } });
45
+ }
46
+ function captured(r) {
47
+ const services = o.services(), session = services.sessions.get(r.sessionId);
48
+ if (!session || !int(session.seq) || session.header.id !== r.sessionId || !validHeader(session.header))
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 === 'turn/start' && e.data.turn === r.expectedUserTurn.turn) || ![...proof.values()].some(e => e.type === 'user/message' && e.data.id === r.expectedUserTurn.userMessageId))
52
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
53
+ const guard = () => { life(r); const current = o.services(); if (current.persistence.identity !== services.persistence.identity || current.sessions.get(r.sessionId) !== session || canonical(session.header) !== canonical(header) || session.seq !== watermark)
54
+ reject('LOCAL_USER_TURN_CHANGED'); try {
55
+ mapping(r.sessionId, r.workspaceId);
56
+ }
57
+ catch (e) {
58
+ retire(store.read(), v => v.acceptance.sessionId === r.sessionId && v.acceptance.bindingId === r.expectedBindingId);
59
+ throw e;
60
+ } };
61
+ guard();
62
+ return { services, session, header, watermark, proof, guard };
63
+ }
64
+ async function accept(r, c) {
65
+ let items = [];
66
+ try {
67
+ c.guard();
68
+ if (uncertain)
69
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
70
+ items = store.read();
71
+ const context = await o.context();
72
+ c.guard();
73
+ if (!context.ok)
74
+ return context;
75
+ const identity = context.value.identity;
76
+ const result = await o.withLocalBinding(r, async (directory, bindingGuard) => {
77
+ try {
78
+ const guard = () => { c.guard(); context.value.guard?.(); bindingGuard(); if (canonical(directory) !== canonical({ ...r.expectedDirectory, path: directory.path }))
79
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); };
80
+ guard();
81
+ // Canonical session cwd must be the selected official directory; no basename/host mapping.
82
+ const { realpath } = await import('node:fs/promises');
83
+ if (typeof c.header.cwd !== 'string' || await realpath(c.header.cwd) !== directory.path)
84
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
85
+ guard();
86
+ const flushed = await c.services.sessions.flush(c.session);
87
+ guard();
88
+ if (!flushed)
89
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
90
+ const handle = await c.services.persistence.open(r.sessionId, 'read');
91
+ let events = [];
92
+ let inherited = 0;
93
+ try {
94
+ guard();
95
+ if (handle.id !== r.sessionId || handle.access !== 'read' || canonical(handle.header) !== canonical(c.header) || !int(handle.inheritedEventCount))
96
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
97
+ inherited = handle.inheritedEventCount;
98
+ events = (await handle.read()).events;
99
+ guard();
100
+ }
101
+ finally {
102
+ await handle.close();
103
+ }
104
+ guard();
105
+ if (!Array.isArray(events) || events.length < c.watermark || events.some((e, n) => e.seq !== n))
106
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
107
+ let start, step, input, route, routeContext;
108
+ for (const e of events.slice(0, c.watermark)) {
109
+ if (e.type === 'turn/start') {
110
+ start = e;
111
+ step = undefined;
112
+ input = undefined;
113
+ }
114
+ else if (e.type === 'turn/end') {
115
+ start = undefined;
116
+ step = undefined;
117
+ input = undefined;
118
+ }
119
+ else if (e.type === 'step/start')
120
+ step = e;
121
+ else if (e.type === 'step/end')
122
+ step = undefined;
123
+ else if (e.type === 'user/message' && start && e.data?.source?.kind === 'user' && e.data?.id === r.expectedUserTurn.userMessageId)
124
+ input = e;
125
+ else if (e.type === 'request/header')
126
+ route = e.data?.header?.config?.provider;
127
+ else if (e.type === 'request/context')
128
+ routeContext = e.data?.provider;
129
+ }
130
+ const expectedRoute = r.provider === 'claude' ? 'claude-code-workbench' : 'codex-remote';
131
+ if (!start || !step || !input || start.data.turn !== r.expectedUserTurn.turn || step.data.turn !== start.data.turn || [start.seq, step.seq, input.seq].some(n => n < inherited) || !c.proof.has(start.seq) || !c.proof.has(input.seq) || route !== expectedRoute || (routeContext !== undefined && routeContext !== expectedRoute))
132
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
133
+ 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
+ // Re-read inside the location queue; another acceptance may have committed while awaiting it.
135
+ items = store.read();
136
+ const same = items.find(v => v.identity === identity && canonical(v.header) === canonical(c.header) && sameProof(v.acceptance, a));
137
+ const oldInput = items.find(v => v.acceptance.sessionId === r.sessionId && canonical(v.header) === canonical(c.header) && v.acceptance.provider === r.provider && canonical(v.acceptance.userTurn) === canonical(a.userTurn) && !sameProof(v.acceptance, a));
138
+ if (oldInput || same && (same.retired || same.runtimeId !== runtimeId || blocked.has(same.acceptance.acceptanceId)))
139
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
140
+ guard();
141
+ if (same) {
142
+ store.verify(same, guard);
143
+ return ok(structuredClone(same.acceptance));
144
+ }
145
+ items.push({ acceptance: a, header: c.header, identity, retired: false, runtimeId, key: '' });
146
+ store.save(items, guard);
147
+ guard();
148
+ return ok(structuredClone(a));
149
+ }
150
+ catch (e) {
151
+ return resultError(e);
152
+ }
153
+ });
154
+ retireFailed(store.read(), r.workspaceId, r.expectedBindingId, result);
155
+ return result;
156
+ }
157
+ catch (e) {
158
+ return resultError(e);
159
+ }
160
+ }
161
+ async function readScope(sessionId, provider, acceptanceId, detail, expectedIdentity) {
162
+ try {
163
+ const before = o.getConnectionState();
164
+ life(before);
165
+ const items = store.read(), context = await o.context();
166
+ life(before);
167
+ if (!context.ok)
168
+ return context;
169
+ const liveAtStart = o.services().sessions.get(sessionId), revision = sessionRevisions.get(sessionId) ?? 0;
170
+ const header = await o.readHeader(sessionId);
171
+ life(before);
172
+ context.value.guard?.();
173
+ const record = acceptanceId ? items.find(r => r.acceptance.acceptanceId === acceptanceId) : undefined;
174
+ if (acceptanceId && !record)
175
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
176
+ 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
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
178
+ const matches = acceptanceId ? [record] : items;
179
+ if (!header || !matches.some(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider && canonical(r.header) === canonical(header) && (!detail || (r.acceptance.instanceId === detail.instanceId && r.acceptance.epoch === detail.epoch))))
180
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
181
+ const admitted = matches.filter(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider && canonical(r.header) === canonical(header));
182
+ const guard = () => {
183
+ life(before);
184
+ context.value.guard?.();
185
+ const current = o.services().sessions.get(sessionId);
186
+ if ((sessionRevisions.get(sessionId) ?? 0) !== revision || liveAtStart && current !== liveAtStart || current && canonical(current.header) !== canonical(header))
187
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
188
+ const now = store.read();
189
+ for (const r of admitted) {
190
+ const same = now.find(n => n.acceptance.acceptanceId === r.acceptance.acceptanceId);
191
+ if (!same)
192
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
193
+ if (canonical([same.acceptance, same.header, same.identity, same.runtimeId]) !== canonical([r.acceptance, r.header, r.identity, r.runtimeId]))
194
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
195
+ }
196
+ };
197
+ guard();
198
+ const cacheGuard = () => { guard(); if (!liveAtStart || o.services().sessions.get(sessionId) !== liveAtStart)
199
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); };
200
+ return ok({ identity: context.value.identity, guard, cacheGuard });
201
+ }
202
+ catch (e) {
203
+ return resultError(e);
204
+ }
205
+ }
206
+ async function withWrite(acceptanceId, detail, run) {
207
+ try {
208
+ const before = o.getConnectionState();
209
+ life(before);
210
+ if (uncertain)
211
+ reject('REMOTE_DETAIL_STORAGE_FAILED');
212
+ let items = store.read();
213
+ const r = items.find(r => r.acceptance.acceptanceId === acceptanceId);
214
+ if (!r || r.retired || r.runtimeId !== runtimeId || blocked.has(acceptanceId))
215
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
216
+ const a = r.acceptance;
217
+ if (a.instanceId !== before.instanceId || a.epoch !== before.epoch || detail.instanceId !== a.instanceId || detail.epoch !== a.epoch || detail.sessionId !== a.sessionId || detail.provider !== a.provider)
218
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
219
+ const context = await o.context();
220
+ life(before);
221
+ if (!context.ok)
222
+ return context;
223
+ if (context.value.identity !== r.identity)
224
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
225
+ const header = await o.readHeader(a.sessionId);
226
+ life(before);
227
+ if (!header || canonical(header) !== canonical(r.header))
228
+ reject('REMOTE_DETAIL_SCOPE_INVALID');
229
+ const result = await o.withLocalBinding({ instanceId: a.instanceId, epoch: a.epoch, workspaceId: a.workspaceId, expectedBindingId: a.bindingId }, async (directory, bindingGuard) => {
230
+ const guard = () => { life(before); context.value.guard?.(); try {
231
+ mapping(a.sessionId, a.workspaceId);
232
+ }
233
+ catch (e) {
234
+ retire(store.read(), v => v.acceptance.sessionId === a.sessionId && v.acceptance.bindingId === a.bindingId);
235
+ throw e;
236
+ } bindingGuard(); if (blocked.has(acceptanceId) || canonical(directory) !== canonical(a.directory))
237
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); const live = o.services().sessions.get(a.sessionId); if (live && canonical(live.header) !== canonical(r.header))
238
+ reject('REMOTE_DETAIL_SCOPE_INVALID'); };
239
+ try {
240
+ guard();
241
+ return await run({ identity: r.identity, acceptanceId, guard });
242
+ }
243
+ catch (e) {
244
+ return resultError(e);
245
+ }
246
+ });
247
+ items = store.read();
248
+ retireFailed(items, a.workspaceId, a.bindingId, result);
249
+ return result;
250
+ }
251
+ catch (e) {
252
+ return resultError(e);
253
+ }
254
+ }
255
+ function observeLocations(state) {
256
+ if (disposed || state.phase !== 'ready')
257
+ return;
258
+ retire(store.read(), r => { const item = state.items.find(i => i.workspaceId === r.acceptance.workspaceId); return !item || item.bindingId !== r.acceptance.bindingId || item.source !== 'local' || item.status === 'invalid'; });
259
+ }
260
+ function observeSessionDisposed(session) {
261
+ if (disposed)
262
+ return;
263
+ observed.delete(session);
264
+ sessionRevisions.set(session.header.id, (sessionRevisions.get(session.header.id) ?? 0) + 1);
265
+ retire(store.read(), r => r.acceptance.sessionId === session.header.id && canonical(r.header) === canonical(session.header));
266
+ }
267
+ return { active, observe, observeLocations, observeSessionDisposed, readScope, withWrite, acceptLocalWorkspaceUserTurn(request) {
268
+ try {
269
+ if (disposed || o.getConnectionState().phase === 'disposed')
270
+ reject('DISPOSED');
271
+ if (!validRequest(request))
272
+ return Promise.resolve(fail('REMOTE_DETAIL_SCOPE_INVALID'));
273
+ life(request);
274
+ const r = structuredClone(request), c = captured(r);
275
+ return accept(r, c);
276
+ }
277
+ catch (e) {
278
+ return Promise.resolve(resultError(e));
279
+ }
280
+ }, dispose() { disposed = true; }, };
281
+ }
@@ -0,0 +1,40 @@
1
+ import type { Provider } from './api.ts';
2
+ export interface LocalUserTurnAcceptanceRequest {
3
+ instanceId: string;
4
+ epoch: number;
5
+ sessionId: string;
6
+ provider: Provider;
7
+ purpose: 'user-turn';
8
+ workspaceId: string;
9
+ expectedBindingId: string;
10
+ expectedDirectory: {
11
+ device: number;
12
+ inode: number;
13
+ };
14
+ expectedUserTurn: {
15
+ turn: number;
16
+ userMessageId: string;
17
+ };
18
+ }
19
+ export interface LocalUserTurnAcceptance {
20
+ version: 1;
21
+ acceptanceId: string;
22
+ instanceId: string;
23
+ epoch: number;
24
+ sessionId: string;
25
+ provider: Provider;
26
+ workspaceId: string;
27
+ bindingId: string;
28
+ source: 'local';
29
+ directory: {
30
+ path: string;
31
+ device: number;
32
+ inode: number;
33
+ };
34
+ userTurn: {
35
+ turn: number;
36
+ startSequence: number;
37
+ userMessageId: string;
38
+ userMessageSequence: number;
39
+ };
40
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -2,7 +2,9 @@ import type { RemoteConversationDetail } from './api.ts';
2
2
  import { type ConversationDetailOptions } from './conversation-details.ts';
3
3
  export declare function validLoginDiagnostic(detail: RemoteConversationDetail): boolean;
4
4
  export declare function createLoginDiagnostics(options: Omit<ConversationDetailOptions, 'storageName' | 'validate' | 'knownKinds'>): {
5
- appendLoginDiagnostic: (detail: RemoteConversationDetail) => Promise<import("./api.ts").Result<{
5
+ appendLoginDiagnostic: (detail: RemoteConversationDetail, scope?: {
6
+ localAcceptanceId: string;
7
+ }) => Promise<import("./api.ts").Result<{
6
8
  eventId: string;
7
9
  recorded: true;
8
10
  }>>;
@@ -4,8 +4,23 @@ const object = (value) => !!value && typeof value === 'object' && !Array.isArray
4
4
  const keys = (value, required, optional = []) => required.every(key => Object.hasOwn(value, key)) && Object.keys(value).every(key => required.includes(key) || optional.includes(key));
5
5
  const providers = (value) => Array.isArray(value) && value.every(provider => provider === 'claude' || provider === 'codex') && new Set(value).size === value.length;
6
6
  // Only structured status facts belong here. Ordinary user-turn payloads retain D19's scope.
7
+ function validPreflightPayload(payload) {
8
+ if (!object(payload) || !keys(payload, ['phase', 'stage', 'workspaceId', 'bindingId', 'source', 'status', 'outcome']))
9
+ return false;
10
+ const id = (value) => value === null || typeof value === 'string' && value.length > 0 && !/[\x00-\x1f\x7f]/.test(value);
11
+ return payload.phase === 'workspace-source-admission'
12
+ && ['source-context', 'source-confirmation', 'input-acceptance', 'login-readiness', 'local-admission', 'input-prepare', 'model-catalog', 'runtime-resolve'].includes(payload.stage)
13
+ && id(payload.workspaceId) && id(payload.bindingId)
14
+ && [null, 'local', 'host', 'legacy-host'].includes(payload.source)
15
+ && [null, 'unselected', 'selected', 'legacy-confirmation-required', 'invalid'].includes(payload.status)
16
+ && ['confirmation-required', 'confirmed', 'declined', 'cancelled', 'failed'].includes(payload.outcome);
17
+ }
7
18
  export function validLoginDiagnostic(detail) {
8
- if (!validRemoteConversationDetail(detail) || detail.kind !== 'login-check')
19
+ if (!validRemoteConversationDetail(detail))
20
+ return false;
21
+ if (detail.kind === 'preflight-check')
22
+ return validPreflightPayload(detail.payload);
23
+ if (detail.kind !== 'login-check')
9
24
  return false;
10
25
  const p = detail.payload;
11
26
  if (!object(p) || !keys(p, ['reason', 'connection', 'login'], ['observedLoginInstanceId', 'officialReason', 'officialReasonRejected']))
@@ -37,6 +52,6 @@ export function validLoginDiagnostic(detail) {
37
52
  return p.officialReason === undefined || validAuthDiagnosticReason(p.officialReason);
38
53
  }
39
54
  export function createLoginDiagnostics(options) {
40
- const details = createConversationDetails({ ...options, get maxEventBytes() { return options.maxEventBytes; }, get pageSize() { return options.pageSize; }, context: () => options.context(), scope: (sessionId, provider) => options.scope(sessionId, provider), storageName: 'login-diagnostics', knownKinds: ['login-check'], validate: validLoginDiagnostic });
55
+ const details = createConversationDetails({ ...options, get maxEventBytes() { return options.maxEventBytes; }, get pageSize() { return options.pageSize; }, context: () => options.context(), scope: (sessionId, provider) => options.scope(sessionId, provider), storageName: 'login-diagnostics', knownKinds: ['login-check', 'preflight-check'], validate: validLoginDiagnostic });
41
56
  return { appendLoginDiagnostic: details.appendRemoteConversationDetail, getLoginDiagnosticReceipt: details.getRemoteConversationDetailReceipt, listLoginDiagnostics: details.listRemoteConversationDetails, getLoginDiagnosticState: details.getRemoteConversationDetailState, onLoginDiagnosticState: details.onRemoteConversationDetailState, observeConnection: details.observeConnection, dispose: details.dispose };
42
57
  }
package/lib/needs.js CHANGED
@@ -1,4 +1,5 @@
1
1
  const entries = {
2
+ LOCAL_USER_TURN_CHANGED: { layer: 'integration', message: '本次输入在核实期间发生变化,本轮已停止。', requires: '下一次真实员工输入与当前会话关系', actor: 'plugin', action: { id: 'inspect-local-user-turn', label: '查看技术详情', available: false } },
2
3
  LOCAL_WORKSPACE_CONTEXT_UNSUPPORTED: { layer: 'integration', message: '当前平台尚未接入本地工作区进程环境交接。', requires: '已接入平台的本机后端上下文', actor: 'plugin', action: { id: 'inspect-local-workspace-context', label: '查看技术详情', available: false } },
3
4
  LOCAL_WORKSPACE_CONTEXT_UNAVAILABLE: { layer: 'integration', message: '本机进程环境无法确认,已停止交接;根因未查明。', requires: '当前进程的真实操作系统账户与环境', actor: 'plugin', action: { id: 'inspect-local-workspace-context', label: '查看技术详情', available: false } },
4
5
  HOST_DIRECTORY_INVALID: { layer: 'projects', message: '目录不存在或不是文件夹,请重新选择。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
@@ -1,3 +1,5 @@
1
1
  export declare function privateDirectory(path: string): Promise<void>;
2
2
  export declare function privateFile(path: string): Promise<void>;
3
3
  export declare function readPrivate(path: string, maxBytes?: number): Promise<string>;
4
+ /** Synchronous final-commit check of already-selected public trust material. */
5
+ export declare function readPrivateSync(path: string, maxBytes: number): string;
@@ -1,5 +1,5 @@
1
1
  import { lstat, mkdir, open } from 'node:fs/promises';
2
- import { constants } from 'node:fs';
2
+ import { constants, openSync, fstatSync, readFileSync, closeSync } from 'node:fs';
3
3
  export async function privateDirectory(path) {
4
4
  await mkdir(path, { recursive: true, mode: 0o700 });
5
5
  const s = await lstat(path);
@@ -39,3 +39,19 @@ export async function readPrivate(path, maxBytes) {
39
39
  await h.close();
40
40
  }
41
41
  }
42
+ /** Synchronous final-commit check of already-selected public trust material. */
43
+ export function readPrivateSync(path, maxBytes) {
44
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
45
+ try {
46
+ const st = fstatSync(fd);
47
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o177) !== 0 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || st.size > maxBytes)
48
+ throw Error('PRIVATE_FILE_INVALID');
49
+ const bytes = readFileSync(fd);
50
+ if (bytes.length > maxBytes)
51
+ throw Error('PRIVATE_FILE_LIMIT');
52
+ return bytes.toString('utf8');
53
+ }
54
+ finally {
55
+ closeSync(fd);
56
+ }
57
+ }
@@ -6,7 +6,8 @@ import { createWorkspaceBindings } from "./workspace-bindings.js";
6
6
  import { NeedError, need, fail } from "./needs.js";
7
7
  import { createNativeImportPicker } from "./native-import-picker.js";
8
8
  import { createHash } from 'node:crypto';
9
- import { readPrivate } from "./private-files.js";
9
+ import { readPrivate, readPrivateSync } from "./private-files.js";
10
+ import { createLocalUserTurnAcceptance } from "./local-user-turn-acceptance.js";
10
11
  import { createConversationDetails } from "./conversation-details.js";
11
12
  import { createLoginDiagnostics } from "./login-diagnostics.js";
12
13
  import { CONVERSATION_DETAIL_DEFAULTS, L_DEFAULTS } from "./defaults.js";
@@ -35,6 +36,11 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
35
36
  const profile = native.get('profileContext');
36
37
  if (!profile || typeof profile.dir !== 'string')
37
38
  return;
39
+ // Invalidate diagnostic snapshots before any of our lifecycle handlers can emit SSE.
40
+ let diagnosticSessionRevision = 0;
41
+ const advanceDiagnosticSessions = () => { diagnosticSessionRevision++; };
42
+ native.on('session/created', advanceDiagnosticSessions);
43
+ native.on('session/disposed', advanceDiagnosticSessions);
38
44
  const registry = native.get('workspaceRegistry');
39
45
  const readHeader = async (id) => {
40
46
  const live = native.get('sessions');
@@ -60,35 +66,81 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
60
66
  native.effect(() => () => { if (api.getLocalWorkspaceContext === locations.getLocalWorkspaceContext)
61
67
  delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; return locations.dispose(); });
62
68
  const settings = ctx.get('aiWorkbenchConversationDetailSettings');
63
- const context = async () => { const current = api.getModelCatalogTarget('codex'); if (!current.ok)
64
- return current; const t = current.value.target; try {
65
- const trust = await readPrivate(t.knownHostsFile, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
66
- return { ok: true, value: { identity: createHash('sha256').update(JSON.stringify([t.host, t.username, t.port, trust])).digest('hex') } };
69
+ const identityOf = (target, trust) => createHash('sha256').update(JSON.stringify([target.host, target.username, target.port, trust])).digest('hex');
70
+ const context = async () => {
71
+ const current = api.getModelCatalogTarget('codex');
72
+ if (!current.ok)
73
+ return current;
74
+ const t = current.value.target, budget = config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes;
75
+ try {
76
+ const trust = await readPrivate(t.knownHostsFile, budget), identity = identityOf(t, trust);
77
+ const guard = () => { const latest = api.getModelCatalogTarget('codex'); if (!latest.ok)
78
+ throw new NeedError(latest.error); try {
79
+ if (identityOf(latest.value.target, readPrivateSync(latest.value.target.knownHostsFile, budget)) !== identity)
80
+ throw Error('TRUST_CHANGED');
81
+ }
82
+ catch (e) {
83
+ if (e instanceof NeedError)
84
+ throw e;
85
+ throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID'));
86
+ } };
87
+ guard();
88
+ return { ok: true, value: { identity, guard } };
89
+ }
90
+ catch (e) {
91
+ return e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_SCOPE_INVALID');
92
+ }
93
+ };
94
+ 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,
96
+ // SessionStore proxies are not instance IDs. Check the exact live Session and
97
+ // SessionPersistence's public stable identity, plus the injected lifetime.
98
+ services: () => ({ sessions: native.get('sessions'), persistence: native.get('sessionPersistence') }) }) : undefined;
99
+ if (localAcceptance) {
100
+ api.acceptLocalWorkspaceUserTurn = localAcceptance.acceptLocalWorkspaceUserTurn;
101
+ native.on('session/event', (session, event) => localAcceptance.observe(session, event));
102
+ native.on('session/disposed', (session) => localAcceptance.observeSessionDisposed(session));
103
+ native.effect(() => locations.onWorkspaceLocationState(localAcceptance.observeLocations));
104
+ native.effect(() => () => { localAcceptance.dispose(); if (api.acceptLocalWorkspaceUserTurn === localAcceptance.acceptLocalWorkspaceUserTurn)
105
+ delete api.acceptLocalWorkspaceUserTurn; });
67
106
  }
68
- catch {
69
- return fail('REMOTE_DETAIL_SCOPE_INVALID');
70
- } };
71
107
  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,
72
- context,
108
+ context, localAcceptance,
73
109
  scope: async (sessionId, provider) => { const current = api.getModelCatalogTarget(provider); if (!current.ok)
74
110
  return current; return bindings.verifyRemoteConversationScope(sessionId, provider, current.value.target); },
75
111
  onState: state => ctx.emit('ai-workbench/remote-conversation-detail-state', state) });
112
+ native.on('session/created', () => details.observeConnection(api.getConnectionState()));
113
+ native.on('session/disposed', () => details.observeConnection(api.getConnectionState()));
76
114
  api.appendRemoteConversationDetail = details.appendRemoteConversationDetail;
77
115
  api.getRemoteConversationDetailReceipt = details.getRemoteConversationDetailReceipt;
78
116
  api.getRemoteConversationDetailState = details.getRemoteConversationDetailState;
79
117
  api.onRemoteConversationDetailState = details.onRemoteConversationDetailState;
80
118
  api.listRemoteConversationDetails = details.listRemoteConversationDetails;
81
119
  const loginDiagnostics = createLoginDiagnostics({ 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, context,
120
+ publicationRevision: () => diagnosticSessionRevision,
121
+ cacheContext: identity => { const current = api.getModelCatalogTarget('codex'); if (!current.ok)
122
+ throw new NeedError(current.error); const t = current.value.target; try {
123
+ if (identityOf(t, readPrivateSync(t.knownHostsFile, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes)) !== identity)
124
+ throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID'));
125
+ }
126
+ catch (e) {
127
+ if (e instanceof NeedError)
128
+ throw e;
129
+ throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID'));
130
+ } },
82
131
  scope: async (sessionId, provider) => { const current = api.getModelCatalogTarget(provider); if (!current.ok)
83
132
  return current; const header = await readHeader(sessionId); if (!header || header.id !== sessionId)
84
133
  return fail('REMOTE_DETAIL_SCOPE_INVALID'); return context(); },
85
134
  onState: state => ctx.emit('ai-workbench/login-diagnostic-state', state) });
135
+ const refreshDiagnosticSessions = () => loginDiagnostics.observeConnection(api.getConnectionState());
136
+ native.on('session/created', refreshDiagnosticSessions);
137
+ native.on('session/disposed', refreshDiagnosticSessions);
86
138
  api.appendLoginDiagnostic = loginDiagnostics.appendLoginDiagnostic;
87
139
  api.getLoginDiagnosticReceipt = loginDiagnostics.getLoginDiagnosticReceipt;
88
140
  api.listLoginDiagnostics = loginDiagnostics.listLoginDiagnostics;
89
141
  api.getLoginDiagnosticState = loginDiagnostics.getLoginDiagnosticState;
90
142
  api.onLoginDiagnosticState = loginDiagnostics.onLoginDiagnosticState;
91
- const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1, workspaceLocations: 1, ...(process.platform === 'darwin' && api.getConnectionState().phase !== 'disposed' ? { localWorkspaceContext: 1 } : {}) });
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 } : {}) } : {}) });
92
144
  api.getContractInfo = detailContractInfo;
93
145
  native.effect(() => { details.observeConnection(api.getConnectionState()); return api.onConnectionState(details.observeConnection); });
94
146
  native.effect(() => { loginDiagnostics.observeConnection(api.getConnectionState()); return api.onConnectionState(loginDiagnostics.observeConnection); });
@@ -31,6 +31,11 @@ interface Options {
31
31
  nextRevision?: () => number;
32
32
  }
33
33
  export declare function createWorkspaceLocations(o: Options): {
34
+ withLocalBinding: <T>(c: LocalWorkspaceContextRequest, run: (directory: {
35
+ path: string;
36
+ device: number;
37
+ inode: number;
38
+ }, guard: () => void) => Promise<Result<T>>) => Promise<Result<T>>;
34
39
  getLocalWorkspaceContext: (request: LocalWorkspaceContextRequest) => Promise<Result<LocalWorkspaceContext>>;
35
40
  getWorkspaceLocationState: () => WorkspaceLocationState;
36
41
  onWorkspaceLocationState(listener: (s: WorkspaceLocationState) => void): () => void;
@@ -1,4 +1,4 @@
1
- import { renameSync } from 'node:fs';
1
+ import { renameSync, realpathSync, lstatSync } from 'node:fs';
2
2
  import { lstat, realpath, open, rm } from 'node:fs/promises';
3
3
  import { join, isAbsolute } from 'node:path';
4
4
  import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
@@ -401,7 +401,35 @@ export function createWorkspaceLocations(o) {
401
401
  return fail('WORKSPACE_LOCATION_INVALID');
402
402
  return ok(undefined);
403
403
  }
404
- return { getLocalWorkspaceContext, getWorkspaceLocationState: () => structuredClone(snapshot), 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 () => {
404
+ // Internal transaction only: same queue as source selection, never a public execution API.
405
+ function withLocalBinding(c, run) {
406
+ return serial(async () => {
407
+ const x = await context(c);
408
+ checkLocalContext(c);
409
+ if (!x.current || x.current.source !== 'local')
410
+ reject('WORKSPACE_LOCATION_INVALID');
411
+ const registeredPath = registeredLocalPath(c.workspaceId);
412
+ const guard = () => {
413
+ checkLocalContext(c);
414
+ if (registeredLocalPath(c.workspaceId) !== registeredPath)
415
+ reject('WORKSPACE_LOCATION_INVALID');
416
+ try {
417
+ const path = realpathSync(registeredPath), st = lstatSync(path);
418
+ if (path !== x.n.localPath || !st.isDirectory() || st.isSymbolicLink() || st.dev !== x.n.localDev || st.ino !== x.n.localIno)
419
+ reject('WORKSPACE_LOCATION_INVALID');
420
+ }
421
+ catch (e) {
422
+ if (e instanceof NeedError)
423
+ throw e;
424
+ reject('WORKSPACE_LOCATION_INVALID');
425
+ }
426
+ checkLocalContext(c);
427
+ };
428
+ guard();
429
+ return run({ path: x.n.localPath, device: x.n.localDev, inode: x.n.localIno }, guard);
430
+ });
431
+ }
432
+ return { withLocalBinding, getLocalWorkspaceContext, getWorkspaceLocationState: () => structuredClone(snapshot), 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 () => {
405
433
  const c = connection(), before = await guard(id);
406
434
  if (!before.ok)
407
435
  return before;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/connect",
3
- "version": "0.7.14",
3
+ "version": "0.7.18",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.13.1"