@ai-workbench/connect 0.7.14 → 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.
package/lib/index.js CHANGED
@@ -27,7 +27,7 @@ export const Config = z.object({
27
27
  maxEventBytes: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.maxEventBytes).description('conversationDetails.maxEventBytes:完整UTF-8 JSON事件的字节上限;默认1048576,范围1至9007199254740991整数。改大增加单事件存储与内存;改小会拒收超过新值的新事件,不裁剪或删除旧记录。'),
28
28
  pageSize: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.pageSize).description('conversationDetails.pageSize:每页条数;默认100,范围1至9007199254740991整数。改大增加一次读取与界面负担,改小增加继续加载次数,不减少完整快照总数。'),
29
29
  }).description('管理员诊断记录设置:不自动过期、不按条数淘汰、没有隐藏总条数上限,本版没有清除入口。'),
30
- enrollmentMetadataMaxBytes: positive().max(2147483647).default(L_DEFAULTS.enrollmentMetadataMaxBytes).description('开通元数据、工作区关联文件、诊断设置文件及设置提交JSON的字节上限;默认1048576,可由管理员修改;改小可能拒绝设置读取/提交,不读取key内容'),
30
+ enrollmentMetadataMaxBytes: positive().max(2147483647).default(L_DEFAULTS.enrollmentMetadataMaxBytes).description('开通元数据、工作区关联文件、本地接纳关系文件、诊断设置文件及设置提交JSON各单份文件的字节上限;默认1048576,可由管理员修改;改小可能拒绝设置读取/提交,不读取key内容'),
31
31
  inventory: z.object({ network: z.string(), connect: z.string(), claude: z.string(), codex: z.string() }).description('由已安装组件的实际版本自动生成,只读信息,不作为功能开关'),
32
32
  enrollmentPackageDir: z.string().description('连接资料目录:由管理员安装时配置,员工无需手填'),
33
33
  trustDir: z.string().description('主机信任缓存目录:由管理员安装时配置'),
