@ai-workbench/connect 0.7.23 → 0.7.26

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 (62) hide show
  1. package/README.md +20 -73
  2. package/client/index.cjs +93 -65
  3. package/helper/host-directories.cjs +8 -1
  4. package/lib/api.d.ts +21 -163
  5. package/lib/component-download.d.ts +1 -1
  6. package/lib/component-download.js +1 -1
  7. package/lib/component-source.d.ts +6 -27
  8. package/lib/component-source.js +10 -138
  9. package/lib/components.d.ts +1 -1
  10. package/lib/components.js +86 -98
  11. package/lib/connect.d.ts +0 -3
  12. package/lib/connect.js +15 -62
  13. package/lib/connection-messages.d.ts +2 -3
  14. package/lib/connection-messages.js +5 -4
  15. package/lib/conversation-log.d.ts +9 -0
  16. package/lib/conversation-log.js +44 -0
  17. package/lib/cordis.d.ts +1 -4
  18. package/lib/defaults.d.ts +0 -7
  19. package/lib/defaults.js +0 -2
  20. package/lib/enrollment.js +1 -8
  21. package/lib/host-directories.d.ts +6 -4
  22. package/lib/host-directories.js +4 -4
  23. package/lib/host-session-projects.d.ts +8 -58
  24. package/lib/host-session-projects.js +45 -270
  25. package/lib/index.d.ts +2 -11
  26. package/lib/index.js +11 -23
  27. package/lib/integration.d.ts +2 -2
  28. package/lib/integration.js +0 -2
  29. package/lib/native-workspace.d.ts +10 -0
  30. package/lib/needs.js +13 -25
  31. package/lib/ports.d.ts +1 -6
  32. package/lib/profile-runtime.js +59 -152
  33. package/lib/profile-settings.d.ts +6 -1
  34. package/lib/profile-settings.js +3 -5
  35. package/lib/startup.js +2 -2
  36. package/lib/workspace-directory-picker-types.d.ts +44 -0
  37. package/lib/workspace-directory-picker-types.js +1 -0
  38. package/lib/workspace-directory-picker.d.ts +30 -0
  39. package/lib/workspace-directory-picker.js +394 -0
  40. package/lib/workspace-location-types.d.ts +3 -7
  41. package/lib/workspace-locations.d.ts +5 -29
  42. package/lib/workspace-locations.js +81 -204
  43. package/package.json +3 -2
  44. package/helper/projects.cjs +0 -57
  45. package/lib/conversation-detail-settings.d.ts +0 -32
  46. package/lib/conversation-detail-settings.js +0 -119
  47. package/lib/conversation-details.d.ts +0 -30
  48. package/lib/conversation-details.js +0 -595
  49. package/lib/host-session-store.d.ts +0 -27
  50. package/lib/host-session-store.js +0 -130
  51. package/lib/local-acceptance-store.d.ts +0 -18
  52. package/lib/local-acceptance-store.js +0 -133
  53. package/lib/local-user-turn-acceptance.d.ts +0 -76
  54. package/lib/local-user-turn-acceptance.js +0 -289
  55. package/lib/local-user-turn-types.d.ts +0 -40
  56. package/lib/login-diagnostics.d.ts +0 -28
  57. package/lib/login-diagnostics.js +0 -57
  58. package/lib/projects.d.ts +0 -4
  59. package/lib/projects.js +0 -41
  60. package/lib/workspace-bindings.d.ts +0 -64
  61. package/lib/workspace-bindings.js +0 -379
  62. /package/lib/{local-user-turn-types.js → native-workspace.js} +0 -0
