@ai-workbench/connect 0.7.11 → 0.7.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +34 -3
  2. package/client/index.cjs +29 -9
  3. package/helper/host-directories.cjs +72 -0
  4. package/lib/api.d.ts +31 -2
  5. package/lib/api.js +1 -1
  6. package/lib/cache.js +2 -2
  7. package/lib/component-download.d.ts +2 -0
  8. package/lib/component-download.js +13 -3
  9. package/lib/components.d.ts +1 -1
  10. package/lib/components.js +80 -5
  11. package/lib/connect.d.ts +3 -0
  12. package/lib/connect.js +53 -11
  13. package/lib/connection-messages.d.ts +7 -0
  14. package/lib/connection-messages.js +6 -0
  15. package/lib/conversation-details.d.ts +2 -0
  16. package/lib/conversation-details.js +158 -51
  17. package/lib/cordis.d.ts +2 -1
  18. package/lib/defaults.d.ts +6 -0
  19. package/lib/defaults.js +2 -0
  20. package/lib/host-directories.d.ts +53 -0
  21. package/lib/host-directories.js +76 -0
  22. package/lib/index.d.ts +8 -1
  23. package/lib/index.js +10 -5
  24. package/lib/integration.js +2 -0
  25. package/lib/local-acceptance-store.d.ts +17 -0
  26. package/lib/local-acceptance-store.js +129 -0
  27. package/lib/local-user-turn-acceptance.d.ts +74 -0
  28. package/lib/local-user-turn-acceptance.js +281 -0
  29. package/lib/local-user-turn-types.d.ts +40 -0
  30. package/lib/local-user-turn-types.js +1 -0
  31. package/lib/local-workspace-context.d.ts +46 -0
  32. package/lib/local-workspace-context.js +17 -0
  33. package/lib/login-diagnostics.d.ts +3 -1
  34. package/lib/needs.js +13 -0
  35. package/lib/ports.d.ts +2 -0
  36. package/lib/private-files.d.ts +2 -0
  37. package/lib/private-files.js +17 -1
  38. package/lib/profile-runtime.js +62 -12
  39. package/lib/startup.d.ts +1 -1
  40. package/lib/startup.js +33 -13
  41. package/lib/workspace-bindings.d.ts +30 -1
  42. package/lib/workspace-bindings.js +1 -0
  43. package/lib/workspace-location-types.d.ts +65 -0
  44. package/lib/workspace-location-types.js +1 -0
  45. package/lib/workspace-locations.d.ts +50 -0
  46. package/lib/workspace-locations.js +455 -0
  47. package/node_modules/argparse/CHANGELOG.md +216 -0
  48. package/package.json +4 -3
@@ -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 {};
@@ -0,0 +1,46 @@
1
+ import type { Result } from './api.ts';
2
+ /** Local metadata; neither OS consent nor an authenticated endpoint identity. */
3
+ export interface LocalWorkspaceContextRequest {
4
+ instanceId: string;
5
+ epoch: number;
6
+ workspaceId: string;
7
+ expectedBindingId: string;
8
+ }
9
+ export interface LocalWorkspaceProcess {
10
+ pid: number;
11
+ ppid: number;
12
+ platform: string;
13
+ arch: string;
14
+ executable: string;
15
+ realUid: number;
16
+ effectiveUid: number;
17
+ realGid: number;
18
+ effectiveGid: number;
19
+ account: {
20
+ name: string;
21
+ home: string;
22
+ shell: string | null;
23
+ };
24
+ environment: {
25
+ HOME: string | null;
26
+ PATH: string | null;
27
+ SHELL: string | null;
28
+ };
29
+ }
30
+ export interface LocalWorkspaceContext {
31
+ version: 1;
32
+ instanceId: string;
33
+ epoch: number;
34
+ workspaceId: string;
35
+ bindingId: string;
36
+ source: 'local';
37
+ directory: {
38
+ path: string;
39
+ device: number;
40
+ inode: number;
41
+ };
42
+ provenance: 'official-workspace-registry';
43
+ process: LocalWorkspaceProcess;
44
+ }
45
+ /** Read the current backend's OS facts and three named variables. Never spawn a shell. */
46
+ export declare function readLocalWorkspaceProcess(): Result<LocalWorkspaceProcess>;
@@ -0,0 +1,17 @@
1
+ import { userInfo } from 'node:os';
2
+ import { fail, ok } from "./needs.js";
3
+ /** Read the current backend's OS facts and three named variables. Never spawn a shell. */
4
+ export function readLocalWorkspaceProcess() {
5
+ if (process.platform !== 'darwin')
6
+ return fail('LOCAL_WORKSPACE_CONTEXT_UNSUPPORTED');
7
+ try {
8
+ const account = userInfo();
9
+ return ok({ pid: process.pid, ppid: process.ppid, platform: process.platform, arch: process.arch, executable: process.execPath,
10
+ realUid: process.getuid(), effectiveUid: process.geteuid(), realGid: process.getgid(), effectiveGid: process.getegid(),
11
+ account: { name: account.username, home: account.homedir, shell: account.shell },
12
+ environment: { HOME: process.env.HOME ?? null, PATH: process.env.PATH ?? null, SHELL: process.env.SHELL ?? null } });
13
+ }
14
+ catch {
15
+ return fail('LOCAL_WORKSPACE_CONTEXT_UNAVAILABLE');
16
+ }
17
+ }
@@ -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
  }>>;
