export type HostKind = 'node' | 'deno' export type DistributionKind = 'developer' | 'system' export type HostErrorCode = | 'NotFound' | 'PermissionDenied' | 'AlreadyExists' | 'InvalidInput' | 'Unknown' export class HostError extends Error { readonly code: HostErrorCode readonly path?: string constructor(code: HostErrorCode, message: string, path?: string, cause?: unknown) { super(message, { cause }) this.name = 'HostError' this.code = code this.path = path } } export function isHostError(error: unknown, code: HostErrorCode): error is HostError { return error instanceof HostError && error.code === code } export interface HostFileInfo { isFile: boolean isDirectory: boolean isSymlink: boolean size: number mode: number | null mtime: Date | null dev: number | null ino: number | null } export interface HostDirEntry { name: string isFile: boolean isDirectory: boolean isSymlink: boolean } export interface HostFile { read(buffer: Uint8Array): Promise write(buffer: Uint8Array): Promise seek(offset: number): Promise stat(): Promise sync(): Promise close(): Promise } export interface HostHash { update(bytes: Uint8Array): void digestHex(): string } export interface HostCommandOutput { success: boolean code: number stdout: Uint8Array stderr: Uint8Array } /** A child process the tool talks to line by line (a wish macro's stdio bridge). */ export interface HostChild { /** Lines the child writes to stdout, without the newline. */ lines(): AsyncIterable writeLine(line: string): Promise closeInput(): Promise /** Everything the child wrote to stderr, once it exits. */ readonly stderr: Promise readonly status: Promise kill(): void } export interface HostPath { readonly sep: string basename(path: string): string dirname(path: string): string isAbsolute(path: string): boolean join(...parts: string[]): string relative(from: string, to: string): string resolve(...parts: string[]): string parse(path: string): { root: string; dir: string; base: string; ext: string; name: string } } export interface DistributionPolicy { readonly name: 'developer-default' | 'system-default' readonly distribution: DistributionKind readonly packageRoot: string readonly readPaths: readonly string[] readonly writePaths: readonly string[] readonly environment: readonly string[] readonly subprocesses: readonly string[] readonly network: boolean readonly buckyosRoot?: string } export interface ToolHost { readonly kind: HostKind readonly runtimeName: string readonly runtimeVersion: string readonly platform: string readonly arch: string readonly pid: number readonly executable: string readonly runtimeExecutable: string readonly policy: DistributionPolicy readonly path: HostPath cwd(): string homeDir(): string env(name: string): string | undefined exit(code: number): never setExitCode(code: number): void readTextFile(path: string): Promise readFile(path: string): Promise writeTextFile( path: string, value: string, options?: { createNew?: boolean; mode?: number }, ): Promise writeFile( path: string, value: Uint8Array, options?: { createNew?: boolean; mode?: number }, ): Promise readDir(path: string): Promise stat(path: string): Promise lstat(path: string): Promise realPath(path: string): Promise makeTempDir(options?: { dir?: string; prefix?: string }): Promise makeTempFile(options?: { dir?: string; prefix?: string }): Promise rename(from: string, to: string): Promise remove(path: string, options?: { recursive?: boolean }): Promise mkdir(path: string, options?: { recursive?: boolean; mode?: number }): Promise chmod(path: string, mode: number): Promise symlink(target: string, path: string): Promise copyFile(from: string, to: string): Promise open( path: string, options: { read?: boolean; write?: boolean; createNew?: boolean; mode?: number }, ): Promise // Policy check without a filesystem side effect: rejects paths outside the // distribution policy (or escaping it through symlinks) with PermissionDenied. assertAccess(path: string, operation: 'read' | 'write'): Promise createHash(algorithm: 'sha256'): HostHash gzipFile(source: string, destination: string): Promise run(command: string, args: string[]): Promise runGzip(command: string, args: string[], destination: string): Promise /** Start `command` in `cwd` with exactly `env` (nothing inherited), stdin and stdout piped line by line. */ spawn(command: string, args: string[], options: { cwd: string; env: Record }): HostChild stdout(value: string | Uint8Array): Promise stderr(value: string | Uint8Array): Promise readStdin(): Promise readLine(prompt: string): Promise readSecret(prompt: string): Promise inputIsTerminal(): boolean createLineReader(options: { history: string[] historySize: number completer(line: string): [string[], string] onSigint(): void }): HostLineReader } export interface HostLineReader extends AsyncIterable { write(value: string): void setPrompt(value: string): void prompt(): void close(): void } let activeHost: ToolHost | undefined export function installHost(host: ToolHost): void { if (activeHost && activeHost !== host) throw new Error('CLI host is already installed') activeHost = host } export function getHost(): ToolHost { if (!activeHost) throw new Error('CLI host was not injected by a launcher') return activeHost } export function resetHostForTest(): void { activeHost = undefined } export const TOOL_ENVIRONMENT_NAMES = [ 'HOME', 'USERPROFILE', 'APPDATA', 'BUCKYOS_TOOL_CONFIG_DIR', 'BUCKYOS_TOOL_PROFILE', 'BUCKYOS_TOOL_ZONE', 'BUCKYOS_TOOL_ENDPOINT', 'BUCKYOS_TOOL_IDENTITY', 'BUCKYOS_TOOL_OUTPUT', 'BUCKYOS_APPCLIENT_SESSION_TOKEN', 'BUCKYOS_ROOT', 'SOURCE_DATE_EPOCH', ] as const interface PolicyOptions { /** The runtime running the tool (Deno): `aiws run-exec` / `run-program` run a wish macro with it. */ runtimeExecutable?: string distribution: DistributionKind argv: string[] cwd: string packageRoot: string homeDir: string environment: Record path: HostPath buckyosRoot?: string } export function buildDistributionPolicy(options: PolicyOptions): DistributionPolicy { const { argv, cwd, packageRoot, homeDir, environment, path } = options const buckyosRoot = path.resolve( options.buckyosRoot ?? environment.BUCKYOS_ROOT ?? defaultBuckyosRoot(options), ) const configRoot = path.resolve( environment.BUCKYOS_TOOL_CONFIG_DIR ?? path.join(homeDir, '.buckyos_tool'), ) const readPaths = new Set([ path.resolve(packageRoot), path.resolve(cwd), configRoot, path.resolve(path.join(homeDir, '.buckyos')), path.resolve(path.join(homeDir, '.buckycli')), ]) const writePaths = new Set([path.resolve(cwd), configRoot]) if (options.distribution === 'system') readPaths.add(buckyosRoot) const parsed = collectArgumentPaths(argv) if ( options.distribution === 'system' && parsed.module === 'app' && ['fetch', 'install'].includes(parsed.verb ?? '') ) { writePaths.add(path.join(buckyosRoot, 'cache', 'control_panel', 'pikg_staging', 'incoming')) } for (const candidate of parsed.read) readPaths.add(resolveInputPath(candidate, cwd, path)) for (const candidate of parsed.readParents) { readPaths.add(path.dirname(resolveInputPath(candidate, cwd, path))) } for (const candidate of parsed.write) writePaths.add(resolveInputPath(candidate, cwd, path)) for (const candidate of parsed.writeParents) { writePaths.add(path.dirname(resolveInputPath(candidate, cwd, path))) } const subprocesses = parsed.module === 'pikg' && ['init', 'build'].includes(parsed.verb ?? '') ? ['docker'] : parsed.module === 'aiws' && ['run-exec', 'run-program'].includes(parsed.verb ?? '') && options.runtimeExecutable ? [options.runtimeExecutable] : options.distribution === 'system' && parsed.module === 'obj' && parsed.verb === 'call' ? [path.join(buckyosRoot, 'bin', 'opendan', path.sep === '\\' ? 'agent_tool.exe' : 'agent_tool')] : [] const network = parsed.module !== undefined && !['pikg', 'command', 'completion', 'config', 'provision'].includes(parsed.module) const allowedEnvironment = options.distribution === 'developer' ? TOOL_ENVIRONMENT_NAMES.filter((name) => name !== 'BUCKYOS_ROOT') : TOOL_ENVIRONMENT_NAMES return Object.freeze({ name: options.distribution === 'system' ? 'system-default' : 'developer-default', distribution: options.distribution, packageRoot: path.resolve(packageRoot), readPaths: Object.freeze([...readPaths]), writePaths: Object.freeze([...writePaths]), environment: Object.freeze(allowedEnvironment), subprocesses: Object.freeze(subprocesses), network, ...(options.distribution === 'system' ? { buckyosRoot } : {}), }) } function defaultBuckyosRoot(options: PolicyOptions): string { if (options.path.sep === '\\') { return options.environment.APPDATA ? options.path.join(options.environment.APPDATA, 'buckyos') : options.path.join(options.homeDir, 'AppData', 'Roaming', 'buckyos') } return '/opt/buckyos' } function resolveInputPath(value: string, cwd: string, path: HostPath): string { return path.isAbsolute(value) ? path.resolve(value) : path.resolve(cwd, value) } function collectArgumentPaths(argv: string[]): { read: string[] readParents: string[] write: string[] writeParents: string[] module?: string verb?: string } { const read: string[] = [] const readParents: string[] = [] const write: string[] = [] const writeParents: string[] = [] let module: string | undefined let verb: string | undefined let positional = 0 const valueOptions = new Set([ 'profile', 'zone', 'endpoint', 'identity', 'session-token', 'output', 'timeout', 'trace-id', 'idempotency-key', 'from', 'app-class', 'owner', 'policy', 'data', 'strategy', 'kind', 'source', 'version', 'name', ]) const booleanOptions = new Set([ 'replace', 'cli', 'wait', 'non-interactive', 'yes', 'no-color', 'verbose', 'help', 'version', ]) for (let index = 0; index < argv.length; index++) { const token = argv[index] if (!module && !token.startsWith('-')) { module = token continue } if (module && !verb && !token.startsWith('-')) { verb = token continue } if (token.startsWith('--')) { const equal = token.indexOf('=') const name = token.slice(2, equal < 0 ? undefined : equal) if (booleanOptions.has(name)) continue const inline = equal < 0 ? undefined : token.slice(equal + 1) const value = inline ?? argv[index + 1] if (inline === undefined && value !== undefined && !value.startsWith('--')) index++ if (value === undefined) continue if (name === 'config-dir') { read.push(value) write.push(value) } else if (name === 'allow-read') { read.push(value) } else if (['input', 'session-token-file', 'pikg'].includes(name)) { if (value !== '-') read.push(value) } else if (name === 'catalog' && module === 'pikg') { read.push(value) } else if (name === 'source' && module === 'pikg') { read.push(value) } else if (name === 'plan') { read.push(value) if (module === 'app' && verb === 'fetch') write.push(value) } else if (name === 'path') write.push(value) else if (name === 'app-doc' && module === 'app' && verb === 'publish') read.push(value) else if (name === 'file' && module === 'system-config' && verb === 'set-file') { read.push(value) } else if (name === 'root' && module === 'provision') { // status/check read the target root; activate also writes it. read.push(value) if (verb === 'activate') write.push(value) } else if (name === 'owner-key-backup' && module === 'provision') { // check inspects the backup location; activate creates the file there. readParents.push(value) if (verb === 'activate') writeParents.push(value) } else if (!valueOptions.has(name)) continue continue } if (module === 'app' && ['fetch', 'install'].includes(verb ?? '') && positional++ === 0) { if (!/^https?:\/\//i.test(token)) read.push(token) } else if (module === 'skill' && verb === 'install' && positional++ === 0) { read.push(token) } else if (module === 'pikg' && positional++ === 0) { read.push(token) if (verb === 'init' || verb === 'pack') write.push(token) else if (verb === 'build' || verb === 'clean') writeParents.push(token) } } return { read, readParents, write, writeParents, module, verb } } export function policyView(host: ToolHost): Record { return { executable: host.executable, runtime_executable: host.runtimeExecutable, distribution: host.policy.distribution, policy: host.policy.name, host: host.kind, runtime: host.runtimeName, runtime_version: host.runtimeVersion, platform: host.platform, arch: host.arch, package_root: host.policy.packageRoot, read_paths: [...host.policy.readPaths], write_paths: [...host.policy.writePaths], environment: [...host.policy.environment], subprocesses: [...host.policy.subprocesses], network: host.policy.network, } } export async function readDistributionManifest( host: ToolHost = getHost(), ): Promise | null> { const path = host.path.join(host.policy.packageRoot, 'distribution.json') try { const value = JSON.parse(await host.readTextFile(path)) as unknown return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : null } catch (error) { if (isHostError(error, 'NotFound')) return null throw error } } export function distributionManifestView( manifest: Record | null, ): Record | null { if (!manifest) return null const { npm_files: files, ...summary } = manifest return { ...summary, npm_file_count: Array.isArray(files) ? files.length : null, } }