@@ -1,130 +0,0 @@
1
- import { constants, openSync, closeSync, fstatSync, lstatSync, readFileSync, writeFileSync, fsyncSync, renameSync, unlinkSync, realpathSync } from 'node:fs';
2
- import { join, isAbsolute } from 'node:path';
3
- import { randomUUID } from 'node:crypto';
4
- import { canonical, hash, validHeader } from "./local-acceptance-store.js";
5
- const text = (v) => typeof v === 'string' && !!v && !/[\x00-\x1f\x7f]/.test(v);
6
- const int = (v) => Number.isSafeInteger(v) && v >= 0;
7
- function validRecord(r) {
8
- if (!r || Object.keys(r).sort().join(',') !== 'bindingId,directory,epoch,header,id,identity,instanceId,key,local,provider,revoked,runtimeId,sessionId,workspaceId' || !['id', 'sessionId', 'workspaceId', 'bindingId', 'instanceId', 'runtimeId'].every(k => text(r[k])) || !['claude', 'codex'].includes(r.provider) || !int(r.epoch) || !validHeader(r.header) || r.header.id !== r.sessionId || !/^[a-f0-9]{64}$/.test(r.identity) || typeof r.revoked !== 'boolean' || r.key !== hash({ ...r, key: '' }))
9
- return false;
10
- const d = r.directory, l = r.local;
11
- return l && Object.keys(l).sort().join(',') === 'device,inode,path' && typeof l.path === 'string' && isAbsolute(l.path) && int(l.device) && int(l.inode) && d && Object.keys(d).sort().join(',') === 'entryIdentity,identity,isSymlink,parentPath,path,permissions,requestedPath' && (d.parentPath === null || typeof d.parentPath === 'string' && isAbsolute(d.parentPath)) && typeof d.path === 'string' && isAbsolute(d.path) && typeof d.requestedPath === 'string' && isAbsolute(d.requestedPath) && d.identity && Object.keys(d.identity).sort().join(',') === 'ctimeNs,device,inode,mtimeNs' && ['device', 'inode'].every(k => typeof d.identity[k] === 'string' && /^\d+$/.test(d.identity[k])) && ['mtimeNs', 'ctimeNs'].every(k => typeof d.identity[k] === 'string' && /^-?\d+$/.test(d.identity[k])) && d.entryIdentity && Object.keys(d.entryIdentity).sort().join(',') === 'device,inode' && ['device', 'inode'].every(k => typeof d.entryIdentity[k] === 'string' && /^\d+$/.test(d.entryIdentity[k])) && typeof d.isSymlink === 'boolean' && d.permissions && Object.keys(d.permissions).every(k => ['read', 'write', 'execute', 'reason'].includes(k)) && ([d.permissions.read, d.permissions.write, d.permissions.execute].includes(null) ? d.permissions.reason === 'HOST_PERMISSION_UNKNOWN' : d.permissions.reason === undefined) && ['read', 'write', 'execute'].every(k => [true, false, null].includes(d.permissions[k]));
12
- }
13
- export function hostProjectStore(profile, maxBytes) {
14
- const root = join(profile, 'ai-workbench-connect'), file = join(root, 'host-session-projects.json');
15
- const directory = (path) => { const st = lstatSync(path); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0 || realpathSync(path) !== path)
16
- throw Error('HOST_SESSION_DIRECTORY_INVALID'); };
17
- function read() {
18
- if (realpathSync(profile) !== profile)
19
- throw Error('HOST_SESSION_PROFILE_INVALID');
20
- try {
21
- directory(root);
22
- }
23
- catch (e) {
24
- if (e.code === 'ENOENT')
25
- return [];
26
- throw e;
27
- }
28
- let fd;
29
- try {
30
- fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
31
- }
32
- catch (e) {
33
- if (e.code === 'ENOENT')
34
- return [];
35
- throw e;
36
- }
37
- try {
38
- const st = fstatSync(fd);
39
- if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || st.size > maxBytes)
40
- throw Error('HOST_SESSION_FILE_INVALID');
41
- const bytes = readFileSync(fd);
42
- if (bytes.length > maxBytes)
43
- throw Error('HOST_SESSION_LIMIT');
44
- const data = JSON.parse(bytes.toString('utf8'));
45
- if (!data || Object.keys(data).sort().join(',') !== 'items,version' || data.version !== 1 || !Array.isArray(data.items))
46
- throw Error('HOST_SESSION_FORMAT_INVALID');
47
- const ids = new Set();
48
- for (const r of data.items) {
49
- if (!validRecord(r) || ids.has(r.id))
50
- throw Error('HOST_SESSION_RECORD_INVALID');
51
- ids.add(r.id);
52
- }
53
- return data.items;
54
- }
55
- finally {
56
- closeSync(fd);
57
- }
58
- }
59
- function save(items, guard) {
60
- directory(root);
61
- for (const r of items)
62
- r.key = hash({ ...r, key: '' });
63
- const bytes = JSON.stringify({ version: 1, items }) + '\n';
64
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || Buffer.byteLength(bytes) > maxBytes)
65
- throw Error('HOST_SESSION_LIMIT');
66
- const temp = join(root, '.host-session-' + randomUUID());
67
- let created = false;
68
- try {
69
- const fd = openSync(temp, 'wx', 0o600);
70
- created = true;
71
- try {
72
- writeFileSync(fd, bytes);
73
- fsyncSync(fd);
74
- }
75
- finally {
76
- closeSync(fd);
77
- }
78
- guard();
79
- renameSync(temp, file);
80
- created = false;
81
- for (const path of [root, profile]) {
82
- const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
83
- try {
84
- fsyncSync(d);
85
- }
86
- finally {
87
- closeSync(d);
88
- }
89
- }
90
- }
91
- finally {
92
- if (created)
93
- unlinkSync(temp);
94
- }
95
- }
96
- function verify(expected, guard) {
97
- directory(root);
98
- if (realpathSync(profile) !== profile)
99
- throw Error('HOST_SESSION_PROFILE_INVALID');
100
- const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
101
- try {
102
- const st = fstatSync(fd);
103
- if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || st.size > maxBytes)
104
- throw Error('HOST_SESSION_FILE_INVALID');
105
- const bytes = readFileSync(fd);
106
- if (bytes.length > maxBytes)
107
- throw Error('HOST_SESSION_LIMIT');
108
- const data = JSON.parse(bytes.toString('utf8'));
109
- if (!Array.isArray(data.items) || !data.items.some((r) => canonical(r) === canonical(expected)))
110
- throw Error('HOST_SESSION_CHANGED');
111
- guard();
112
- fsyncSync(fd);
113
- }
114
- finally {
115
- closeSync(fd);
116
- }
117
- for (const path of [root, profile]) {
118
- const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
119
- try {
120
- guard();
121
- fsyncSync(d);
122
- }
123
- finally {
124
- closeSync(d);
125
- }
126
- }
127
- guard();
128
- }
129
- return { read, save, verify };
130
- }
@@ -1,18 +0,0 @@
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 sameSessionHeader(a: any, b: any): boolean;
14
- export declare function acceptanceStore(profile: string, maxBytes: number): {
15
- read: () => AcceptanceRecord[];
16
- save: (items: AcceptanceRecord[], guard: () => void) => void;
17
- verify: (expected: AcceptanceRecord, guard: () => void) => void;
18
- };
@@ -1,133 +0,0 @@
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.hasOwn(h, 'delegationDepth') || int(h.delegationDepth) && !Object.is(h.delegationDepth, -0)) && Object.keys(h).every(k => ['version', 'id', 'createdAt', 'cwd', 'parentSession', 'isSeeded', 'origin', 'delegationDepth', 'agentPreset'].includes(k)); }
10
- // Official rc.2 JSONL encodes an omitted delegationDepth as 0. Compare only
11
- // those two native representations as equivalent; retain every other field.
12
- // Stored headers and integrity hashes stay byte-for-byte in their original form.
13
- export function sameSessionHeader(a, b) { return validHeader(a) && validHeader(b) && canonical({ ...a, delegationDepth: a.delegationDepth ?? 0 }) === canonical({ ...b, delegationDepth: b.delegationDepth ?? 0 }); }
14
- function validAcceptance(a) { return exact(a, 'acceptanceId,bindingId,directory,epoch,instanceId,provider,sessionId,source,userTurn,version,workspaceId') && a.version === 1 && ['acceptanceId', 'bindingId', 'instanceId', 'sessionId', 'workspaceId'].every(k => text(a[k])) && int(a.epoch) && ['claude', 'codex'].includes(a.provider) && a.source === 'local' && exact(a.directory, 'device,inode,path') && isAbsolute(a.directory.path) && int(a.directory.device) && int(a.directory.inode) && exact(a.userTurn, 'startSequence,turn,userMessageId,userMessageSequence') && int(a.userTurn.turn) && int(a.userTurn.startSequence) && int(a.userTurn.userMessageSequence) && a.userTurn.userMessageSequence > a.userTurn.startSequence && text(a.userTurn.userMessageId); }
15
- export function acceptanceStore(profile, maxBytes) {
16
- const root = join(profile, 'ai-workbench-connect'), file = join(root, 'local-user-turn-acceptances.json');
17
- const directory = (path) => { const st = lstatSync(path); if (!st.isDirectory() || st.isSymbolicLink() || st.uid !== process.getuid() || (st.mode & 0o077) !== 0 || realpathSync(path) !== path)
18
- throw Error('ACCEPTANCE_DIRECTORY_INVALID'); };
19
- function read() {
20
- if (realpathSync(profile) !== profile)
21
- throw Error('ACCEPTANCE_PROFILE_INVALID');
22
- try {
23
- directory(root);
24
- }
25
- catch (e) {
26
- if (e.code === 'ENOENT')
27
- return [];
28
- throw e;
29
- }
30
- let fd;
31
- try {
32
- fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
33
- }
34
- catch (e) {
35
- if (e.code === 'ENOENT')
36
- return [];
37
- throw e;
38
- }
39
- try {
40
- const st = fstatSync(fd);
41
- if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || !Number.isSafeInteger(maxBytes) || maxBytes < 1 || st.size > maxBytes)
42
- throw Error('ACCEPTANCE_FILE_INVALID');
43
- const bytes = readFileSync(fd);
44
- if (bytes.length > maxBytes)
45
- throw Error('ACCEPTANCE_LIMIT');
46
- const data = JSON.parse(bytes.toString('utf8'));
47
- if (!data || Object.keys(data).sort().join(',') !== 'items,version' || data.version !== 1 || !Array.isArray(data.items))
48
- throw Error('ACCEPTANCE_FORMAT_INVALID');
49
- const ids = new Set();
50
- for (const r of data.items) {
51
- const a = r?.acceptance;
52
- 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 }))
53
- throw Error('ACCEPTANCE_RECORD_INVALID');
54
- ids.add(a.acceptanceId);
55
- }
56
- return data.items;
57
- }
58
- finally {
59
- closeSync(fd);
60
- }
61
- }
62
- function save(items, guard) {
63
- directory(root);
64
- for (const r of items)
65
- r.key = hash({ acceptance: r.acceptance, identity: r.identity, header: r.header, retired: r.retired, runtimeId: r.runtimeId });
66
- const bytes = JSON.stringify({ version: 1, items }) + '\n';
67
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || Buffer.byteLength(bytes) > maxBytes)
68
- throw Error('ACCEPTANCE_LIMIT');
69
- const temp = join(root, '.local-acceptance-' + randomUUID());
70
- let created = false;
71
- try {
72
- const fd = openSync(temp, 'wx', 0o600);
73
- created = true;
74
- try {
75
- writeFileSync(fd, bytes);
76
- fsyncSync(fd);
77
- }
78
- finally {
79
- closeSync(fd);
80
- }
81
- guard();
82
- renameSync(temp, file);
83
- created = false;
84
- for (const path of [root, profile]) {
85
- const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
86
- try {
87
- fsyncSync(d);
88
- }
89
- finally {
90
- closeSync(d);
91
- }
92
- }
93
- }
94
- finally {
95
- if (created)
96
- unlinkSync(temp);
97
- }
98
- }
99
- function verify(expected, guard) {
100
- directory(root);
101
- if (realpathSync(profile) !== profile)
102
- throw Error('ACCEPTANCE_PROFILE_INVALID');
103
- const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
104
- try {
105
- const st = fstatSync(fd);
106
- if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.nlink !== 1 || st.size > maxBytes)
107
- throw Error('ACCEPTANCE_FILE_INVALID');
108
- const bytes = readFileSync(fd);
109
- if (bytes.length > maxBytes)
110
- throw Error('ACCEPTANCE_LIMIT');
111
- const data = JSON.parse(bytes.toString('utf8'));
112
- if (!Array.isArray(data.items) || !data.items.some((r) => canonical(r) === canonical(expected)))
113
- throw Error('ACCEPTANCE_CHANGED');
114
- guard();
115
- fsyncSync(fd);
116
- }
117
- finally {
118
- closeSync(fd);
119
- }
120
- for (const path of [root, profile]) {
121
- const d = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
122
- try {
123
- guard();
124
- fsyncSync(d);
125
- }
126
- finally {
127
- closeSync(d);
128
- }
129
- }
130
- guard();
131
- }
132
- return { read, save, verify };
133
- }
@@ -1,76 +0,0 @@
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
- assertPriorBinding?: (sessionId: string, header: Record<string, any>, bindingId: string) => Promise<void>;
35
- assertSessionBinding?: (sessionId: string, header: Record<string, any>, source: 'local', bindingId: string) => void;
36
- profileDir: string;
37
- metadataMaxBytes: number;
38
- registry: NativeWorkspaceRegistry;
39
- getConnectionState: () => ConnectionState;
40
- services: () => Services;
41
- readHeader: (id: string) => Promise<Record<string, any> | undefined>;
42
- context: () => Promise<Result<{
43
- identity: string;
44
- guard?: () => void;
45
- }>>;
46
- withLocalBinding: <T>(c: {
47
- instanceId: string;
48
- epoch: number;
49
- workspaceId: string;
50
- expectedBindingId: string;
51
- }, run: (directory: {
52
- path: string;
53
- device: number;
54
- inode: number;
55
- }, guard: () => void) => Promise<Result<T>>, queue?: 'detail-write') => Promise<Result<T>>;
56
- }
57
- export declare function createLocalUserTurnAcceptance(o: Options): {
58
- active: () => boolean;
59
- observe: (session: Session, event: SessionEvent) => void;
60
- observeLocations: (state: WorkspaceLocationState) => void;
61
- observeSessionDisposed: (session: Session) => void;
62
- readScope: (sessionId: string, provider: Provider, acceptanceId?: string, detail?: Pick<RemoteConversationDetail, "sessionId" | "provider" | "instanceId" | "epoch">, expectedIdentity?: string) => Promise<Result<{
63
- identity: string;
64
- guard: () => void;
65
- cacheGuard: () => void;
66
- }>>;
67
- withWrite: <T>(acceptanceId: string, detail: RemoteConversationDetail, run: (proof: {
68
- identity: string;
69
- acceptanceId: string;
70
- guard: () => void;
71
- }) => Promise<Result<T>>) => Promise<Result<T>>;
72
- acceptLocalWorkspaceUserTurn(request: LocalUserTurnAcceptanceRequest): Promise<Result<LocalUserTurnAcceptance>>;
73
- dispose(): void;
74
- };
75
- export type LocalDetailsAdmission = ReturnType<typeof createLocalUserTurnAcceptance>;
76
- export {};
@@ -1,289 +0,0 @@
1
- import { randomUUID } from 'node:crypto';
2
- import { acceptanceStore, canonical, validHeader, sameSessionHeader } from "./local-acceptance-store.js";
3
- import { changedSessionBinding } from "./host-session-projects.js";
4
- import { fail, ok, need, NeedError } from "./needs.js";
5
- const text = (v) => typeof v === 'string' && v.length > 0 && !/[\x00-\x1f\x7f]/.test(v);
6
- const int = (v) => Number.isSafeInteger(v) && v >= 0;
7
- const keys = (v, k) => v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).sort().join(',') === k;
8
- function reject(code) { throw new NeedError(need(code)); }
9
- const resultError = (e) => e instanceof NeedError ? { ok: false, error: e.need } : fail('REMOTE_DETAIL_STORAGE_FAILED');
10
- export function createLocalUserTurnAcceptance(o) {
11
- const store = acceptanceStore(o.profileDir, o.metadataMaxBytes), observed = new WeakMap(), blocked = new Set(), sessionRevisions = new Map(), runtimeId = randomUUID(), persistenceIdentity = o.services().persistence.identity;
12
- let disposed = false, uncertain = false;
13
- function active() { if (o.services().persistence?.identity !== persistenceIdentity)
14
- disposed = true; return !disposed; }
15
- function life(c) { const now = o.getConnectionState(); if (!active() || now.phase === 'disposed')
16
- reject('DISPOSED'); if (now.phase !== 'connected' || now.instanceId !== c.instanceId || now.epoch !== c.epoch)
17
- reject('CONNECTION_LOST'); }
18
- 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)
19
- reject('REMOTE_DETAIL_SCOPE_INVALID'); }
20
- function retire(items, matching) { const changed = items.filter(r => !r.retired && matching(r)); for (const r of changed) {
21
- blocked.add(r.acceptance.acceptanceId);
22
- r.retired = true;
23
- } if (changed.length) {
24
- try {
25
- store.save(items, () => { });
26
- }
27
- catch (e) {
28
- uncertain = true;
29
- throw e;
30
- }
31
- } }
32
- function retireFailed(items, workspaceId, bindingId, result) { if (!result.ok && ['WORKSPACE_LOCATION_INVALID', 'WORKSPACE_LOCATION_CONFLICT'].includes(result.error.code))
33
- retire(items, r => r.acceptance.workspaceId === workspaceId && r.acceptance.bindingId === bindingId); }
34
- const sameProof = (a, b) => canonical({ ...a, acceptanceId: '' }) === canonical({ ...b, acceptanceId: '' });
35
- 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); }
36
- function observe(session, event) {
37
- if (disposed || o.services().sessions.get(session.header.id) !== session)
38
- return;
39
- // Keep only current turn's proof metadata, never prompt/headers/whole events.
40
- if (event.type === 'turn/start')
41
- observed.set(session, new Map([[event.seq, { seq: event.seq, type: event.type, data: { turn: event.data.turn } }]]));
42
- else if (event.type === 'turn/end')
43
- observed.delete(session);
44
- else if (event.type === 'user/message' && event.data?.source?.kind === 'user')
45
- observed.get(session)?.set(event.seq, { seq: event.seq, type: event.type, data: { id: event.data.id } });
46
- }
47
- function captured(r) {
48
- const services = o.services(), session = services.sessions.get(r.sessionId);
49
- if (!session || !int(session.seq) || session.header.id !== r.sessionId || !validHeader(session.header))
50
- reject('REMOTE_DETAIL_SCOPE_INVALID');
51
- const header = structuredClone(session.header), watermark = session.seq, proof = observed.get(session);
52
- 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))
53
- reject('REMOTE_DETAIL_SCOPE_INVALID');
54
- 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)
55
- reject('LOCAL_USER_TURN_CHANGED'); try {
56
- mapping(r.sessionId, r.workspaceId);
57
- }
58
- catch (e) {
59
- retire(store.read(), v => v.acceptance.sessionId === r.sessionId && v.acceptance.bindingId === r.expectedBindingId);
60
- throw e;
61
- } };
62
- guard();
63
- return { services, session, header, watermark, proof, guard };
64
- }
65
- async function accept(r, c) {
66
- let items = [];
67
- try {
68
- c.guard();
69
- await o.assertPriorBinding?.(r.sessionId, c.header, r.expectedBindingId);
70
- c.guard();
71
- o.assertSessionBinding?.(r.sessionId, c.header, 'local', r.expectedBindingId);
72
- if (uncertain)
73
- reject('REMOTE_DETAIL_STORAGE_FAILED');
74
- items = store.read();
75
- if (items.some(v => v.acceptance.sessionId === r.sessionId && sameSessionHeader(v.header, c.header) && v.acceptance.bindingId !== r.expectedBindingId))
76
- changedSessionBinding();
77
- const context = await o.context();
78
- c.guard();
79
- if (!context.ok)
80
- return context;
81
- const identity = context.value.identity;
82
- const result = await o.withLocalBinding(r, async (directory, bindingGuard) => {
83
- try {
84
- const guard = () => { c.guard(); o.assertSessionBinding?.(r.sessionId, c.header, 'local', r.expectedBindingId); context.value.guard?.(); bindingGuard(); if (canonical(directory) !== canonical({ ...r.expectedDirectory, path: directory.path }))
85
- reject('REMOTE_DETAIL_SCOPE_INVALID'); };
86
- guard();
87
- // Canonical session cwd must be the selected official directory; no basename/host mapping.
88
- const { realpath } = await import('node:fs/promises');
89
- if (typeof c.header.cwd !== 'string' || await realpath(c.header.cwd) !== directory.path)
90
- reject('REMOTE_DETAIL_SCOPE_INVALID');
91
- guard();
92
- const flushed = await c.services.sessions.flush(c.session);
93
- guard();
94
- if (!flushed)
95
- reject('REMOTE_DETAIL_SCOPE_INVALID');
96
- const handle = await c.services.persistence.open(r.sessionId, 'read');
97
- let events = [];
98
- let inherited = 0;
99
- try {
100
- guard();
101
- if (handle.id !== r.sessionId || handle.access !== 'read' || !sameSessionHeader(handle.header, c.header) || !int(handle.inheritedEventCount))
102
- reject('REMOTE_DETAIL_SCOPE_INVALID');
103
- inherited = handle.inheritedEventCount;
104
- events = (await handle.read()).events;
105
- guard();
106
- }
107
- finally {
108
- await handle.close();
109
- }
110
- guard();
111
- if (!Array.isArray(events) || events.length < c.watermark || events.some((e, n) => e.seq !== n))
112
- reject('REMOTE_DETAIL_SCOPE_INVALID');
113
- let start, step, input, route, routeContext;
114
- for (const e of events.slice(0, c.watermark)) {
115
- if (e.type === 'turn/start') {
116
- start = e;
117
- step = undefined;
118
- input = undefined;
119
- }
120
- else if (e.type === 'turn/end') {
121
- start = undefined;
122
- step = undefined;
123
- input = undefined;
124
- }
125
- else if (e.type === 'step/start')
126
- step = e;
127
- else if (e.type === 'step/end')
128
- step = undefined;
129
- else if (e.type === 'user/message' && start && e.data?.source?.kind === 'user' && e.data?.id === r.expectedUserTurn.userMessageId)
130
- input = e;
131
- else if (e.type === 'request/header')
132
- route = e.data?.header?.config?.provider;
133
- else if (e.type === 'request/context')
134
- routeContext = e.data?.provider;
135
- }
136
- const expectedRoute = r.provider === 'claude' ? 'claude-code-workbench' : 'codex-remote';
137
- 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))
138
- reject('REMOTE_DETAIL_SCOPE_INVALID');
139
- const a = { version: 1, acceptanceId: randomUUID(), instanceId: r.instanceId, epoch: r.epoch, sessionId: r.sessionId, provider: r.provider, workspaceId: r.workspaceId, bindingId: r.expectedBindingId, source: 'local', directory, userTurn: { turn: start.data.turn, startSequence: start.seq, userMessageId: input.data.id, userMessageSequence: input.seq } };
140
- // Re-read inside the location queue; another acceptance may have committed while awaiting it.
141
- items = store.read();
142
- const same = items.find(v => v.identity === identity && sameSessionHeader(v.header, c.header) && sameProof(v.acceptance, a));
143
- const oldInput = items.find(v => v.acceptance.sessionId === r.sessionId && sameSessionHeader(v.header, c.header) && v.acceptance.provider === r.provider && canonical(v.acceptance.userTurn) === canonical(a.userTurn) && !sameProof(v.acceptance, a));
144
- if (oldInput || same && (same.retired || same.runtimeId !== runtimeId || blocked.has(same.acceptance.acceptanceId)))
145
- reject('REMOTE_DETAIL_SCOPE_INVALID');
146
- guard();
147
- if (same) {
148
- if (canonical(same.header) !== canonical(c.header))
149
- reject('REMOTE_DETAIL_SCOPE_INVALID');
150
- store.verify(same, guard);
151
- return ok(structuredClone(same.acceptance));
152
- }
153
- items.push({ acceptance: a, header: c.header, identity, retired: false, runtimeId, key: '' });
154
- store.save(items, guard);
155
- guard();
156
- return ok(structuredClone(a));
157
- }
158
- catch (e) {
159
- return resultError(e);
160
- }
161
- });
162
- retireFailed(store.read(), r.workspaceId, r.expectedBindingId, result);
163
- return result;
164
- }
165
- catch (e) {
166
- return resultError(e);
167
- }
168
- }
169
- async function readScope(sessionId, provider, acceptanceId, detail, expectedIdentity) {
170
- try {
171
- const before = o.getConnectionState();
172
- life(before);
173
- const items = store.read(), context = await o.context();
174
- life(before);
175
- if (!context.ok)
176
- return context;
177
- const liveAtStart = o.services().sessions.get(sessionId), revision = sessionRevisions.get(sessionId) ?? 0;
178
- const header = await o.readHeader(sessionId);
179
- life(before);
180
- context.value.guard?.();
181
- const record = acceptanceId ? items.find(r => r.acceptance.acceptanceId === acceptanceId) : undefined;
182
- if (acceptanceId && !record)
183
- reject('REMOTE_DETAIL_STORAGE_FAILED');
184
- if (record && detail && (record.acceptance.sessionId !== detail.sessionId || record.acceptance.provider !== detail.provider || record.acceptance.instanceId !== detail.instanceId || record.acceptance.epoch !== detail.epoch || expectedIdentity !== undefined && record.identity !== expectedIdentity))
185
- reject('REMOTE_DETAIL_STORAGE_FAILED');
186
- const matches = acceptanceId ? [record] : items;
187
- if (!header || !matches.some(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider && sameSessionHeader(r.header, header) && (!detail || (r.acceptance.instanceId === detail.instanceId && r.acceptance.epoch === detail.epoch))))
188
- reject('REMOTE_DETAIL_SCOPE_INVALID');
189
- const admitted = matches.filter(r => r.identity === context.value.identity && r.acceptance.sessionId === sessionId && r.acceptance.provider === provider && sameSessionHeader(r.header, header));
190
- const guard = () => {
191
- life(before);
192
- context.value.guard?.();
193
- const current = o.services().sessions.get(sessionId);
194
- if ((sessionRevisions.get(sessionId) ?? 0) !== revision || liveAtStart && current !== liveAtStart || current && canonical(current.header) !== canonical(header))
195
- reject('REMOTE_DETAIL_SCOPE_INVALID');
196
- const now = store.read();
197
- for (const r of admitted) {
198
- const same = now.find(n => n.acceptance.acceptanceId === r.acceptance.acceptanceId);
199
- if (!same)
200
- reject('REMOTE_DETAIL_STORAGE_FAILED');
201
- if (canonical([same.acceptance, same.header, same.identity, same.runtimeId]) !== canonical([r.acceptance, r.header, r.identity, r.runtimeId]))
202
- reject('REMOTE_DETAIL_STORAGE_FAILED');
203
- }
204
- };
205
- guard();
206
- const cacheGuard = () => { guard(); if (!liveAtStart || o.services().sessions.get(sessionId) !== liveAtStart)
207
- reject('REMOTE_DETAIL_SCOPE_INVALID'); };
208
- return ok({ identity: context.value.identity, guard, cacheGuard });
209
- }
210
- catch (e) {
211
- return resultError(e);
212
- }
213
- }
214
- async function withWrite(acceptanceId, detail, run) {
215
- try {
216
- const before = o.getConnectionState();
217
- life(before);
218
- if (uncertain)
219
- reject('REMOTE_DETAIL_STORAGE_FAILED');
220
- let items = store.read();
221
- const r = items.find(r => r.acceptance.acceptanceId === acceptanceId);
222
- if (!r || r.retired || r.runtimeId !== runtimeId || blocked.has(acceptanceId))
223
- reject('REMOTE_DETAIL_SCOPE_INVALID');
224
- const a = r.acceptance;
225
- 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)
226
- reject('REMOTE_DETAIL_SCOPE_INVALID');
227
- const context = await o.context();
228
- life(before);
229
- if (!context.ok)
230
- return context;
231
- if (context.value.identity !== r.identity)
232
- reject('REMOTE_DETAIL_SCOPE_INVALID');
233
- const header = await o.readHeader(a.sessionId);
234
- life(before);
235
- if (!header || canonical(header) !== canonical(r.header))
236
- reject('REMOTE_DETAIL_SCOPE_INVALID');
237
- const result = await o.withLocalBinding({ instanceId: a.instanceId, epoch: a.epoch, workspaceId: a.workspaceId, expectedBindingId: a.bindingId }, async (directory, bindingGuard) => {
238
- const guard = () => { life(before); context.value.guard?.(); try {
239
- mapping(a.sessionId, a.workspaceId);
240
- }
241
- catch (e) {
242
- retire(store.read(), v => v.acceptance.sessionId === a.sessionId && v.acceptance.bindingId === a.bindingId);
243
- throw e;
244
- } bindingGuard(); if (blocked.has(acceptanceId) || canonical(directory) !== canonical(a.directory))
245
- reject('REMOTE_DETAIL_SCOPE_INVALID'); const live = o.services().sessions.get(a.sessionId); if (live && canonical(live.header) !== canonical(r.header))
246
- reject('REMOTE_DETAIL_SCOPE_INVALID'); };
247
- try {
248
- guard();
249
- return await run({ identity: r.identity, acceptanceId, guard });
250
- }
251
- catch (e) {
252
- return resultError(e);
253
- }
254
- }, 'detail-write');
255
- items = store.read();
256
- retireFailed(items, a.workspaceId, a.bindingId, result);
257
- return result;
258
- }
259
- catch (e) {
260
- return resultError(e);
261
- }
262
- }
263
- function observeLocations(state) {
264
- if (disposed || state.phase !== 'ready')
265
- return;
266
- 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'; });
267
- }
268
- function observeSessionDisposed(session) {
269
- if (disposed)
270
- return;
271
- observed.delete(session);
272
- sessionRevisions.set(session.header.id, (sessionRevisions.get(session.header.id) ?? 0) + 1);
273
- retire(store.read(), r => r.acceptance.sessionId === session.header.id && sameSessionHeader(r.header, session.header));
274
- }
275
- return { active, observe, observeLocations, observeSessionDisposed, readScope, withWrite, acceptLocalWorkspaceUserTurn(request) {
276
- try {
277
- if (disposed || o.getConnectionState().phase === 'disposed')
278
- reject('DISPOSED');
279
- if (!validRequest(request))
280
- return Promise.resolve(fail('REMOTE_DETAIL_SCOPE_INVALID'));
281
- life(request);
282
- const r = structuredClone(request), c = captured(r);
283
- return accept(r, c);
284
- }
285
- catch (e) {
286
- return Promise.resolve(resultError(e));
287
- }
288
- }, dispose() { disposed = true; }, };
289
- }