package/lib/needs.js CHANGED
@@ -1,4 +1,17 @@
1
1
  const entries = {
2
+ LOCAL_USER_TURN_CHANGED: { layer: 'integration', message: '本次输入在核实期间发生变化,本轮已停止。', requires: '下一次真实员工输入与当前会话关系', actor: 'plugin', action: { id: 'inspect-local-user-turn', label: '查看技术详情', available: false } },
3
+ LOCAL_WORKSPACE_CONTEXT_UNSUPPORTED: { layer: 'integration', message: '当前平台尚未接入本地工作区进程环境交接。', requires: '已接入平台的本机后端上下文', actor: 'plugin', action: { id: 'inspect-local-workspace-context', label: '查看技术详情', available: false } },
4
+ LOCAL_WORKSPACE_CONTEXT_UNAVAILABLE: { layer: 'integration', message: '本机进程环境无法确认,已停止交接;根因未查明。', requires: '当前进程的真实操作系统账户与环境', actor: 'plugin', action: { id: 'inspect-local-workspace-context', label: '查看技术详情', available: false } },
5
+ HOST_DIRECTORY_INVALID: { layer: 'projects', message: '目录不存在或不是文件夹,请重新选择。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
6
+ HOST_DIRECTORY_UNREADABLE: { layer: 'projects', message: '主机目录无法列出,请查看目录权限或连接状态。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
7
+ HOST_DIRECTORY_CHANGED: { layer: 'projects', message: '目录内容或位置已变化,请重新浏览后选择。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
8
+ HOST_DIRECTORY_PAGE_TOO_LARGE: { layer: 'projects', message: '本页目录元数据超过 commandOutputMaxBytes,请减小每页条数或联系管理员调整。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
9
+ WORKSPACE_LOCATION_REQUIRED: { layer: 'projects', message: '请先在远程主机连接设置中选择此工作区的文件来源;旧关联需要确认。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
10
+ WORKSPACE_LOCATION_INVALID: { layer: 'projects', message: '工作区位置与当前目录或主机身份不符,请重新选择。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
11
+ WORKSPACE_LOCATION_CONFLICT: { layer: 'projects', message: '工作区或连接已变化,请刷新位置后重选。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
12
+ WORKSPACE_LOCATION_PROVIDER_REQUIRED: { layer: 'projects', message: '主机文件夹已记录,等待远程提供方接入位置合同后才能执行。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
13
+ WORKSPACE_EXECUTION_UNAVAILABLE: { layer: 'projects', message: '本地文件夹已记录,按需远程文件与命令执行尚未接通。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
14
+ WORKSPACE_LOCATION_STORAGE_FAILED: { layer: 'projects', message: '工作区位置记录无法读取或保存,已停止操作,请联系管理员。', requires: '当前工作区位置与连接合同', actor: 'employee', action: { id: 'select-workspace-location', label: '查看工作区位置', available: true } },
2
15
  REMOTE_DETAIL_INVALID: { layer: 'integration', message: '诊断内容格式无效或含未脱敏认证材料,已拒绝保存。', requires: '有效且已脱敏的诊断与可信连接', actor: 'plugin', action: { id: 'inspect-remote-details', label: '查看技术详情', available: false } },
3
16
  REMOTE_DETAIL_SCOPE_INVALID: { layer: 'integration', message: '诊断内容与当前连接、原生会话或已核验品牌关联不符,已拒绝保存。', requires: '有效且已脱敏的诊断与可信连接', actor: 'plugin', action: { id: 'inspect-remote-details', label: '查看技术详情', available: false } },
4
17
  REMOTE_DETAIL_STORAGE_FAILED: { layer: 'integration', message: '诊断记录无法持久保存或读取,结果无法确认,请联系管理员。', requires: '有效且已脱敏的诊断与可信连接', actor: 'plugin', action: { id: 'inspect-remote-details', label: '查看技术详情', available: false } },
package/lib/ports.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Provider, Result, SshTarget, SessionTarget, HostContext, Project, ProjectList } from './api.ts';
2
+ import type { createHostDirectories } from './host-directories.ts';
2
3
  export interface Enrollment {
3
4
  authKeyFile?: string;
4
5
  hostContext?: HostContext;
@@ -20,6 +21,7 @@ export type NetworkEvent = {
20
21
  kind: 'restored';
21
22
  };
22
23
  export interface Ports {
24
+ hostDirectories?: ReturnType<typeof createHostDirectories>;
23
25
  enrollment?: {
24
26
  read(signal: AbortSignal): Promise<Result<Enrollment>>;
25
27
  };
@@ -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
+ }
@@ -1,10 +1,13 @@
1
+ import { WORKSPACE_LOCATION_DEFAULTS } from "./defaults.js";
2
+ import { createWorkspaceLocations } from "./workspace-locations.js";
1
3
  import { mapNetworkNeed } from "./provider.js";
2
4
  import { createProfileEnrollment } from "./profile-enrollment.js";
3
5
  import { createWorkspaceBindings } from "./workspace-bindings.js";
4
6
  import { NeedError, need, fail } from "./needs.js";
5
7
  import { createNativeImportPicker } from "./native-import-picker.js";
6
8
  import { createHash } from 'node:crypto';
7
- import { readPrivate } from "./private-files.js";
9
+ import { readPrivate, readPrivateSync } from "./private-files.js";
10
+ import { createLocalUserTurnAcceptance } from "./local-user-turn-acceptance.js";
8
11
  import { createConversationDetails } from "./conversation-details.js";
9
12
  import { createLoginDiagnostics } from "./login-diagnostics.js";
10
13
  import { CONVERSATION_DETAIL_DEFAULTS, L_DEFAULTS } from "./defaults.js";
@@ -25,10 +28,14 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
25
28
  api.importEnrollment = async () => { const result = await manager.importEnrollment(); if (result.ok && result.value.outcome === 'imported')
26
29
  await api.refreshLoginPrompts(); return result; };
27
30
  ctx.effect(() => () => manager.dispose());
31
+ let locationRevision = 0;
28
32
  let workspaceRevision = 0;
29
33
  let lastWorkspaceError;
30
34
  ctx.provide('aiWorkbenchWorkspaceDiagnostics', { getLatest: () => lastWorkspaceError });
31
- ctx.inject(['workspaceRegistry', 'sessions', 'sessionPersistence'], native => {
35
+ ctx.inject(['profileContext', 'workspaceRegistry', 'sessions', 'sessionPersistence'], native => {
36
+ const profile = native.get('profileContext');
37
+ if (!profile || typeof profile.dir !== 'string')
38
+ return;
32
39
  const registry = native.get('workspaceRegistry');
33
40
  const readHeader = async (id) => {
34
41
  const live = native.get('sessions');
@@ -42,20 +49,63 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
42
49
  };
43
50
  const bindings = createWorkspaceBindings({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, api, registry,
44
51
  readHeader, nextRevision: () => ++workspaceRevision, onState: state => ctx.emit('ai-workbench/workspace-binding-state', state), diagnostic: error => { lastWorkspaceError = error; ctx.emit('ai-workbench/workspace-diagnostic', error); } });
52
+ const locations = createWorkspaceLocations({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, pageSize: config.workspaceLocations?.pageSize ?? WORKSPACE_LOCATION_DEFAULTS.pageSize, nextRevision: () => ++locationRevision, api, registry, readLegacy: bindings.readLegacyLocations, hostDirectories: ports.hostDirectories, onState: state => ctx.emit('ai-workbench/workspace-location-state', state) });
53
+ if (process.platform === 'darwin')
54
+ api.getLocalWorkspaceContext = locations.getLocalWorkspaceContext;
55
+ api.getWorkspaceLocationState = locations.getWorkspaceLocationState;
56
+ api.onWorkspaceLocationState = locations.onWorkspaceLocationState;
57
+ api.refreshWorkspaceLocations = locations.refreshWorkspaceLocations;
58
+ api.browseWorkspaceHostDirectories = locations.browseWorkspaceHostDirectories;
59
+ api.selectWorkspaceLocation = locations.selectWorkspaceLocation;
60
+ native.effect(() => { void locations.refreshWorkspaceLocations(); return api.onConnectionState(() => locations.observeConnection()); });
61
+ native.effect(() => () => { if (api.getLocalWorkspaceContext === locations.getLocalWorkspaceContext)
62
+ delete api.getLocalWorkspaceContext; delete api.getWorkspaceLocationState; delete api.onWorkspaceLocationState; delete api.refreshWorkspaceLocations; delete api.browseWorkspaceHostDirectories; delete api.selectWorkspaceLocation; return locations.dispose(); });
45
63
  const settings = ctx.get('aiWorkbenchConversationDetailSettings');
46
- const context = async () => { const current = api.getModelCatalogTarget('codex'); if (!current.ok)
47
- return current; const t = current.value.target; try {
48
- const trust = await readPrivate(t.knownHostsFile, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
49
- return { ok: true, value: { identity: createHash('sha256').update(JSON.stringify([t.host, t.username, t.port, trust])).digest('hex') } };
64
+ const context = async () => {
65
+ const current = api.getModelCatalogTarget('codex');
66
+ if (!current.ok)
67
+ return current;
68
+ const t = current.value.target, budget = config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes;
69
+ const identityOf = (target, trust) => createHash('sha256').update(JSON.stringify([target.host, target.username, target.port, trust])).digest('hex');
70
+ try {
71
+ const trust = await readPrivate(t.knownHostsFile, budget), identity = identityOf(t, trust);
72
+ const guard = () => { const latest = api.getModelCatalogTarget('codex'); if (!latest.ok)
73
+ throw new NeedError(latest.error); try {
74
+ if (identityOf(latest.value.target, readPrivateSync(latest.value.target.knownHostsFile, budget)) !== identity)
75
+ throw Error('TRUST_CHANGED');
76
+ }
77
+ catch (e) {
78
+ if (e instanceof NeedError)
79
+ throw e;
80
+ throw new NeedError(need('REMOTE_DETAIL_SCOPE_INVALID'));
81
+ } };
82
+ guard();
83
+ return { ok: true, value: { identity, guard } };
84
+ }
85
+ catch (e) {
86
+ return e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_SCOPE_INVALID');
87
+ }
88
+ };
89
+ const nativeSessions = native.get('sessions'), nativePersistence = native.get('sessionPersistence');
90
+ 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,
91
+ // SessionStore proxies are not instance IDs. Check the exact live Session and
92
+ // SessionPersistence's public stable identity, plus the injected lifetime.
93
+ services: () => ({ sessions: native.get('sessions'), persistence: native.get('sessionPersistence') }) }) : undefined;
94
+ if (localAcceptance) {
95
+ api.acceptLocalWorkspaceUserTurn = localAcceptance.acceptLocalWorkspaceUserTurn;
96
+ native.on('session/event', (session, event) => localAcceptance.observe(session, event));
97
+ native.on('session/disposed', (session) => localAcceptance.observeSessionDisposed(session));
98
+ native.effect(() => locations.onWorkspaceLocationState(localAcceptance.observeLocations));
99
+ native.effect(() => () => { localAcceptance.dispose(); if (api.acceptLocalWorkspaceUserTurn === localAcceptance.acceptLocalWorkspaceUserTurn)
100
+ delete api.acceptLocalWorkspaceUserTurn; });
50
101
  }
51
- catch {
52
- return fail('REMOTE_DETAIL_SCOPE_INVALID');
53
- } };
54
102
  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,
55
- context,
103
+ context, localAcceptance,
56
104
  scope: async (sessionId, provider) => { const current = api.getModelCatalogTarget(provider); if (!current.ok)
57
105
  return current; return bindings.verifyRemoteConversationScope(sessionId, provider, current.value.target); },
58
106
  onState: state => ctx.emit('ai-workbench/remote-conversation-detail-state', state) });
107
+ native.on('session/created', () => details.observeConnection(api.getConnectionState()));
108
+ native.on('session/disposed', () => details.observeConnection(api.getConnectionState()));
59
109
  api.appendRemoteConversationDetail = details.appendRemoteConversationDetail;
60
110
  api.getRemoteConversationDetailReceipt = details.getRemoteConversationDetailReceipt;
61
111
  api.getRemoteConversationDetailState = details.getRemoteConversationDetailState;
@@ -71,7 +121,7 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
71
121
  api.listLoginDiagnostics = loginDiagnostics.listLoginDiagnostics;
72
122
  api.getLoginDiagnosticState = loginDiagnostics.getLoginDiagnosticState;
73
123
  api.onLoginDiagnosticState = loginDiagnostics.onLoginDiagnosticState;
74
- const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1 });
124
+ const previousContractInfo = api.getContractInfo, detailContractInfo = () => ({ ...previousContractInfo(), remoteConversationDetails: 1, loginDiagnostics: 1, workspaceLocations: 1, ...(process.platform === 'darwin' && api.getConnectionState().phase !== 'disposed' ? { localWorkspaceContext: 1, ...(localAcceptance?.active() ? { localUserTurnAcceptance: 1 } : {}) } : {}) });
75
125
  api.getContractInfo = detailContractInfo;
76
126
  native.effect(() => { details.observeConnection(api.getConnectionState()); return api.onConnectionState(details.observeConnection); });
77
127
  native.effect(() => { loginDiagnostics.observeConnection(api.getConnectionState()); return api.onConnectionState(loginDiagnostics.observeConnection); });
@@ -81,7 +131,7 @@ export function attachProfileRuntime(ctx, api, ports, config, network) {
81
131
  api.getWorkspaceBindingState = bindings.getWorkspaceBindingState;
82
132
  api.onWorkspaceBindingState = bindings.onWorkspaceBindingState;
83
133
  api.acknowledgeWorkspaceNotice = bindings.acknowledgeWorkspaceNotice;
84
- api.resolveSessionProject = bindings.resolveSessionProject;
134
+ api.resolveSessionProject = (sessionId, use) => locations.resolveLegacySession(sessionId, () => bindings.resolveSessionProject(sessionId, use));
85
135
  native.effect(() => () => { api.resolveSessionProject = async () => fail('DEPENDENCY_REQUIRED'); api.acknowledgeWorkspaceNotice = async () => fail('DEPENDENCY_REQUIRED'); return bindings.dispose(); });
86
136
  });
87
137
  }
package/lib/startup.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ConnectApi, ConnectionState, LoginPromptState, LoginPromptResult, LoginState, Provider, NeedCode, Result } from './api.ts';
2
2
  export type StartupState = LoginPromptState;
3
- export declare function employeeMessage(code?: NeedCode): string;
3
+ export declare function employeeMessage(code?: NeedCode, connection?: ConnectionState): string;
4
4
  type Operations = Pick<ConnectApi, 'connect' | 'checkLogin' | 'login' | 'getState'>;
5
5
  export declare function createStartup(api: Operations, providers: Provider[], emit?: (s: LoginPromptState) => void, result?: (r: LoginPromptResult) => void, instanceId?: string): {
6
6
  getState: () => LoginPromptState;