@@ -0,0 +1,17 @@
1
+ import type { LocalUserTurnAcceptance } from './local-user-turn-types.ts';
2
+ export declare const canonical: (v: any) => string;
3
+ export declare const hash: (v: unknown) => string;
4
+ export interface AcceptanceRecord {
5
+ acceptance: LocalUserTurnAcceptance;
6
+ identity: string;
7
+ header: Record<string, unknown>;
8
+ retired: boolean;
9
+ runtimeId: string;
10
+ key: string;
11
+ }
12
+ export declare function validHeader(h: any): boolean;
13
+ export declare function acceptanceStore(profile: string, maxBytes: number): {
14
+ read: () => AcceptanceRecord[];
15
+ save: (items: AcceptanceRecord[], guard: () => void) => void;
16
+ verify: (expected: AcceptanceRecord, guard: () => void) => void;
17
+ };
@@ -0,0 +1,129 @@
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 { createHash, randomUUID } from 'node:crypto';
4
+ export const canonical = (v) => v === null || typeof v !== 'object' ? JSON.stringify(v) : Array.isArray(v) ? '[' + v.map(canonical).join(',') + ']' : '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}';
5
+ export const hash = (v) => createHash('sha256').update(canonical(v)).digest('hex');
6
+ const exact = (v, fields) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).sort().join(',') === fields;
7
+ const text = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
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)); }
10
+ 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
+ export function acceptanceStore(profile, maxBytes) {
12
+ const root = join(profile, 'ai-workbench-connect'), file = join(root, 'local-user-turn-acceptances.json');
13
+ const directory = (path) => { const st = lstatSync(path); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0 || realpathSync(path) !== path)
14
+ throw Error('ACCEPTANCE_DIRECTORY_INVALID'); };
15
+ function read() {
16
+ if (realpathSync(profile) !== profile)
17
+ throw Error('ACCEPTANCE_PROFILE_INVALID');
18
+ try {
19
+ directory(root);
20
+ }
21
+ catch (e) {
22
+ if (e.code === 'ENOENT')
23
+ return [];
24
+ throw e;
25
+ }
26
+ let fd;
27
+ try {
28
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
29
+ }
30
+ catch (e) {
31
+ if (e.code === 'ENOENT')
32
+ return [];
33
+ throw e;
34
+ }
35
+ try {
36
+ const st = fstatSync(fd);
37
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || st.size > maxBytes)
38
+ throw Error('ACCEPTANCE_FILE_INVALID');
39
+ const bytes = readFileSync(fd);
40
+ if (bytes.length > maxBytes)
41
+ throw Error('ACCEPTANCE_LIMIT');
42
+ const data = JSON.parse(bytes.toString('utf8'));
43
+ if (!data || Object.keys(data).sort().join(',') !== 'items,version' || data.version !== 1 || !Array.isArray(data.items))
44
+ throw Error('ACCEPTANCE_FORMAT_INVALID');
45
+ const ids = new Set();
46
+ for (const r of data.items) {
47
+ const a = r?.acceptance;
48
+ if (!r || Object.keys(r).sort().join(',') !== 'acceptance,header,identity,key,retired,runtimeId' || !a || a.version !== 1 || typeof a.acceptanceId !== 'string' || !a.acceptanceId || ids.has(a.acceptanceId) || !['claude', 'codex'].includes(a.provider) || a.source !== 'local' || !a.directory || !a.userTurn || !r.header || typeof r.retired !== 'boolean' || !/^[a-f0-9]{64}$/.test(r.identity) || !validAcceptance(a) || !validHeader(r.header) || r.header.id !== a.sessionId || typeof r.runtimeId !== 'string' || !r.runtimeId || r.key !== hash({ acceptance: a, identity: r.identity, header: r.header, retired: r.retired, runtimeId: r.runtimeId }))
49
+ throw Error('ACCEPTANCE_RECORD_INVALID');
50
+ ids.add(a.acceptanceId);
51
+ }
52
+ return data.items;
53
+ }
54
+ finally {
55
+ closeSync(fd);
56
+ }
57
+ }
58
+ function save(items, guard) {
59
+ directory(root);
60
+ for (const r of items)
61
+ r.key = hash({ acceptance: r.acceptance, identity: r.identity, header: r.header, retired: r.retired, runtimeId: r.runtimeId });
62
+ const bytes = JSON.stringify({ version: 1, items }) + '\n';
63
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || Buffer.byteLength(bytes) > maxBytes)
64
+ throw Error('ACCEPTANCE_LIMIT');
65
+ const temp = join(root, '.local-acceptance-' + randomUUID());
66
+ let created = false;
67
+ try {
68
+ const fd = openSync(temp, 'wx', 0o600);
69
+ created = true;
70
+ try {
71
+ writeFileSync(fd, bytes);
72
+ fsyncSync(fd);
73
+ }
74
+ finally {
75
+ closeSync(fd);
76
+ }
77
+ guard();
78
+ renameSync(temp, file);
79
+ created = false;
80
+ for (const path of [root, profile]) {
81
+ const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
82
+ try {
83
+ fsyncSync(d);
84
+ }
85
+ finally {
86
+ closeSync(d);
87
+ }
88
+ }
89
+ }
90
+ finally {
91
+ if (created)
92
+ unlinkSync(temp);
93
+ }
94
+ }
95
+ function verify(expected, guard) {
96
+ directory(root);
97
+ if (realpathSync(profile) !== profile)
98
+ throw Error('ACCEPTANCE_PROFILE_INVALID');
99
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
100
+ try {
101
+ const st = fstatSync(fd);
102
+ if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || st.size > maxBytes)
103
+ throw Error('ACCEPTANCE_FILE_INVALID');
104
+ const bytes = readFileSync(fd);
105
+ if (bytes.length > maxBytes)
106
+ throw Error('ACCEPTANCE_LIMIT');
107
+ const data = JSON.parse(bytes.toString('utf8'));
108
+ if (!Array.isArray(data.items) || !data.items.some((r) => canonical(r) === canonical(expected)))
109
+ throw Error('ACCEPTANCE_CHANGED');
110
+ guard();
111
+ fsyncSync(fd);
112
+ }
113
+ finally {
114
+ closeSync(fd);
115
+ }
116
+ for (const path of [root, profile]) {
117
+ const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
118
+ try {
119
+ guard();
120
+ fsyncSync(d);
121
+ }
122
+ finally {
123
+ closeSync(d);
124
+ }
125
+ }
126
+ guard();
127
+ }
128
+ return { read, save, verify };
129
+ }
@@ -0,0 +1,74 @@
1
+ import type { ConnectionState, Provider, RemoteConversationDetail, Result } from './api.ts';
2
+ import type { LocalUserTurnAcceptance, LocalUserTurnAcceptanceRequest } from './local-user-turn-types.ts';
3
+ import type { WorkspaceLocationState } from './workspace-location-types.ts';
4
+ import type { NativeWorkspaceRegistry } from './workspace-bindings.ts';
5
+ interface Session {
6
+ header: Record<string, any>;
7
+ seq: number;
8
+ }
9
+ interface SessionEvent {
10
+ seq: number;
11
+ type: string;
12
+ data: any;
13
+ }
14
+ interface Services {
15
+ sessions: {
16
+ get(id: string): Session | undefined;
17
+ flush(session: Session): Promise<boolean>;
18
+ };
19
+ persistence: {
20
+ identity?: symbol;
21
+ open(id: string, access: 'read'): Promise<{
22
+ id: string;
23
+ access: string;
24
+ header: Record<string, any>;
25
+ inheritedEventCount: number;
26
+ read(): Promise<{
27
+ events: readonly SessionEvent[];
28
+ }>;
29
+ close(): Promise<void>;
30
+ }>;
31
+ };
32
+ }
33
+ interface Options {
34
+ profileDir: string;
35
+ metadataMaxBytes: number;
36
+ registry: NativeWorkspaceRegistry;
37
+ getConnectionState: () => ConnectionState;
38
+ services: () => Services;
39
+ readHeader: (id: string) => Promise<Record<string, any> | undefined>;
40
+ context: () => Promise<Result<{
41
+ identity: string;
42
+ guard?: () => void;
43
+ }>>;
44
+ withLocalBinding: <T>(c: {
45
+ instanceId: string;
46
+ epoch: number;
47
+ workspaceId: string;
48
+ expectedBindingId: string;
49
+ }, run: (directory: {
50
+ path: string;
51
+ device: number;
52
+ inode: number;
53
+ }, guard: () => void) => Promise<Result<T>>) => Promise<Result<T>>;
54
+ }
55
+ export declare function createLocalUserTurnAcceptance(o: Options): {
56
+ active: () => boolean;
57
+ observe: (session: Session, event: SessionEvent) => void;
58
+ observeLocations: (state: WorkspaceLocationState) => void;
59
+ observeSessionDisposed: (session: Session) => void;
60
+ readScope: (sessionId: string, provider: Provider, acceptanceId?: string, detail?: RemoteConversationDetail, expectedIdentity?: string) => Promise<Result<{
61
+ identity: string;
62
+ guard: () => void;
63
+ cacheGuard: () => void;
64
+ }>>;
65
+ withWrite: <T>(acceptanceId: string, detail: RemoteConversationDetail, run: (proof: {
66
+ identity: string;
67
+ acceptanceId: string;
68
+ guard: () => void;
69
+ }) => Promise<Result<T>>) => Promise<Result<T>>;
70
+ acceptLocalWorkspaceUserTurn(request: LocalUserTurnAcceptanceRequest): Promise<Result<LocalUserTurnAcceptance>>;
71
+ dispose(): void;
72
+ };
73
+ export type LocalDetailsAdmission = ReturnType<typeof createLocalUserTurnAcceptance>;
74
+ export {};
@@ -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
  }>>;
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
+ }