@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.
- package/README.md +34 -3
- package/client/index.cjs +29 -9
- package/helper/host-directories.cjs +72 -0
- package/lib/api.d.ts +31 -2
- package/lib/api.js +1 -1
- package/lib/cache.js +2 -2
- package/lib/component-download.d.ts +2 -0
- package/lib/component-download.js +13 -3
- package/lib/components.d.ts +1 -1
- package/lib/components.js +80 -5
- package/lib/connect.d.ts +3 -0
- package/lib/connect.js +53 -11
- package/lib/connection-messages.d.ts +7 -0
- package/lib/connection-messages.js +6 -0
- package/lib/conversation-details.d.ts +2 -0
- package/lib/conversation-details.js +158 -51
- package/lib/cordis.d.ts +2 -1
- package/lib/defaults.d.ts +6 -0
- package/lib/defaults.js +2 -0
- package/lib/host-directories.d.ts +53 -0
- package/lib/host-directories.js +76 -0
- package/lib/index.d.ts +8 -1
- package/lib/index.js +10 -5
- package/lib/integration.js +2 -0
- package/lib/local-acceptance-store.d.ts +17 -0
- package/lib/local-acceptance-store.js +129 -0
- package/lib/local-user-turn-acceptance.d.ts +74 -0
- package/lib/local-user-turn-acceptance.js +281 -0
- package/lib/local-user-turn-types.d.ts +40 -0
- package/lib/local-user-turn-types.js +1 -0
- package/lib/local-workspace-context.d.ts +46 -0
- package/lib/local-workspace-context.js +17 -0
- package/lib/login-diagnostics.d.ts +3 -1
- package/lib/needs.js +13 -0
- package/lib/ports.d.ts +2 -0
- package/lib/private-files.d.ts +2 -0
- package/lib/private-files.js +17 -1
- package/lib/profile-runtime.js +62 -12
- package/lib/startup.d.ts +1 -1
- package/lib/startup.js +33 -13
- package/lib/workspace-bindings.d.ts +30 -1
- package/lib/workspace-bindings.js +1 -0
- package/lib/workspace-location-types.d.ts +65 -0
- package/lib/workspace-location-types.js +1 -0
- package/lib/workspace-locations.d.ts +50 -0
- package/lib/workspace-locations.js +455 -0
- package/node_modules/argparse/CHANGELOG.md +216 -0
- package/package.json +4 -3
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { runRemote } from "./ssh.js";
|
|
3
|
+
import { fail, ok } from "./needs.js";
|
|
4
|
+
import { AuthDiagnosticError } from "./auth-diagnostics.js";
|
|
5
|
+
const codes = ['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE', 'HOST_DIRECTORY_CHANGED', 'HOST_DIRECTORY_PAGE_TOO_LARGE', 'PROJECT_PROTOCOL_INVALID'];
|
|
6
|
+
const object = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
7
|
+
const decimal = (value) => typeof value === 'string' && /^\d+$/.test(value);
|
|
8
|
+
function validEntryIdentity(value) { return object(value) && decimal(value.device) && decimal(value.inode); }
|
|
9
|
+
function validIdentity(value) { return object(value) && validEntryIdentity(value) && ['mtimeNs', 'ctimeNs'].every(key => typeof value[key] === 'string' && /^-?\d+$/.test(value[key])); }
|
|
10
|
+
function validPermissions(value) { return object(value) && ['read', 'write', 'execute'].every(key => typeof value[key] === 'boolean' || value[key] === null) && ([value.read, value.write, value.execute].includes(null) ? value.reason === 'HOST_PERMISSION_UNKNOWN' : value.reason === undefined); }
|
|
11
|
+
const validPath = (value) => typeof value === 'string' && value.startsWith('/') && !value.includes('\0');
|
|
12
|
+
const validName = (value) => typeof value === 'string' && value !== '' && value !== '.' && value !== '..' && !value.includes('/') && !value.includes('\0');
|
|
13
|
+
function validInfo(value) { return object(value) && validPath(value.requestedPath) && validPath(value.path) && (value.parentPath === null || validPath(value.parentPath)) && validIdentity(value.identity) && validEntryIdentity(value.entryIdentity) && typeof value.isSymlink === 'boolean' && validPermissions(value.permissions); }
|
|
14
|
+
function validEntry(value, parent) {
|
|
15
|
+
if (!object(value) || !validName(value.name) || value.requestedPath !== (parent.endsWith('/') ? parent : parent + '/') + value.name || !validEntryIdentity(value.entryIdentity) || typeof value.isSymlink !== 'boolean' || !validPermissions(value.permissions))
|
|
16
|
+
return false;
|
|
17
|
+
if (value.errorCode !== undefined && !['HOST_DIRECTORY_INVALID', 'HOST_DIRECTORY_UNREADABLE'].includes(value.errorCode))
|
|
18
|
+
return false;
|
|
19
|
+
if (value.path === undefined || value.identity === undefined)
|
|
20
|
+
return value.path === undefined && value.identity === undefined && value.errorCode !== undefined;
|
|
21
|
+
return validPath(value.path) && validIdentity(value.identity) && (value.errorCode !== undefined || value.permissions.read === true && value.permissions.execute === true);
|
|
22
|
+
}
|
|
23
|
+
const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
24
|
+
export function createHostDirectories(runner, maxOutputBytes) {
|
|
25
|
+
async function request(target, operation, data, signal) {
|
|
26
|
+
if (signal.aborted)
|
|
27
|
+
return fail('CONNECTION_LOST');
|
|
28
|
+
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.expected !== undefined && !validIdentity(data.expected) || data.after !== undefined && (!validName(data.after) || !validIdentity(data.expected))))
|
|
29
|
+
return fail('HOST_DIRECTORY_INVALID');
|
|
30
|
+
try {
|
|
31
|
+
const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
|
|
32
|
+
const command = 'node -e ' + "'" + (source + '\nmain();').replaceAll("'", "'\\''") + "'";
|
|
33
|
+
const raw = await runRemote(runner, target, command, signal, JSON.stringify({ protocolVersion: 1, operation, ...data, maxOutputBytes }));
|
|
34
|
+
if (signal.aborted)
|
|
35
|
+
return fail('CONNECTION_LOST');
|
|
36
|
+
if (raw.exitCode !== 0 || raw.stderr !== '')
|
|
37
|
+
return fail('HOST_DIRECTORY_UNREADABLE');
|
|
38
|
+
if (Buffer.byteLength(raw.stdout, 'utf8') > maxOutputBytes)
|
|
39
|
+
return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
40
|
+
let result;
|
|
41
|
+
try {
|
|
42
|
+
result = JSON.parse(raw.stdout);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
46
|
+
}
|
|
47
|
+
if (!object(result) || result.protocolVersion !== 1 || typeof result.ok !== 'boolean')
|
|
48
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
49
|
+
if (!result.ok) {
|
|
50
|
+
const error = result.error;
|
|
51
|
+
const code = object(error) ? codes.find(code => code === error.code) : undefined;
|
|
52
|
+
return fail(code ?? 'PROJECT_PROTOCOL_INVALID');
|
|
53
|
+
}
|
|
54
|
+
if (!validInfo(result.value) || data.path !== undefined && result.value.requestedPath !== data.path)
|
|
55
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
56
|
+
if (operation === 'browse') {
|
|
57
|
+
const value = result.value;
|
|
58
|
+
if (!Array.isArray(value.entries) || value.entries.length > data.pageSize || !value.entries.every(entry => validEntry(entry, value.requestedPath)) || value.entries.some((entry, index) => index > 0 && binaryCompare(value.entries[index - 1].name, entry.name) >= 0 || data.after !== undefined && binaryCompare(entry.name, data.after) <= 0) || value.nextAfter !== undefined && (value.entries.length !== data.pageSize || value.nextAfter !== value.entries[value.entries.length - 1]?.name) || data.expected !== undefined && ['device', 'inode', 'mtimeNs', 'ctimeNs'].some(key => value.identity[key] !== data.expected[key]))
|
|
59
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
60
|
+
}
|
|
61
|
+
return ok(result.value);
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (signal.aborted)
|
|
65
|
+
return fail('CONNECTION_LOST');
|
|
66
|
+
if (error instanceof AuthDiagnosticError) {
|
|
67
|
+
if (error.diagnostic.reason === 'OUTPUT_LIMIT_EXCEEDED')
|
|
68
|
+
return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
69
|
+
if (error.diagnostic.stage === 'remote-frame')
|
|
70
|
+
return fail('PROJECT_PROTOCOL_INVALID');
|
|
71
|
+
}
|
|
72
|
+
return fail('HOST_DIRECTORY_UNREADABLE');
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
|
|
76
|
+
}
|
package/lib/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from './connection-messages.ts';
|
|
1
2
|
import type { Context } from '@deepseek-ai/cordis';
|
|
2
3
|
import z from '@deepseek-ai/schemastery';
|
|
3
4
|
export type * from './cordis.ts';
|
|
@@ -12,6 +13,12 @@ export { sshArgs } from './ssh.ts';
|
|
|
12
13
|
export declare const name = "ai-workbench-connect";
|
|
13
14
|
export declare const inject: string[];
|
|
14
15
|
export interface Config {
|
|
16
|
+
connectionMessages?: {
|
|
17
|
+
administratorAfterMs?: number;
|
|
18
|
+
};
|
|
19
|
+
workspaceLocations?: {
|
|
20
|
+
pageSize?: number;
|
|
21
|
+
};
|
|
15
22
|
conversationDetails?: {
|
|
16
23
|
maxEventBytes?: number;
|
|
17
24
|
pageSize?: number;
|
|
@@ -39,7 +46,7 @@ export interface Config {
|
|
|
39
46
|
};
|
|
40
47
|
}
|
|
41
48
|
export declare const Config: z<Config>;
|
|
42
|
-
export declare function register(ctx: Context, ports: Ports, _inventory?: ComponentInventory, extend?: (api: import('./api.ts').ConnectApi) => void): void;
|
|
49
|
+
export declare function register(ctx: Context, ports: Ports, _inventory?: ComponentInventory, extend?: (api: import('./api.ts').ConnectApi) => void, connectionMessages?: Config['connectionMessages']): void;
|
|
43
50
|
export declare function apply(ctx: Context, config?: Config): void;
|
|
44
51
|
export { createProfileEnrollment } from './profile-enrollment.ts';
|
|
45
52
|
export { createWorkspaceBindings } from './workspace-bindings.ts';
|
package/lib/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
export { CONNECTION_MESSAGES, connectionEmployeeMessage } from "./connection-messages.js";
|
|
2
|
+
import { CONNECTION_MESSAGE_DEFAULTS } from "./defaults.js";
|
|
3
|
+
import { WORKSPACE_LOCATION_DEFAULTS } from "./defaults.js";
|
|
1
4
|
import z from '@deepseek-ai/schemastery';
|
|
2
5
|
import { createConversationDetailSettings } from "./conversation-detail-settings.js";
|
|
3
6
|
import { createConnect } from "./connect.js";
|
|
@@ -18,11 +21,13 @@ const positive = () => z.number().step(1).min(1);
|
|
|
18
21
|
// aiWorkbenchNetwork itself is a required Cordis injection; missing N holds this module from loading.
|
|
19
22
|
// Own technical defaults use the approved settings record; no global DSH policy is changed.
|
|
20
23
|
export const Config = z.object({
|
|
24
|
+
connectionMessages: z.object({ administratorAfterMs: positive().max(2147483647).default(CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs).description('connectionMessages.administratorAfterMs:持续断线多久改为“请联系管理员”;默认30000毫秒,范围1至2147483647整数,可修改。改大延后提示、改小提前;只改变提示,不改重连/SSH超时,不重放请求。') }),
|
|
25
|
+
workspaceLocations: z.object({ pageSize: positive().max(Number.MAX_SAFE_INTEGER).default(WORKSPACE_LOCATION_DEFAULTS.pageSize).description('workspaceLocations.pageSize:主机目录每页条数,默认100,可修改;改大增加元数据与内存,超过commandOutputMaxBytes会明确拒绝整页。') }),
|
|
21
26
|
conversationDetails: z.object({
|
|
22
27
|
maxEventBytes: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.maxEventBytes).description('conversationDetails.maxEventBytes:完整UTF-8 JSON事件的字节上限;默认1048576,范围1至9007199254740991整数。改大增加单事件存储与内存;改小会拒收超过新值的新事件,不裁剪或删除旧记录。'),
|
|
23
28
|
pageSize: positive().max(Number.MAX_SAFE_INTEGER).default(CONVERSATION_DETAIL_DEFAULTS.pageSize).description('conversationDetails.pageSize:每页条数;默认100,范围1至9007199254740991整数。改大增加一次读取与界面负担,改小增加继续加载次数,不减少完整快照总数。'),
|
|
24
29
|
}).description('管理员诊断记录设置:不自动过期、不按条数淘汰、没有隐藏总条数上限,本版没有清除入口。'),
|
|
25
|
-
enrollmentMetadataMaxBytes: positive().max(2147483647).default(L_DEFAULTS.enrollmentMetadataMaxBytes).description('
|
|
30
|
+
enrollmentMetadataMaxBytes: positive().max(2147483647).default(L_DEFAULTS.enrollmentMetadataMaxBytes).description('开通元数据、工作区关联文件、本地接纳关系文件、诊断设置文件及设置提交JSON各单份文件的字节上限;默认1048576,可由管理员修改;改小可能拒绝设置读取/提交,不读取key内容'),
|
|
26
31
|
inventory: z.object({ network: z.string(), connect: z.string(), claude: z.string(), codex: z.string() }).description('由已安装组件的实际版本自动生成,只读信息,不作为功能开关'),
|
|
27
32
|
enrollmentPackageDir: z.string().description('连接资料目录:由管理员安装时配置,员工无需手填'),
|
|
28
33
|
trustDir: z.string().description('主机信任缓存目录:由管理员安装时配置'),
|
|
@@ -39,9 +44,9 @@ export const Config = z.object({
|
|
|
39
44
|
executable: z.string().description('darwin-arm64默认Electron.app/Contents/MacOS/Electron;其他平台无默认,管理员可改'), loginOutputMaxBytes: positive().default(L_DEFAULTS.loginOutputMaxBytes).description('登录进程输出字节上限;默认1048576,管理员可改'), ipcMaxBytes: positive().default(L_DEFAULTS.ipcMaxBytes).description('私有IPC字节上限;默认1048576,管理员可改'),
|
|
40
45
|
}),
|
|
41
46
|
});
|
|
42
|
-
export function register(ctx, ports, _inventory, extend) {
|
|
47
|
+
export function register(ctx, ports, _inventory, extend, connectionMessages) {
|
|
43
48
|
// 当前独立插件始终检查两品牌;保留旧inventory参数兼容调用,但不以交付清单开关能力。
|
|
44
|
-
const api = createConnect(ports, state => ctx.emit('ai-workbench/connect-state', state), { onConnectionState: state => ctx.emit('ai-workbench/connection-state', state), onPromptState: state => ctx.emit('ai-workbench/login-prompt-state', state), onPromptResult: result => ctx.emit('ai-workbench/login-prompt-result', result) });
|
|
49
|
+
const api = createConnect(ports, state => ctx.emit('ai-workbench/connect-state', state), { connectionMessages, onConnectionState: state => ctx.emit('ai-workbench/connection-state', state), onPromptState: state => ctx.emit('ai-workbench/login-prompt-state', state), onPromptResult: result => ctx.emit('ai-workbench/login-prompt-result', result) });
|
|
45
50
|
extend?.(api);
|
|
46
51
|
ctx.provide('aiWorkbenchConnect', api);
|
|
47
52
|
ctx.effect(() => { void api.refreshLoginPrompts(); return () => api.dispose(); });
|
|
@@ -56,8 +61,8 @@ export function apply(ctx, config = {}) {
|
|
|
56
61
|
const sources = createComponentSources({ profileDir: ctx.get('profileContext')?.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, source: config.helper?.source, sha256: config.helper?.sha256, reason: sourceReason, busy: () => ['downloading', 'verifying', 'unpacking'].includes(component.getState().phase) || ctx.get('aiWorkbenchConnect')?.getLoginPromptState().phase === 'authorizing' });
|
|
57
62
|
ctx.effect(() => () => sources.dispose());
|
|
58
63
|
const ports = configuredPorts(config, network, component, sources);
|
|
59
|
-
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network));
|
|
60
|
-
registerComponents(ctx, config.inventory, config.helper?.cacheDir, component, sources, config.helper?.componentObservationIntervalMs, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
64
|
+
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network), config.connectionMessages);
|
|
65
|
+
registerComponents(ctx, config.inventory, config.helper?.cacheDir, component, sources, config.helper?.componentObservationIntervalMs, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, config.connectionMessages?.administratorAfterMs ?? CONNECTION_MESSAGE_DEFAULTS.administratorAfterMs);
|
|
61
66
|
}
|
|
62
67
|
export { createProfileEnrollment } from "./profile-enrollment.js";
|
|
63
68
|
export { createWorkspaceBindings } from "./workspace-bindings.js";
|
package/lib/integration.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHostDirectories } from "./host-directories.js";
|
|
1
2
|
import { ComponentDownloadError } from "./component-download.js";
|
|
2
3
|
import { fileURLToPath } from 'node:url';
|
|
3
4
|
import { readEnrollment } from "./enrollment.js";
|
|
@@ -24,6 +25,7 @@ export function configuredPorts(config, provider, component = createComponentPro
|
|
|
24
25
|
const runner = createRunner(config.commandOutputMaxBytes);
|
|
25
26
|
ports.ssh = createSsh(runner, config.commandOutputMaxBytes);
|
|
26
27
|
ports.projects = createProjects(runner);
|
|
28
|
+
ports.hostDirectories = createHostDirectories(runner, config.commandOutputMaxBytes);
|
|
27
29
|
}
|
|
28
30
|
else if (provider)
|
|
29
31
|
ports.ssh = { verify: async () => fail('SETTINGS_REQUIRED'), status: async () => fail('SETTINGS_REQUIRED') };
|
|
@@ -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 {};
|