@moxt-ai/cli 0.3.3-moxt-run.1 → 0.4.0-beta.0
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 +0 -38
- package/dist/index.js +1723 -1990
- package/dist/index.js.map +1 -1
- package/package.json +4 -6
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/program.ts","../src/commands/file.ts","../src/utils/file-selector.ts","../src/utils/http.ts","../src/utils/config.ts","../src/utils/output.ts","../src/utils/search-options.ts","../src/utils/run-or-exit.ts","../src/utils/spinner.ts","../src/commands/memory.ts","../src/utils/miniapp-db.ts","../src/commands/miniapp.ts","../src/run/run-agent.ts","../src/run/capture.ts","../src/run/redaction.ts","../src/run/sanitize.ts","../src/run/session.ts","../src/run/status.ts","../src/run/live-capture.ts","../src/run/moxt-uploader.ts","../src/utils/cf-access.ts","../src/run/process-session.ts","../src/run/repo.ts","../src/run/session-dir.ts","../src/commands/run.ts","../src/telemetry/config.ts","../src/telemetry/opt-out.ts","../src/commands/telemetry.ts","../src/commands/whoami.ts","../src/commands/workspace.ts","../src/telemetry/client.ts","../src/telemetry/notice.ts","../src/telemetry/instrument.ts"],"sourcesContent":["import updateNotifier from 'update-notifier'\nimport { createProgram } from './program.js'\nimport { flush } from './telemetry/client.js'\nimport { installExitHandler, instrumentProgram } from './telemetry/instrument.js'\n\ndeclare const __CLI_VERSION__: string\n\nupdateNotifier({\n pkg: { name: '@moxt-ai/cli', version: __CLI_VERSION__ },\n}).notify()\n\nconst program = createProgram(__CLI_VERSION__)\n\ninstrumentProgram(program)\ninstallExitHandler()\n\nprogram\n .parseAsync(process.argv)\n .then(async () => {\n await flush()\n })\n .catch(async (err: unknown) => {\n console.error('CLI Error:', err)\n await flush()\n process.exit(1)\n })\n","import { Command } from 'commander'\nimport { registerFileCommand } from './commands/file.js'\nimport { registerMemoryCommand } from './commands/memory.js'\nimport { registerMiniappCommand } from './commands/miniapp.js'\nimport { registerRunCommand } from './commands/run.js'\nimport { registerTelemetryCommand } from './commands/telemetry.js'\nimport { registerWhoamiCommand } from './commands/whoami.js'\nimport { registerWorkspaceCommand } from './commands/workspace.js'\n\nexport function createProgram(version: string): Command {\n const program = new Command()\n\n program\n .name('moxt')\n .description('Moxt CLI - AI Workspace')\n .version(version)\n .action(() => {\n program.help()\n })\n\n registerWhoamiCommand(program)\n registerWorkspaceCommand(program)\n registerFileCommand(program)\n registerMemoryCommand(program)\n registerRunCommand(program)\n registerMiniappCommand(program)\n registerTelemetryCommand(program)\n\n return program\n}\n","import * as fs from 'node:fs'\nimport { Command } from 'commander'\nimport {\n buildFileQueryString,\n isBinaryContent,\n resolveReadMode,\n resolveSpaceSelector,\n resolveWriteMode,\n SpaceOptions,\n SpaceOptionsError,\n} from '../utils/file-selector.js'\nimport { httpDelete, httpGet, httpPost, httpPut } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { runOrExit } from '../utils/run-or-exit.js'\nimport { parseSearchLimit, parseSearchMode } from '../utils/search-options.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface FileEntry {\n name: string\n type: 'file' | 'directory'\n size: number | null\n}\n\ninterface FileReadResponse {\n path: string\n type: 'file' | 'directory'\n entries: FileEntry[] | null\n content: string | null\n}\n\ninterface FileWriteResponse {\n path: string\n created: boolean\n}\n\ninterface MkdirResponse {\n path: string\n created: boolean\n}\n\ninterface DeleteResponse {\n path: string\n}\n\ninterface FileUrlResponse {\n path: string\n url: string\n}\n\ninterface FieldHighlight {\n text: string\n}\n\ninterface SemanticSnippet {\n content: string\n}\n\ninterface FileSearchItem {\n repoId: string\n fileId: string\n filePath: string\n rank: number\n contentHighlight?: FieldHighlight\n filePathHighlight?: FieldHighlight\n semanticSnippets: SemanticSnippet[]\n}\n\ninterface FileSearchResponse {\n items: FileSearchItem[]\n}\n\nfunction addSpaceOptions(cmd: Command): Command {\n return cmd\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n}\n\nexport function registerFileCommand(program: Command): void {\n const file = program.command('file').description('File operations')\n\n addSpaceOptions(\n file.command('search')\n .description('Search files in accessible spaces')\n .argument('<query>', 'Search query')\n .option('-l, --limit <limit>', 'Maximum number of files to return', '30')\n .option('--mode <mode>', 'Keyword matching mode: any or all', 'any'),\n ).action(async (query: string, options: SpaceOptions & { limit?: string; mode?: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const limit = runOrExit(() => parseSearchLimit(options.limit, 30, 80))\n const mode = runOrExit(() => parseSearchMode(options.mode))\n\n startSpinner('Searching files...')\n const response = await httpPost<FileSearchResponse>(\n `/workspaces/${options.workspace}/files/search`,\n {\n query,\n limit,\n mode,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { items } = response.data\n if (items.length === 0) {\n stopSpinner(true, 'No files found.')\n return\n }\n\n stopSpinner(true, `Found ${items.length} file(s)`)\n for (const item of items) {\n print(`${colors.bold}${item.rank}. ${item.filePath}${colors.reset}`)\n print(`${colors.dim}repo=${item.repoId} file=${item.fileId}${colors.reset}`)\n const snippet = item.contentHighlight?.text ?? item.semanticSnippets[0]?.content\n if (snippet) {\n print(snippet)\n }\n print('')\n }\n })\n\n addSpaceOptions(\n file.command('get-url')\n .description('Resolve the shareable browser URL for a file')\n .requiredOption('-p, --path <path>', 'File path'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Resolving URL...')\n const response = await httpGet<FileUrlResponse>(\n `/workspaces/${options.workspace}/files/url${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, response.data.path)\n print(`${colors.cyan}${response.data.url}${colors.reset}`)\n })\n\n addSpaceOptions(\n file.command('list')\n .description('List directory contents')\n .option('-p, --path <path>', 'Directory path', '/'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Listing files...')\n const response = await httpGet<FileReadResponse>(\n `/workspaces/${options.workspace}/files/list${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { path, entries } = response.data\n\n if (!entries || entries.length === 0) {\n stopSpinner(true, `${path}: empty directory`)\n return\n }\n\n stopSpinner(true, path)\n for (const entry of entries) {\n if (entry.type === 'directory') {\n print(`${colors.blue}${entry.name}/${colors.reset}`)\n } else {\n print(entry.name)\n }\n }\n })\n\n file.command('read')\n .description('Read file content')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'File path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .action(async (options: Partial<SpaceOptions> & { path?: string; url?: string }) => {\n const mode = runOrExit(() => resolveReadMode(options))\n\n startSpinner('Reading file...')\n\n let response: { ok: boolean; status: number; data: FileReadResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpGet<FileReadResponse>(\n `/files/read-by-url?url=${encodeURIComponent(mode.url)}`,\n )\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n const qs = buildFileQueryString(mode.path, spaceParams)\n response = await httpGet<FileReadResponse>(\n `/workspaces/${mode.workspace}/files/read${qs}`,\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { type, content } = response.data\n\n if (type === 'directory') {\n stopSpinner(false, 'Failed')\n print(`${colors.red}☠ ${displayPath} is a directory${colors.reset}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Done')\n print(content ?? '')\n })\n\n file.command('put')\n .description('Upload a file')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'Remote file path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .requiredOption('-l, --local-path <localPath>', 'Local file path')\n .option('-r, --recursive', 'Create parent directories if needed')\n .action(\n async (options: Partial<SpaceOptions> & {\n path?: string\n url?: string\n localPath: string\n recursive?: boolean\n }) => {\n const mode = runOrExit(() => resolveWriteMode(options))\n\n // check local file exists\n if (!fs.existsSync(options.localPath)) {\n print(`${colors.red}☠ Local file not found: ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // check it is a file, not a directory\n const stats = fs.statSync(options.localPath)\n if (!stats.isFile()) {\n print(`${colors.red}☠ Not a file: ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // check file size (10MB limit)\n const maxSize = 10 * 1024 * 1024\n if (stats.size > maxSize) {\n print(`${colors.red}☠ File too large (max 10MB): ${options.localPath}${colors.reset}`)\n process.exit(1)\n }\n\n // read file and check for binary content\n const buffer = fs.readFileSync(options.localPath)\n if (isBinaryContent(buffer)) {\n print(`${colors.red}☠ Binary files are not allowed. Only text files can be uploaded.${colors.reset}`)\n process.exit(1)\n }\n\n const content = buffer.toString('utf8')\n\n startSpinner('Uploading...')\n\n let response: { ok: boolean; status: number; data: FileWriteResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpPut<FileWriteResponse>('/files/write-by-url', {\n url: mode.url,\n content,\n })\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n response = await httpPut<FileWriteResponse>(\n `/workspaces/${mode.workspace}/files/write`,\n {\n path: mode.path,\n content,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n if (mode.kind === 'by-url') {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n }\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Updated'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n addSpaceOptions(\n file.command('mkdir')\n .description('Create a directory')\n .requiredOption('-p, --path <path>', 'Directory path')\n .option('-r, --recursive', 'Create parent directories if needed'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n recursive?: boolean\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Creating directory...')\n const response = await httpPost<MkdirResponse>(\n `/workspaces/${options.workspace}/files/mkdir`,\n {\n path: options.path,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Already exists'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n addSpaceOptions(\n file.command('del')\n .description('Delete a file or empty directory')\n .requiredOption('-p, --path <path>', 'File or directory path'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Deleting...')\n const response = await httpDelete<DeleteResponse>(\n `/workspaces/${options.workspace}/files/delete`,\n {\n path: options.path,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Path not found: ${options.path}${colors.reset}`)\n } else if (response.status === 400) {\n print(`${colors.red}☠ Cannot delete non-empty directory${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, `Deleted: ${response.data.path}`)\n },\n )\n}\n","/**\n * Pure logic for resolving file-command space selectors and building request URLs.\n *\n * These functions are extracted from commands/file.ts so they can be unit tested\n * without spawning the CLI or mocking process.exit. All error conditions are\n * surfaced as thrown Errors; action handlers are responsible for turning them\n * into user-facing output and exit codes.\n */\n\nexport interface SpaceOptions {\n workspace: string\n space?: string\n personal?: boolean\n teamSpaceId?: string\n teammateId?: string\n}\n\nexport interface SpaceParams {\n space?: string\n teamSpaceId?: string\n agentId?: number\n}\n\n/**\n * Error thrown when selector options violate a contract (mutually exclusive,\n * wrong format, etc). Action handlers catch this and print the message before\n * exiting with code 1.\n */\nexport class SpaceOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SpaceOptionsError'\n }\n}\n\n/**\n * Resolve mutually-exclusive space selector flags into normalized request params.\n *\n * Priority (only one must be set): --team-space-id > --teammate-id > --personal > -s <name>.\n * When none is set, returns empty params (server treats this as personal space).\n */\nexport function resolveSpaceSelector(options: SpaceOptions): SpaceParams {\n // Destructure first so TypeScript's control-flow analysis can narrow each\n // field through the subsequent non-null / non-empty checks without having\n // to re-read options.* at the point of use (which would lose narrowing).\n const { space, teamSpaceId, teammateId } = options\n const personalIsSet = options.personal === true\n\n // Count \"user-set\" selectors explicitly so the mutual-exclusion check\n // reflects intent (\"which flags did the user pass?\") rather than a\n // generic truthiness filter. This keeps the mutual-exclusion check\n // cleanly separated from the downstream format validation (e.g.\n // `parsed <= 0` for teammateId).\n const spaceIsSet = space != null && space !== ''\n const teamSpaceIdIsSet = teamSpaceId != null && teamSpaceId !== ''\n const teammateIdIsSet = teammateId != null && teammateId !== ''\n const selectorCount =\n (spaceIsSet ? 1 : 0) + (personalIsSet ? 1 : 0) + (teamSpaceIdIsSet ? 1 : 0) + (teammateIdIsSet ? 1 : 0)\n if (selectorCount > 1) {\n throw new SpaceOptionsError(\n 'Error: -s, --personal, --team-space-id, and --teammate-id are mutually exclusive.',\n )\n }\n\n // Dispatch via the underlying field checks (not `*IsSet`) so TypeScript\n // narrows each local to `string`, letting us return without `!`.\n if (teamSpaceId != null && teamSpaceId !== '') {\n return { teamSpaceId }\n }\n if (teammateId != null && teammateId !== '') {\n const parsed = Number.parseInt(teammateId, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== teammateId) {\n throw new SpaceOptionsError(\n `Error: --teammate-id must be a positive integer, got \"${teammateId}\".`,\n )\n }\n return { agentId: parsed }\n }\n if (personalIsSet) {\n return { space: 'personal' }\n }\n if (space != null && space !== '') {\n return { space }\n }\n return {}\n}\n\n/**\n * Build the `?path=...&space=...` query string for file endpoints.\n * Returns empty string when no params are set (caller should not append `?`).\n * Values are URL-encoded via URLSearchParams.\n *\n * An empty-string `path` is treated as \"not provided\" and omitted from the query;\n * callers should pass `undefined` rather than `\"\"` when no path is intended.\n */\nexport function buildFileQueryString(path: string | undefined, spaceParams: SpaceParams): string {\n const params = new URLSearchParams()\n if (path != null && path !== '') {\n params.set('path', path)\n }\n if (spaceParams.space) {\n params.set('space', spaceParams.space)\n }\n if (spaceParams.teamSpaceId) {\n params.set('teamSpaceId', spaceParams.teamSpaceId)\n }\n if (spaceParams.agentId != null) {\n params.set('agentId', String(spaceParams.agentId))\n }\n const qs = params.toString()\n return qs ? `?${qs}` : ''\n}\n\n/**\n * Detect if a Buffer contains binary content by sampling the first 8192 bytes.\n * Control characters other than tab (9), LF (10), and CR (13) are treated as binary.\n */\nexport function isBinaryContent(buffer: Buffer): boolean {\n const sampleSize = Math.min(buffer.length, 8192)\n\n for (let i = 0; i < sampleSize; i++) {\n const byte = buffer[i]\n if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Validate `file read` command's top-level mutually-exclusive options (-u vs -w/-p).\n * Returns the resolved mode ('by-url' or 'by-path'). Throws SpaceOptionsError on conflict.\n *\n * Empty strings are treated as \"not provided\" (commander never passes empty strings\n * for optional flags, but callers outside the CLI context should pass undefined instead\n * of \"\" to avoid unexpected branch behaviour).\n */\nexport type ReadMode = { kind: 'by-url'; url: string } | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveReadMode(options: {\n url?: string\n workspace?: string\n path?: string\n}): ReadMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n // At this point both workspace and path are guaranteed non-empty by the guards\n // above. Use explicit checks so TypeScript narrows the types without needing `!`.\n if (!options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n return { kind: 'by-path', workspace: options.workspace, path: options.path }\n}\n\n/**\n * Validate `file put` command's top-level mutually-exclusive options (-u vs -w/-p).\n *\n * By-URL puts overwrite an existing file (the URL already identifies it), so\n * `--recursive` is meaningless in that mode and is rejected outright to keep the\n * user's intent unambiguous.\n */\nexport type WriteMode =\n | { kind: 'by-url'; url: string }\n | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveWriteMode(options: {\n url?: string\n workspace?: string\n path?: string\n recursive?: boolean\n}): WriteMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (options.url && options.recursive) {\n throw new SpaceOptionsError('Error: --recursive cannot be used with --url (the file must already exist)')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n return { kind: 'by-path', workspace: options.workspace!, path: options.path! }\n}\n","import { arch, platform } from 'os'\nimport { getApiBaseUrl, getApiKey } from './config.js'\n\ndeclare const __CLI_VERSION__: string\n\nexport interface ApiResponse<T> {\n ok: boolean\n status: number\n data: T\n}\n\nexport interface RawApiResponse {\n ok: boolean\n status: number\n text: string\n contentType: string | null\n}\n\nfunction getUserAgent(): string {\n return `moxt-cli/${__CLI_VERSION__} (${platform()}/${arch()}) node/${process.versions.node}`\n}\n\nasync function fetchApi(method: string, path: string, body?: unknown): Promise<Response> {\n const apiKey = getApiKey()\n const url = `${getApiBaseUrl()}${path}`\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n 'User-Agent': getUserAgent(),\n },\n body: body ? JSON.stringify(body) : undefined,\n })\n\n if (response.status === 401) {\n console.error('Authentication failed. Check your MOXT_API_KEY.')\n console.error('Get a new key at: https://moxt.ai')\n process.exit(1)\n }\n\n return response\n}\n\nasync function request<T>(method: string, path: string, body?: unknown): Promise<ApiResponse<T>> {\n const response = await fetchApi(method, path, body)\n const contentType = response.headers.get('content-type')\n const data = contentType?.includes('application/json') ? ((await response.json()) as T) : ((await response.text()) as T)\n\n return {\n ok: response.ok,\n status: response.status,\n data,\n }\n}\n\nexport async function httpGet<T>(path: string): Promise<ApiResponse<T>> {\n return request<T>('GET', path)\n}\n\nexport async function httpPut<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('PUT', path, body)\n}\n\nexport async function httpPost<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('POST', path, body)\n}\n\nexport async function httpDelete<T>(path: string, body?: unknown): Promise<ApiResponse<T>> {\n return request<T>('DELETE', path, body)\n}\n\nexport async function httpRaw(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', path: string, body?: unknown): Promise<RawApiResponse> {\n const response = await fetchApi(method, path, body)\n return {\n ok: response.ok,\n status: response.status,\n text: await response.text(),\n contentType: response.headers.get('content-type'),\n }\n}\n","const DEFAULT_HOST = 'api.moxt.ai'\n\nexport function getApiBaseUrl(): string {\n const host = process.env.MOXT_HOST ?? DEFAULT_HOST\n return `https://${host}/openapi/v1`\n}\n\nexport function getApiKey(): string {\n const apiKey = process.env.MOXT_API_KEY\n\n if (!apiKey) {\n console.error('MOXT_API_KEY environment variable is not set.')\n console.error('')\n console.error('Get your API key at: https://moxt.ai')\n console.error('')\n console.error('Then set it:')\n console.error(' export MOXT_API_KEY=moxt_...')\n process.exit(1)\n }\n\n return apiKey\n}\n\nexport function getApiKeyOrUndefined(): string | undefined {\n return process.env.MOXT_API_KEY\n}\n","// ANSI colors\nexport const colors = {\n bold: '\\x1b[1m',\n blue: '\\x1b[1;34m',\n green: '\\x1b[32m',\n red: '\\x1b[31m',\n cyan: '\\x1b[36m',\n dim: '\\x1b[2m',\n reset: '\\x1b[0m',\n}\n\nexport function print(message: string): void {\n console.log(message)\n}\n\nexport function printError(message: string): void {\n console.error(`${colors.red}${message}${colors.reset}`)\n}\n","export class SearchOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SearchOptionsError'\n }\n}\n\nexport function parseSearchLimit(raw: string | undefined, defaultValue: number, max: number): number {\n if (raw == null || raw === '') {\n return defaultValue\n }\n const parsed = Number.parseInt(raw, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {\n throw new SearchOptionsError(`Error: --limit must be a positive integer, got \"${raw}\".`)\n }\n if (parsed > max) {\n throw new SearchOptionsError(`Error: --limit must be less than or equal to ${max}.`)\n }\n return parsed\n}\n\nexport function parseSearchMode(raw: string | undefined): 'all' | 'any' {\n if (raw == null || raw === '') {\n return 'any'\n }\n if (raw === 'all' || raw === 'any') {\n return raw\n }\n throw new SearchOptionsError(`Error: --mode must be \"any\" or \"all\", got \"${raw}\".`)\n}\n\nexport function parseTeammateId(raw: string | undefined): number | undefined {\n if (raw == null || raw === '') {\n return undefined\n }\n const parsed = Number.parseInt(raw, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {\n throw new SearchOptionsError(`Error: --teammate-id must be a positive integer, got \"${raw}\".`)\n }\n return parsed\n}\n","import { SpaceOptionsError } from './file-selector.js'\nimport { printError } from './output.js'\nimport { SearchOptionsError } from './search-options.js'\n\n/**\n * Call a pure resolver that may throw a known CLI option error; on error,\n * print the message and exit(1). This keeps the user-facing contract\n * (stderr + exit code 1) consistent across subcommands while letting the\n * resolvers stay pure and unit-testable.\n */\nexport function runOrExit<T>(fn: () => T): T {\n try {\n return fn()\n } catch (err) {\n if (err instanceof SpaceOptionsError || err instanceof SearchOptionsError) {\n printError(err.message)\n process.exit(1)\n }\n throw err\n }\n}\n","const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']\n\nlet intervalId: ReturnType<typeof setInterval> | null = null\nlet frameIndex = 0\n\nexport function startSpinner(message: string): void {\n frameIndex = 0\n process.stdout.write(`${frames[frameIndex]} ${message}`)\n\n intervalId = setInterval(() => {\n frameIndex = (frameIndex + 1) % frames.length\n process.stdout.write(`\\r${frames[frameIndex]} ${message}`)\n }, 80)\n}\n\nexport function stopSpinner(success: boolean, message?: string): void {\n if (intervalId) {\n clearInterval(intervalId)\n intervalId = null\n }\n\n const symbol = success ? '\\x1b[32m✓\\x1b[0m' : '\\x1b[31m✗\\x1b[0m'\n // \\x1b[2K 清除整行,\\r 回到行首\n process.stdout.write(`\\x1b[2K\\r${symbol} ${message ?? ''}\\n`)\n}\n","import { Command } from 'commander'\nimport { httpPost } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { runOrExit } from '../utils/run-or-exit.js'\nimport { parseSearchLimit, parseTeammateId } from '../utils/search-options.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface MemorySearchItem {\n rank: number\n pipelineId: string\n chunkId: string\n chunkIndex: number\n content: string\n contentTruncated: boolean\n}\n\ninterface MemorySearchResponse {\n items: MemorySearchItem[]\n}\n\nexport function registerMemoryCommand(program: Command): void {\n const memory = program.command('memory').description('Memory operations')\n\n memory.command('search')\n .description('Search archived agent memory')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('--teammate-id <teammateId>', 'Search a managed AI teammate memory')\n .option('-l, --limit <limit>', 'Maximum number of memory chunks to return', '5')\n .argument('<query>', 'Search query')\n .action(\n async (\n query: string,\n options: {\n workspace: string\n teammateId?: string\n limit?: string\n },\n ) => {\n const limit = runOrExit(() => parseSearchLimit(options.limit, 5, 10))\n const teammateId = runOrExit(() => parseTeammateId(options.teammateId))\n\n startSpinner('Searching memory...')\n const response = await httpPost<MemorySearchResponse>(\n `/workspaces/${options.workspace}/memory/search`,\n {\n query,\n limit,\n ...(teammateId !== undefined ? { agentId: teammateId } : {}),\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { items } = response.data\n if (items.length === 0) {\n stopSpinner(true, 'No memory found.')\n return\n }\n\n stopSpinner(true, `Found ${items.length} memory chunk(s)`)\n for (const item of items) {\n print(`${colors.bold}${item.rank}. pipeline=${item.pipelineId} chunk=${item.chunkIndex}${colors.reset}`)\n print(`${colors.dim}chunkId=${item.chunkId}${item.contentTruncated ? ' truncated=true' : ''}${colors.reset}`)\n print(item.content)\n print('')\n }\n },\n )\n}\n","export class MiniappDbOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'MiniappDbOptionsError'\n }\n}\n\nconst NON_FILTER_QUERY_PARAMS = new Set([\n 'select',\n 'order',\n 'limit',\n 'offset',\n 'range',\n 'range-unit',\n])\n\nconst ALLOWED_MINIAPP_DB_EMAIL_DOMAINS = ['@paraflow.com', '@moxt.ai', '@kanyun.com']\n\nexport function normalizePostgrestPath(path: string): string {\n const trimmed = path.trim()\n if (!trimmed) {\n throw new MiniappDbOptionsError('Error: PostgREST path is required.')\n }\n return trimmed.startsWith('/') ? trimmed : `/${trimmed}`\n}\n\nexport function buildMiniappDbDataPath(workspaceId: string, appId: string, postgrestPath: string): string {\n return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/data${normalizePostgrestPath(postgrestPath)}`\n}\n\nexport function buildMiniappDbSchemaPath(workspaceId: string, appId: string): string {\n return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/schema`\n}\n\nexport function parseJsonBody(raw: string): unknown {\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n throw new MiniappDbOptionsError(`Error: --body must be valid JSON. ${detail}`)\n }\n\n if (parsed === null || (typeof parsed !== 'object' && !Array.isArray(parsed))) {\n throw new MiniappDbOptionsError('Error: --body must be a JSON object or array.')\n }\n return parsed\n}\n\nexport function hasPostgrestFilter(postgrestPath: string): boolean {\n const normalizedPath = normalizePostgrestPath(postgrestPath)\n const parsed = new URL(normalizedPath, 'https://postgrest.local')\n for (const [name] of parsed.searchParams.entries()) {\n if (!NON_FILTER_QUERY_PARAMS.has(name.toLowerCase())) {\n return true\n }\n }\n return false\n}\n\nexport function assertPostgrestFilter(postgrestPath: string, method: 'PATCH' | 'DELETE'): void {\n if (!hasPostgrestFilter(postgrestPath)) {\n throw new MiniappDbOptionsError(\n `Error: ${method.toLowerCase()} requires at least one PostgREST filter query parameter.`,\n )\n }\n}\n\nexport function formatRawResponse(text: string, pretty?: boolean): string {\n if (!pretty || !text) {\n return text\n }\n try {\n return JSON.stringify(JSON.parse(text), null, 2)\n } catch {\n return text\n }\n}\n\nexport function isAllowedMiniappDbUserEmail(email: string): boolean {\n const normalized = email.trim().toLowerCase()\n return ALLOWED_MINIAPP_DB_EMAIL_DOMAINS.some((domain) => normalized.endsWith(domain))\n}\n","import { Command } from 'commander'\nimport {\n assertPostgrestFilter,\n buildMiniappDbDataPath,\n buildMiniappDbSchemaPath,\n formatRawResponse,\n isAllowedMiniappDbUserEmail,\n MiniappDbOptionsError,\n parseJsonBody,\n} from '../utils/miniapp-db.js'\nimport { httpGet, httpRaw } from '../utils/http.js'\nimport { print, printError } from '../utils/output.js'\n\ninterface MiniappDbOptions {\n workspace: string\n appId: string\n pretty?: boolean\n body?: string\n yes?: boolean\n}\n\ninterface MiniappDbSchemaResponse {\n sql: string\n}\n\ninterface WhoamiResponse {\n email: string\n}\n\nfunction runOrExit<T>(fn: () => T): T {\n try {\n return fn()\n } catch (err) {\n if (err instanceof MiniappDbOptionsError) {\n printError(err.message)\n process.exit(1)\n }\n throw err\n }\n}\n\nfunction addMiniappDbTargetOptions(command: Command): Command {\n return command\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .requiredOption('--app-id <appId>', 'Miniapp app ID')\n}\n\nfunction handleRawResponse(response: Awaited<ReturnType<typeof httpRaw>>, pretty?: boolean): void {\n if (!response.ok) {\n printError(`Error [${response.status}]: ${response.text}`)\n process.exit(1)\n }\n print(formatRawResponse(response.text, pretty))\n}\n\nasync function ensureAllowedMiniappDbUser(): Promise<void> {\n const response = await httpGet<WhoamiResponse>('/users/whoami')\n if (!response.ok) {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n if (!isAllowedMiniappDbUserEmail(response.data.email)) {\n printError('Error: miniapp db commands are only available to @paraflow.com, @moxt.ai, or @kanyun.com users.')\n process.exit(1)\n }\n}\n\nasync function requestDataApi(\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n postgrestPath: string,\n options: MiniappDbOptions,\n body?: unknown,\n): Promise<void> {\n await ensureAllowedMiniappDbUser()\n const path = buildMiniappDbDataPath(options.workspace, options.appId, postgrestPath)\n const response = await httpRaw(method, path, body)\n handleRawResponse(response, options.pretty)\n}\n\nexport function registerMiniappCommand(program: Command): void {\n const miniapp = program.command('miniapp', { hidden: true }).description('Miniapp operations')\n const db = miniapp.command('db').description('Miniapp database operations')\n\n addMiniappDbTargetOptions(\n db.command('schema').description('Print the miniapp database schema SQL'),\n ).action(async (options: MiniappDbOptions) => {\n await ensureAllowedMiniappDbUser()\n const response = await httpGet<MiniappDbSchemaResponse>(buildMiniappDbSchemaPath(options.workspace, options.appId))\n\n if (!response.ok) {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n print(response.data.sql)\n })\n\n addMiniappDbTargetOptions(\n db.command('get')\n .description('Read miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path, for example /todos?select=*')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n await requestDataApi('GET', postgrestPath, options)\n })\n\n addMiniappDbTargetOptions(\n db.command('post')\n .description('Create miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path, for example /todos')\n .requiredOption('--body <json>', 'JSON object or array request body')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n const body = runOrExit(() => parseJsonBody(options.body ?? ''))\n await requestDataApi('POST', postgrestPath, options, body)\n })\n\n addMiniappDbTargetOptions(\n db.command('patch')\n .description('Update miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path with a filter, for example /todos?id=eq.1')\n .requiredOption('--body <json>', 'JSON object or array request body')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n runOrExit(() => assertPostgrestFilter(postgrestPath, 'PATCH'))\n const body = runOrExit(() => parseJsonBody(options.body ?? ''))\n await requestDataApi('PATCH', postgrestPath, options, body)\n })\n\n addMiniappDbTargetOptions(\n db.command('delete')\n .description('Delete miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path with a filter, for example /todos?id=eq.1')\n .option('--yes', 'Confirm the delete operation')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n if (options.yes !== true) {\n printError('Error: delete requires --yes.')\n process.exit(1)\n }\n runOrExit(() => assertPostgrestFilter(postgrestPath, 'DELETE'))\n await requestDataApi('DELETE', postgrestPath, options)\n })\n}\n","import { type ChildProcess, spawn } from 'node:child_process'\nimport { closeSync, fstatSync, openSync, readSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport {\n CaptureOutputPrepareError,\n createCaptureRunId,\n prepareCaptureOutputs,\n withDefaultCaptureOutput,\n writeCaptureDirectoryPayload,\n} from './capture.js'\nimport { redactText } from './redaction.js'\nimport { sanitizeRepo } from './sanitize.js'\nimport {\n type MatchOptions,\n matchKnownSessionFile,\n matchSession,\n recordingFromSessionMatch,\n type SnapshotMap,\n snapshotJsonl,\n} from './session.js'\nimport { classifyExit, signalNumber } from './status.js'\nimport type { CapturePayload, RunAgent, SessionMatch } from './types.js'\nimport { createLiveCapture } from './live-capture.js'\nimport { type RunUploadOptions, uploadRunArtifacts } from './moxt-uploader.js'\nimport { findOpenSessionFile, type OpenSessionFileMatch } from './process-session.js'\nimport { collectRepoFingerprint } from './repo.js'\nimport { agentKnownSessionFile, agentSessionCandidateFilter, agentSessionDir } from './session-dir.js'\nimport { printError } from '../utils/output.js'\n\nconst MAX_TRANSCRIPT_CAPTURE_BYTES = 1024 * 1024\nconst SESSION_SETTLE_TIMEOUT_MS = 1500\nconst SESSION_SETTLE_INTERVAL_MS = 100\nconst PROCESS_SESSION_POLL_INTERVAL_MS = 100\nconst CODEX_OPTIONS_WITH_VALUE = new Set([\n '-a',\n '--add-dir',\n '--ask-for-approval',\n '-c',\n '-C',\n '--cd',\n '--color',\n '--config',\n '-i',\n '--image',\n '--local-provider',\n '-m',\n '--model',\n '-o',\n '--output-last-message',\n '--output-schema',\n '-p',\n '--profile',\n '--remote',\n '--remote-auth-token-env',\n '-s',\n '--sandbox',\n])\n\nexport interface RunLocalAgentOptions {\n readonly agent: RunAgent\n readonly agentArgs: readonly string[]\n readonly upload?: RunUploadOptions\n readonly cwd?: string\n readonly env?: NodeJS.ProcessEnv\n readonly home?: string\n}\n\ninterface WaitResult {\n readonly code: number | null\n readonly signal: NodeJS.Signals | null\n readonly waitAt: number\n readonly errorCode?: string\n}\n\nexport async function runLocalAgent(options: RunLocalAgentOptions): Promise<number> {\n const cwd = options.cwd ?? process.cwd()\n const env = options.env ?? process.env\n const home = options.home ?? env.HOME ?? homedir()\n const startedAtMs = Date.now()\n const startedAt = new Date(startedAtMs).toISOString()\n const runId = createCaptureRunId(startedAt, options.agent)\n const captureEnv = withDefaultCaptureOutput(env, home)\n\n try {\n await prepareCaptureOutputs(captureEnv, runId)\n } catch (error) {\n printPrepareError(options.agent, error)\n return 1\n }\n\n const repo = collectRepoFingerprint(cwd)\n let baselineOk = false\n let before = new Map<string, { mtimeMs: number; size: number }>()\n let sessions = ''\n let isSessionCandidate: ((path: string) => boolean) | undefined\n let knownSessionFile: string | undefined\n let childRootPid: number | undefined\n let openSessionFileMatch: OpenSessionFileMatch = { match: 'none' }\n let processSessionTimer: NodeJS.Timeout | undefined\n const newSessionFilesOnly = shouldUseNewSessionFilesOnly(options.agent, options.agentArgs)\n\n try {\n const sessionOptions = {\n agent: options.agent,\n cwd,\n home,\n env: captureEnv,\n agentArgs: options.agentArgs,\n }\n sessions = agentSessionDir(sessionOptions)\n isSessionCandidate = agentSessionCandidateFilter(sessionOptions)\n knownSessionFile = agentKnownSessionFile(sessionOptions)\n before = snapshotJsonl(sessions)\n baselineOk = true\n } catch {\n baselineOk = false\n }\n\n const rememberOpenSessionFile = (): OpenSessionFileMatch => {\n if (\n !baselineOk ||\n sessions === '' ||\n childRootPid === undefined ||\n openSessionFileMatch.match !== 'none'\n ) {\n return openSessionFileMatch\n }\n\n const matched = findOpenSessionFile({\n rootPid: childRootPid,\n sessionRoot: sessions,\n ...(isSessionCandidate === undefined ? {} : { isCandidate: isSessionCandidate }),\n })\n if (matched.match !== 'none') {\n openSessionFileMatch = matched\n }\n\n return openSessionFileMatch\n }\n\n const stopProcessSessionWatcher = (): void => {\n if (processSessionTimer !== undefined) {\n clearInterval(processSessionTimer)\n processSessionTimer = undefined\n }\n }\n\n const liveCapture = createLiveCapture({\n env: captureEnv,\n runId,\n agent: options.agent,\n startedAt,\n sessions,\n before,\n baselineOk,\n startedAtMs,\n ...(knownSessionFile === undefined ? {} : { knownSessionFile }),\n ...(isSessionCandidate === undefined ? {} : { isSessionCandidate }),\n ...(newSessionFilesOnly ? { newSessionFilesOnly: true as const } : {}),\n openSessionFile: rememberOpenSessionFile,\n })\n\n try {\n await liveCapture.start()\n } catch (error) {\n printError(\n [\n 'moxt: cannot prepare run output',\n `reason: ${errorMessage(error)}`,\n '',\n `${options.agent} was not started because this run cannot be recorded.`,\n ].join('\\n'),\n )\n return 1\n }\n\n const observedSignals = new Set<number>()\n let child: ChildProcess | null = null\n let pendingForward: NodeJS.Signals | null = null\n\n const observe = (signal: NodeJS.Signals): void => {\n const number = signalNumber(signal)\n if (number !== 0) observedSignals.add(number)\n }\n const terminalSignalsReachChild =\n process.stdin.isTTY === true || process.stdout.isTTY === true || process.stderr.isTTY === true\n const forwardInteractiveSignal = (signal: NodeJS.Signals): void => {\n observe(signal)\n if (terminalSignalsReachChild) {\n return\n }\n if (child === null) {\n pendingForward = signal\n return\n }\n\n safeKill(child, signal)\n }\n const onInt = (): void => forwardInteractiveSignal('SIGINT')\n const onQuit = (): void => forwardInteractiveSignal('SIGQUIT')\n const onTerm = (): void => {\n observe('SIGTERM')\n if (child === null) pendingForward = 'SIGTERM'\n else safeKill(child, 'SIGTERM')\n }\n const onHup = (): void => {\n observe('SIGHUP')\n if (child === null) pendingForward = 'SIGHUP'\n else safeKill(child, 'SIGHUP')\n }\n\n process.on('SIGINT', onInt)\n process.on('SIGQUIT', onQuit)\n process.on('SIGTERM', onTerm)\n process.on('SIGHUP', onHup)\n\n const spawned = spawn(options.agent, [...options.agentArgs], {\n cwd,\n env: captureEnv,\n stdio: 'inherit',\n })\n child = spawned\n childRootPid = spawned.pid\n if (childRootPid !== undefined && baselineOk) {\n rememberOpenSessionFile()\n processSessionTimer = setInterval(() => {\n rememberOpenSessionFile()\n }, PROCESS_SESSION_POLL_INTERVAL_MS)\n }\n if (pendingForward !== null) {\n safeKill(spawned, pendingForward)\n }\n\n const exit = await waitForExit(spawned, options.agent)\n stopProcessSessionWatcher()\n\n const onCaptureSignal = (): void => {}\n process.on('SIGINT', onCaptureSignal)\n process.on('SIGQUIT', onCaptureSignal)\n process.on('SIGTERM', onCaptureSignal)\n process.on('SIGHUP', onCaptureSignal)\n process.off('SIGINT', onInt)\n process.off('SIGQUIT', onQuit)\n process.off('SIGTERM', onTerm)\n process.off('SIGHUP', onHup)\n\n const classified = classifyExit(exit, observedSignals)\n const endedAtMs = exit.waitAt\n const endedAt = new Date(endedAtMs).toISOString()\n const durationMs = endedAtMs - startedAtMs\n let after: SnapshotMap | undefined\n if (baselineOk) {\n try {\n after = await waitForSessionSettle(\n sessions,\n before,\n startedAtMs,\n isSessionCandidate,\n newSessionFilesOnly,\n )\n } catch {}\n }\n try {\n await liveCapture.stop()\n } catch {}\n\n const payload = buildPayload({\n agent: options.agent,\n cwd,\n startedAt,\n endedAt,\n durationMs,\n exitCode: classified.code,\n status: classified.status,\n repo: sanitizeRepo(repo),\n baselineOk,\n sessions,\n before,\n after,\n startedAtMs,\n knownSessionFile,\n isSessionCandidate,\n newSessionFilesOnly,\n openSessionFileMatch,\n })\n\n let finalized = false\n try {\n if (liveCapture.enabled) {\n await liveCapture.finalize(payload, new Date().toISOString())\n } else {\n await writeCaptureDirectoryPayload(payload, captureEnv, runId, new Date().toISOString())\n }\n finalized = true\n } catch (error) {\n printError(`moxt: cannot finalize run artifact: ${errorMessage(error)}`)\n } finally {\n process.off('SIGINT', onCaptureSignal)\n process.off('SIGQUIT', onCaptureSignal)\n process.off('SIGTERM', onCaptureSignal)\n process.off('SIGHUP', onCaptureSignal)\n }\n\n if (finalized && options.upload !== undefined) {\n try {\n await uploadRunArtifacts({\n env: captureEnv,\n runId,\n upload: options.upload,\n })\n } catch (error) {\n printError(`moxt: cannot upload run artifact: ${errorMessage(error)}`)\n }\n }\n\n return classified.code\n}\n\nasync function waitForSessionSettle(\n sessions: string,\n before: SnapshotMap,\n startedAtMs: number,\n isSessionCandidate: ((path: string) => boolean) | undefined,\n newSessionFilesOnly: boolean,\n): Promise<SnapshotMap> {\n const deadline = Date.now() + SESSION_SETTLE_TIMEOUT_MS\n let after = snapshotJsonl(sessions)\n\n while (!hasSessionChange(before, after, startedAtMs, isSessionCandidate, newSessionFilesOnly) && Date.now() < deadline) {\n await sleep(SESSION_SETTLE_INTERVAL_MS)\n after = snapshotJsonl(sessions)\n }\n\n return after\n}\n\nfunction hasSessionChange(\n before: SnapshotMap,\n after: SnapshotMap,\n startedAtMs: number,\n isSessionCandidate: ((path: string) => boolean) | undefined,\n newSessionFilesOnly: boolean,\n): boolean {\n const matched = matchSession(before, after, startedAtMs, matchOptions(isSessionCandidate, newSessionFilesOnly))\n if (matched.match !== 'unique') {\n return matched.match !== 'none'\n }\n\n if (matched.sessionFile === null) {\n return false\n }\n\n const snapshot = after.get(matched.sessionFile)\n return snapshot !== undefined && snapshot.size > matched.startOffset\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction safeKill(child: ChildProcess, signal: NodeJS.Signals): void {\n try {\n child.kill(signal)\n } catch {}\n}\n\nfunction waitForExit(child: ChildProcess, agent: RunAgent): Promise<WaitResult> {\n return new Promise<WaitResult>((resolve) => {\n child.once('error', (error: NodeJS.ErrnoException) => {\n const errorCode = error.code ?? 'UNKNOWN'\n const reason = errorCode === 'ENOENT' ? 'command not found' : error.message\n printError(`moxt: cannot start ${agent}: ${reason}`)\n resolve({\n code: null,\n signal: null,\n waitAt: Date.now(),\n errorCode,\n })\n })\n child.once('exit', (code, signal) => {\n resolve({ code, signal, waitAt: Date.now() })\n })\n })\n}\n\ninterface PayloadInput {\n readonly agent: RunAgent\n readonly cwd: string\n readonly startedAt: string\n readonly endedAt: string\n readonly durationMs: number\n readonly exitCode: number\n readonly status: CapturePayload['run']['status']\n readonly repo: CapturePayload['repo']\n readonly baselineOk: boolean\n readonly sessions: string\n readonly before: Map<string, { mtimeMs: number; size: number }>\n readonly after: SnapshotMap | undefined\n readonly startedAtMs: number\n readonly knownSessionFile: string | undefined\n readonly isSessionCandidate: ((path: string) => boolean) | undefined\n readonly newSessionFilesOnly: boolean\n readonly openSessionFileMatch: OpenSessionFileMatch\n}\n\nfunction buildPayload(input: PayloadInput): CapturePayload {\n let sessionMatch: SessionMatch = input.baselineOk ? 'none' : 'prep_failed'\n let transcript: string | undefined\n let redactionFailed = false\n\n if (input.baselineOk) {\n try {\n const after = input.after ?? snapshotJsonl(input.sessions)\n const knownMatched =\n input.knownSessionFile === undefined\n ? null\n : matchKnownSessionFile(input.before, after, input.knownSessionFile)\n const matched =\n knownMatched?.match === 'unique'\n ? knownMatched\n : input.openSessionFileMatch.match === 'unique'\n ? matchKnownSessionFile(input.before, after, input.openSessionFileMatch.sessionFile)\n : input.openSessionFileMatch.match === 'ambiguous'\n ? {\n match: 'ambiguous' as const,\n sessionFile: null,\n startOffset: 0,\n }\n : matchSession(\n input.before,\n after,\n input.startedAtMs,\n matchOptions(input.isSessionCandidate, input.newSessionFilesOnly),\n )\n sessionMatch = matched.match\n if (matched.match === 'unique' && matched.sessionFile !== null) {\n try {\n transcript = redactText(readFileFromOffset(matched.sessionFile, matched.startOffset)).text\n } catch {\n redactionFailed = true\n }\n }\n } catch {\n sessionMatch = 'prep_failed'\n }\n }\n\n return {\n ...(transcript === undefined ? {} : { transcript_redacted: transcript }),\n ...(redactionFailed ? { redaction_failed: true as const } : {}),\n run: {\n agent: input.agent,\n cwd: input.cwd,\n git_root: input.repo?.root ?? null,\n started_at: input.startedAt,\n ended_at: input.endedAt,\n duration_ms: input.durationMs,\n status: input.status,\n exit_code: input.exitCode,\n },\n recording: recordingFromSessionMatch(sessionMatch),\n repo: input.repo,\n }\n}\n\nfunction matchOptions(\n isSessionCandidate: ((path: string) => boolean) | undefined,\n newSessionFilesOnly: boolean,\n): MatchOptions {\n return {\n ...(isSessionCandidate === undefined ? {} : { isCandidate: isSessionCandidate }),\n ...(newSessionFilesOnly ? { newFilesOnly: true as const } : {}),\n }\n}\n\nfunction shouldUseNewSessionFilesOnly(agent: RunAgent, agentArgs: readonly string[]): boolean {\n return agent === 'codex' && !isCodexResumeInvocation(agentArgs)\n}\n\nfunction isCodexResumeInvocation(agentArgs: readonly string[]): boolean {\n const command = nextCodexCommandArg(agentArgs, 0)\n if (command === null) {\n return false\n }\n\n if (command.value === 'resume') {\n return true\n }\n\n if (command.value !== 'exec' && command.value !== 'e') {\n return false\n }\n\n return nextCodexCommandArg(agentArgs, command.index + 1)?.value === 'resume'\n}\n\nfunction nextCodexCommandArg(\n agentArgs: readonly string[],\n startIndex: number,\n): { readonly value: string; readonly index: number } | null {\n for (let index = startIndex; index < agentArgs.length; index += 1) {\n const arg = agentArgs[index]\n if (arg === undefined) {\n continue\n }\n\n if (arg === '--') {\n return null\n }\n\n if (arg.startsWith('-')) {\n if (!arg.includes('=') && CODEX_OPTIONS_WITH_VALUE.has(arg)) {\n index += 1\n }\n continue\n }\n\n return { value: arg, index }\n }\n\n return null\n}\n\nfunction readFileFromOffset(path: string, offset: number): string {\n const fd = openSync(path, 'r')\n try {\n const stat = fstatSync(fd)\n const length = Math.max(0, stat.size - offset)\n if (length > MAX_TRANSCRIPT_CAPTURE_BYTES) {\n throw new Error('transcript capture exceeds maximum size')\n }\n const buffer = Buffer.alloc(length)\n if (length === 0) {\n return ''\n }\n readSync(fd, buffer, 0, length, offset)\n return buffer.toString('utf8')\n } finally {\n closeSync(fd)\n }\n}\n\nfunction printPrepareError(agent: RunAgent, error: unknown): void {\n if (error instanceof CaptureOutputPrepareError) {\n printError(\n [\n 'moxt: cannot create run output directory',\n `path: ${error.path}`,\n `reason: ${error.message}`,\n '',\n `${agent} was not started because this run cannot be recorded.`,\n ].join('\\n'),\n )\n return\n }\n\n printError(\n [\n 'moxt: cannot prepare run output',\n `reason: ${errorMessage(error)}`,\n '',\n `${agent} was not started because this run cannot be recorded.`,\n ].join('\\n'),\n )\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error && error.message !== '') {\n return error.message\n }\n return String(error)\n}\n","import { randomUUID } from 'node:crypto'\nimport { access, mkdir, readdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, posix, win32 } from 'node:path'\nimport type { CapturePayload, RunAgent } from './types.js'\n\nconst DATA_FILE_TARGET_BYTES = 1024 * 1024\nconst RUNLOG_DIRECTORY_MARKER = '.runlog'\nconst RUNLOG_DIRECTORY_MARKER_SCHEMA = 'runlog.directory.v1'\nconst RUNLOG_MANAGED_OUTPUT_NAMES = new Set([\n '.DS_Store',\n RUNLOG_DIRECTORY_MARKER,\n 'events',\n 'events.jsonl',\n 'run.json',\n 'state.json',\n 'transcript',\n 'transcript.jsonl',\n 'upload.json',\n])\nconst RUNLOG_METADATA_SCHEMAS = {\n 'run.json': 'runlog.capture.v1',\n 'state.json': 'runlog.state.v1',\n 'upload.json': 'runlog.upload.v1',\n} as const\nconst RUNLOG_METADATA_FILE_NAMES = Object.keys(RUNLOG_METADATA_SCHEMAS) as RunlogMetadataFileName[]\n\ntype RunlogMetadataFileName = keyof typeof RUNLOG_METADATA_SCHEMAS\n\ninterface CaptureRunFile {\n readonly schema_version: 'runlog.capture.v1'\n readonly run_id: string\n readonly run: CapturePayload['run']\n readonly recording: CapturePayload['recording']\n readonly repo: CapturePayload['repo']\n readonly redaction_failed?: true\n readonly files: {\n readonly state: 'state.json'\n readonly upload: 'upload.json'\n readonly events: readonly DataFileInfo[]\n readonly transcript: readonly DataFileInfo[]\n }\n}\n\ninterface CaptureStateFile {\n readonly schema_version: 'runlog.state.v1'\n readonly run_id: string\n readonly status: 'open' | 'closed'\n readonly updated_at: string\n}\n\ninterface CaptureUploadFile {\n readonly schema_version: 'runlog.upload.v1'\n readonly run_id: string\n readonly status: 'pending' | 'uploading' | 'partial' | 'uploaded' | 'failed'\n readonly updated_at?: string\n readonly files: Record<string, CaptureUploadFileEntry>\n}\n\nexport interface CaptureUploadFileEntry {\n readonly status: 'uploading' | 'uploaded' | 'failed'\n readonly bytes: number\n readonly sha256: string\n readonly attempts: number\n readonly uploaded_at?: string\n readonly failed_at?: string\n readonly etag?: string\n readonly error?: string\n}\n\nexport interface DataFileInfo {\n readonly path: string\n readonly bytes: number\n readonly lines: number\n readonly oversized_line: boolean\n}\n\ninterface DataFileChunk extends DataFileInfo {\n readonly content: string\n}\n\nexport interface CaptureDirectoryFiles {\n readonly events: readonly DataFileInfo[]\n readonly transcript: readonly DataFileInfo[]\n}\n\nexport interface SerializedAnalysisEvents {\n readonly text: string\n readonly nextSeq: number\n}\n\ntype AnalysisEvent = UserMessageEvent | AssistantMessageEvent | TurnSummaryEvent\n\ninterface BaseAnalysisEvent {\n readonly schema_version: 'runlog.events.v1'\n readonly seq: number\n readonly timestamp?: string\n}\n\ninterface UserMessageEvent extends BaseAnalysisEvent {\n readonly type: 'user_message'\n readonly text: string\n}\n\ninterface AssistantMessageEvent extends BaseAnalysisEvent {\n readonly type: 'assistant_message'\n readonly model?: string\n readonly text: string\n readonly input_tokens?: number\n readonly output_tokens?: number\n}\n\ninterface TurnSummaryEvent extends BaseAnalysisEvent {\n readonly type: 'turn_summary'\n readonly duration_ms?: number\n readonly message_count?: number\n}\n\ninterface RawTranscriptLine {\n readonly type?: unknown\n readonly subtype?: unknown\n readonly timestamp?: unknown\n readonly message?: unknown\n readonly payload?: unknown\n readonly durationMs?: unknown\n readonly messageCount?: unknown\n}\n\ninterface RawMessage {\n readonly content?: unknown\n readonly model?: unknown\n readonly usage?: unknown\n}\n\ninterface RawCodexPayload {\n readonly type?: unknown\n readonly message?: unknown\n readonly duration_ms?: unknown\n}\n\ninterface RawUsage {\n readonly input_tokens?: unknown\n readonly output_tokens?: unknown\n}\n\ninterface JsonObject {\n readonly schema_version?: unknown\n readonly run_id?: unknown\n readonly [key: string]: unknown\n}\n\ninterface RawContentPart {\n readonly type?: unknown\n readonly text?: unknown\n}\n\nexport class CaptureOutputPrepareError extends Error {\n readonly path: string\n\n constructor(path: string, cause: unknown) {\n super(errorMessage(cause))\n this.name = 'CaptureOutputPrepareError'\n this.path = path\n this.cause = cause\n }\n}\n\nexport function defaultCaptureOutputRoot(\n home = homedir(),\n env: NodeJS.ProcessEnv = process.env,\n nodePlatform: NodeJS.Platform = process.platform,\n): string {\n const pathJoin = nodePlatform === 'win32' ? win32.join : posix.join\n\n if (nodePlatform === 'darwin') {\n return pathJoin(home, 'Library', 'Application Support', 'moxt', 'runs')\n }\n\n if (nodePlatform === 'win32') {\n return pathJoin(env.LOCALAPPDATA ?? pathJoin(home, 'AppData', 'Local'), 'Moxt', 'runs')\n }\n\n return pathJoin(env.XDG_DATA_HOME ?? pathJoin(home, '.local', 'share'), 'moxt', 'runs')\n}\n\nexport function withDefaultCaptureOutput(env: NodeJS.ProcessEnv, home = homedir()): NodeJS.ProcessEnv {\n const { outputDir, outputRoot } = captureEnvPaths(env)\n if (hasValue(outputDir) || hasValue(outputRoot)) {\n return env\n }\n\n return {\n ...env,\n MOXT_RUN_OUTPUT_ROOT: defaultCaptureOutputRoot(home, env),\n }\n}\n\nexport async function prepareCaptureOutputs(env: NodeJS.ProcessEnv, runId: string): Promise<void> {\n const { outputDir, outputRoot } = captureEnvPaths(env)\n\n if (hasValue(outputDir)) {\n await prepareOutputPath(outputDir, () => prepareCaptureDirectory(outputDir))\n }\n\n if (hasValue(outputRoot)) {\n const runDir = join(outputRoot, runId)\n await prepareOutputPath(runDir, () => prepareCaptureDirectory(runDir))\n }\n}\n\nexport function captureOutputDirectories(env: NodeJS.ProcessEnv, runId: string): readonly string[] {\n const { outputDir, outputRoot } = captureEnvPaths(env)\n const dirs = new Set<string>()\n\n if (hasValue(outputDir)) {\n dirs.add(outputDir)\n }\n\n if (hasValue(outputRoot)) {\n dirs.add(join(outputRoot, runId))\n }\n\n return [...dirs]\n}\n\nexport async function emitOpenCaptureDirectories(\n env: NodeJS.ProcessEnv,\n runId: string,\n capturedAt: string,\n): Promise<void> {\n await Promise.all(\n captureOutputDirectories(env, runId).map(async (outputDir) => {\n await writeCaptureUploadFile(outputDir, runId)\n await writeCaptureStateFile(outputDir, runId, 'open', capturedAt)\n }),\n )\n}\n\nexport async function finalizeCaptureDirectories(\n payload: CapturePayload,\n env: NodeJS.ProcessEnv,\n runId: string,\n capturedAt: string,\n files: CaptureDirectoryFiles,\n): Promise<void> {\n await Promise.all(\n captureOutputDirectories(env, runId).map(async (outputDir) => {\n await writeCaptureRunFile(outputDir, payload, runId, files)\n await writeCaptureUploadFile(outputDir, runId)\n await writeCaptureStateFile(outputDir, runId, 'closed', capturedAt)\n }),\n )\n}\n\nexport function createCaptureRunId(startedAt: string, agent?: RunAgent): string {\n const timestamp = startedAt.replaceAll(/[^A-Za-z0-9]/g, '-')\n const suffix = randomUUID().replaceAll('-', '').slice(0, 8)\n return agent === undefined ? `${timestamp}-${suffix}` : `${timestamp}-${agent}-${suffix}`\n}\n\nexport async function writeCaptureDirectoryPayload(\n payload: CapturePayload,\n env: NodeJS.ProcessEnv,\n runId: string,\n capturedAt: string,\n): Promise<void> {\n const hasTranscript = payload.transcript_redacted !== undefined\n const transcript = hasTranscript ? normalizeJsonl(payload.transcript_redacted ?? '') : ''\n const transcriptChunks = hasTranscript ? chunkJsonl(transcript, 'transcript', 'transcript') : []\n const eventChunks = hasTranscript\n ? chunkJsonl(serializeEventsFromTranscript(transcript, 1, payload.run.agent).text, 'events', 'events')\n : []\n\n await Promise.all(\n captureOutputDirectories(env, runId).map(async (outputDir) => {\n await prepareCaptureDirectory(outputDir)\n if (hasTranscript) {\n await writeChunks(outputDir, eventChunks)\n await writeChunks(outputDir, transcriptChunks)\n }\n await writeCaptureRunFile(outputDir, payload, runId, {\n events: eventChunks.map(withoutContent),\n transcript: transcriptChunks.map(withoutContent),\n })\n await writeCaptureUploadFile(outputDir, runId)\n await writeCaptureStateFile(outputDir, runId, 'closed', capturedAt)\n }),\n )\n}\n\nexport function serializeEventsFromTranscript(\n transcript: string,\n startSeq: number,\n agent: RunAgent = 'claude',\n): SerializedAnalysisEvents {\n const events = normalizeEvents(transcript, startSeq, agent)\n return {\n text: serializeEvents(events),\n nextSeq: startSeq + events.length,\n }\n}\n\nfunction normalizeJsonl(text: string): string {\n if (text === '') {\n return ''\n }\n return text.endsWith('\\n') ? text : `${text}\\n`\n}\n\nasync function prepareCaptureDirectory(outputDir: string): Promise<void> {\n await mkdir(outputDir, { recursive: true })\n await assertMoxtManagedOutputDir(outputDir)\n await Promise.all([\n rm(join(outputDir, RUNLOG_DIRECTORY_MARKER), { force: true }),\n rm(join(outputDir, 'run.json'), { force: true }),\n rm(join(outputDir, 'state.json'), { force: true }),\n rm(join(outputDir, 'upload.json'), { force: true }),\n rm(join(outputDir, 'events.jsonl'), { force: true }),\n rm(join(outputDir, 'transcript.jsonl'), { force: true }),\n rm(join(outputDir, 'events'), { recursive: true, force: true }),\n rm(join(outputDir, 'transcript'), { recursive: true, force: true }),\n ])\n await writeRunlogDirectoryMarker(outputDir)\n await mkdir(join(outputDir, 'events'), { recursive: true })\n await mkdir(join(outputDir, 'transcript'), { recursive: true })\n}\n\nasync function assertMoxtManagedOutputDir(outputDir: string): Promise<void> {\n const entries = await readdir(outputDir)\n const unmanaged = entries.filter((entry) => !RUNLOG_MANAGED_OUTPUT_NAMES.has(entry))\n if (unmanaged.length > 0) {\n throw new Error(`refusing to use run output directory with unmanaged files: ${unmanaged.slice(0, 5).join(', ')}`)\n }\n\n const meaningfulEntries = entries.filter((entry) => entry !== '.DS_Store')\n if (meaningfulEntries.length === 0) {\n return\n }\n\n if (!entries.includes(RUNLOG_DIRECTORY_MARKER)) {\n throw new Error('refusing to use run output directory without ownership marker')\n }\n await assertRunlogDirectoryMarker(outputDir)\n\n const metadataEntries = RUNLOG_METADATA_FILE_NAMES.filter((entry) => entries.includes(entry))\n if (metadataEntries.length === 0) {\n return\n }\n\n const runIds = await Promise.all(\n metadataEntries.map((entry) => readRunlogMetadataRunId(outputDir, entry)),\n )\n const uniqueRunIds = new Set(runIds)\n if (uniqueRunIds.size > 1) {\n throw new Error('refusing to use run output directory with mismatched run metadata')\n }\n}\n\nasync function readRunlogMetadataRunId(outputDir: string, fileName: RunlogMetadataFileName): Promise<string> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(join(outputDir, fileName), 'utf8'))\n } catch (error) {\n throw new Error(`invalid ${fileName}: ${errorMessage(error)}`)\n }\n\n const value = objectValue(parsed)\n if (value === null) {\n throw new Error(`invalid ${fileName}: expected object`)\n }\n\n if (value.schema_version !== RUNLOG_METADATA_SCHEMAS[fileName]) {\n throw new Error(`invalid ${fileName}: unexpected schema_version`)\n }\n\n if (typeof value.run_id !== 'string' || value.run_id.trim() === '') {\n throw new Error(`invalid ${fileName}: missing run_id`)\n }\n\n return value.run_id\n}\n\nasync function assertRunlogDirectoryMarker(outputDir: string): Promise<void> {\n let parsed: unknown\n try {\n parsed = JSON.parse(await readFile(join(outputDir, RUNLOG_DIRECTORY_MARKER), 'utf8'))\n } catch (error) {\n throw new Error(`invalid ${RUNLOG_DIRECTORY_MARKER}: ${errorMessage(error)}`)\n }\n\n const value = objectValue(parsed)\n if (value?.schema_version !== RUNLOG_DIRECTORY_MARKER_SCHEMA) {\n throw new Error(`invalid ${RUNLOG_DIRECTORY_MARKER}: unexpected schema_version`)\n }\n}\n\nasync function prepareOutputPath(\n path: string,\n prepare: () => Promise<void> = async () => {\n await mkdir(path, { recursive: true })\n },\n): Promise<void> {\n try {\n await prepare()\n } catch (error) {\n throw new CaptureOutputPrepareError(path, error)\n }\n}\n\nasync function writeCaptureRunFile(\n outputDir: string,\n payload: CapturePayload,\n runId: string,\n files: CaptureDirectoryFiles,\n): Promise<void> {\n const runFile: CaptureRunFile = {\n schema_version: 'runlog.capture.v1',\n run_id: runId,\n run: payload.run,\n recording: payload.recording,\n repo: payload.repo,\n ...(payload.redaction_failed ? { redaction_failed: true as const } : {}),\n files: {\n state: 'state.json',\n upload: 'upload.json',\n events: files.events,\n transcript: files.transcript,\n },\n }\n\n await writeFile(join(outputDir, 'run.json'), `${JSON.stringify(runFile, null, 2)}\\n`, 'utf8')\n}\n\nasync function writeRunlogDirectoryMarker(outputDir: string): Promise<void> {\n await writeFile(\n join(outputDir, RUNLOG_DIRECTORY_MARKER),\n `${JSON.stringify({ schema_version: RUNLOG_DIRECTORY_MARKER_SCHEMA }, null, 2)}\\n`,\n 'utf8',\n )\n}\n\nasync function writeCaptureUploadFile(outputDir: string, runId: string): Promise<void> {\n const path = join(outputDir, 'upload.json')\n try {\n await access(path)\n return\n } catch {}\n\n const uploadFile: CaptureUploadFile = {\n schema_version: 'runlog.upload.v1',\n run_id: runId,\n status: 'pending',\n files: {},\n }\n\n await writeFile(path, `${JSON.stringify(uploadFile, null, 2)}\\n`, 'utf8')\n}\n\nasync function writeCaptureStateFile(\n outputDir: string,\n runId: string,\n status: CaptureStateFile['status'],\n capturedAt: string,\n): Promise<void> {\n const stateFile: CaptureStateFile = {\n schema_version: 'runlog.state.v1',\n run_id: runId,\n status,\n updated_at: capturedAt,\n }\n\n await writeFile(join(outputDir, 'state.json'), `${JSON.stringify(stateFile, null, 2)}\\n`, 'utf8')\n}\n\nasync function writeChunks(outputDir: string, chunks: readonly DataFileChunk[]): Promise<void> {\n await Promise.all(chunks.map((chunk) => writeFile(join(outputDir, chunk.path), chunk.content, 'utf8')))\n}\n\nfunction withoutContent(chunk: DataFileChunk): DataFileInfo {\n return {\n path: chunk.path,\n bytes: chunk.bytes,\n lines: chunk.lines,\n oversized_line: chunk.oversized_line,\n }\n}\n\nfunction captureEnvPaths(env: NodeJS.ProcessEnv): {\n readonly outputDir: string | undefined\n readonly outputRoot: string | undefined\n} {\n const { MOXT_RUN_OUTPUT_DIR: outputDir, MOXT_RUN_OUTPUT_ROOT: outputRoot } = env\n return { outputDir, outputRoot }\n}\n\nfunction chunkJsonl(\n text: string,\n dir: 'events' | 'transcript',\n prefix: 'events' | 'transcript',\n): readonly DataFileChunk[] {\n if (text === '') {\n return []\n }\n\n const chunks: DataFileChunk[] = []\n let content = ''\n let bytes = 0\n let lines = 0\n let oversizedLine = false\n\n const flush = (): void => {\n if (content === '') {\n return\n }\n\n const index = String(chunks.length + 1).padStart(6, '0')\n chunks.push({\n path: `${dir}/${prefix}-${index}.jsonl`,\n content,\n bytes,\n lines,\n oversized_line: oversizedLine,\n })\n content = ''\n bytes = 0\n lines = 0\n oversizedLine = false\n }\n\n for (const line of jsonlLines(text)) {\n const lineBytes = Buffer.byteLength(line)\n if (lineBytes > DATA_FILE_TARGET_BYTES) {\n flush()\n content = line\n bytes = lineBytes\n lines = 1\n oversizedLine = true\n flush()\n continue\n }\n\n if (bytes > 0 && bytes + lineBytes > DATA_FILE_TARGET_BYTES) {\n flush()\n }\n\n content += line\n bytes += lineBytes\n lines += 1\n }\n\n flush()\n return chunks\n}\n\nfunction jsonlLines(text: string): readonly string[] {\n const normalized = normalizeJsonl(text)\n if (normalized === '') {\n return []\n }\n\n return normalized\n .slice(0, -1)\n .split('\\n')\n .map((line) => `${line}\\n`)\n}\n\nfunction serializeEvents(events: readonly AnalysisEvent[]): string {\n if (events.length === 0) {\n return ''\n }\n return `${events.map((event) => JSON.stringify(event)).join('\\n')}\\n`\n}\n\nfunction normalizeEvents(transcript: string, startSeq: number, agent: RunAgent): readonly AnalysisEvent[] {\n const events: AnalysisEvent[] = []\n\n for (const line of transcript.split('\\n')) {\n if (line.trim() === '') {\n continue\n }\n\n const raw = parseTranscriptLine(line)\n const event =\n agent === 'codex'\n ? normalizeCodexEvent(raw, startSeq + events.length)\n : normalizeClaudeEvent(raw, startSeq + events.length)\n if (event !== null) {\n events.push(event)\n }\n }\n\n return events\n}\n\nfunction normalizeClaudeEvent(raw: RawTranscriptLine | null, seq: number): AnalysisEvent | null {\n if (raw === null) {\n return null\n }\n\n const timestamp = stringValue(raw.timestamp)\n\n if (raw.type === 'user') {\n const message = messageValue(raw.message)\n const text = textFromContent(message?.content)\n if (text === '') {\n return null\n }\n\n return {\n schema_version: 'runlog.events.v1',\n seq,\n type: 'user_message',\n ...(timestamp === undefined ? {} : { timestamp }),\n text,\n }\n }\n\n if (raw.type === 'assistant') {\n const message = messageValue(raw.message)\n const text = textFromContent(message?.content)\n if (text === '') {\n return null\n }\n\n const usage = usageValue(message?.usage)\n const model = stringValue(message?.model)\n const inputTokens = numberValue(usage?.input_tokens)\n const outputTokens = numberValue(usage?.output_tokens)\n\n return {\n schema_version: 'runlog.events.v1',\n seq,\n type: 'assistant_message',\n ...(timestamp === undefined ? {} : { timestamp }),\n ...(model === undefined ? {} : { model }),\n text,\n ...(inputTokens === undefined ? {} : { input_tokens: inputTokens }),\n ...(outputTokens === undefined ? {} : { output_tokens: outputTokens }),\n }\n }\n\n if (raw.type === 'system' && raw.subtype === 'turn_duration') {\n const durationMs = numberValue(raw.durationMs)\n const messageCount = numberValue(raw.messageCount)\n\n return {\n schema_version: 'runlog.events.v1',\n seq,\n type: 'turn_summary',\n ...(timestamp === undefined ? {} : { timestamp }),\n ...(durationMs === undefined ? {} : { duration_ms: durationMs }),\n ...(messageCount === undefined ? {} : { message_count: messageCount }),\n }\n }\n\n return null\n}\n\nfunction normalizeCodexEvent(raw: RawTranscriptLine | null, seq: number): AnalysisEvent | null {\n if (raw === null || raw.type !== 'event_msg') {\n return null\n }\n\n const timestamp = stringValue(raw.timestamp)\n const payload = codexPayloadValue(raw.payload)\n const payloadType = stringValue(payload?.type)\n\n if (payloadType === 'user_message') {\n const text = stringValue(payload?.message) ?? ''\n if (text === '') {\n return null\n }\n\n return {\n schema_version: 'runlog.events.v1',\n seq,\n type: 'user_message',\n ...(timestamp === undefined ? {} : { timestamp }),\n text,\n }\n }\n\n if (payloadType === 'agent_message') {\n const text = stringValue(payload?.message) ?? ''\n if (text === '') {\n return null\n }\n\n return {\n schema_version: 'runlog.events.v1',\n seq,\n type: 'assistant_message',\n ...(timestamp === undefined ? {} : { timestamp }),\n text,\n }\n }\n\n if (payloadType === 'task_complete') {\n const durationMs = numberValue(payload?.duration_ms)\n return {\n schema_version: 'runlog.events.v1',\n seq,\n type: 'turn_summary',\n ...(timestamp === undefined ? {} : { timestamp }),\n ...(durationMs === undefined ? {} : { duration_ms: durationMs }),\n }\n }\n\n return null\n}\n\nfunction parseTranscriptLine(line: string): RawTranscriptLine | null {\n try {\n const value: unknown = JSON.parse(line)\n return isObject(value) ? value : null\n } catch {\n return null\n }\n}\n\nfunction textFromContent(content: unknown): string {\n if (typeof content === 'string') {\n return content\n }\n\n if (!Array.isArray(content)) {\n return ''\n }\n\n return content\n .map((part) => {\n const contentPart = contentPartValue(part)\n if (contentPart?.type !== 'text') {\n return ''\n }\n return stringValue(contentPart.text) ?? ''\n })\n .filter((text) => text !== '')\n .join('\\n')\n}\n\nfunction messageValue(value: unknown): RawMessage | undefined {\n return isObject(value) ? value : undefined\n}\n\nfunction codexPayloadValue(value: unknown): RawCodexPayload | undefined {\n return isObject(value) ? value : undefined\n}\n\nfunction usageValue(value: unknown): RawUsage | undefined {\n return isObject(value) ? value : undefined\n}\n\nfunction contentPartValue(value: unknown): RawContentPart | undefined {\n return isObject(value) ? value : undefined\n}\n\nfunction stringValue(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction numberValue(value: unknown): number | undefined {\n return typeof value === 'number' ? value : undefined\n}\n\nfunction isObject(value: unknown): value is object {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction hasValue(value: string | undefined): value is string {\n return value !== undefined && value !== ''\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error && error.message !== '') {\n return error.message\n }\n return String(error)\n}\n\nfunction objectValue(value: unknown): JsonObject | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as JsonObject) : null\n}\n","import { createHmac } from 'node:crypto'\n\nexport interface RedactionHit {\n readonly rule: string\n readonly count: number\n}\n\nexport interface RedactionResult {\n readonly text: string\n readonly hits: readonly RedactionHit[]\n}\n\ninterface RedactionRule {\n readonly name: string\n readonly pattern: RegExp\n readonly replacement: (value: string, salt: string) => string\n}\n\nconst SECRET_RULES: readonly RedactionRule[] = [\n {\n name: 'private_key',\n pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\\s\\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,\n replacement: (value, salt) => `<REDACTED:private_key:${tag(value, salt)}>`,\n },\n {\n name: 'bearer',\n pattern: /Bearer\\s+[A-Za-z0-9._~+/=-]+/gi,\n replacement: (value, salt) => `<REDACTED:bearer:${tag(value, salt)}>`,\n },\n {\n name: 'basic',\n pattern: /Basic\\s+[A-Za-z0-9+/=-]+/gi,\n replacement: (value, salt) => `<REDACTED:basic:${tag(value, salt)}>`,\n },\n {\n name: 'jwt',\n pattern: /eyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/g,\n replacement: (value, salt) => `<REDACTED:jwt:${tag(value, salt)}>`,\n },\n {\n name: 'github',\n pattern: /github_pat_[A-Za-z0-9_]{20,}/g,\n replacement: (value, salt) => `<REDACTED:github:${tag(value, salt)}>`,\n },\n {\n name: 'github',\n pattern: /github_pat_[A-Za-z0-9_]{4,}(?:\\u2026|\\.{3})/g,\n replacement: (value, salt) => `<REDACTED:github:${tag(value, salt)}>`,\n },\n {\n name: 'github',\n pattern: /gh[opsu]_[A-Za-z0-9_]{8,}/g,\n replacement: (value, salt) => `<REDACTED:github:${tag(value, salt)}>`,\n },\n {\n name: 'github',\n pattern: /gh[opsu]_[A-Za-z0-9_]{4,}(?:\\u2026|\\.{3})/g,\n replacement: (value, salt) => `<REDACTED:github:${tag(value, salt)}>`,\n },\n {\n name: 'openai',\n pattern: /sk-(?:proj-)?[A-Za-z0-9_-]{20,}/g,\n replacement: (value, salt) => `<REDACTED:openai:${tag(value, salt)}>`,\n },\n {\n name: 'openai',\n pattern: /sk-(?:proj-)?[A-Za-z0-9_-]{4,}(?:\\u2026|\\.{3})/g,\n replacement: (value, salt) => `<REDACTED:openai:${tag(value, salt)}>`,\n },\n {\n name: 'slack',\n pattern: /xox[baprs]-[A-Za-z0-9-]{10,}/g,\n replacement: (value, salt) => `<REDACTED:slack:${tag(value, salt)}>`,\n },\n {\n name: 'stripe',\n pattern: /(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,}/g,\n replacement: (value, salt) => `<REDACTED:stripe:${tag(value, salt)}>`,\n },\n {\n name: 'aws_key',\n pattern: /(?:AKIA|ASIA)[0-9A-Z]{16}/g,\n replacement: (value, salt) => `<REDACTED:aws_key:${tag(value, salt)}>`,\n },\n {\n name: 'aws_key',\n pattern: /(?:AKIA|ASIA)[0-9A-Z]{4,}(?:\\u2026|\\.{3})/g,\n replacement: (value, salt) => `<REDACTED:aws_key:${tag(value, salt)}>`,\n },\n]\n\nconst FIELD_QUOTED_PATTERN =\n /([\"']?(?:password|passwd|pwd|secret|client_secret|token|access_token|refresh_token|authorization|cookie|set-cookie|api_key|apikey|private_key)[\"']?\\s*[:=]\\s*)([\"'])(?:\\\\.|(?!\\2)[\\s\\S])*?\\2/gi\n\nconst FIELD_UNQUOTED_PATTERN =\n /([\"']?(?:password|passwd|pwd|secret|client_secret|token|access_token|refresh_token|cookie|set-cookie|api_key|apikey|private_key)[\"']?\\s*[:=]\\s*)[^\"',\\n}\\s]+/gi\n\nexport function redactText(text: string, salt = 'moxt-run-local-salt'): RedactionResult {\n const hitCounts = new Map<string, number>()\n let redacted = text\n\n for (const rule of SECRET_RULES) {\n redacted = redacted.replace(rule.pattern, (value) => {\n addHit(hitCounts, rule.name)\n return rule.replacement(value, salt)\n })\n }\n\n redacted = redacted\n .replace(FIELD_QUOTED_PATTERN, (_match, prefix: string, quote: string) => {\n addHit(hitCounts, 'field')\n return `${prefix}${quote}<REDACTED:field>${quote}`\n })\n .replace(FIELD_UNQUOTED_PATTERN, (_match, prefix: string) => {\n addHit(hitCounts, 'field')\n return `${prefix}<REDACTED:field>`\n })\n\n return {\n text: redacted,\n hits: [...hitCounts.entries()].map(([rule, count]) => ({ rule, count })),\n }\n}\n\nfunction tag(value: string, salt: string): string {\n return createHmac('sha256', salt).update(value).digest('hex').slice(0, 8)\n}\n\nfunction addHit(hitCounts: Map<string, number>, rule: string): void {\n hitCounts.set(rule, (hitCounts.get(rule) ?? 0) + 1)\n}\n","import type { RepoInfo } from './types.js'\n\nexport function stripRemoteCredentials(remote: string): string {\n if (!/^[a-z][a-z0-9+.-]*:\\/\\//i.test(remote)) {\n return remote\n }\n\n try {\n const url = new URL(remote)\n url.username = ''\n url.password = ''\n return url.toString()\n } catch {\n return remote\n }\n}\n\nexport function sanitizeRepo(repo: RepoInfo | null): RepoInfo | null {\n if (repo === null) return null\n return {\n ...repo,\n remote: stripRemoteCredentials(repo.remote),\n }\n}\n","import { existsSync, readdirSync, statSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { RecordingInfo, SessionMatch } from './types.js'\n\nconst SESSION_START_TOLERANCE_MS = 1000\n\nexport interface FileSnapshot {\n readonly mtimeMs: number\n readonly size: number\n}\n\nexport type SnapshotMap = Map<string, FileSnapshot>\n\nexport interface MatchResult {\n readonly match: SessionMatch\n readonly sessionFile: string | null\n readonly startOffset: number\n}\n\nexport interface MatchOptions {\n readonly isCandidate?: (path: string) => boolean\n readonly newFilesOnly?: boolean\n}\n\nexport function snapshotJsonl(root: string): SnapshotMap {\n const snapshot: SnapshotMap = new Map()\n if (!existsSync(root)) {\n return snapshot\n }\n\n collectJsonl(root, snapshot)\n return snapshot\n}\n\nexport function matchSession(\n before: SnapshotMap,\n after: SnapshotMap,\n startedAtMs: number,\n options: MatchOptions = {},\n): MatchResult {\n const candidates: Array<{\n readonly path: string\n readonly startOffset: number\n }> = []\n\n for (const [path, current] of after.entries()) {\n const previous = before.get(path)\n if (previous === undefined) {\n if (wasChangedAfterStart(current, startedAtMs)) {\n candidates.push({ path, startOffset: 0 })\n }\n continue\n }\n\n if (!options.newFilesOnly && current.size > previous.size) {\n candidates.push({ path, startOffset: previous.size })\n }\n }\n\n if (candidates.length === 0) {\n return { match: 'none', sessionFile: null, startOffset: 0 }\n }\n\n const trustedCandidates =\n options.isCandidate === undefined\n ? candidates\n : candidates.filter((candidate) => options.isCandidate?.(candidate.path))\n\n if (trustedCandidates.length === 0) {\n return { match: 'none', sessionFile: null, startOffset: 0 }\n }\n\n if (trustedCandidates.length === 1) {\n const [candidate] = trustedCandidates\n if (candidate !== undefined) {\n return {\n match: 'unique',\n sessionFile: candidate.path,\n startOffset: candidate.startOffset,\n }\n }\n }\n\n return { match: 'ambiguous', sessionFile: null, startOffset: 0 }\n}\n\nexport function matchKnownSessionFile(before: SnapshotMap, after: SnapshotMap, sessionFile: string): MatchResult {\n const current = after.get(sessionFile)\n if (current === undefined) {\n return { match: 'none', sessionFile: null, startOffset: 0 }\n }\n\n const previous = before.get(sessionFile)\n if (previous !== undefined && current.size <= previous.size) {\n return { match: 'none', sessionFile: null, startOffset: 0 }\n }\n\n return {\n match: 'unique',\n sessionFile,\n startOffset: previous?.size ?? 0,\n }\n}\n\nexport function recordingFromSessionMatch(match: SessionMatch): RecordingInfo {\n switch (match) {\n case 'unique':\n return { found_chat: true, quality: 'complete' }\n case 'none':\n return { found_chat: false, quality: 'not_found' }\n case 'ambiguous':\n return { found_chat: false, quality: 'uncertain' }\n case 'prep_failed':\n return { found_chat: false, quality: 'unavailable' }\n }\n}\n\nfunction collectJsonl(dir: string, snapshot: SnapshotMap): void {\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n const path = join(dir, entry.name)\n if (entry.isDirectory()) {\n collectJsonl(path, snapshot)\n continue\n }\n\n if (!entry.isFile() || !entry.name.endsWith('.jsonl')) {\n continue\n }\n\n const stat = statSync(path)\n snapshot.set(path, {\n mtimeMs: stat.mtimeMs,\n size: stat.size,\n })\n }\n}\n\nfunction wasChangedAfterStart(current: FileSnapshot, startedAtMs: number): boolean {\n return current.mtimeMs >= startedAtMs - SESSION_START_TOLERANCE_MS\n}\n","import type { RunStatus } from './types.js'\n\nconst SIGNAL_NUMBERS = new Map<NodeJS.Signals, number>([\n ['SIGHUP', 1],\n ['SIGINT', 2],\n ['SIGQUIT', 3],\n ['SIGKILL', 9],\n ['SIGTERM', 15],\n])\n\nexport interface ExitEvent {\n readonly code: number | null\n readonly signal: NodeJS.Signals | null\n readonly errorCode?: string\n}\n\nexport interface ClassifiedExit {\n readonly code: number\n readonly status: RunStatus\n}\n\nexport function signalNumber(signal: NodeJS.Signals): number {\n return SIGNAL_NUMBERS.get(signal) ?? 0\n}\n\nexport function classifyExit(event: ExitEvent, observedSignals: ReadonlySet<number>): ClassifiedExit {\n if (event.errorCode !== undefined) {\n return {\n code: event.errorCode === 'ENOENT' ? 127 : 126,\n status: 'unknown',\n }\n }\n\n if (event.signal !== null) {\n return {\n code: 128 + signalNumber(event.signal),\n status: 'cancelled',\n }\n }\n\n if (event.code !== null) {\n if (event.code === 0) {\n return { code: 0, status: 'completed' }\n }\n\n const signal = event.code - 128\n return {\n code: event.code,\n status: event.code > 128 && observedSignals.has(signal) ? 'cancelled' : 'failed',\n }\n }\n\n return { code: 1, status: 'unknown' }\n}\n","import { appendFile, open, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n type CaptureDirectoryFiles,\n captureOutputDirectories,\n type DataFileInfo,\n emitOpenCaptureDirectories,\n finalizeCaptureDirectories,\n serializeEventsFromTranscript,\n} from './capture.js'\nimport { redactText } from './redaction.js'\nimport {\n type MatchOptions,\n matchKnownSessionFile,\n matchSession,\n recordingFromSessionMatch,\n type SnapshotMap,\n snapshotJsonl,\n} from './session.js'\nimport type { CapturePayload, SessionMatch } from './types.js'\nimport type { OpenSessionFileMatch } from './process-session.js'\n\nconst DATA_FILE_TARGET_BYTES = 1024 * 1024\nconst LIVE_CAPTURE_INTERVAL_MS = 250\n\ninterface LiveCaptureOptions {\n readonly env: NodeJS.ProcessEnv\n readonly runId: string\n readonly agent: CapturePayload['run']['agent']\n readonly startedAt: string\n readonly sessions: string\n readonly before: SnapshotMap\n readonly baselineOk: boolean\n readonly startedAtMs: number\n readonly knownSessionFile?: string\n readonly isSessionCandidate?: (path: string) => boolean\n readonly newSessionFilesOnly?: boolean\n readonly openSessionFile?: () => OpenSessionFileMatch\n}\n\ninterface ReadResult {\n readonly text: string\n readonly bytes: number\n}\n\ninterface MutableFileInfo {\n readonly path: string\n bytes: number\n lines: number\n oversized_line: boolean\n}\n\nexport function createLiveCapture(options: LiveCaptureOptions): LiveCaptureRecorder {\n return new LiveCaptureRecorder(options)\n}\n\nexport class LiveCaptureRecorder {\n readonly enabled: boolean\n private readonly outputs: readonly CaptureDirectoryOutput[]\n private readonly env: NodeJS.ProcessEnv\n private readonly runId: string\n private readonly agent: CapturePayload['run']['agent']\n private readonly startedAt: string\n private readonly sessions: string\n private readonly before: SnapshotMap\n private readonly baselineOk: boolean\n private readonly startedAtMs: number\n private readonly knownSessionFile: string | undefined\n private readonly isSessionCandidate: ((path: string) => boolean) | undefined\n private readonly newSessionFilesOnly: boolean\n private readonly openSessionFile: (() => OpenSessionFileMatch) | undefined\n private timer: NodeJS.Timeout | undefined\n private pollInFlight: Promise<void> | null = null\n private sessionFile: string | null = null\n private readOffset = 0\n private pendingText = ''\n private nextSeq = 1\n private sessionMatch: SessionMatch\n private captureFailed = false\n\n constructor(options: LiveCaptureOptions) {\n const outputDirs = captureOutputDirectories(options.env, options.runId)\n this.enabled = outputDirs.length > 0\n this.outputs = outputDirs.map((outputDir) => new CaptureDirectoryOutput(outputDir))\n this.env = options.env\n this.runId = options.runId\n this.agent = options.agent\n this.startedAt = options.startedAt\n this.sessions = options.sessions\n this.before = options.before\n this.baselineOk = options.baselineOk\n this.startedAtMs = options.startedAtMs\n this.knownSessionFile = options.knownSessionFile\n this.isSessionCandidate = options.isSessionCandidate\n this.newSessionFilesOnly = options.newSessionFilesOnly ?? false\n this.openSessionFile = options.openSessionFile\n this.sessionMatch = options.baselineOk ? 'none' : 'prep_failed'\n }\n\n async start(): Promise<void> {\n if (!this.enabled) {\n return\n }\n\n await emitOpenCaptureDirectories(this.env, this.runId, this.startedAt)\n if (this.baselineOk) {\n this.timer = setInterval(() => {\n this.queuePoll()\n }, LIVE_CAPTURE_INTERVAL_MS)\n }\n }\n\n async stop(): Promise<void> {\n if (!this.enabled) {\n return\n }\n\n if (this.timer !== undefined) {\n clearInterval(this.timer)\n this.timer = undefined\n }\n\n if (this.pollInFlight !== null) {\n await this.pollInFlight\n }\n\n await this.poll()\n await this.flushPendingText()\n }\n\n async finalize(payload: CapturePayload, capturedAt: string): Promise<void> {\n if (!this.enabled) {\n return\n }\n\n if (!isCompleteRecording(payload)) {\n await Promise.all(this.outputs.map((output) => output.invalidate()))\n }\n\n await finalizeCaptureDirectories(this.directoryPayload(payload), this.env, this.runId, capturedAt, this.files())\n }\n\n private queuePoll(): void {\n if (this.pollInFlight !== null) {\n return\n }\n\n this.pollInFlight = this.poll().finally(() => {\n this.pollInFlight = null\n })\n }\n\n private async poll(): Promise<void> {\n if (!this.baselineOk || this.captureFailed) {\n return\n }\n\n try {\n const snapshot = snapshotJsonl(this.sessions)\n if (this.sessionFile === null) {\n if (this.knownSessionFile !== undefined) {\n const matched = matchKnownSessionFile(this.before, snapshot, this.knownSessionFile)\n if (matched.match === 'unique' && matched.sessionFile !== null) {\n this.sessionMatch = matched.match\n this.sessionFile = matched.sessionFile\n this.readOffset = matched.startOffset\n await this.captureNewText()\n return\n }\n }\n\n const opened = this.openSessionFile?.() ?? { match: 'none' }\n if (opened.match === 'ambiguous') {\n this.sessionMatch = 'ambiguous'\n return\n }\n\n if (opened.match === 'unique') {\n const matched = matchKnownSessionFile(this.before, snapshot, opened.sessionFile)\n this.sessionMatch = matched.match\n if (matched.match === 'unique' && matched.sessionFile !== null) {\n this.sessionFile = matched.sessionFile\n this.readOffset = matched.startOffset\n await this.captureNewText()\n }\n return\n }\n\n const matched = matchSession(this.before, snapshot, this.startedAtMs, this.matchOptions())\n this.sessionMatch = matched.match\n if (matched.match !== 'unique' || matched.sessionFile === null) {\n return\n }\n\n this.sessionFile = matched.sessionFile\n this.readOffset = matched.startOffset\n }\n\n await this.captureNewText()\n } catch {\n this.captureFailed = true\n }\n }\n\n private async captureNewText(): Promise<void> {\n if (this.sessionFile === null) {\n return\n }\n\n const next = await readFileFromOffset(this.sessionFile, this.readOffset)\n if (next.bytes === 0) {\n return\n }\n\n this.readOffset += next.bytes\n await this.captureCompleteLines(next.text)\n }\n\n private async captureCompleteLines(text: string): Promise<void> {\n const combined = `${this.pendingText}${text}`\n const lastNewline = combined.lastIndexOf('\\n')\n if (lastNewline === -1) {\n this.pendingText = combined\n return\n }\n\n const complete = combined.slice(0, lastNewline + 1)\n this.pendingText = combined.slice(lastNewline + 1)\n await this.captureTranscriptText(complete)\n }\n\n private async flushPendingText(): Promise<void> {\n if (this.pendingText === '') {\n return\n }\n\n const text = `${this.pendingText}\\n`\n this.pendingText = ''\n await this.captureTranscriptText(text)\n }\n\n private async captureTranscriptText(text: string): Promise<void> {\n const redacted = redactText(text).text\n const events = serializeEventsFromTranscript(redacted, this.nextSeq, this.agent)\n this.nextSeq = events.nextSeq\n\n await Promise.all(\n this.outputs.map(async (output) => {\n await output.appendTranscript(redacted)\n await output.appendEvents(events.text)\n }),\n )\n }\n\n private directoryPayload(payload: CapturePayload): CapturePayload {\n const recording = isCompleteRecording(payload)\n ? this.sessionFile === null\n ? payload.recording\n : recordingFromSessionMatch(this.sessionMatch)\n : payload.recording\n const keepRedactionFailure = this.captureFailed || (this.files().transcript.length === 0 && payload.redaction_failed)\n const { redaction_failed: _redactionFailed, ...rest } = payload\n\n return {\n ...rest,\n ...(keepRedactionFailure ? { redaction_failed: true as const } : {}),\n recording,\n }\n }\n\n private files(): CaptureDirectoryFiles {\n const [output] = this.outputs\n if (output === undefined) {\n return { events: [], transcript: [] }\n }\n\n return output.files()\n }\n\n private matchOptions(): MatchOptions {\n return {\n ...(this.isSessionCandidate === undefined ? {} : { isCandidate: this.isSessionCandidate }),\n ...(this.newSessionFilesOnly ? { newFilesOnly: true as const } : {}),\n }\n }\n}\n\nclass CaptureDirectoryOutput {\n private readonly transcript: JsonlStreamWriter\n private readonly events: JsonlStreamWriter\n\n constructor(outputDir: string) {\n this.transcript = new JsonlStreamWriter(outputDir, 'transcript', 'transcript')\n this.events = new JsonlStreamWriter(outputDir, 'events', 'events')\n }\n\n async appendTranscript(text: string): Promise<void> {\n await this.transcript.appendText(text)\n }\n\n async appendEvents(text: string): Promise<void> {\n await this.events.appendText(text)\n }\n\n async invalidate(): Promise<void> {\n await Promise.all([this.transcript.invalidate(), this.events.invalidate()])\n }\n\n files(): CaptureDirectoryFiles {\n return {\n events: this.events.files(),\n transcript: this.transcript.files(),\n }\n }\n}\n\nclass JsonlStreamWriter {\n private readonly outputDir: string\n private readonly dir: 'events' | 'transcript'\n private readonly prefix: 'events' | 'transcript'\n private readonly writtenFiles: MutableFileInfo[] = []\n private current: MutableFileInfo | null = null\n\n constructor(outputDir: string, dir: 'events' | 'transcript', prefix: 'events' | 'transcript') {\n this.outputDir = outputDir\n this.dir = dir\n this.prefix = prefix\n }\n\n async appendText(text: string): Promise<void> {\n for (const line of jsonlLines(text)) {\n await this.appendLine(line)\n }\n }\n\n async invalidate(): Promise<void> {\n await Promise.all(\n this.writtenFiles.map(async (file) => {\n file.bytes = 0\n file.lines = 0\n file.oversized_line = false\n await writeFile(join(this.outputDir, file.path), '', 'utf8')\n }),\n )\n this.current = null\n }\n\n files(): readonly DataFileInfo[] {\n return this.writtenFiles.map((file) => ({ ...file }))\n }\n\n private async appendLine(line: string): Promise<void> {\n const lineBytes = Buffer.byteLength(line)\n if (lineBytes > DATA_FILE_TARGET_BYTES) {\n this.current = null\n const file = this.createFile()\n file.bytes += lineBytes\n file.lines += 1\n file.oversized_line = true\n await appendFile(join(this.outputDir, file.path), line, 'utf8')\n this.current = null\n return\n }\n\n if (this.current !== null && this.current.bytes + lineBytes > DATA_FILE_TARGET_BYTES) {\n this.current = null\n }\n\n const file = this.current ?? this.createFile()\n file.bytes += lineBytes\n file.lines += 1\n await appendFile(join(this.outputDir, file.path), line, 'utf8')\n }\n\n private createFile(): MutableFileInfo {\n const index = String(this.writtenFiles.length + 1).padStart(6, '0')\n const file: MutableFileInfo = {\n path: `${this.dir}/${this.prefix}-${index}.jsonl`,\n bytes: 0,\n lines: 0,\n oversized_line: false,\n }\n this.writtenFiles.push(file)\n this.current = file\n return file\n }\n}\n\nfunction isCompleteRecording(payload: CapturePayload): boolean {\n return payload.recording.found_chat && payload.recording.quality === 'complete'\n}\n\nfunction jsonlLines(text: string): readonly string[] {\n if (text === '') {\n return []\n }\n\n const normalized = text.endsWith('\\n') ? text : `${text}\\n`\n return normalized\n .slice(0, -1)\n .split('\\n')\n .map((line) => `${line}\\n`)\n}\n\nasync function readFileFromOffset(path: string, offset: number): Promise<ReadResult> {\n const file = await open(path, 'r')\n try {\n const stat = await file.stat()\n const length = Math.max(0, stat.size - offset)\n if (length === 0) {\n return { text: '', bytes: 0 }\n }\n\n const buffer = Buffer.alloc(length)\n const result = await file.read(buffer, 0, length, offset)\n return { text: buffer.subarray(0, result.bytesRead).toString('utf8'), bytes: result.bytesRead }\n } finally {\n await file.close()\n }\n}\n","import { createHash } from 'node:crypto'\nimport type { Dirent } from 'node:fs'\nimport { readdir, readFile, stat, writeFile } from 'node:fs/promises'\nimport { arch, platform } from 'node:os'\nimport { join, relative } from 'node:path'\nimport { type CaptureUploadFileEntry, captureOutputDirectories } from './capture.js'\nimport { cloudflareAccessHeaders } from '../utils/cf-access.js'\n\ndeclare const __CLI_VERSION__: string\n\nconst DEFAULT_HOST = 'api.moxt.ai'\nconst DEFAULT_UPLOAD_TIMEOUT_MS = 30000\n\nexport interface RunUploadOptions {\n readonly workspaceId: string\n}\n\ninterface UploadConfig extends RunUploadOptions {\n readonly timeoutMs?: number\n}\n\ninterface UploadFile {\n readonly artifactPath: string\n readonly bytes: number\n readonly sha256: string\n readonly contentText: string\n}\n\ninterface UploadState {\n readonly schema_version: 'runlog.upload.v1'\n readonly run_id: string\n status: 'pending' | 'uploading' | 'partial' | 'uploaded' | 'failed'\n updated_at: string\n files: Record<string, CaptureUploadFileEntry>\n}\n\ninterface UploadResponse {\n readonly etag?: string\n}\n\nexport interface UploadRunArtifactsOptions {\n readonly env: NodeJS.ProcessEnv\n readonly runId: string\n readonly upload: RunUploadOptions\n}\n\nexport async function uploadRunArtifacts(options: UploadRunArtifactsOptions): Promise<void> {\n const outputDirs = captureOutputDirectories(options.env, options.runId)\n const failures: string[] = []\n\n for (const outputDir of outputDirs) {\n try {\n await uploadDirectory(outputDir, options.runId, options.upload, options.env)\n } catch (error) {\n failures.push(`${outputDir}: ${errorMessage(error)}`)\n }\n }\n\n if (failures.length > 0) {\n throw new Error(failures.join('; '))\n }\n}\n\nexport async function uploadDirectory(\n outputDir: string,\n runId: string,\n config: UploadConfig,\n env: NodeJS.ProcessEnv,\n): Promise<void> {\n const files = await discoverUploadFiles(outputDir)\n const state = await readUploadState(outputDir, runId)\n\n for (const file of files) {\n const previous = state.files[file.artifactPath]\n if (previous?.status === 'uploaded' && previous.sha256 === file.sha256 && previous.bytes === file.bytes) {\n continue\n }\n\n const attempts = (previous?.attempts ?? 0) + 1\n state.files[file.artifactPath] = {\n status: 'uploading',\n bytes: file.bytes,\n sha256: file.sha256,\n attempts,\n }\n state.status = 'uploading'\n state.updated_at = new Date().toISOString()\n await writeUploadState(outputDir, state)\n\n try {\n const response = await uploadFile(runId, file, config, env)\n state.files[file.artifactPath] = {\n status: 'uploaded',\n bytes: file.bytes,\n sha256: file.sha256,\n attempts,\n uploaded_at: new Date().toISOString(),\n ...(response.etag === undefined ? {} : { etag: response.etag }),\n }\n } catch (error) {\n state.files[file.artifactPath] = {\n status: 'failed',\n bytes: file.bytes,\n sha256: file.sha256,\n attempts,\n failed_at: new Date().toISOString(),\n error: errorMessage(error),\n }\n }\n\n state.status = uploadStatus(\n state.files,\n files.map((candidate) => candidate.artifactPath),\n )\n state.updated_at = new Date().toISOString()\n await writeUploadState(outputDir, state)\n }\n\n state.status = uploadStatus(\n state.files,\n files.map((file) => file.artifactPath),\n )\n state.updated_at = new Date().toISOString()\n await writeUploadState(outputDir, state)\n\n if (state.status === 'failed') {\n throw new Error('one or more run files failed to upload')\n }\n}\n\nasync function discoverUploadFiles(outputDir: string): Promise<UploadFile[]> {\n const paths = await uploadPaths(outputDir)\n const files = await Promise.all(\n paths.map(async (path) => {\n const absolute = join(outputDir, path)\n const content = await readFile(absolute)\n return {\n artifactPath: path,\n bytes: content.byteLength,\n sha256: createHash('sha256').update(content).digest('hex'),\n contentText: content.toString('utf8'),\n }\n }),\n )\n return files.sort((a, b) => a.artifactPath.localeCompare(b.artifactPath))\n}\n\nasync function uploadPaths(outputDir: string): Promise<string[]> {\n const paths: string[] = []\n\n for (const name of ['run.json', 'state.json'] as const) {\n const absolute = join(outputDir, name)\n try {\n const fileStat = await stat(absolute)\n if (fileStat.isFile()) {\n paths.push(name)\n }\n } catch {}\n }\n\n for (const dir of ['events', 'transcript'] as const) {\n await collectFiles(outputDir, join(outputDir, dir), paths)\n }\n\n return paths.sort()\n}\n\nasync function collectFiles(outputDir: string, dir: string, paths: string[]): Promise<void> {\n let entries: Dirent[]\n try {\n entries = await readdir(dir, { withFileTypes: true })\n } catch {\n return\n }\n\n for (const entry of entries) {\n const absolute = join(dir, entry.name)\n if (entry.isDirectory()) {\n await collectFiles(outputDir, absolute, paths)\n continue\n }\n\n if (!entry.isFile()) {\n continue\n }\n\n const fileStat = await stat(absolute)\n if (fileStat.size === 0) {\n continue\n }\n\n paths.push(relative(outputDir, absolute).replaceAll('\\\\', '/'))\n }\n}\n\nasync function uploadFile(\n runId: string,\n file: UploadFile,\n config: UploadConfig,\n env: NodeJS.ProcessEnv,\n): Promise<UploadResponse> {\n const apiKey = env.MOXT_API_KEY\n if (apiKey === undefined || apiKey === '') {\n throw new Error('MOXT_API_KEY is required for run upload')\n }\n\n const timeoutMs = config.timeoutMs ?? DEFAULT_UPLOAD_TIMEOUT_MS\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, timeoutMs)\n\n try {\n const response = await fetch(\n `${apiBaseUrl(env)}/workspaces/${encodeURIComponent(config.workspaceId)}/local-agent-runs/${encodeURIComponent(runId)}/files`,\n {\n method: 'PUT',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n 'User-Agent': userAgent(),\n ...cloudflareAccessHeaders(env),\n },\n signal: controller.signal,\n body: JSON.stringify({\n schema_version: 'local_agent_run.upload_file.v1',\n artifact_path: file.artifactPath,\n bytes: file.bytes,\n sha256: file.sha256,\n encoding: 'utf8',\n content_text: file.contentText,\n }),\n },\n )\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}`)\n }\n\n const headerEtag = response.headers.get('etag') ?? undefined\n const body = await responseJson(response)\n const { etag: bodyEtagValue } = isObject(body) ? body : {}\n const bodyEtag = typeof bodyEtagValue === 'string' ? bodyEtagValue : undefined\n const etag = bodyEtag ?? headerEtag\n return etag === undefined ? {} : { etag }\n } catch (error) {\n if (controller.signal.aborted) {\n throw new Error(`upload timed out after ${timeoutMs}ms`)\n }\n throw error\n } finally {\n clearTimeout(timeout)\n }\n}\n\nasync function readUploadState(outputDir: string, runId: string): Promise<UploadState> {\n try {\n const value: unknown = JSON.parse(await readFile(join(outputDir, 'upload.json'), 'utf8'))\n if (isUploadState(value, runId)) {\n return value\n }\n } catch {}\n\n return {\n schema_version: 'runlog.upload.v1',\n run_id: runId,\n status: 'pending',\n updated_at: new Date().toISOString(),\n files: {},\n }\n}\n\nasync function writeUploadState(outputDir: string, state: UploadState): Promise<void> {\n await writeFile(join(outputDir, 'upload.json'), `${JSON.stringify(state, null, 2)}\\n`, 'utf8')\n}\n\nfunction uploadStatus(\n files: Record<string, CaptureUploadFileEntry>,\n expectedPaths: readonly string[],\n): UploadState['status'] {\n if (expectedPaths.length === 0) {\n return 'pending'\n }\n\n const states = expectedPaths.map((path) => files[path]?.status ?? 'pending')\n if (states.some((status) => status === 'failed')) {\n return 'failed'\n }\n\n if (states.every((status) => status === 'uploaded')) {\n return 'uploaded'\n }\n\n if (states.some((status) => status === 'uploaded')) {\n return 'partial'\n }\n\n return 'uploading'\n}\n\nfunction isUploadState(value: unknown, runId: string): value is UploadState {\n if (!isObject(value)) {\n return false\n }\n\n const { schema_version: schemaVersion, run_id: valueRunId, files } = value\n return schemaVersion === 'runlog.upload.v1' && valueRunId === runId && isObject(files)\n}\n\nasync function responseJson(response: Response): Promise<unknown> {\n try {\n return await response.json()\n } catch {\n return null\n }\n}\n\nfunction apiBaseUrl(env: NodeJS.ProcessEnv): string {\n return `https://${env.MOXT_HOST ?? DEFAULT_HOST}/openapi/v1`\n}\n\nfunction userAgent(): string {\n return `moxt-cli/${__CLI_VERSION__} (${platform()}/${arch()}) node/${process.versions.node}`\n}\n\nfunction errorMessage(error: unknown): string {\n if (error instanceof Error && error.message !== '') {\n return error.message\n }\n return String(error)\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","export function cloudflareAccessHeaders(env: NodeJS.ProcessEnv = process.env): Record<string, string> {\n const headers: Record<string, string> = {}\n const token = firstValue(env.MOXT_CF_ACCESS_TOKEN, env.CF_ACCESS_TOKEN)\n if (token !== undefined) {\n headers['CF-Access-Token'] = token\n }\n\n const clientId = firstValue(env.MOXT_CF_ACCESS_CLIENT_ID, env.CF_ACCESS_CLIENT_ID)\n const clientSecret = firstValue(env.MOXT_CF_ACCESS_CLIENT_SECRET, env.CF_ACCESS_CLIENT_SECRET)\n if (clientId !== undefined && clientSecret !== undefined) {\n headers['CF-Access-Client-Id'] = clientId\n headers['CF-Access-Client-Secret'] = clientSecret\n }\n\n return headers\n}\n\nfunction firstValue(...values: Array<string | undefined>): string | undefined {\n return values.find((value): value is string => value !== undefined && value !== '')\n}\n","import { execFileSync } from 'node:child_process'\nimport { isAbsolute, relative } from 'node:path'\n\nexport type OpenSessionFileMatch =\n | {\n readonly match: 'unique'\n readonly sessionFile: string\n }\n | {\n readonly match: 'none' | 'ambiguous'\n }\n\nexport interface FindOpenSessionFileOptions {\n readonly rootPid: number\n readonly sessionRoot: string\n readonly isCandidate?: (path: string) => boolean\n readonly platform?: NodeJS.Platform\n}\n\nexport function findOpenSessionFile(options: FindOpenSessionFileOptions): OpenSessionFileMatch {\n if ((options.platform ?? process.platform) !== 'darwin') {\n return { match: 'none' }\n }\n\n try {\n const psOutput = execFileSync('ps', ['-axo', 'pid=,ppid='], {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n const pids = processTreePids(options.rootPid, psOutput)\n const lsofOutput = execFileSync('lsof', ['-F', 'pn', '-p', pids.join(',')], {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n\n return openSessionFileFromLsof(lsofOutput, {\n sessionRoot: options.sessionRoot,\n ...(options.isCandidate === undefined ? {} : { isCandidate: options.isCandidate }),\n })\n } catch {\n return { match: 'none' }\n }\n}\n\nexport function processTreePids(rootPid: number, psOutput: string): readonly number[] {\n const childrenByParent = new Map<number, number[]>()\n for (const line of psOutput.split('\\n')) {\n const [pidText, ppidText] = line.trim().split(/\\s+/, 2)\n const pid = Number(pidText)\n const ppid = Number(ppidText)\n if (!Number.isInteger(pid) || !Number.isInteger(ppid) || pid <= 0) {\n continue\n }\n\n const children = childrenByParent.get(ppid) ?? []\n children.push(pid)\n childrenByParent.set(ppid, children)\n }\n\n const pids: number[] = []\n const seen = new Set<number>()\n const queue = [rootPid]\n while (queue.length > 0) {\n const pid = queue.shift() as number\n if (seen.has(pid)) {\n continue\n }\n\n seen.add(pid)\n pids.push(pid)\n queue.push(...(childrenByParent.get(pid) ?? []))\n }\n\n return pids\n}\n\nexport function openSessionFileFromLsof(\n lsofOutput: string,\n options: {\n readonly sessionRoot: string\n readonly isCandidate?: (path: string) => boolean\n },\n): OpenSessionFileMatch {\n const files = new Set<string>()\n for (const line of lsofOutput.split('\\n')) {\n if (!line.startsWith('n')) {\n continue\n }\n\n const path = line.slice(1)\n if (!path.endsWith('.jsonl') || !isInside(options.sessionRoot, path)) {\n continue\n }\n\n if (options.isCandidate !== undefined && !options.isCandidate(path)) {\n continue\n }\n\n files.add(alignPathToRoot(options.sessionRoot, path))\n }\n\n if (files.size === 0) {\n return { match: 'none' }\n }\n\n if (files.size === 1) {\n return { match: 'unique', sessionFile: [...files].join('') }\n }\n\n return { match: 'ambiguous' }\n}\n\nfunction isInside(root: string, path: string): boolean {\n if (isPathInside(root, path)) {\n return true\n }\n\n return isPathInside(normalizeDarwinVarPath(root), normalizeDarwinVarPath(path))\n}\n\nfunction isPathInside(root: string, path: string): boolean {\n const fromRoot = relative(root, path)\n return fromRoot === '' || (!fromRoot.startsWith('..') && !isAbsolute(fromRoot))\n}\n\nfunction normalizeDarwinVarPath(path: string): string {\n return path.startsWith('/private/var/') ? path.slice('/private'.length) : path\n}\n\nfunction alignPathToRoot(root: string, path: string): string {\n if (root.startsWith('/var/') && path.startsWith('/private/var/')) {\n return path.slice('/private'.length)\n }\n\n if (root.startsWith('/private/var/') && path.startsWith('/var/')) {\n return `/private${path}`\n }\n\n return path\n}\n","import { execFileSync } from 'node:child_process'\nimport type { RepoInfo } from './types.js'\n\nexport function collectRepoFingerprint(cwd: string): RepoInfo | null {\n const root = git(['rev-parse', '--show-toplevel'], cwd)\n if (root === null) {\n return null\n }\n\n return {\n root,\n remote: git(['config', '--get', 'remote.origin.url'], cwd) ?? '',\n branch: git(['branch', '--show-current'], cwd) ?? '',\n head: git(['rev-parse', 'HEAD'], cwd) ?? '',\n }\n}\n\nfunction git(args: readonly string[], cwd: string): string | null {\n try {\n return execFileSync('git', args, {\n cwd,\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n }).trim()\n } catch {\n return null\n }\n}\n","import { closeSync, openSync, readSync, realpathSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\nimport type { RunAgent } from './types.js'\n\nconst CODEX_METADATA_READ_BYTES = 256 * 1024\n\ninterface RawCodexSessionLine {\n readonly type?: unknown\n readonly payload?: unknown\n}\n\ninterface RawCodexSessionPayload {\n readonly cwd?: unknown\n}\n\nexport interface AgentSessionOptions {\n readonly agent: RunAgent\n readonly cwd: string\n readonly home: string\n readonly env: NodeJS.ProcessEnv\n readonly agentArgs: readonly string[]\n}\n\nexport function claudeProjectDir(cwd: string, home: string): string {\n return join(home, '.claude', 'projects', encodeClaudeProjectPath(cwd))\n}\n\nexport function encodeClaudeProjectPath(cwd: string): string {\n return cwd.replaceAll(/[^A-Za-z0-9]/g, '-')\n}\n\nexport function agentSessionDir(options: AgentSessionOptions): string {\n switch (options.agent) {\n case 'claude':\n return claudeProjectDir(options.cwd, options.home)\n case 'codex':\n return codexSessionsDir(options.home, options.env)\n }\n}\n\nexport function agentSessionCandidateFilter(\n options: AgentSessionOptions,\n): ((path: string) => boolean) | undefined {\n switch (options.agent) {\n case 'claude':\n return undefined\n case 'codex': {\n const expectedCwd = expectedCodexCwd(options.cwd, options.agentArgs)\n return (path: string) => {\n try {\n const sessionCwd = codexSessionCwd(path)\n return sessionCwd !== null && sameCodexCwd(sessionCwd, expectedCwd)\n } catch {\n return false\n }\n }\n }\n }\n}\n\nexport function agentKnownSessionFile(options: AgentSessionOptions): string | undefined {\n switch (options.agent) {\n case 'claude': {\n const sessionId =\n claudeSessionIdArg(options.agentArgs) ??\n (claudeForkSessionArg(options.agentArgs) ? undefined : claudeResumeSessionIdArg(options.agentArgs))\n return sessionId === undefined ? undefined : join(claudeProjectDir(options.cwd, options.home), `${sessionId}.jsonl`)\n }\n case 'codex':\n return undefined\n }\n}\n\nexport function codexSessionsDir(home: string, env: NodeJS.ProcessEnv = {}): string {\n return join(codexHome(home, env), 'sessions')\n}\n\nexport function codexHome(home: string, env: NodeJS.ProcessEnv = {}): string {\n const { CODEX_HOME: configured } = env\n return hasValue(configured) ? configured : join(home, '.codex')\n}\n\nexport function expectedCodexCwd(cwd: string, agentArgs: readonly string[]): string {\n const cd = codexCdArg(agentArgs)\n return cd === undefined ? resolve(cwd) : resolve(cwd, cd)\n}\n\nexport function claudeSessionIdArg(agentArgs: readonly string[]): string | undefined {\n const optionArgs = claudeOptionArgs(agentArgs)\n for (let index = 0; index < optionArgs.length; index += 1) {\n const arg = optionArgs[index] as string\n\n if (arg === '--session-id') {\n return optionArgs[index + 1]\n }\n\n if (arg.startsWith('--session-id=')) {\n return arg.slice('--session-id='.length)\n }\n }\n\n return undefined\n}\n\nexport function claudeResumeSessionIdArg(agentArgs: readonly string[]): string | undefined {\n const optionArgs = claudeOptionArgs(agentArgs)\n for (let index = 0; index < optionArgs.length; index += 1) {\n const arg = optionArgs[index] as string\n\n if (arg === '--resume' || arg === '-r') {\n const value = optionArgs[index + 1]\n return isUuid(value) ? value : undefined\n }\n\n if (arg.startsWith('--resume=')) {\n const value = arg.slice('--resume='.length)\n return isUuid(value) ? value : undefined\n }\n }\n\n return undefined\n}\n\nexport function isClaudeResumeInvocation(agentArgs: readonly string[]): boolean {\n for (const arg of claudeOptionArgs(agentArgs)) {\n if (\n arg === '--continue' ||\n arg === '-c' ||\n arg === '--resume' ||\n arg === '-r' ||\n arg.startsWith('--resume=') ||\n arg === '--from-pr' ||\n arg.startsWith('--from-pr=')\n ) {\n return true\n }\n }\n\n return false\n}\n\nexport function codexSessionCwd(path: string): string | null {\n const text = readFilePrefix(path, CODEX_METADATA_READ_BYTES)\n for (const line of text.split('\\n')) {\n const cwd = codexLineCwd(line)\n if (cwd !== null) {\n return cwd\n }\n }\n\n return null\n}\n\nfunction codexCdArg(agentArgs: readonly string[]): string | undefined {\n const optionArgs = codexOptionArgs(agentArgs)\n for (let index = 0; index < optionArgs.length; index += 1) {\n const arg = optionArgs[index] as string\n\n if (arg === '--cd' || arg === '-C') {\n return optionArgs[index + 1]\n }\n\n if (arg.startsWith('--cd=')) {\n return arg.slice('--cd='.length)\n }\n }\n\n return undefined\n}\n\nfunction codexOptionArgs(agentArgs: readonly string[]): readonly string[] {\n const separatorIndex = agentArgs.indexOf('--')\n return separatorIndex === -1 ? agentArgs : agentArgs.slice(0, separatorIndex)\n}\n\nfunction sameCodexCwd(left: string, right: string): boolean {\n return normalizeCodexCwd(left) === normalizeCodexCwd(right)\n}\n\nfunction normalizeCodexCwd(path: string): string {\n try {\n return realpathSync(path)\n } catch {\n return resolve(path)\n }\n}\n\nfunction claudeForkSessionArg(agentArgs: readonly string[]): boolean {\n return claudeOptionArgs(agentArgs).includes('--fork-session')\n}\n\nfunction claudeOptionArgs(agentArgs: readonly string[]): readonly string[] {\n const separatorIndex = agentArgs.indexOf('--')\n return separatorIndex === -1 ? agentArgs : agentArgs.slice(0, separatorIndex)\n}\n\nfunction isUuid(value: string | undefined): value is string {\n return (\n value !== undefined &&\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{12}$/i.test(value)\n )\n}\n\nfunction codexLineCwd(line: string): string | null {\n if (line.trim() === '') {\n return null\n }\n\n let value: unknown\n try {\n value = JSON.parse(line)\n } catch {\n return null\n }\n\n const entry = rawCodexSessionLine(value)\n if (entry === null) {\n return null\n }\n\n const type = entry.type\n if (type !== 'session_meta' && type !== 'turn_context') {\n return null\n }\n\n const payload = rawCodexSessionPayload(entry.payload)\n const cwd = payload?.cwd\n return typeof cwd === 'string' ? cwd : null\n}\n\nfunction readFilePrefix(path: string, bytes: number): string {\n const fd = openSync(path, 'r')\n try {\n const buffer = Buffer.alloc(bytes)\n const read = readSync(fd, buffer, 0, bytes, 0)\n return buffer.subarray(0, read).toString('utf8')\n } finally {\n closeSync(fd)\n }\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null\n}\n\nfunction rawCodexSessionLine(value: unknown): RawCodexSessionLine | null {\n return objectValue(value) as RawCodexSessionLine | null\n}\n\nfunction rawCodexSessionPayload(value: unknown): RawCodexSessionPayload | null {\n return objectValue(value) as RawCodexSessionPayload | null\n}\n\nfunction hasValue(value: string | undefined): value is string {\n return value !== undefined && value !== ''\n}\n","import { Command } from 'commander'\nimport { type RunUploadOptions } from '../run/moxt-uploader.js'\nimport { runLocalAgent } from '../run/run-agent.js'\nimport type { RunAgent } from '../run/types.js'\nimport { printError } from '../utils/output.js'\n\ninterface RunCommandOptions {\n workspace?: string\n}\n\nexport function registerRunCommand(program: Command): void {\n program\n .command('run')\n .description('Run a local agent and capture its work as Moxt context')\n .option('-w, --workspace <workspaceId>', 'Workspace ID for upload mode')\n .argument('<agent>', 'Local agent to run: claude or codex')\n .argument('[agentArgs...]', 'Arguments passed to the local agent after --')\n .allowUnknownOption(true)\n .allowExcessArguments(true)\n .action(async (agentArg: string, agentArgs: string[] | undefined, options: RunCommandOptions) => {\n const agent = parseAgent(agentArg)\n const upload = resolveUploadOptions(options)\n const exitCode = await runLocalAgentOrExit(agent, agentArgs ?? [], upload)\n process.exit(exitCode)\n })\n}\n\nfunction parseAgent(agent: string): RunAgent {\n if (agent === 'claude' || agent === 'codex') {\n return agent\n }\n printError(`Error: moxt run supports only \"claude\" or \"codex\", got \"${agent}\".`)\n process.exit(1)\n}\n\nfunction resolveUploadOptions(options: RunCommandOptions): RunUploadOptions | undefined {\n const workspaceId = resolveWorkspaceId(options)\n if (workspaceId === undefined) {\n return undefined\n }\n\n if (!process.env.MOXT_API_KEY) {\n printError('Error: MOXT_API_KEY is required when using moxt run upload mode with -w/--workspace or MOXT_WORKSPACE_ID.')\n process.exit(1)\n }\n\n return {\n workspaceId,\n }\n}\n\nfunction resolveWorkspaceId(options: RunCommandOptions): string | undefined {\n return normalizeWorkspaceId(options.workspace) ?? normalizeWorkspaceId(process.env.MOXT_WORKSPACE_ID)\n}\n\nfunction normalizeWorkspaceId(value: string | undefined): string | undefined {\n const trimmed = value?.trim()\n return trimmed === undefined || trimmed === '' ? undefined : trimmed\n}\n\nasync function runLocalAgentOrExit(\n agent: RunAgent,\n agentArgs: readonly string[],\n upload: RunUploadOptions | undefined,\n): Promise<number> {\n return await runLocalAgent({\n agent,\n agentArgs,\n ...(upload === undefined ? {} : { upload }),\n })\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\n\nexport interface TelemetryConfig {\n disabled?: boolean\n noticeShown?: boolean\n}\n\nfunction getConfigPath(): string {\n return path.join(os.homedir(), '.moxt', 'config.json')\n}\n\nexport function readTelemetryConfig(): TelemetryConfig {\n try {\n const raw = fs.readFileSync(getConfigPath(), 'utf8')\n const parsed = JSON.parse(raw) as { telemetry?: TelemetryConfig }\n return parsed.telemetry ?? {}\n } catch {\n return {}\n }\n}\n\nexport function writeTelemetryConfig(update: Partial<TelemetryConfig>): void {\n const configPath = getConfigPath()\n let existing: Record<string, unknown> = {}\n try {\n existing = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>\n } catch {\n existing = {}\n }\n const currentTelemetry = (existing.telemetry as TelemetryConfig | undefined) ?? {}\n const next = { ...existing, telemetry: { ...currentTelemetry, ...update } }\n fs.mkdirSync(path.dirname(configPath), { recursive: true })\n fs.writeFileSync(configPath, JSON.stringify(next, null, 2))\n}\n","import { readTelemetryConfig } from './config.js'\n\nexport function isCiEnvironment(): boolean {\n return process.env.CI === 'true' || process.env.CI === '1'\n}\n\nexport function isTelemetryDisabled(): boolean {\n if (process.env.MOXT_TELEMETRY_DISABLED === '1' || process.env.MOXT_TELEMETRY_DISABLED === 'true') {\n return true\n }\n if (process.env.DO_NOT_TRACK === '1' || process.env.DO_NOT_TRACK === 'true') {\n return true\n }\n return readTelemetryConfig().disabled === true\n}\n","import { Command } from 'commander'\nimport { readTelemetryConfig, writeTelemetryConfig } from '../telemetry/config.js'\nimport { isTelemetryDisabled } from '../telemetry/opt-out.js'\nimport { print } from '../utils/output.js'\n\nexport function registerTelemetryCommand(program: Command): void {\n const telemetry = program.command('telemetry').description('Manage Moxt CLI telemetry')\n\n telemetry\n .command('status')\n .description('Show telemetry status')\n .action(() => {\n const cfg = readTelemetryConfig()\n const envOverride =\n process.env.MOXT_TELEMETRY_DISABLED === '1' ||\n process.env.MOXT_TELEMETRY_DISABLED === 'true' ||\n process.env.DO_NOT_TRACK === '1' ||\n process.env.DO_NOT_TRACK === 'true'\n\n const state = isTelemetryDisabled() ? 'disabled' : 'enabled'\n print(`telemetry: ${state}`)\n if (envOverride) {\n print('(disabled via environment variable)')\n } else if (cfg.disabled) {\n print('(disabled via config file)')\n }\n })\n\n telemetry\n .command('enable')\n .description('Enable telemetry')\n .action(() => {\n writeTelemetryConfig({ disabled: false })\n print('telemetry: enabled')\n })\n\n telemetry\n .command('disable')\n .description('Disable telemetry')\n .action(() => {\n writeTelemetryConfig({ disabled: true })\n print('telemetry: disabled')\n })\n}\n","import { Command } from 'commander'\nimport { httpGet } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WhoamiResponse {\n nickname: string\n email: string\n}\n\nexport function registerWhoamiCommand(program: Command): void {\n program\n .command('whoami')\n .description('Show current user information')\n .action(async () => {\n startSpinner('Fetching user info...')\n const response = await httpGet<WhoamiResponse>('/users/whoami')\n\n if (response.ok) {\n stopSpinner(true, 'Done')\n print(`${colors.bold}Nickname${colors.reset}: ${response.data.nickname}`)\n print(`${colors.bold}Email${colors.reset}: ${response.data.email}`)\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\nimport { httpGet, httpDelete } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WorkspaceItem {\n workspaceId: string\n name: string\n}\n\ninterface WorkspaceListResponse {\n workspaces: WorkspaceItem[]\n}\n\ninterface MemberItem {\n userId: number\n email: string\n displayName: string | null\n role: string\n}\n\ninterface MembersResponse {\n members: MemberItem[]\n}\n\ninterface SpaceItem {\n type: 'personal' | 'team' | 'teammate'\n name: string\n teamSpaceId: string | null\n agentId: number | null\n}\n\n// Email regex (same as web/src/utils/email.ts)\nconst emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/\n\nfunction isValidEmail(email: string): boolean {\n return emailRegex.test(email)\n}\n\nexport function registerWorkspaceCommand(program: Command): void {\n const workspace = program.command('workspace').description('Workspace management')\n\n workspace\n .command('list')\n .description('List all workspaces you belong to')\n .action(async () => {\n startSpinner('Fetching workspaces...')\n const response = await httpGet<WorkspaceListResponse>('/workspaces')\n\n if (response.ok) {\n const { workspaces } = response.data\n if (workspaces.length === 0) {\n stopSpinner(true, 'No workspaces found.')\n return\n }\n\n stopSpinner(true, `Found ${workspaces.length} workspace(s)`)\n\n for (const ws of workspaces) {\n print(`${colors.bold}${ws.workspaceId}${colors.reset}\\t${ws.name}`)\n }\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n\n const members = program.command('members').description('Manage workspace members')\n\n members\n .command('list')\n .description('List all members in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching workspace members...')\n const response = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { members } = response.data\n if (members.length === 0) {\n stopSpinner(true, 'No members found.')\n return\n }\n\n stopSpinner(true, `Found ${members.length} member(s)`)\n\n for (const member of members) {\n const name = member.displayName || '-'\n print(`${colors.bold}${member.email}${colors.reset}\\t${name}\\t${member.role}`)\n }\n })\n\n members\n .command('remove')\n .description('Remove members from a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .argument('<emails>', 'Emails to remove (comma-separated)')\n .action(async (emailsArg: string, options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n const emails = emailsArg.split(',').map((e) => e.trim()).filter(Boolean)\n if (emails.length === 0) {\n printError('No valid emails provided')\n process.exit(1)\n }\n\n // Validate email format\n const invalidEmails = emails.filter((e) => !isValidEmail(e))\n if (invalidEmails.length > 0) {\n for (const email of invalidEmails) {\n printError(`Invalid email format: ${email}`)\n }\n process.exit(1)\n }\n\n // Fetch members to get userId by email\n startSpinner('Fetching workspace members...')\n const membersResponse = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!membersResponse.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${membersResponse.status}]: ${JSON.stringify(membersResponse.data)}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Members fetched')\n\n const { members } = membersResponse.data\n const emailToMember = new Map(members.map((m) => [m.email.toLowerCase(), m]))\n\n // Remove each member\n for (const email of emails) {\n const member = emailToMember.get(email.toLowerCase())\n if (!member) {\n print(`${colors.red}✗${colors.reset} ${email} - not found in workspace`)\n continue\n }\n\n const deleteResponse = await httpDelete(`/workspaces/${workspaceId}/members/${member.userId}`)\n\n if (deleteResponse.ok) {\n print(`${colors.green}✓${colors.reset} ${email} - removed`)\n } else {\n print(`${colors.red}✗${colors.reset} ${email} - failed: ${JSON.stringify(deleteResponse.data)}`)\n }\n }\n })\n\n const space = program.command('space').description('Manage spaces')\n\n space\n .command('list')\n .description('List accessible spaces in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching spaces...')\n const response = await httpGet<{ spaces: SpaceItem[] }>(`/workspaces/${workspaceId}/spaces`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch spaces')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { spaces } = response.data\n if (spaces.length === 0) {\n stopSpinner(true, 'No spaces found.')\n return\n }\n\n stopSpinner(true, `Found ${spaces.length} space(s)`)\n\n print(\n `${colors.bold}TYPE${colors.reset}\\t${colors.bold}TEAM_SPACE_ID${colors.reset}\\t${colors.bold}TEAMMATE_ID${colors.reset}\\t${colors.bold}NAME${colors.reset}`,\n )\n for (const s of spaces) {\n const teamSpaceId = s.teamSpaceId ?? ''\n const teammateId = s.agentId != null ? String(s.agentId) : ''\n print(`${s.type}\\t${teamSpaceId}\\t${teammateId}\\t${s.name}`)\n }\n })\n\n}\n","import { arch, platform } from 'node:os'\nimport { getApiBaseUrl, getApiKeyOrUndefined } from '../utils/config.js'\nimport { isCiEnvironment, isTelemetryDisabled } from './opt-out.js'\n\ndeclare const __CLI_VERSION__: string\n\nexport type MetricType = 'counter' | 'gauge' | 'histogram'\n\nexport interface MetricRecord {\n metric_id: string\n metric_type: MetricType\n value: number\n extra_label_name_2_value?: Record<string, string>\n}\n\nconst buffer: MetricRecord[] = []\nconst FLUSH_TIMEOUT_MS = 3000\nconst MAX_BATCH_SIZE = 100\n\nfunction commonLabels(): Record<string, string> {\n return {\n cli_version: __CLI_VERSION__,\n node_version: process.versions.node,\n os: platform(),\n arch: arch(),\n is_ci: isCiEnvironment() ? 'true' : 'false',\n }\n}\n\nexport function record(metric: MetricRecord): void {\n if (isTelemetryDisabled()) {\n debugLog(`record: disabled, dropping ${metric.metric_id}`)\n return\n }\n if (!getApiKeyOrUndefined()) {\n debugLog(`record: no API key, dropping ${metric.metric_id}`)\n return\n }\n buffer.push({\n ...metric,\n extra_label_name_2_value: {\n ...commonLabels(),\n ...(metric.extra_label_name_2_value ?? {}),\n },\n })\n debugLog(`record: buffered ${metric.metric_id} (buffer=${buffer.length})`)\n}\n\nfunction isDebug(): boolean {\n return process.env.MOXT_TELEMETRY_DEBUG === '1' || process.env.MOXT_TELEMETRY_DEBUG === 'true'\n}\n\nfunction debugLog(msg: string, detail?: unknown): void {\n if (!isDebug()) return\n process.stderr.write(`[telemetry] ${msg}${detail !== undefined ? ` ${JSON.stringify(detail)}` : ''}\\n`)\n}\n\nexport async function flush(): Promise<void> {\n if (buffer.length === 0) {\n debugLog('flush: buffer empty, skipping')\n return\n }\n const apiKey = getApiKeyOrUndefined()\n if (!apiKey) {\n debugLog('flush: no API key, dropping buffer')\n buffer.length = 0\n return\n }\n\n const batch = buffer.splice(0, MAX_BATCH_SIZE)\n const payload = {\n release_id: __CLI_VERSION__,\n client_type: 'cli',\n metric_data_list: batch.map((m) => ({\n profile: 'cli',\n metric_id: m.metric_id,\n metric_type: m.metric_type,\n value: m.value,\n extra_label_name_2_value: m.extra_label_name_2_value,\n })),\n }\n\n const url = `${getApiBaseUrl()}/cli-metrics`\n debugLog(`flush: POST ${url} with ${batch.length} metrics`, payload)\n\n try {\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, FLUSH_TIMEOUT_MS)\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n })\n debugLog(`flush: response status=${res.status}`)\n } finally {\n clearTimeout(timeout)\n }\n } catch (err) {\n debugLog('flush: failed', err instanceof Error ? err.message : String(err))\n // fire-and-forget — never surface telemetry failures to the user\n }\n}\n","import { readTelemetryConfig, writeTelemetryConfig } from './config.js'\nimport { isCiEnvironment, isTelemetryDisabled } from './opt-out.js'\n\nconst NOTICE = [\n '',\n 'Attention: Moxt CLI now collects anonymous telemetry regarding usage.',\n \"This information is used to shape Moxt CLI's roadmap and prioritize features.\",\n '',\n 'You may opt out by setting MOXT_TELEMETRY_DISABLED=1 in your env',\n 'or by running `moxt telemetry disable`.',\n 'Details: https://www.npmjs.com/package/@moxt-ai/cli#telemetry',\n '',\n]\n\nexport function maybeShowTelemetryNotice(): void {\n if (isTelemetryDisabled()) return\n if (isCiEnvironment()) return\n if (readTelemetryConfig().noticeShown) return\n\n for (const line of NOTICE) {\n process.stderr.write(`${line}\\n`)\n }\n\n try {\n writeTelemetryConfig({ noticeShown: true })\n } catch {\n // persistence failure is not user-visible — we'll just show the notice again next run\n }\n}\n","import type { Command } from 'commander'\nimport { flush, record } from './client.js'\nimport { maybeShowTelemetryNotice } from './notice.js'\n\ninterface RunningCommand {\n name: string\n subcommand?: string\n startedAt: number\n}\n\nlet current: RunningCommand | null = null\n\nfunction commandPath(cmd: Command): { command: string; subcommand?: string } {\n const names: string[] = []\n let node: Command | null = cmd\n while (node && node.parent) {\n names.unshift(node.name())\n node = node.parent\n }\n if (names.length === 0) return { command: 'unknown' }\n if (names.length === 1) return { command: names[0] }\n return { command: names[0], subcommand: names.slice(1).join(' ') }\n}\n\nexport function instrumentProgram(program: Command): void {\n program.hook('preAction', (_thisCommand, actionCommand) => {\n const { command, subcommand } = commandPath(actionCommand)\n if (command !== 'telemetry') {\n maybeShowTelemetryNotice()\n }\n current = { name: command, subcommand, startedAt: Date.now() }\n record({\n metric_id: 'client.cli.command_invocation.count',\n metric_type: 'counter',\n value: 1,\n extra_label_name_2_value: {\n command,\n ...(subcommand ? { subcommand } : {}),\n status: 'started',\n },\n })\n })\n\n program.hook('postAction', async () => {\n await reportOutcome('success')\n })\n}\n\nasync function reportOutcome(status: 'success' | 'error', errorCode?: string): Promise<void> {\n if (!current) return\n const { name, subcommand, startedAt } = current\n const durationSeconds = (Date.now() - startedAt) / 1000\n\n record({\n metric_id: 'client.cli.command_duration_seconds',\n metric_type: 'histogram',\n value: durationSeconds,\n extra_label_name_2_value: {\n command: name,\n ...(subcommand ? { subcommand } : {}),\n status,\n },\n })\n\n if (status === 'error') {\n record({\n metric_id: 'client.cli.command_error.count',\n metric_type: 'counter',\n value: 1,\n extra_label_name_2_value: {\n command: name,\n ...(subcommand ? { subcommand } : {}),\n ...(errorCode ? { error_code: errorCode } : {}),\n },\n })\n }\n\n current = null\n await flush()\n}\n\n/**\n * Wire a final error/exit hook. Call before program.parseAsync so we can capture\n * failures routed through process.exit or unhandled rejections.\n *\n * Best-effort only: `reportOutcome` is fire-and-forget, and the subsequent\n * `process.exit(1)` terminates the process before `flush()` can complete — so\n * the error metric recorded here will typically be dropped. Reliable crash\n * reporting belongs to Sentry/APM, not this telemetry path.\n */\nexport function installExitHandler(): void {\n const handleError = (errorCode: string): void => {\n void reportOutcome('error', errorCode)\n }\n\n process.on('uncaughtException', () => {\n handleError('uncaught_exception')\n process.exit(1)\n })\n process.on('unhandledRejection', () => {\n handleError('unhandled_rejection')\n process.exit(1)\n })\n}\n"],"mappings":";;;AAAA,OAAO,oBAAoB;;;ACA3B,SAAS,eAA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AAAA,MACnC;AAAA,IACJ;AAAA,EACJ,CAAC;AAED,MAAI,WAAW,SAAS;AACpB,WAAO;AAAA,MACH,WAAW;AAAA,MACX,aAAa;AAAA,MACb,OAAO;AAAA,MACP,0BAA0B;AAAA,QACtB,SAAS;AAAA,QACT,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;AAAA,QACnC,GAAI,YAAY,EAAE,YAAY,UAAU,IAAI,CAAC;AAAA,MACjD;AAAA,IACJ,CAAC;AAAA,EACL;AAEA,YAAU;AACV,QAAM,MAAM;AAChB;AAWO,SAAS,qBAA2B;AACvC,QAAM,cAAc,CAAC,cAA4B;AAC7C,SAAK,cAAc,SAAS,SAAS;AAAA,EACzC;AAEA,UAAQ,GAAG,qBAAqB,MAAM;AAClC,gBAAY,oBAAoB;AAChC,YAAQ,KAAK,CAAC;AAAA,EAClB,CAAC;AACD,UAAQ,GAAG,sBAAsB,MAAM;AACnC,gBAAY,qBAAqB;AACjC,YAAQ,KAAK,CAAC;AAAA,EAClB,CAAC;AACL;;;AjChGA,eAAe;AAAA,EACX,KAAK,EAAE,MAAM,gBAAgB,SAAS,mBAAgB;AAC1D,CAAC,EAAE,OAAO;AAEV,IAAM,UAAU,cAAc,kBAAe;AAE7C,kBAAkB,OAAO;AACzB,mBAAmB;AAEnB,QACK,WAAW,QAAQ,IAAI,EACvB,KAAK,YAAY;AACd,QAAM,MAAM;AAChB,CAAC,EACA,MAAM,OAAO,QAAiB;AAC3B,UAAQ,MAAM,cAAc,GAAG;AAC/B,QAAM,MAAM;AACZ,UAAQ,KAAK,CAAC;AAClB,CAAC;","names":["path","buffer","path","program","path","buffer","program","path","runOrExit","path","program","closeSync","openSync","readSync","homedir","path","uploadFile","flush","existsSync","statSync","join","path","current","stat","writeFile","join","DATA_FILE_TARGET_BYTES","matched","jsonlLines","writeFile","join","file","path","stat","buffer","readdir","readFile","writeFile","arch","platform","join","DEFAULT_HOST","errorMessage","path","join","readFile","readdir","isObject","writeFile","platform","arch","relative","path","execFileSync","join","path","hasValue","path","buffer","objectValue","hasValue","homedir","errorMessage","resolve","readFileFromOffset","path","openSync","stat","buffer","readSync","closeSync","program","fs","program","program","program","members","program","arch","platform","platform","arch","program"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/program.ts","../src/utils/output.ts","../src/utils/runtime-context.ts","../src/utils/sandbox-path.ts","../src/commands/auth.ts","../src/commands/file.ts","../src/utils/file-selector.ts","../src/utils/http.ts","../src/utils/config.ts","../src/utils/search-options.ts","../src/utils/run-or-exit.ts","../src/utils/sandbox-client.ts","../src/utils/sandbox-file.ts","../src/utils/spinner.ts","../src/utils/write-content.ts","../src/commands/memory.ts","../src/utils/miniapp-db.ts","../src/commands/miniapp.ts","../src/commands/pull.ts","../src/utils/sandbox-pull.ts","../src/utils/checkout-state.ts","../src/utils/sandbox-push.ts","../src/utils/concurrency.ts","../src/commands/push.ts","../src/utils/checkout-status.ts","../src/commands/status.ts","../src/telemetry/config.ts","../src/telemetry/opt-out.ts","../src/commands/telemetry.ts","../src/commands/whoami.ts","../src/commands/workspace.ts","../src/telemetry/client.ts","../src/telemetry/notice.ts","../src/telemetry/instrument.ts"],"sourcesContent":["import updateNotifier from 'update-notifier'\nimport { createProgram } from './program.js'\nimport { flush } from './telemetry/client.js'\nimport { installExitHandler, instrumentProgram } from './telemetry/instrument.js'\n\ndeclare const __CLI_VERSION__: string\n\nupdateNotifier({\n pkg: { name: '@moxt-ai/cli', version: __CLI_VERSION__ },\n}).notify()\n\nconst program = createProgram(__CLI_VERSION__)\n\ninstrumentProgram(program)\ninstallExitHandler()\n\nprogram\n .parseAsync(process.argv)\n .then(async () => {\n await flush()\n })\n .catch(async (err: unknown) => {\n console.error('CLI Error:', err)\n await flush()\n process.exit(1)\n })\n","import { Command } from 'commander'\nimport { registerAuthCommand } from './commands/auth.js'\nimport { registerFileCommand } from './commands/file.js'\nimport { registerMemoryCommand } from './commands/memory.js'\nimport { registerMiniappCommand } from './commands/miniapp.js'\nimport { registerPullCommand } from './commands/pull.js'\nimport { registerPushCommand } from './commands/push.js'\nimport { registerStatusCommand } from './commands/status.js'\nimport { registerTelemetryCommand } from './commands/telemetry.js'\nimport { registerWhoamiCommand } from './commands/whoami.js'\nimport { registerWorkspaceCommand } from './commands/workspace.js'\n\nexport function createProgram(version: string): Command {\n const program = new Command()\n\n program\n .name('moxt')\n .description('Moxt CLI - AI Workspace')\n .version(version)\n .action(() => {\n program.help()\n })\n\n registerAuthCommand(program)\n registerWhoamiCommand(program)\n registerWorkspaceCommand(program)\n registerFileCommand(program)\n registerMemoryCommand(program)\n registerMiniappCommand(program)\n registerPullCommand(program)\n registerPushCommand(program)\n registerStatusCommand(program)\n registerTelemetryCommand(program)\n\n return program\n}\n","// ANSI colors\nexport const colors = {\n bold: '\\x1b[1m',\n blue: '\\x1b[1;34m',\n green: '\\x1b[32m',\n red: '\\x1b[31m',\n cyan: '\\x1b[36m',\n dim: '\\x1b[2m',\n reset: '\\x1b[0m',\n}\n\nexport function print(message: string): void {\n console.log(message)\n}\n\nexport function printError(message: string): void {\n console.error(`${colors.red}${message}${colors.reset}`)\n}\n","export interface RepoEntry {\n repoId: string\n name: string\n}\n\nexport interface RepoPayload {\n teams: RepoEntry[]\n personal: RepoEntry\n workspace?: RepoEntry | null\n}\n\nexport interface SandboxRuntimeContext {\n mode: 'sandbox'\n baseApiHost: string\n sandboxToolApiToken: string\n workspaceId: string\n repoPayload: RepoPayload\n}\n\nexport interface UserRuntimeContext {\n mode: 'user'\n host: string\n apiKey: string\n}\n\nexport type RuntimeContext = SandboxRuntimeContext | UserRuntimeContext\n\nconst DEFAULT_USER_HOST = 'api.moxt.ai'\nexport const SANDBOX_ENV_KEYS = [\n 'BASE_API_HOST',\n 'SANDBOX_TOOL_API_TOKEN',\n 'MOXT_REPO_PAYLOAD',\n 'MOXT_WORKSPACE_ID',\n] as const\n\nexport class RuntimeContextError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'RuntimeContextError'\n }\n}\n\nexport function resolveRuntimeContext(env: NodeJS.ProcessEnv = process.env): RuntimeContext {\n if (hasAnySandboxEnv(env)) {\n return resolveSandboxRuntimeContext(env)\n }\n\n const apiKey = readNonEmptyEnv(env, 'MOXT_API_KEY')\n if (apiKey) {\n return {\n mode: 'user',\n host: readNonEmptyEnv(env, 'MOXT_HOST') ?? DEFAULT_USER_HOST,\n apiKey,\n }\n }\n\n throw new RuntimeContextError('Missing auth. Set sandbox environment variables or MOXT_API_KEY.')\n}\n\nexport function resolveSandboxRuntimeContext(env: NodeJS.ProcessEnv = process.env): SandboxRuntimeContext {\n const missingKeys = SANDBOX_ENV_KEYS.filter((key) => !readNonEmptyEnv(env, key))\n if (missingKeys.length > 0) {\n throw new RuntimeContextError(`Incomplete sandbox environment. Missing: ${missingKeys.join(', ')}.`)\n }\n\n return {\n mode: 'sandbox',\n baseApiHost: normalizeBaseApiHost(readRequiredEnv(env, 'BASE_API_HOST')),\n sandboxToolApiToken: readRequiredEnv(env, 'SANDBOX_TOOL_API_TOKEN'),\n workspaceId: readRequiredEnv(env, 'MOXT_WORKSPACE_ID'),\n repoPayload: parseRepoPayload(readRequiredEnv(env, 'MOXT_REPO_PAYLOAD')),\n }\n}\n\nexport function parseRepoPayload(raw: string): RepoPayload {\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (error) {\n throw new RuntimeContextError(`MOXT_REPO_PAYLOAD must be valid JSON: ${error instanceof Error ? error.message : String(error)}`)\n }\n\n if (!isRecord(parsed)) {\n throw new RuntimeContextError('MOXT_REPO_PAYLOAD must be a JSON object.')\n }\n\n const personal = parseRepoEntry(parsed.personal, 'personal')\n const teamsValue = parsed.teams\n if (!Array.isArray(teamsValue)) {\n throw new RuntimeContextError('MOXT_REPO_PAYLOAD.teams must be an array.')\n }\n const teams = teamsValue.map((entry, index) => parseRepoEntry(entry, `teams[${index}]`))\n const workspace = parsed.workspace == null ? null : parseRepoEntry(parsed.workspace, 'workspace')\n\n return { personal, teams, workspace }\n}\n\nexport function normalizeBaseApiHost(value: string): string {\n const trimmed = value.trim()\n if (!trimmed) {\n throw new RuntimeContextError('BASE_API_HOST must not be empty.')\n }\n return trimmed.replace(/\\/+$/, '')\n}\n\nfunction hasAnySandboxEnv(env: NodeJS.ProcessEnv): boolean {\n return SANDBOX_ENV_KEYS.some((key) => readNonEmptyEnv(env, key) !== undefined)\n}\n\nfunction readRequiredEnv(env: NodeJS.ProcessEnv, key: string): string {\n const value = readNonEmptyEnv(env, key)\n if (!value) {\n throw new RuntimeContextError(`${key} is required.`)\n }\n return value\n}\n\nfunction readNonEmptyEnv(env: NodeJS.ProcessEnv, key: string): string | undefined {\n const value = env[key]\n if (typeof value !== 'string') return undefined\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : undefined\n}\n\nfunction parseRepoEntry(value: unknown, path: string): RepoEntry {\n if (!isRecord(value)) {\n throw new RuntimeContextError(`MOXT_REPO_PAYLOAD.${path} must be an object.`)\n }\n const repoId = readStringField(value, 'repoId', path)\n const name = readStringField(value, 'name', path)\n return { repoId, name }\n}\n\nfunction readStringField(record: Record<string, unknown>, field: string, path: string): string {\n const value = record[field]\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new RuntimeContextError(`MOXT_REPO_PAYLOAD.${path}.${field} must be a non-empty string.`)\n }\n return value\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n","import type { RepoEntry, RepoPayload } from './runtime-context.js'\n\nexport interface ResolvedWorkspacePath {\n repoId: string\n repoName: string\n repoPath: string\n}\n\nexport class WorkspacePathError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'WorkspacePathError'\n }\n}\n\nexport function resolveWorkspacePath(repoPayload: RepoPayload, workspacePath: string): ResolvedWorkspacePath {\n const normalizedPath = normalizeWorkspacePath(workspacePath)\n const [repoName, ...repoPathParts] = normalizedPath.split('/')\n const repoEntries = listRepoEntries(repoPayload)\n const repo = repoEntries.find((entry) => entry.name === repoName)\n\n if (!repo) {\n throw new WorkspacePathError(`Workspace path must start with one of: ${repoEntries.map((entry) => entry.name).join(', ')}.`)\n }\n\n return {\n repoId: repo.repoId,\n repoName: repo.name,\n repoPath: repoPathParts.join('/'),\n }\n}\n\nexport function listRepoEntries(repoPayload: RepoPayload): RepoEntry[] {\n return [\n repoPayload.personal,\n ...repoPayload.teams,\n ...(repoPayload.workspace ? [repoPayload.workspace] : []),\n ]\n}\n\nfunction normalizeWorkspacePath(workspacePath: string): string {\n const trimmed = workspacePath.trim()\n if (!trimmed) {\n throw new WorkspacePathError('Workspace path must not be empty.')\n }\n if (trimmed.startsWith('/')) {\n throw new WorkspacePathError('Workspace path must be relative.')\n }\n\n const parts = trimmed.split('/').filter((part) => part.length > 0 && part !== '.')\n if (parts.length === 0) {\n throw new WorkspacePathError('Workspace path must include a repo name.')\n }\n if (parts.some((part) => part === '..')) {\n throw new WorkspacePathError('Workspace path must not contain \"..\".')\n }\n\n return parts.join('/')\n}\n","import { Command } from 'commander'\nimport { colors, print, printError } from '../utils/output.js'\nimport { resolveRuntimeContext, RuntimeContextError } from '../utils/runtime-context.js'\nimport { listRepoEntries } from '../utils/sandbox-path.js'\n\nexport function registerAuthCommand(program: Command): void {\n const auth = program.command('auth').description('Authentication utilities')\n\n auth.command('status')\n .description('Show CLI authentication mode')\n .action(() => {\n try {\n const context = resolveRuntimeContext()\n if (context.mode === 'sandbox') {\n print(`${colors.bold}Mode${colors.reset}: sandbox`)\n print(`${colors.bold}Workspace${colors.reset}: ${context.workspaceId}`)\n print(`${colors.bold}Base API${colors.reset}: ${context.baseApiHost}`)\n print(`${colors.bold}Repos${colors.reset}:`)\n for (const repo of listRepoEntries(context.repoPayload)) {\n print(` ${repo.name}\\t${repo.repoId}`)\n }\n return\n }\n\n print(`${colors.bold}Mode${colors.reset}: user`)\n print(`${colors.bold}Host${colors.reset}: ${context.host}`)\n } catch (error) {\n if (error instanceof RuntimeContextError) {\n printError(error.message)\n process.exit(1)\n }\n throw error\n }\n })\n}\n","import * as fs from 'node:fs'\nimport { Command } from 'commander'\nimport {\n buildFileQueryString,\n isBinaryContent,\n resolveReadMode,\n resolveSpaceSelector,\n resolveWriteMode,\n SpaceOptions,\n SpaceOptionsError,\n} from '../utils/file-selector.js'\nimport { httpDelete, httpGet, httpPost, httpPut } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport {\n resolveRuntimeContext,\n RuntimeContextError,\n SANDBOX_ENV_KEYS,\n type RuntimeContext,\n} from '../utils/runtime-context.js'\nimport { runOrExit } from '../utils/run-or-exit.js'\nimport { SandboxApiError } from '../utils/sandbox-client.js'\nimport {\n MFS_FILE_SIZE_LIMIT_LABEL,\n MFS_FILE_SIZE_LIMIT_BYTES,\n readSandboxFile,\n SandboxFileError,\n type SandboxFileWritePolicy,\n writeSandboxFile,\n} from '../utils/sandbox-file.js'\nimport { parseSearchLimit, parseSearchMode } from '../utils/search-options.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\nimport { readWriteCommandContentOrExit } from '../utils/write-content.js'\n\ninterface FileEntry {\n name: string\n type: 'file' | 'directory'\n size: number | null\n}\n\ninterface FileReadResponse {\n path: string\n type: 'file' | 'directory'\n entries: FileEntry[] | null\n content: string | null\n}\n\ninterface FileWriteResponse {\n path: string\n created: boolean\n}\n\ninterface MkdirResponse {\n path: string\n created: boolean\n}\n\ninterface DeleteResponse {\n path: string\n}\n\ninterface FileUrlResponse {\n path: string\n url: string\n}\n\ninterface FieldHighlight {\n text: string\n}\n\ninterface SemanticSnippet {\n content: string\n}\n\ninterface FileSearchItem {\n repoId: string\n fileId: string\n filePath: string\n rank: number\n contentHighlight?: FieldHighlight\n filePathHighlight?: FieldHighlight\n semanticSnippets: SemanticSnippet[]\n}\n\ninterface FileSearchResponse {\n items: FileSearchItem[]\n}\n\ninterface LocalTextFile {\n content: string\n}\n\nfunction addSpaceOptions(cmd: Command): Command {\n return cmd\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n}\n\nexport function registerFileCommand(program: Command): void {\n const file = program.command('file').description('File operations')\n\n addSpaceOptions(\n file.command('search')\n .description('Search files in accessible spaces')\n .argument('<query>', 'Search query')\n .option('-l, --limit <limit>', 'Maximum number of files to return', '30')\n .option('--mode <mode>', 'Keyword matching mode: any or all', 'any'),\n ).action(async (query: string, options: SpaceOptions & { limit?: string; mode?: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const limit = runOrExit(() => parseSearchLimit(options.limit, 30, 80))\n const mode = runOrExit(() => parseSearchMode(options.mode))\n\n startSpinner('Searching files...')\n const response = await httpPost<FileSearchResponse>(\n `/workspaces/${options.workspace}/files/search`,\n {\n query,\n limit,\n mode,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { items } = response.data\n if (items.length === 0) {\n stopSpinner(true, 'No files found.')\n return\n }\n\n stopSpinner(true, `Found ${items.length} file(s)`)\n for (const item of items) {\n print(`${colors.bold}${item.rank}. ${item.filePath}${colors.reset}`)\n print(`${colors.dim}repo=${item.repoId} file=${item.fileId}${colors.reset}`)\n const snippet = item.contentHighlight?.text ?? item.semanticSnippets[0]?.content\n if (snippet) {\n print(snippet)\n }\n print('')\n }\n })\n\n addSpaceOptions(\n file.command('get-url')\n .description('Resolve the shareable browser URL for a file')\n .requiredOption('-p, --path <path>', 'File path'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Resolving URL...')\n const response = await httpGet<FileUrlResponse>(\n `/workspaces/${options.workspace}/files/url${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, response.data.path)\n print(`${colors.cyan}${response.data.url}${colors.reset}`)\n })\n\n addSpaceOptions(\n file.command('list')\n .description('List directory contents')\n .option('-p, --path <path>', 'Directory path', '/'),\n ).action(async (options: SpaceOptions & { path: string }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n const qs = buildFileQueryString(options.path, spaceParams)\n\n startSpinner('Listing files...')\n const response = await httpGet<FileReadResponse>(\n `/workspaces/${options.workspace}/files/list${qs}`,\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${options.path} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { path, entries } = response.data\n\n if (!entries || entries.length === 0) {\n stopSpinner(true, `${path}: empty directory`)\n return\n }\n\n stopSpinner(true, path)\n for (const entry of entries) {\n if (entry.type === 'directory') {\n print(`${colors.blue}${entry.name}/${colors.reset}`)\n } else {\n print(entry.name)\n }\n }\n })\n\n file.command('read')\n .description('Read file content')\n .argument('[workspacePath]', 'Workspace path in sandbox mode, e.g. personal/docs/readme.md')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'File path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .option('--json', 'Print sandbox file content and metadata as JSON')\n .action(async (\n workspacePath: string | undefined,\n options: Partial<SpaceOptions> & { path?: string; url?: string; json?: boolean },\n ) => {\n const sandboxRuntime = resolveSandboxRuntimeContextOrExit()\n if (sandboxRuntime) {\n if (options.url) {\n printError('--url cannot be used in sandbox mode')\n process.exit(1)\n }\n const path = workspacePath ?? options.path\n if (!path) {\n printError('Workspace path is required in sandbox mode')\n process.exit(1)\n }\n\n if (!options.json) startSpinner('Reading file...')\n try {\n const result = await readSandboxFile(sandboxRuntime, path)\n if (options.json) {\n print(JSON.stringify(result, null, 2))\n } else {\n stopSpinner(true, 'Done')\n print(result.content)\n }\n } catch (error) {\n handleSandboxFileError(error, path)\n }\n return\n }\n\n if (options.json) {\n printError('--json is only available for sandbox workspace paths')\n process.exit(1)\n }\n\n if (workspacePath && !options.path) {\n options.path = workspacePath\n }\n const mode = runOrExit(() => resolveReadMode(options))\n\n startSpinner('Reading file...')\n\n let response: { ok: boolean; status: number; data: FileReadResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpGet<FileReadResponse>(\n `/files/read-by-url?url=${encodeURIComponent(mode.url)}`,\n )\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n const qs = buildFileQueryString(mode.path, spaceParams)\n response = await httpGet<FileReadResponse>(\n `/workspaces/${mode.workspace}/files/read${qs}`,\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const { type, content } = response.data\n\n if (type === 'directory') {\n stopSpinner(false, 'Failed')\n print(`${colors.red}☠ ${displayPath} is a directory${colors.reset}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Done')\n print(content ?? '')\n })\n\n file.command('put')\n .description('Upload a file')\n .argument('[workspacePath]', 'Workspace path in sandbox mode, e.g. personal/docs/readme.md')\n .option('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('-s, --space <name>', 'Space name (personal or teamspace name)')\n .option('--personal', 'Use personal space (default)')\n .option('--team-space-id <teamSpaceId>', 'Team space ID')\n .option('--teammate-id <teammateId>', 'Teammate ID (teammate space)')\n .option('-p, --path <path>', 'Remote file path')\n .option('-u, --url <url>', 'Moxt file URL (e.g., https://moxt.ai/w/{workspaceId}/{fileId})')\n .requiredOption('-l, --local-path <localPath>', 'Local file path')\n .option('-r, --recursive', 'Create parent directories if needed')\n .action(\n async (\n workspacePath: string | undefined,\n options: Partial<SpaceOptions> & {\n path?: string\n url?: string\n localPath: string\n recursive?: boolean\n },\n ) => {\n const sandboxRuntime = resolveSandboxRuntimeContextOrExit()\n\n if (sandboxRuntime) {\n if (options.url) {\n printError('--url cannot be used in sandbox mode')\n process.exit(1)\n }\n const path = workspacePath ?? options.path\n if (!path) {\n printError('Workspace path is required in sandbox mode')\n process.exit(1)\n }\n const { content } = readLocalTextFileOrExit(options.localPath)\n\n startSpinner('Uploading...')\n try {\n const response = await writeSandboxFile(sandboxRuntime, path, content, {\n type: 'use-current-sha',\n })\n const action = response.created ? 'Created' : 'Updated'\n stopSpinner(true, `${action}: ${response.path}`)\n } catch (error) {\n handleSandboxFileError(error, path)\n }\n return\n }\n\n if (workspacePath && !options.path) {\n options.path = workspacePath\n }\n const mode = runOrExit(() => resolveWriteMode(options))\n const { content } = readLocalTextFileOrExit(options.localPath)\n\n startSpinner('Uploading...')\n\n let response: { ok: boolean; status: number; data: FileWriteResponse }\n let displayPath: string\n\n if (mode.kind === 'by-url') {\n displayPath = mode.url\n response = await httpPut<FileWriteResponse>('/files/write-by-url', {\n url: mode.url,\n content,\n })\n } else {\n displayPath = mode.path\n const spaceParams = runOrExit(() => resolveSpaceSelector(options as SpaceOptions))\n response = await httpPut<FileWriteResponse>(\n `/workspaces/${mode.workspace}/files/write`,\n {\n path: mode.path,\n content,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n }\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n if (mode.kind === 'by-url') {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n }\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Updated'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n file.command('write')\n .description('Write file content in sandbox mode')\n .argument('<workspacePath>', 'Workspace path, e.g. personal/docs/readme.md')\n .option('--content <content>', 'Text content to write')\n .option('--content-file <contentFile>', 'Local text file to write')\n .option('--stdin', 'Read text content from stdin (default)')\n .option('--base-sha <sha>', 'Write only if the remote file still has this SHA')\n .option('--force', 'Overwrite an existing remote file without a version condition')\n .action(async (\n workspacePath: string,\n options: {\n content?: string\n contentFile?: string\n stdin?: boolean\n baseSha?: string\n force?: boolean\n },\n ) => {\n const runtime = resolveSandboxRuntimeContextOrExit()\n if (!runtime) {\n printError('file write is only available in sandbox mode')\n process.exit(1)\n }\n\n const policy = resolveSandboxFileWritePolicyOrExit(options)\n const content = readWriteCommandContentOrExit(options, (path) => readLocalTextFileOrExit(path).content)\n startSpinner('Writing file...')\n try {\n const response = await writeSandboxFile(runtime, workspacePath, content, policy)\n const action = response.created ? 'Created' : 'Updated'\n stopSpinner(true, `${action}: ${response.path}`)\n } catch (error) {\n handleSandboxFileError(error, workspacePath)\n }\n })\n\n addSpaceOptions(\n file.command('mkdir')\n .description('Create a directory')\n .requiredOption('-p, --path <path>', 'Directory path')\n .option('-r, --recursive', 'Create parent directories if needed'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n recursive?: boolean\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Creating directory...')\n const response = await httpPost<MkdirResponse>(\n `/workspaces/${options.workspace}/files/mkdir`,\n {\n path: options.path,\n recursive: options.recursive ?? false,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Parent directory does not exist${colors.reset}`)\n } else if (response.status === 400) {\n printError(`Error: ${JSON.stringify(response.data)}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n const action = response.data.created ? 'Created' : 'Already exists'\n stopSpinner(true, `${action}: ${response.data.path}`)\n },\n )\n\n addSpaceOptions(\n file.command('del')\n .description('Delete a file or empty directory')\n .requiredOption('-p, --path <path>', 'File or directory path'),\n ).action(\n async (options: SpaceOptions & {\n path: string\n }) => {\n const spaceParams = runOrExit(() => resolveSpaceSelector(options))\n\n startSpinner('Deleting...')\n const response = await httpDelete<DeleteResponse>(\n `/workspaces/${options.workspace}/files/delete`,\n {\n path: options.path,\n ...spaceParams,\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n if (response.status === 404) {\n print(`${colors.red}☠ Path not found: ${options.path}${colors.reset}`)\n } else if (response.status === 400) {\n print(`${colors.red}☠ Cannot delete non-empty directory${colors.reset}`)\n } else {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n }\n process.exit(1)\n }\n\n stopSpinner(true, `Deleted: ${response.data.path}`)\n },\n )\n}\n\nfunction resolveSandboxFileWritePolicyOrExit(options: {\n baseSha?: string\n force?: boolean\n}): SandboxFileWritePolicy {\n if (options.baseSha && options.force) {\n printError('Only one of --base-sha or --force can be used')\n process.exit(1)\n }\n if (options.baseSha) {\n if (!/^[a-f0-9]{64}$/.test(options.baseSha)) {\n printError('--base-sha must be a lowercase SHA-256 hash')\n process.exit(1)\n }\n return { type: 'base-sha', sha: options.baseSha }\n }\n return options.force ? { type: 'force' } : { type: 'create-only' }\n}\n\nfunction resolveRuntimeContextOrExit(): RuntimeContext {\n try {\n return resolveRuntimeContext()\n } catch (error) {\n if (error instanceof RuntimeContextError) {\n printError(error.message)\n process.exit(1)\n }\n throw error\n }\n}\n\nfunction resolveSandboxRuntimeContextOrExit(): Extract<RuntimeContext, { mode: 'sandbox' }> | undefined {\n // Keep user-mode file commands on their existing OpenAPI path when no sandbox env is present.\n if (!SANDBOX_ENV_KEYS.some((key) => (process.env[key] ?? '').trim().length > 0)) {\n return undefined\n }\n const context = resolveRuntimeContextOrExit()\n return context.mode === 'sandbox' ? context : undefined\n}\n\nfunction readLocalTextFileOrExit(localPath: string): LocalTextFile {\n if (!fs.existsSync(localPath)) {\n print(`${colors.red}☠ Local file not found: ${localPath}${colors.reset}`)\n process.exit(1)\n }\n\n const stats = fs.statSync(localPath)\n if (!stats.isFile()) {\n print(`${colors.red}☠ Not a file: ${localPath}${colors.reset}`)\n process.exit(1)\n }\n\n if (stats.size > MFS_FILE_SIZE_LIMIT_BYTES) {\n print(`${colors.red}☠ File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${localPath}${colors.reset}`)\n process.exit(1)\n }\n\n const buffer = fs.readFileSync(localPath)\n if (isBinaryContent(buffer)) {\n print(`${colors.red}☠ Binary files are not allowed. Only text files can be uploaded.${colors.reset}`)\n process.exit(1)\n }\n\n return { content: buffer.toString('utf8') }\n}\n\nfunction handleSandboxFileError(error: unknown, displayPath: string): never {\n stopSpinner(false, 'Failed')\n if (error instanceof SandboxFileError) {\n if (error.code === 'not-found') {\n print(`${colors.red}☠ ${displayPath} does not exist${colors.reset}`)\n } else if (error.code === 'directory') {\n print(`${colors.red}☠ ${displayPath} is a directory${colors.reset}`)\n } else {\n printError(error.message)\n }\n process.exit(1)\n }\n if (error instanceof SandboxApiError) {\n printError(`Sandbox API error [${error.status}]: ${error.body}`)\n process.exit(1)\n }\n if (error instanceof Error) {\n printError(`Sandbox file operation failed: ${error.message}`)\n process.exit(1)\n }\n printError(`Sandbox file operation failed: ${String(error)}`)\n process.exit(1)\n}\n","/**\n * Pure logic for resolving file-command space selectors and building request URLs.\n *\n * These functions are extracted from commands/file.ts so they can be unit tested\n * without spawning the CLI or mocking process.exit. All error conditions are\n * surfaced as thrown Errors; action handlers are responsible for turning them\n * into user-facing output and exit codes.\n */\n\nexport interface SpaceOptions {\n workspace: string\n space?: string\n personal?: boolean\n teamSpaceId?: string\n teammateId?: string\n}\n\nexport interface SpaceParams {\n space?: string\n teamSpaceId?: string\n agentId?: number\n}\n\n/**\n * Error thrown when selector options violate a contract (mutually exclusive,\n * wrong format, etc). Action handlers catch this and print the message before\n * exiting with code 1.\n */\nexport class SpaceOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SpaceOptionsError'\n }\n}\n\n/**\n * Resolve mutually-exclusive space selector flags into normalized request params.\n *\n * Priority (only one must be set): --team-space-id > --teammate-id > --personal > -s <name>.\n * When none is set, returns empty params (server treats this as personal space).\n */\nexport function resolveSpaceSelector(options: SpaceOptions): SpaceParams {\n // Destructure first so TypeScript's control-flow analysis can narrow each\n // field through the subsequent non-null / non-empty checks without having\n // to re-read options.* at the point of use (which would lose narrowing).\n const { space, teamSpaceId, teammateId } = options\n const personalIsSet = options.personal === true\n\n // Count \"user-set\" selectors explicitly so the mutual-exclusion check\n // reflects intent (\"which flags did the user pass?\") rather than a\n // generic truthiness filter. This keeps the mutual-exclusion check\n // cleanly separated from the downstream format validation (e.g.\n // `parsed <= 0` for teammateId).\n const spaceIsSet = space != null && space !== ''\n const teamSpaceIdIsSet = teamSpaceId != null && teamSpaceId !== ''\n const teammateIdIsSet = teammateId != null && teammateId !== ''\n const selectorCount =\n (spaceIsSet ? 1 : 0) + (personalIsSet ? 1 : 0) + (teamSpaceIdIsSet ? 1 : 0) + (teammateIdIsSet ? 1 : 0)\n if (selectorCount > 1) {\n throw new SpaceOptionsError(\n 'Error: -s, --personal, --team-space-id, and --teammate-id are mutually exclusive.',\n )\n }\n\n // Dispatch via the underlying field checks (not `*IsSet`) so TypeScript\n // narrows each local to `string`, letting us return without `!`.\n if (teamSpaceId != null && teamSpaceId !== '') {\n return { teamSpaceId }\n }\n if (teammateId != null && teammateId !== '') {\n const parsed = Number.parseInt(teammateId, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== teammateId) {\n throw new SpaceOptionsError(\n `Error: --teammate-id must be a positive integer, got \"${teammateId}\".`,\n )\n }\n return { agentId: parsed }\n }\n if (personalIsSet) {\n return { space: 'personal' }\n }\n if (space != null && space !== '') {\n return { space }\n }\n return {}\n}\n\n/**\n * Build the `?path=...&space=...` query string for file endpoints.\n * Returns empty string when no params are set (caller should not append `?`).\n * Values are URL-encoded via URLSearchParams.\n *\n * An empty-string `path` is treated as \"not provided\" and omitted from the query;\n * callers should pass `undefined` rather than `\"\"` when no path is intended.\n */\nexport function buildFileQueryString(path: string | undefined, spaceParams: SpaceParams): string {\n const params = new URLSearchParams()\n if (path != null && path !== '') {\n params.set('path', path)\n }\n if (spaceParams.space) {\n params.set('space', spaceParams.space)\n }\n if (spaceParams.teamSpaceId) {\n params.set('teamSpaceId', spaceParams.teamSpaceId)\n }\n if (spaceParams.agentId != null) {\n params.set('agentId', String(spaceParams.agentId))\n }\n const qs = params.toString()\n return qs ? `?${qs}` : ''\n}\n\n/**\n * Detect if a Buffer contains binary content by sampling the first 8192 bytes.\n * Control characters other than tab (9), LF (10), and CR (13) are treated as binary.\n */\nexport function isBinaryContent(buffer: Buffer): boolean {\n const sampleSize = Math.min(buffer.length, 8192)\n\n for (let i = 0; i < sampleSize; i++) {\n const byte = buffer[i]\n if (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) {\n return true\n }\n }\n\n return false\n}\n\n/**\n * Validate `file read` command's top-level mutually-exclusive options (-u vs -w/-p).\n * Returns the resolved mode ('by-url' or 'by-path'). Throws SpaceOptionsError on conflict.\n *\n * Empty strings are treated as \"not provided\" (commander never passes empty strings\n * for optional flags, but callers outside the CLI context should pass undefined instead\n * of \"\" to avoid unexpected branch behaviour).\n */\nexport type ReadMode = { kind: 'by-url'; url: string } | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveReadMode(options: {\n url?: string\n workspace?: string\n path?: string\n}): ReadMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n // At this point both workspace and path are guaranteed non-empty by the guards\n // above. Use explicit checks so TypeScript narrows the types without needing `!`.\n if (!options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n return { kind: 'by-path', workspace: options.workspace, path: options.path }\n}\n\n/**\n * Validate `file put` command's top-level mutually-exclusive options (-u vs -w/-p).\n *\n * By-URL puts overwrite an existing file (the URL already identifies it), so\n * `--recursive` is meaningless in that mode and is rejected outright to keep the\n * user's intent unambiguous.\n */\nexport type WriteMode =\n | { kind: 'by-url'; url: string }\n | { kind: 'by-path'; workspace: string; path: string }\n\nexport function resolveWriteMode(options: {\n url?: string\n workspace?: string\n path?: string\n recursive?: boolean\n}): WriteMode {\n if (options.url && options.workspace) {\n throw new SpaceOptionsError('Error: --url cannot be used with --workspace')\n }\n if (options.url && options.path) {\n throw new SpaceOptionsError('Error: --url cannot be used with --path')\n }\n if (options.url && options.recursive) {\n throw new SpaceOptionsError('Error: --recursive cannot be used with --url (the file must already exist)')\n }\n if (!options.url && !options.workspace) {\n throw new SpaceOptionsError('Error: Either --url or --workspace is required')\n }\n if (!options.url && !options.path) {\n throw new SpaceOptionsError('Error: --path is required when not using --url')\n }\n\n if (options.url) {\n return { kind: 'by-url', url: options.url }\n }\n return { kind: 'by-path', workspace: options.workspace!, path: options.path! }\n}\n","import { arch, platform } from 'os'\nimport { getApiBaseUrl, getApiKey } from './config.js'\n\ndeclare const __CLI_VERSION__: string\n\nexport interface ApiResponse<T> {\n ok: boolean\n status: number\n data: T\n}\n\nexport interface RawApiResponse {\n ok: boolean\n status: number\n text: string\n contentType: string | null\n}\n\nfunction getUserAgent(): string {\n return `moxt-cli/${__CLI_VERSION__} (${platform()}/${arch()}) node/${process.versions.node}`\n}\n\nasync function fetchApi(method: string, path: string, body?: unknown): Promise<Response> {\n const apiKey = getApiKey()\n const url = `${getApiBaseUrl()}${path}`\n\n const response = await fetch(url, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n 'User-Agent': getUserAgent(),\n },\n body: body ? JSON.stringify(body) : undefined,\n })\n\n if (response.status === 401) {\n console.error('Authentication failed. Check your MOXT_API_KEY.')\n console.error('Get a new key at: https://moxt.ai')\n process.exit(1)\n }\n\n return response\n}\n\nasync function request<T>(method: string, path: string, body?: unknown): Promise<ApiResponse<T>> {\n const response = await fetchApi(method, path, body)\n const contentType = response.headers.get('content-type')\n const data = contentType?.includes('application/json') ? ((await response.json()) as T) : ((await response.text()) as T)\n\n return {\n ok: response.ok,\n status: response.status,\n data,\n }\n}\n\nexport async function httpGet<T>(path: string): Promise<ApiResponse<T>> {\n return request<T>('GET', path)\n}\n\nexport async function httpPut<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('PUT', path, body)\n}\n\nexport async function httpPost<T>(path: string, body: unknown): Promise<ApiResponse<T>> {\n return request<T>('POST', path, body)\n}\n\nexport async function httpDelete<T>(path: string, body?: unknown): Promise<ApiResponse<T>> {\n return request<T>('DELETE', path, body)\n}\n\nexport async function httpRaw(method: 'GET' | 'POST' | 'PATCH' | 'DELETE', path: string, body?: unknown): Promise<RawApiResponse> {\n const response = await fetchApi(method, path, body)\n return {\n ok: response.ok,\n status: response.status,\n text: await response.text(),\n contentType: response.headers.get('content-type'),\n }\n}\n","const DEFAULT_HOST = 'api.moxt.ai'\n\nexport function getApiBaseUrl(): string {\n const host = process.env.MOXT_HOST ?? DEFAULT_HOST\n return `https://${host}/openapi/v1`\n}\n\nexport function getApiKey(): string {\n const apiKey = process.env.MOXT_API_KEY\n\n if (!apiKey) {\n console.error('MOXT_API_KEY environment variable is not set.')\n console.error('')\n console.error('Get your API key at: https://moxt.ai')\n console.error('')\n console.error('Then set it:')\n console.error(' export MOXT_API_KEY=moxt_...')\n process.exit(1)\n }\n\n return apiKey\n}\n\nexport function getApiKeyOrUndefined(): string | undefined {\n return process.env.MOXT_API_KEY\n}\n","export class SearchOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SearchOptionsError'\n }\n}\n\nexport function parseSearchLimit(raw: string | undefined, defaultValue: number, max: number): number {\n if (raw == null || raw === '') {\n return defaultValue\n }\n const parsed = Number.parseInt(raw, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {\n throw new SearchOptionsError(`Error: --limit must be a positive integer, got \"${raw}\".`)\n }\n if (parsed > max) {\n throw new SearchOptionsError(`Error: --limit must be less than or equal to ${max}.`)\n }\n return parsed\n}\n\nexport function parseSearchMode(raw: string | undefined): 'all' | 'any' {\n if (raw == null || raw === '') {\n return 'any'\n }\n if (raw === 'all' || raw === 'any') {\n return raw\n }\n throw new SearchOptionsError(`Error: --mode must be \"any\" or \"all\", got \"${raw}\".`)\n}\n\nexport function parseTeammateId(raw: string | undefined): number | undefined {\n if (raw == null || raw === '') {\n return undefined\n }\n const parsed = Number.parseInt(raw, 10)\n if (!Number.isInteger(parsed) || parsed <= 0 || String(parsed) !== raw) {\n throw new SearchOptionsError(`Error: --teammate-id must be a positive integer, got \"${raw}\".`)\n }\n return parsed\n}\n","import { SpaceOptionsError } from './file-selector.js'\nimport { printError } from './output.js'\nimport { SearchOptionsError } from './search-options.js'\n\n/**\n * Call a pure resolver that may throw a known CLI option error; on error,\n * print the message and exit(1). This keeps the user-facing contract\n * (stderr + exit code 1) consistent across subcommands while letting the\n * resolvers stay pure and unit-testable.\n */\nexport function runOrExit<T>(fn: () => T): T {\n try {\n return fn()\n } catch (err) {\n if (err instanceof SpaceOptionsError || err instanceof SearchOptionsError) {\n printError(err.message)\n process.exit(1)\n }\n throw err\n }\n}\n","import type { SandboxRuntimeContext } from './runtime-context.js'\n\nexport interface SandboxApiResponse<T> {\n status: number\n data: T\n}\n\nexport interface SandboxApiRequestOptions {\n timeoutMs?: number\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000\n\nexport class SandboxApiError extends Error {\n readonly status: number\n readonly body: string\n\n constructor(status: number, body: string) {\n super(`Sandbox API request failed with ${status}: ${body}`)\n this.name = 'SandboxApiError'\n this.status = status\n this.body = body\n }\n}\n\nexport class SandboxMoxtClient {\n constructor(private readonly context: SandboxRuntimeContext) {}\n\n async request<T>(\n method: 'GET' | 'POST' | 'PUT' | 'DELETE',\n path: string,\n body?: unknown,\n options: SandboxApiRequestOptions = {},\n ): Promise<SandboxApiResponse<T>> {\n const signal = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)\n const response = await fetch(`${this.context.baseApiHost}${path}`, {\n method,\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${this.context.sandboxToolApiToken}`,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n })\n\n const contentType = response.headers.get('content-type')\n const data = contentType?.includes('application/json') ? ((await response.json()) as T) : ((await response.text()) as T)\n\n if (!response.ok) {\n throw new SandboxApiError(response.status, typeof data === 'string' ? data : JSON.stringify(data))\n }\n\n return {\n status: response.status,\n data,\n }\n }\n}\n","import { createHash } from 'node:crypto'\nimport { SandboxMoxtClient } from './sandbox-client.js'\nimport type { PresignUrlsResponse } from './sandbox-mfs-types.js'\nimport type { SandboxRuntimeContext } from './runtime-context.js'\nimport { resolveWorkspacePath } from './sandbox-path.js'\n\nconst MFS_FILE_TYPE_REGULAR = 1\nexport const MFS_FILE_SIZE_LIMIT_BYTES = 10 * 1024 * 1024\nexport const MFS_FILE_SIZE_LIMIT_LABEL = `${MFS_FILE_SIZE_LIMIT_BYTES / (1024 * 1024)}MB`\n\ninterface UnifiedPushResponse {\n repoVersions: Record<string, number>\n fileMap: Record<string, Record<string, string>>\n}\n\ninterface SandboxResolvedFilePath {\n repoId: string\n repoName: string\n repoPath: string\n}\n\ninterface RepoTreeEntry {\n path: string\n type: 'blob' | 'tree'\n size: number | null\n sha: string | null\n fileId: string | null\n fileType: number | null\n}\n\ninterface RepoTreeResponse {\n sha: string\n entries: RepoTreeEntry[]\n}\n\nexport interface SandboxFileReadResult {\n path: string\n content: string\n sha: string\n size: number\n fileId: string | null\n fileType: number | null\n}\n\nexport type SandboxFileWritePolicy =\n | { type: 'base-sha'; sha: string }\n | { type: 'create-only' }\n | { type: 'force' }\n | { type: 'use-current-sha' }\n\nexport class SandboxFileError extends Error {\n constructor(\n message: string,\n readonly code: 'not-found' | 'directory' | 'invalid-path' | 'remote' | 'too-large' | 'conflict',\n ) {\n super(message)\n this.name = 'SandboxFileError'\n }\n}\n\nexport async function readSandboxFile(\n context: SandboxRuntimeContext,\n workspacePath: string,\n): Promise<SandboxFileReadResult> {\n const resolved = resolveSandboxFilePath(context, workspacePath)\n const tree = await fetchRepoTree(context, resolved)\n const entry = findTreeEntry(tree, resolved)\n if (!entry) {\n throw new SandboxFileError(`${workspacePath} does not exist`, 'not-found')\n }\n if (entry.type === 'tree') {\n throw new SandboxFileError(`${workspacePath} is a directory`, 'directory')\n }\n if (!entry.sha) {\n throw new SandboxFileError(`${workspacePath} does not have downloadable content`, 'remote')\n }\n if (entry.size !== null && entry.size > MFS_FILE_SIZE_LIMIT_BYTES) {\n throw new SandboxFileError(`File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${workspacePath}`, 'too-large')\n }\n\n const client = new SandboxMoxtClient(context)\n const presign = await client.request<PresignUrlsResponse>(\n 'POST',\n `/agent/api/pipeline-sandbox/mfs/${encodeURIComponent(resolved.repoId)}/presign-download`,\n { hashes: [entry.sha] },\n )\n const url = presign.data.urls[entry.sha]\n if (!url) {\n throw new SandboxFileError(`No download URL returned for ${workspacePath}`, 'remote')\n }\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new SandboxFileError(`Download failed [${response.status}]`, 'remote')\n }\n const content = await response.text()\n const data = Buffer.from(content, 'utf8')\n if (data.length > MFS_FILE_SIZE_LIMIT_BYTES) {\n throw new SandboxFileError(`File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${workspacePath}`, 'too-large')\n }\n const actualSha = createHash('sha256').update(data).digest('hex')\n if (actualSha !== entry.sha) {\n throw new SandboxFileError(`Downloaded content hash mismatch: ${workspacePath}`, 'remote')\n }\n return {\n path: workspacePath,\n content,\n sha: entry.sha,\n size: data.length,\n fileId: entry.fileId,\n fileType: entry.fileType,\n }\n}\n\nexport async function writeSandboxFile(\n context: SandboxRuntimeContext,\n workspacePath: string,\n content: string,\n policy: SandboxFileWritePolicy,\n): Promise<{ path: string; created: boolean }> {\n const data = Buffer.from(content, 'utf8')\n if (data.length > MFS_FILE_SIZE_LIMIT_BYTES) {\n throw new SandboxFileError(`File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${workspacePath}`, 'too-large')\n }\n\n const resolved = resolveSandboxFilePath(context, workspacePath)\n const tree = await fetchRepoTree(context, resolved)\n const existing = findTreeEntry(tree, resolved)\n if (existing?.type === 'tree') {\n throw new SandboxFileError(`${workspacePath} is a directory`, 'directory')\n }\n if (existing && !existing.sha) {\n throw new SandboxFileError(`${workspacePath} does not have base content hash`, 'remote')\n }\n const baseContentHash = resolveBaseContentHash(workspacePath, existing, policy)\n\n const contentHash = createHash('sha256').update(data).digest('hex')\n const client = new SandboxMoxtClient(context)\n const presign = await client.request<PresignUrlsResponse>(\n 'POST',\n `/agent/api/pipeline-sandbox/mfs/${encodeURIComponent(resolved.repoId)}/presign-upload`,\n { hashes: [contentHash] },\n )\n const uploadUrl = presign.data.urls[contentHash]\n if (!uploadUrl) {\n throw new SandboxFileError(`No upload URL returned for ${workspacePath}`, 'remote')\n }\n\n const upload = await fetch(uploadUrl, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/octet-stream' },\n body: new Uint8Array(data),\n })\n if (!upload.ok) {\n throw new SandboxFileError(`Upload failed [${upload.status}]`, 'remote')\n }\n\n const action = existing ? 'update' : 'create'\n await client.request<UnifiedPushResponse>(\n 'POST',\n '/agent/api/pipeline-sandbox/mfs-workspace/unified-push',\n {\n message: `moxt file write ${workspacePath}`,\n repoPushes: [\n {\n repoId: resolved.repoId,\n changes: [\n {\n action,\n ...(existing?.fileId ? { fileId: existing.fileId } : {}),\n path: resolved.repoPath,\n contentHash,\n ...(baseContentHash ? { baseContentHash } : {}),\n size: data.length,\n fileType: MFS_FILE_TYPE_REGULAR,\n },\n ],\n },\n ],\n crossRepoMoves: [],\n },\n )\n\n return { path: workspacePath, created: !existing }\n}\n\nfunction resolveBaseContentHash(\n workspacePath: string,\n existing: RepoTreeEntry | undefined,\n policy: SandboxFileWritePolicy,\n): string | undefined {\n if (policy.type === 'force') return undefined\n if (policy.type === 'use-current-sha') return existing?.sha ?? undefined\n if (policy.type === 'create-only') {\n if (!existing) return undefined\n throw new SandboxFileError(\n `Existing file requires --base-sha or --force: ${workspacePath} (actual ${existing.sha})`,\n 'conflict',\n )\n }\n if (existing?.sha === policy.sha) return policy.sha\n throw new SandboxFileError(\n `File version conflict: ${workspacePath} (expected ${policy.sha}, actual ${existing?.sha ?? 'missing'})`,\n 'conflict',\n )\n}\n\nfunction resolveSandboxFilePath(context: SandboxRuntimeContext, workspacePath: string): SandboxResolvedFilePath {\n let resolved: SandboxResolvedFilePath\n try {\n resolved = resolveWorkspacePath(context.repoPayload, workspacePath)\n } catch (error) {\n throw new SandboxFileError(error instanceof Error ? error.message : String(error), 'invalid-path')\n }\n if (!resolved.repoPath) {\n throw new SandboxFileError(`${workspacePath} is a directory`, 'directory')\n }\n return resolved\n}\n\nasync function fetchRepoTree(\n context: SandboxRuntimeContext,\n resolved: SandboxResolvedFilePath,\n): Promise<RepoTreeResponse> {\n const client = new SandboxMoxtClient(context)\n const params = new URLSearchParams({ entryFilter: 'paths', path: resolved.repoPath })\n const response = await client.request<RepoTreeResponse>(\n 'GET',\n `/agent/api/pipeline-sandbox/mfs/${encodeURIComponent(resolved.repoId)}/tree?${params.toString()}`,\n )\n return response.data\n}\n\nfunction findTreeEntry(tree: RepoTreeResponse, resolved: SandboxResolvedFilePath): RepoTreeEntry | undefined {\n return tree.entries.find((entry) => entry.path === resolved.repoPath)\n}\n","const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']\n\nlet intervalId: ReturnType<typeof setInterval> | null = null\nlet frameIndex = 0\n\nexport function startSpinner(message: string): void {\n frameIndex = 0\n process.stdout.write(`${frames[frameIndex]} ${message}`)\n\n intervalId = setInterval(() => {\n frameIndex = (frameIndex + 1) % frames.length\n process.stdout.write(`\\r${frames[frameIndex]} ${message}`)\n }, 80)\n}\n\nexport function stopSpinner(success: boolean, message?: string): void {\n if (intervalId) {\n clearInterval(intervalId)\n intervalId = null\n }\n\n const symbol = success ? '\\x1b[32m✓\\x1b[0m' : '\\x1b[31m✗\\x1b[0m'\n // \\x1b[2K 清除整行,\\r 回到行首\n process.stdout.write(`\\x1b[2K\\r${symbol} ${message ?? ''}\\n`)\n}\n","import * as fs from 'node:fs'\nimport { printError } from './output.js'\n\nexport function readWriteCommandContentOrExit(\n options: { content?: string; contentFile?: string; stdin?: boolean },\n readContentFile: (path: string) => string,\n readStdin: () => string = () => fs.readFileSync(0, 'utf8'),\n): string {\n const inputModes = [options.content !== undefined, options.contentFile !== undefined, options.stdin === true].filter(Boolean)\n if (inputModes.length > 1) {\n printError('Only one of --content, --content-file, or --stdin can be used')\n process.exit(1)\n }\n if (options.content !== undefined) {\n return options.content\n }\n if (options.contentFile !== undefined) {\n return readContentFile(options.contentFile)\n }\n return readStdin()\n}\n","import { Command } from 'commander'\nimport { httpPost } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { runOrExit } from '../utils/run-or-exit.js'\nimport { parseSearchLimit, parseTeammateId } from '../utils/search-options.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface MemorySearchItem {\n rank: number\n pipelineId: string\n chunkId: string\n chunkIndex: number\n content: string\n contentTruncated: boolean\n}\n\ninterface MemorySearchResponse {\n items: MemorySearchItem[]\n}\n\nexport function registerMemoryCommand(program: Command): void {\n const memory = program.command('memory').description('Memory operations')\n\n memory.command('search')\n .description('Search archived agent memory')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .option('--teammate-id <teammateId>', 'Search a managed AI teammate memory')\n .option('-l, --limit <limit>', 'Maximum number of memory chunks to return', '5')\n .argument('<query>', 'Search query')\n .action(\n async (\n query: string,\n options: {\n workspace: string\n teammateId?: string\n limit?: string\n },\n ) => {\n const limit = runOrExit(() => parseSearchLimit(options.limit, 5, 10))\n const teammateId = runOrExit(() => parseTeammateId(options.teammateId))\n\n startSpinner('Searching memory...')\n const response = await httpPost<MemorySearchResponse>(\n `/workspaces/${options.workspace}/memory/search`,\n {\n query,\n limit,\n ...(teammateId !== undefined ? { agentId: teammateId } : {}),\n },\n )\n\n if (!response.ok) {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { items } = response.data\n if (items.length === 0) {\n stopSpinner(true, 'No memory found.')\n return\n }\n\n stopSpinner(true, `Found ${items.length} memory chunk(s)`)\n for (const item of items) {\n print(`${colors.bold}${item.rank}. pipeline=${item.pipelineId} chunk=${item.chunkIndex}${colors.reset}`)\n print(`${colors.dim}chunkId=${item.chunkId}${item.contentTruncated ? ' truncated=true' : ''}${colors.reset}`)\n print(item.content)\n print('')\n }\n },\n )\n}\n","export class MiniappDbOptionsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'MiniappDbOptionsError'\n }\n}\n\nconst NON_FILTER_QUERY_PARAMS = new Set([\n 'select',\n 'order',\n 'limit',\n 'offset',\n 'range',\n 'range-unit',\n])\n\nconst ALLOWED_MINIAPP_DB_EMAIL_DOMAINS = ['@paraflow.com', '@moxt.ai', '@kanyun.com']\n\nexport function normalizePostgrestPath(path: string): string {\n const trimmed = path.trim()\n if (!trimmed) {\n throw new MiniappDbOptionsError('Error: PostgREST path is required.')\n }\n return trimmed.startsWith('/') ? trimmed : `/${trimmed}`\n}\n\nexport function buildMiniappDbDataPath(workspaceId: string, appId: string, postgrestPath: string): string {\n return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/data${normalizePostgrestPath(postgrestPath)}`\n}\n\nexport function buildMiniappDbSchemaPath(workspaceId: string, appId: string): string {\n return `/workspaces/${encodeURIComponent(workspaceId)}/miniapps/${encodeURIComponent(appId)}/db/schema`\n}\n\nexport function parseJsonBody(raw: string): unknown {\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error)\n throw new MiniappDbOptionsError(`Error: --body must be valid JSON. ${detail}`)\n }\n\n if (parsed === null || (typeof parsed !== 'object' && !Array.isArray(parsed))) {\n throw new MiniappDbOptionsError('Error: --body must be a JSON object or array.')\n }\n return parsed\n}\n\nexport function hasPostgrestFilter(postgrestPath: string): boolean {\n const normalizedPath = normalizePostgrestPath(postgrestPath)\n const parsed = new URL(normalizedPath, 'https://postgrest.local')\n for (const [name] of parsed.searchParams.entries()) {\n if (!NON_FILTER_QUERY_PARAMS.has(name.toLowerCase())) {\n return true\n }\n }\n return false\n}\n\nexport function assertPostgrestFilter(postgrestPath: string, method: 'PATCH' | 'DELETE'): void {\n if (!hasPostgrestFilter(postgrestPath)) {\n throw new MiniappDbOptionsError(\n `Error: ${method.toLowerCase()} requires at least one PostgREST filter query parameter.`,\n )\n }\n}\n\nexport function formatRawResponse(text: string, pretty?: boolean): string {\n if (!pretty || !text) {\n return text\n }\n try {\n return JSON.stringify(JSON.parse(text), null, 2)\n } catch {\n return text\n }\n}\n\nexport function isAllowedMiniappDbUserEmail(email: string): boolean {\n const normalized = email.trim().toLowerCase()\n return ALLOWED_MINIAPP_DB_EMAIL_DOMAINS.some((domain) => normalized.endsWith(domain))\n}\n","import { Command } from 'commander'\nimport {\n assertPostgrestFilter,\n buildMiniappDbDataPath,\n buildMiniappDbSchemaPath,\n formatRawResponse,\n isAllowedMiniappDbUserEmail,\n MiniappDbOptionsError,\n parseJsonBody,\n} from '../utils/miniapp-db.js'\nimport { httpGet, httpRaw } from '../utils/http.js'\nimport { print, printError } from '../utils/output.js'\n\ninterface MiniappDbOptions {\n workspace: string\n appId: string\n pretty?: boolean\n body?: string\n yes?: boolean\n}\n\ninterface MiniappDbSchemaResponse {\n sql: string\n}\n\ninterface WhoamiResponse {\n email: string\n}\n\nfunction runOrExit<T>(fn: () => T): T {\n try {\n return fn()\n } catch (err) {\n if (err instanceof MiniappDbOptionsError) {\n printError(err.message)\n process.exit(1)\n }\n throw err\n }\n}\n\nfunction addMiniappDbTargetOptions(command: Command): Command {\n return command\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .requiredOption('--app-id <appId>', 'Miniapp app ID')\n}\n\nfunction handleRawResponse(response: Awaited<ReturnType<typeof httpRaw>>, pretty?: boolean): void {\n if (!response.ok) {\n printError(`Error [${response.status}]: ${response.text}`)\n process.exit(1)\n }\n print(formatRawResponse(response.text, pretty))\n}\n\nasync function ensureAllowedMiniappDbUser(): Promise<void> {\n const response = await httpGet<WhoamiResponse>('/users/whoami')\n if (!response.ok) {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n if (!isAllowedMiniappDbUserEmail(response.data.email)) {\n printError('Error: miniapp db commands are only available to @paraflow.com, @moxt.ai, or @kanyun.com users.')\n process.exit(1)\n }\n}\n\nasync function requestDataApi(\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n postgrestPath: string,\n options: MiniappDbOptions,\n body?: unknown,\n): Promise<void> {\n await ensureAllowedMiniappDbUser()\n const path = buildMiniappDbDataPath(options.workspace, options.appId, postgrestPath)\n const response = await httpRaw(method, path, body)\n handleRawResponse(response, options.pretty)\n}\n\nexport function registerMiniappCommand(program: Command): void {\n const miniapp = program.command('miniapp', { hidden: true }).description('Miniapp operations')\n const db = miniapp.command('db').description('Miniapp database operations')\n\n addMiniappDbTargetOptions(\n db.command('schema').description('Print the miniapp database schema SQL'),\n ).action(async (options: MiniappDbOptions) => {\n await ensureAllowedMiniappDbUser()\n const response = await httpGet<MiniappDbSchemaResponse>(buildMiniappDbSchemaPath(options.workspace, options.appId))\n\n if (!response.ok) {\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n print(response.data.sql)\n })\n\n addMiniappDbTargetOptions(\n db.command('get')\n .description('Read miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path, for example /todos?select=*')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n await requestDataApi('GET', postgrestPath, options)\n })\n\n addMiniappDbTargetOptions(\n db.command('post')\n .description('Create miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path, for example /todos')\n .requiredOption('--body <json>', 'JSON object or array request body')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n const body = runOrExit(() => parseJsonBody(options.body ?? ''))\n await requestDataApi('POST', postgrestPath, options, body)\n })\n\n addMiniappDbTargetOptions(\n db.command('patch')\n .description('Update miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path with a filter, for example /todos?id=eq.1')\n .requiredOption('--body <json>', 'JSON object or array request body')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n runOrExit(() => assertPostgrestFilter(postgrestPath, 'PATCH'))\n const body = runOrExit(() => parseJsonBody(options.body ?? ''))\n await requestDataApi('PATCH', postgrestPath, options, body)\n })\n\n addMiniappDbTargetOptions(\n db.command('delete')\n .description('Delete miniapp data through PostgREST')\n .argument('<path>', 'PostgREST path with a filter, for example /todos?id=eq.1')\n .option('--yes', 'Confirm the delete operation')\n .option('--pretty', 'Pretty-print JSON responses'),\n ).action(async (postgrestPath: string, options: MiniappDbOptions) => {\n if (options.yes !== true) {\n printError('Error: delete requires --yes.')\n process.exit(1)\n }\n runOrExit(() => assertPostgrestFilter(postgrestPath, 'DELETE'))\n await requestDataApi('DELETE', postgrestPath, options)\n })\n}\n","import { isAbsolute } from 'node:path'\nimport { Command, Option } from 'commander'\nimport { print, printError } from '../utils/output.js'\nimport { resolveRuntimeContext, RuntimeContextError, type SandboxRuntimeContext } from '../utils/runtime-context.js'\nimport { pullSandboxWorkspace } from '../utils/sandbox-pull.js'\nimport { loadCheckoutState, type CheckoutState } from '../utils/checkout-state.js'\nimport { listRepoEntries } from '../utils/sandbox-path.js'\n\ninterface PullCommandOptions {\n all?: boolean\n dir?: string\n force?: boolean\n scope: string[]\n}\n\ninterface PullInvocation {\n scopes?: string[]\n targetDir: string\n}\n\nexport function registerPullCommand(program: Command): void {\n program\n .command('pull')\n .description('Pull workspace files into the local checkout')\n .argument('[workspacePath]', 'Workspace file or directory to pull')\n .option('--all', 'Pull the entire workspace')\n .option('--force', 'Overwrite changed local files')\n .addOption(new Option('--dir <dir>').hideHelp())\n .addOption(new Option('--scope <workspacePath>').argParser(collectScope).default([]).hideHelp())\n .action(async (workspacePath: string | undefined, options: PullCommandOptions) => {\n const context = resolveSandboxRuntimeContextOrExit()\n\n try {\n const invocation = await resolvePullInvocation(context, workspacePath, options)\n const result = await pullSandboxWorkspace(context, invocation.targetDir, {\n force: Boolean(options.force),\n scopes: invocation.scopes,\n })\n print(`Pulled ${result.fileCount} ${result.fileCount === 1 ? 'file' : 'files'} to ${result.targetDir}`)\n } catch (error) {\n handlePullError(error)\n }\n })\n}\n\nasync function resolvePullInvocation(\n context: SandboxRuntimeContext,\n argument: string | undefined,\n options: PullCommandOptions,\n): Promise<PullInvocation> {\n const legacyTargetDir = argument && isLegacyTargetDirectory(argument) ? argument : undefined\n const workspacePath = legacyTargetDir ? undefined : argument\n if (workspacePath && options.all) {\n throw new Error('Specify either a workspace path or --all, not both')\n }\n if (options.scope.length > 0 && (workspacePath || options.all)) {\n throw new Error('Legacy --scope cannot be combined with a workspace path or --all')\n }\n if (legacyTargetDir && options.dir) {\n throw new Error('Specify the local checkout directory only once')\n }\n\n const state = await loadCheckoutState()\n if (state) validateCheckoutStateContext(state, context)\n const targetDir = options.dir ?? legacyTargetDir ?? state?.checkoutRoot ?? '.'\n\n if (options.all || (legacyTargetDir && options.scope.length === 0)) {\n return { targetDir }\n }\n if (workspacePath) return { targetDir, scopes: [workspacePath] }\n if (options.scope.length > 0) return { targetDir, scopes: options.scope }\n if (!state || state.checkedOutScopes.length === 0) {\n throw new Error('Checkout is not initialized. Run moxt pull <workspace-path> or moxt pull --all first.')\n }\n return {\n targetDir: state.checkoutRoot,\n scopes: state.mode === 'full' ? undefined : state.checkedOutScopes,\n }\n}\n\nfunction isLegacyTargetDirectory(value: string): boolean {\n return value === '.' || value.startsWith('./') || value.startsWith('../') || isAbsolute(value)\n}\n\nfunction validateCheckoutStateContext(state: CheckoutState, context: SandboxRuntimeContext): void {\n if (state.workspaceId !== context.workspaceId) {\n throw new Error(`Checkout state belongs to workspace ${state.workspaceId}, not ${context.workspaceId}`)\n }\n const currentRepos = new Map(listRepoEntries(context.repoPayload).map((repo) => [repo.repoId, repo.name]))\n for (const [repoId, repo] of Object.entries(state.repos)) {\n const currentName = currentRepos.get(repoId)\n if (!currentName) throw new Error(`Checkout state contains unknown repo: ${repoId}`)\n if (currentName !== repo.name) {\n throw new Error(`Checkout state repo name does not match current workspace: ${repo.name}`)\n }\n }\n}\n\nfunction collectScope(value: string, previous: string[]): string[] {\n return [...previous, value]\n}\n\nfunction resolveSandboxRuntimeContextOrExit(): SandboxRuntimeContext {\n let context\n try {\n context = resolveRuntimeContext()\n } catch (error) {\n if (error instanceof RuntimeContextError) {\n printError(error.message)\n process.exit(1)\n }\n throw error\n }\n\n if (context.mode !== 'sandbox') {\n printError('moxt pull is only available in sandbox mode')\n process.exit(1)\n }\n return context\n}\n\nfunction handlePullError(error: unknown): never {\n if (error instanceof Error) {\n printError(error.message)\n process.exit(1)\n }\n throw error\n}\n","import { createHash } from 'node:crypto'\nimport { lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { dirname, isAbsolute, relative, resolve } from 'node:path'\nimport { loadCheckoutState, saveCheckoutState, type CheckoutState, type CheckoutStateFile } from './checkout-state.js'\nimport { SandboxMoxtClient } from './sandbox-client.js'\nimport type { BatchTreesResponse, MfsTreeEntry, PresignUrlsResponse } from './sandbox-mfs-types.js'\nimport type { RepoEntry, SandboxRuntimeContext } from './runtime-context.js'\nimport { listRepoEntries, resolveWorkspacePath } from './sandbox-path.js'\nimport { MFS_FILE_SIZE_LIMIT_BYTES, MFS_FILE_SIZE_LIMIT_LABEL } from './sandbox-file.js'\n\nexport interface PullSandboxWorkspaceOptions {\n force?: boolean\n scopes?: string[]\n}\n\nexport interface PullSandboxWorkspaceResult {\n fileCount: number\n targetDir: string\n}\n\ninterface PullSelection {\n mode: 'partial' | 'full'\n scopes: string[]\n repos: RepoEntry[]\n}\n\ninterface RepoTreeResponse {\n sha: string\n entries: Array<Omit<MfsTreeEntry, 'repoId' | 'prefixedPath'>>\n}\n\ntype RepoTreeFilter = { type: 'all' } | { type: 'paths'; paths: string[] }\n\ninterface BuildNextCheckoutStateInput {\n context: SandboxRuntimeContext\n checkoutRoot: string\n allRepos: RepoEntry[]\n selection: PullSelection\n previousState: CheckoutState | undefined\n pulledRepos: CheckoutState['repos']\n pulledFiles: CheckoutState['files']\n}\n\ninterface PlannedBlobEntry {\n entry: MfsTreeEntry\n localPath: string\n shouldWrite: boolean\n}\n\ninterface PlannedDeletion {\n localPath: string\n}\n\nexport class SandboxPullError extends Error {\n constructor(\n message: string,\n readonly code: 'invalid-path' | 'directory-conflict' | 'file-conflict' | 'remote' | 'too-large',\n ) {\n super(message)\n this.name = 'SandboxPullError'\n }\n}\n\nexport async function pullSandboxWorkspace(\n context: SandboxRuntimeContext,\n targetDir: string,\n options: PullSandboxWorkspaceOptions = {},\n): Promise<PullSandboxWorkspaceResult> {\n const resolvedTargetDir = resolve(targetDir)\n const repos = listRepoEntries(context.repoPayload)\n const previousState = await loadCheckoutState()\n const compatibleState = resolveCompatibleState(previousState, context, resolvedTargetDir, repos)\n const previousFiles = compatibleState?.files ?? {}\n const selection = resolvePullSelection(context, options.scopes)\n const repoById = new Map(selection.repos.map((repo) => [repo.repoId, repo]))\n const tree = await fetchWorkspaceTree(context, selection)\n const stateRepos = resolveStateRepos(tree, selection.repos)\n const entries = [...tree.entries].sort((a, b) => a.prefixedPath.localeCompare(b.prefixedPath))\n\n const directoryPaths = selection.repos.map((repo) => ({\n workspacePath: repo.name,\n localPath: resolveSafeLocalPath(resolvedTargetDir, repo.name, ''),\n }))\n const blobEntries: Array<{ entry: MfsTreeEntry; localPath: string }> = []\n const remoteBlobPaths = new Set<string>()\n const remotePaths = new Set<string>()\n const matchedScopes = new Set<string>()\n for (const entry of entries) {\n const repo = repoById.get(entry.repoId)\n if (!repo) {\n throw new SandboxPullError(`Remote tree returned unknown repo: ${entry.repoId}`, 'remote')\n }\n\n const expectedWorkspacePath = entry.path ? `${repo.name}/${entry.path}` : repo.name\n if (entry.prefixedPath !== expectedWorkspacePath) {\n throw new SandboxPullError(`Remote tree returned inconsistent path: ${entry.prefixedPath}`, 'remote')\n }\n if (remotePaths.has(expectedWorkspacePath)) {\n throw new SandboxPullError(`Remote tree returned duplicate path: ${expectedWorkspacePath}`, 'remote')\n }\n remotePaths.add(expectedWorkspacePath)\n const localPath = resolveSafeLocalPath(resolvedTargetDir, repo.name, entry.path)\n\n for (const scope of selection.scopes) {\n if (pathIsIncluded(scope, expectedWorkspacePath)) matchedScopes.add(scope)\n }\n if (!selection.scopes.some((scope) => pathsIntersect(scope, expectedWorkspacePath))) continue\n\n if (entry.type === 'tree') {\n directoryPaths.push({ workspacePath: entry.prefixedPath, localPath })\n continue\n }\n\n if (!entry.sha) {\n throw new SandboxPullError(`${entry.prefixedPath} does not have downloadable content`, 'remote')\n }\n if (entry.fileId !== null && (typeof entry.fileId !== 'string' || entry.fileId.length === 0)) {\n throw new SandboxPullError(`${entry.prefixedPath} has invalid file metadata`, 'remote')\n }\n if (entry.fileType !== null && (!Number.isInteger(entry.fileType) || entry.fileType < 0)) {\n throw new SandboxPullError(`${entry.prefixedPath} has invalid file metadata`, 'remote')\n }\n if (entry.size !== null && (!Number.isInteger(entry.size) || entry.size < 0)) {\n throw new SandboxPullError(`${entry.prefixedPath} has invalid file metadata`, 'remote')\n }\n if (entry.size !== null && entry.size > MFS_FILE_SIZE_LIMIT_BYTES) {\n throw new SandboxPullError(`File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${entry.prefixedPath}`, 'too-large')\n }\n remoteBlobPaths.add(entry.prefixedPath)\n blobEntries.push({ entry, localPath })\n }\n if (selection.mode === 'partial') {\n for (const scope of selection.scopes) {\n const repoRoot = selection.repos.some((repo) => repo.name === scope)\n const previouslyTracked = Object.keys(previousFiles).some((workspacePath) => pathIsIncluded(scope, workspacePath))\n if (!repoRoot && !matchedScopes.has(scope) && !previouslyTracked) {\n throw new SandboxPullError(`Workspace path does not exist: ${scope}`, 'invalid-path')\n }\n }\n }\n\n const plannedBlobs: PlannedBlobEntry[] = []\n for (const { entry, localPath } of blobEntries) {\n plannedBlobs.push({\n entry,\n localPath,\n shouldWrite: await shouldWritePulledFile(\n localPath,\n requireBlobSha(entry),\n entry.prefixedPath,\n previousFiles[entry.prefixedPath],\n Boolean(options.force),\n ),\n })\n }\n const plannedDeletions = await planRemoteDeletions(\n compatibleState,\n selection,\n resolvedTargetDir,\n remoteBlobPaths,\n Boolean(options.force),\n )\n for (const directory of directoryPaths) {\n await assertCanCreateDirectory(directory.localPath, directory.workspacePath)\n }\n\n const blobsToDownload = plannedBlobs.filter((planned) => planned.shouldWrite)\n const downloadUrls = await presignDownloads(context, blobsToDownload.map(({ entry }) => entry))\n const downloadedEntries: Array<PlannedBlobEntry & { content: Buffer }> = []\n for (const planned of blobsToDownload) {\n const { entry, localPath } = planned\n const remoteContent = await downloadBlob(entry, downloadUrls)\n downloadedEntries.push({ ...planned, content: remoteContent })\n }\n\n for (const deletion of plannedDeletions) {\n await rm(deletion.localPath)\n }\n for (const directory of directoryPaths) {\n await mkdir(directory.localPath, { recursive: true })\n }\n for (const downloaded of downloadedEntries) {\n await writePulledFile(downloaded.localPath, downloaded.content)\n }\n const downloadedContentByPath = new Map(\n downloadedEntries.map(({ entry, content }) => [entry.prefixedPath, content] as const),\n )\n const pulledFiles: CheckoutState['files'] = Object.fromEntries(await Promise.all(plannedBlobs.map(async ({ entry, localPath }) => {\n const content = downloadedContentByPath.get(entry.prefixedPath)\n return [\n entry.prefixedPath,\n {\n repoId: entry.repoId,\n repoPath: entry.path,\n fileId: entry.fileId,\n sha: requireBlobSha(entry),\n size:\n content?.length ??\n entry.size ??\n previousFiles[entry.prefixedPath]?.size ??\n await localFileSize(localPath, entry.prefixedPath),\n fileType: entry.fileType ?? 1,\n },\n ] as const\n })))\n await saveCheckoutState(buildNextCheckoutState({\n context,\n checkoutRoot: resolvedTargetDir,\n allRepos: repos,\n selection,\n previousState: compatibleState,\n pulledRepos: stateRepos,\n pulledFiles,\n }))\n\n return {\n fileCount: blobEntries.length,\n targetDir: resolvedTargetDir,\n }\n}\n\nfunction resolveCompatibleState(\n state: CheckoutState | undefined,\n context: SandboxRuntimeContext,\n checkoutRoot: string,\n repos: RepoEntry[],\n): CheckoutState | undefined {\n if (!state || state.workspaceId !== context.workspaceId || state.checkoutRoot !== checkoutRoot) return undefined\n const currentRepos = new Map(repos.map((repo) => [repo.repoId, repo.name]))\n const stateMatchesRepos = Object.entries(state.repos).every(\n ([repoId, repo]) => currentRepos.get(repoId) === repo.name,\n )\n return stateMatchesRepos ? state : undefined\n}\n\nfunction resolvePullSelection(context: SandboxRuntimeContext, requestedScopes: string[] | undefined): PullSelection {\n const repos = listRepoEntries(context.repoPayload)\n if (!requestedScopes || requestedScopes.length === 0) {\n return { mode: 'full', scopes: repos.map((repo) => repo.name), repos }\n }\n\n const resolvedScopes = requestedScopes.map((scope) => {\n const resolved = resolveWorkspacePath(context.repoPayload, scope)\n return {\n path: resolved.repoPath ? `${resolved.repoName}/${resolved.repoPath}` : resolved.repoName,\n repoId: resolved.repoId,\n }\n })\n const scopes = collapseScopes(resolvedScopes.map((scope) => scope.path))\n const repoIds = new Set(resolvedScopes.map((scope) => scope.repoId))\n return {\n mode: 'partial',\n scopes,\n repos: repos.filter((repo) => repoIds.has(repo.repoId)),\n }\n}\n\nfunction buildNextCheckoutState(input: BuildNextCheckoutStateInput): CheckoutState {\n const { context, checkoutRoot, allRepos, selection, previousState, pulledRepos, pulledFiles } = input\n if (selection.mode === 'full') {\n return {\n version: 1,\n workspaceId: context.workspaceId,\n checkoutRoot,\n mode: 'full',\n checkedOutScopes: selection.scopes,\n repos: pulledRepos,\n files: pulledFiles,\n }\n }\n\n const previousFiles = previousState?.files ?? {}\n const preservedFiles = Object.fromEntries(\n Object.entries(previousFiles).filter(\n ([workspacePath]) => !selection.scopes.some((scope) => pathIsIncluded(scope, workspacePath)),\n ),\n )\n const checkedOutScopes = collapseScopes([...(previousState?.checkedOutScopes ?? []), ...selection.scopes])\n const mode = allRepos.every((repo) => checkedOutScopes.includes(repo.name)) ? 'full' : 'partial'\n return {\n version: 1,\n workspaceId: context.workspaceId,\n checkoutRoot,\n mode,\n checkedOutScopes,\n repos: { ...(previousState?.repos ?? {}), ...pulledRepos },\n files: { ...preservedFiles, ...pulledFiles },\n }\n}\n\nfunction collapseScopes(scopes: string[]): string[] {\n const result: string[] = []\n for (const scope of scopes) {\n if (result.some((existing) => pathIsIncluded(existing, scope))) continue\n for (let index = result.length - 1; index >= 0; index--) {\n if (pathIsIncluded(scope, result[index])) result.splice(index, 1)\n }\n result.push(scope)\n }\n return result\n}\n\nfunction pathsIntersect(left: string, right: string): boolean {\n return pathIsIncluded(left, right) || pathIsIncluded(right, left)\n}\n\nfunction pathIsIncluded(scope: string, workspacePath: string): boolean {\n return workspacePath === scope || workspacePath.startsWith(`${scope}/`)\n}\n\nfunction resolveStateRepos(tree: BatchTreesResponse, repos: RepoEntry[]): CheckoutState['repos'] {\n const knownRepoIds = new Set(repos.map((repo) => repo.repoId))\n for (const repoId of Object.keys(tree.repos)) {\n if (!knownRepoIds.has(repoId)) {\n throw new SandboxPullError(`Remote tree returned unknown repo: ${repoId}`, 'remote')\n }\n }\n\n return Object.fromEntries(repos.map((repo) => {\n const remoteRepo = tree.repos[repo.repoId]\n if (!remoteRepo) {\n throw new SandboxPullError(`Remote tree did not return repo: ${repo.repoId}`, 'remote')\n }\n if (remoteRepo.prefix !== repo.name) {\n throw new SandboxPullError(`Remote tree returned unexpected prefix for repo ${repo.repoId}`, 'remote')\n }\n if (typeof remoteRepo.sha !== 'string' || remoteRepo.sha.length === 0) {\n throw new SandboxPullError(`Remote tree did not return a version for repo ${repo.repoId}`, 'remote')\n }\n return [repo.repoId, { name: repo.name, treeSha: remoteRepo.sha }]\n }))\n}\n\nasync function fetchWorkspaceTree(\n context: SandboxRuntimeContext,\n selection: PullSelection,\n): Promise<BatchTreesResponse> {\n const client = new SandboxMoxtClient(context)\n const results = await Promise.all(selection.repos.map(async (repo) => {\n const filter = resolveRepoTreeFilter(repo, selection)\n const params = new URLSearchParams({ entryFilter: filter.type })\n if (filter.type === 'paths') {\n for (const path of filter.paths) params.append('path', path)\n }\n const response = await client.request<RepoTreeResponse>(\n 'GET',\n `/agent/api/pipeline-sandbox/mfs/${encodeURIComponent(repo.repoId)}/tree?${params.toString()}`,\n )\n return { repo, tree: response.data }\n }))\n\n return {\n repos: Object.fromEntries(\n results.map(({ repo, tree }) => [repo.repoId, { sha: tree.sha, prefix: repo.name }]),\n ),\n entries: results.flatMap(({ repo, tree }) =>\n tree.entries.map((entry) => ({\n ...entry,\n repoId: repo.repoId,\n prefixedPath: entry.path ? `${repo.name}/${entry.path}` : repo.name,\n })),\n ),\n }\n}\n\nfunction resolveRepoTreeFilter(repo: RepoEntry, selection: PullSelection): RepoTreeFilter {\n if (selection.mode === 'full') return { type: 'all' }\n\n const repoPaths: string[] = []\n for (const scope of selection.scopes) {\n if (scope === repo.name) return { type: 'all' }\n if (scope.startsWith(`${repo.name}/`)) repoPaths.push(scope.slice(repo.name.length + 1))\n }\n if (repoPaths.length === 0) {\n throw new SandboxPullError(`No pull scope resolved for repo: ${repo.name}`, 'invalid-path')\n }\n return { type: 'paths', paths: repoPaths }\n}\n\nasync function presignDownloads(\n context: SandboxRuntimeContext,\n entries: readonly MfsTreeEntry[],\n): Promise<Map<string, string>> {\n const client = new SandboxMoxtClient(context)\n const entriesByRepo = new Map<string, MfsTreeEntry[]>()\n for (const entry of entries) {\n const existing = entriesByRepo.get(entry.repoId) ?? []\n existing.push(entry)\n entriesByRepo.set(entry.repoId, existing)\n }\n\n const urls = new Map<string, string>()\n for (const [repoId, repoEntries] of entriesByRepo) {\n const hashes = [...new Set(repoEntries.map((entry) => entry.sha).filter((sha): sha is string => Boolean(sha)))]\n if (hashes.length === 0) continue\n\n const response = await client.request<PresignUrlsResponse>(\n 'POST',\n `/agent/api/pipeline-sandbox/mfs/${encodeURIComponent(repoId)}/presign-download`,\n { hashes },\n )\n for (const hash of hashes) {\n const url = response.data.urls[hash]\n if (!url) {\n throw new SandboxPullError(`No download URL returned for ${hash}`, 'remote')\n }\n urls.set(hash, url)\n }\n }\n return urls\n}\n\nasync function downloadBlob(entry: MfsTreeEntry, urls: ReadonlyMap<string, string>): Promise<Buffer> {\n const hash = entry.sha\n if (!hash) {\n throw new SandboxPullError(`${entry.prefixedPath} does not have downloadable content`, 'remote')\n }\n const url = urls.get(hash)\n if (!url) {\n throw new SandboxPullError(`No download URL returned for ${entry.prefixedPath}`, 'remote')\n }\n\n const response = await fetch(url)\n if (!response.ok) {\n throw new SandboxPullError(`Download failed [${response.status}]: ${entry.prefixedPath}`, 'remote')\n }\n\n const content = Buffer.from(await response.arrayBuffer())\n if (content.length > MFS_FILE_SIZE_LIMIT_BYTES) {\n throw new SandboxPullError(`File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${entry.prefixedPath}`, 'too-large')\n }\n const contentHash = createHash('sha256').update(content).digest('hex')\n if (contentHash !== hash) {\n throw new SandboxPullError(`Downloaded content hash mismatch: ${entry.prefixedPath}`, 'remote')\n }\n return content\n}\n\nasync function shouldWritePulledFile(\n localPath: string,\n remoteContentHash: string,\n workspacePath: string,\n previousFile: CheckoutStateFile | undefined,\n force: boolean,\n): Promise<boolean> {\n const existing = await lstat(localPath).catch((error: unknown) => {\n if (isNodeError(error) && error.code === 'ENOENT') return undefined\n throw error\n })\n if (existing && !existing.isFile()) {\n throw new SandboxPullError(`Refusing to overwrite local path: ${workspacePath}`, 'directory-conflict')\n }\n if (!existing) {\n if (force || !previousFile) return true\n if (remoteContentHash === previousFile.sha) return false\n throw new SandboxPullError(\n `Local file was deleted but remote file changed: ${workspacePath}`,\n 'file-conflict',\n )\n }\n if (force) return true\n\n const localContentHash = await hashLocalFile(localPath)\n if (localContentHash === remoteContentHash) return false\n if (!previousFile) {\n throw new SandboxPullError(\n `Refusing to overwrite modified local file: ${workspacePath}. Use --force to overwrite.`,\n 'file-conflict',\n )\n }\n\n const localChanged = localContentHash !== previousFile.sha\n const remoteChanged = remoteContentHash !== previousFile.sha\n if (!localChanged && remoteChanged) return true\n if (localChanged && !remoteChanged) return false\n if (localChanged && remoteChanged) {\n throw new SandboxPullError(\n `Local and remote file both changed since checkout: ${workspacePath}`,\n 'file-conflict',\n )\n }\n return false\n}\n\nasync function planRemoteDeletions(\n previousState: CheckoutState | undefined,\n selection: PullSelection,\n checkoutRoot: string,\n remoteBlobPaths: ReadonlySet<string>,\n force: boolean,\n): Promise<PlannedDeletion[]> {\n if (!previousState) return []\n\n const deletions: PlannedDeletion[] = []\n for (const [workspacePath, previousFile] of Object.entries(previousState.files)) {\n if (!selection.scopes.some((scope) => pathIsIncluded(scope, workspacePath))) continue\n if (remoteBlobPaths.has(workspacePath)) continue\n\n const repo = previousState.repos[previousFile.repoId]\n if (!repo) {\n throw new SandboxPullError(`Checkout baseline references unknown repo: ${workspacePath}`, 'remote')\n }\n const localPath = resolveSafeLocalPath(checkoutRoot, repo.name, previousFile.repoPath)\n const existing = await lstat(localPath).catch((error: unknown) => {\n if (isNodeError(error) && error.code === 'ENOENT') return undefined\n throw error\n })\n if (!existing) continue\n if (!existing.isFile()) {\n throw new SandboxPullError(`Refusing to overwrite local path: ${workspacePath}`, 'directory-conflict')\n }\n if (!force && await hashLocalFile(localPath) !== previousFile.sha) {\n throw new SandboxPullError(\n `Remote file was deleted but local file changed: ${workspacePath}`,\n 'file-conflict',\n )\n }\n deletions.push({ localPath })\n }\n return deletions\n}\n\nasync function hashLocalFile(localPath: string): Promise<string> {\n return createHash('sha256').update(await readFile(localPath)).digest('hex')\n}\n\nasync function localFileSize(localPath: string, workspacePath: string): Promise<number> {\n const stats = await lstat(localPath)\n if (!stats.isFile()) {\n throw new SandboxPullError(`Cannot determine local file size: ${workspacePath}`, 'directory-conflict')\n }\n return stats.size\n}\n\nfunction requireBlobSha(entry: MfsTreeEntry): string {\n if (!entry.sha) {\n throw new SandboxPullError(`${entry.prefixedPath} does not have downloadable content`, 'remote')\n }\n return entry.sha\n}\n\nasync function assertCanCreateDirectory(localPath: string, workspacePath: string): Promise<void> {\n const existing = await lstat(localPath).catch((error: unknown) => {\n if (isNodeError(error) && error.code === 'ENOENT') return undefined\n throw error\n })\n if (existing && !existing.isDirectory()) {\n throw new SandboxPullError(`Refusing to overwrite local path: ${workspacePath}`, 'directory-conflict')\n }\n}\n\nasync function writePulledFile(localPath: string, remoteContent: Buffer): Promise<void> {\n await mkdir(dirname(localPath), { recursive: true })\n await writeFile(localPath, remoteContent)\n}\n\nfunction resolveSafeLocalPath(targetDir: string, repoName: string, repoPath: string): string {\n const pathParts = [repoName, ...repoPath.split('/').filter((part) => part.length > 0)]\n if (pathParts.some((part) => part === '.' || part === '..' || part.includes('/') || part.includes('\\\\') || part.includes('\\0'))) {\n throw new SandboxPullError(`Remote path is unsafe: ${[repoName, repoPath].filter(Boolean).join('/')}`, 'invalid-path')\n }\n\n const resolved = resolve(targetDir, ...pathParts)\n const relativePath = relative(targetDir, resolved)\n if (relativePath.startsWith('..') || isAbsolute(relativePath)) {\n throw new SandboxPullError(`Remote path escapes target directory: ${repoName}/${repoPath}`, 'invalid-path')\n }\n return resolved\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && 'code' in error\n}\n","import { randomUUID } from 'node:crypto'\nimport { homedir } from 'node:os'\nimport { dirname, isAbsolute, join, posix } from 'node:path'\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\n\nexport type CheckoutMode = 'partial' | 'full'\n\nexport interface CheckoutStateRepo {\n name: string\n treeSha: string\n}\n\nexport interface CheckoutStateFile {\n repoId: string\n repoPath: string\n fileId: string | null\n sha: string\n size: number\n fileType: number\n}\n\nexport interface CheckoutState {\n version: 1\n workspaceId: string\n checkoutRoot: string\n mode: CheckoutMode\n checkedOutScopes: string[]\n repos: Record<string, CheckoutStateRepo>\n files: Record<string, CheckoutStateFile>\n}\n\nexport class CheckoutStateError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CheckoutStateError'\n }\n}\n\nexport function getCheckoutStatePath(): string {\n return join(homedir(), '.moxt', 'checkout-state.json')\n}\n\nexport async function loadCheckoutState(statePath = getCheckoutStatePath()): Promise<CheckoutState | undefined> {\n let raw: string\n try {\n raw = await readFile(statePath, 'utf8')\n } catch (error) {\n if (isNodeError(error) && error.code === 'ENOENT') return undefined\n throw new CheckoutStateError(`Failed to read checkout state: ${errorMessage(error)}`)\n }\n\n let value: unknown\n try {\n value = JSON.parse(raw)\n } catch {\n throw new CheckoutStateError(`Checkout state is not valid JSON: ${statePath}`)\n }\n return validateCheckoutState(value)\n}\n\nexport async function saveCheckoutState(\n state: CheckoutState,\n statePath = getCheckoutStatePath(),\n): Promise<void> {\n const validState = validateCheckoutState(state)\n const stateDir = dirname(statePath)\n const temporaryPath = `${statePath}.${process.pid}.${randomUUID()}.tmp`\n await mkdir(stateDir, { recursive: true })\n try {\n await writeFile(temporaryPath, `${JSON.stringify(validState, null, 2)}\\n`, { mode: 0o600 })\n await rename(temporaryPath, statePath)\n } catch (error) {\n await rm(temporaryPath, { force: true })\n throw new CheckoutStateError(`Failed to save checkout state: ${errorMessage(error)}`)\n }\n}\n\nexport function isCheckoutPathIncluded(state: CheckoutState, workspacePath: string): boolean {\n if (state.mode === 'full') return true\n return state.checkedOutScopes.some(\n (scope) => workspacePath === scope || workspacePath.startsWith(`${scope}/`),\n )\n}\n\nexport function doesCheckoutPathIntersect(state: CheckoutState, workspacePath: string): boolean {\n if (state.mode === 'full') return true\n return state.checkedOutScopes.some(\n (scope) =>\n workspacePath === scope ||\n workspacePath.startsWith(`${scope}/`) ||\n scope.startsWith(`${workspacePath}/`),\n )\n}\n\nfunction validateCheckoutState(value: unknown): CheckoutState {\n const state = requireRecord(value, 'Checkout state')\n if (state.version !== 1) {\n throw new CheckoutStateError(`Unsupported checkout state version: ${String(state.version)}`)\n }\n\n const workspaceId = requireNonEmptyString(state.workspaceId, 'workspaceId')\n const checkoutRoot = requireNonEmptyString(state.checkoutRoot, 'checkoutRoot')\n if (!isAbsolute(checkoutRoot)) throw new CheckoutStateError('checkoutRoot must be an absolute path')\n if (state.mode !== 'partial' && state.mode !== 'full') {\n throw new CheckoutStateError('mode must be partial or full')\n }\n if (!Array.isArray(state.checkedOutScopes)) {\n throw new CheckoutStateError('checkedOutScopes must be an array')\n }\n const checkedOutScopes = state.checkedOutScopes.map((scope, index) =>\n requireWorkspacePath(scope, `checkedOutScopes[${index}]`),\n )\n if (new Set(checkedOutScopes).size !== checkedOutScopes.length) {\n throw new CheckoutStateError('checkedOutScopes must not contain duplicates')\n }\n\n const reposValue = requireRecord(state.repos, 'repos')\n const repos: Record<string, CheckoutStateRepo> = {}\n for (const [repoId, rawRepo] of Object.entries(reposValue)) {\n requireNonEmptyString(repoId, 'repo id')\n const repo = requireRecord(rawRepo, `repos.${repoId}`)\n const name = requireRepoName(repo.name, `repos.${repoId}.name`)\n repos[repoId] = {\n name,\n treeSha: requireNonEmptyString(repo.treeSha, `repos.${repoId}.treeSha`),\n }\n }\n\n const filesValue = requireRecord(state.files, 'files')\n const files: Record<string, CheckoutStateFile> = {}\n for (const [workspacePath, rawFile] of Object.entries(filesValue)) {\n requireWorkspacePath(workspacePath, `files.${workspacePath}`)\n const file = requireRecord(rawFile, `files.${workspacePath}`)\n const repoId = requireNonEmptyString(file.repoId, `files.${workspacePath}.repoId`)\n const repo = repos[repoId]\n if (!repo) throw new CheckoutStateError(`File references unknown repo: ${workspacePath}`)\n const repoPath = requireWorkspacePath(file.repoPath, `files.${workspacePath}.repoPath`)\n if (workspacePath !== `${repo.name}/${repoPath}`) {\n throw new CheckoutStateError(`File path does not match its repo: ${workspacePath}`)\n }\n const fileId = file.fileId === null ? null : requireNonEmptyString(file.fileId, `files.${workspacePath}.fileId`)\n const sha = requireNonEmptyString(file.sha, `files.${workspacePath}.sha`)\n if (!/^[a-f0-9]{64}$/.test(sha)) throw new CheckoutStateError(`Invalid file SHA: ${workspacePath}`)\n files[workspacePath] = {\n repoId,\n repoPath,\n fileId,\n sha,\n size: requireNonNegativeInteger(file.size, `files.${workspacePath}.size`),\n fileType: requireNonNegativeInteger(file.fileType, `files.${workspacePath}.fileType`),\n }\n }\n\n return {\n version: 1,\n workspaceId,\n checkoutRoot,\n mode: state.mode,\n checkedOutScopes,\n repos,\n files,\n }\n}\n\nfunction requireRecord(value: unknown, field: string): Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new CheckoutStateError(`${field} must be an object`)\n }\n return value as Record<string, unknown>\n}\n\nfunction requireNonEmptyString(value: unknown, field: string): string {\n if (typeof value !== 'string' || value.length === 0) {\n throw new CheckoutStateError(`${field} must be a non-empty string`)\n }\n return value\n}\n\nfunction requireWorkspacePath(value: unknown, field: string): string {\n const path = requireNonEmptyString(value, field)\n if (path.includes('\\\\') || path.includes('\\0') || posix.isAbsolute(path) || posix.normalize(path) !== path) {\n throw new CheckoutStateError(`${field} must be a normalized relative path`)\n }\n return path\n}\n\nfunction requireRepoName(value: unknown, field: string): string {\n const name = requireWorkspacePath(value, field)\n if (name.includes('/')) throw new CheckoutStateError(`${field} must be a single path segment`)\n return name\n}\n\nfunction requireNonNegativeInteger(value: unknown, field: string): number {\n if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) {\n throw new CheckoutStateError(`${field} must be a non-negative integer`)\n }\n return value\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && 'code' in error\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import { createHash } from 'node:crypto'\nimport { lstat, readFile, readdir } from 'node:fs/promises'\nimport { isAbsolute, join, relative, resolve } from 'node:path'\nimport {\n doesCheckoutPathIntersect,\n isCheckoutPathIncluded,\n loadCheckoutState,\n saveCheckoutState,\n type CheckoutState,\n type CheckoutStateFile,\n} from './checkout-state.js'\nimport { SandboxMoxtClient } from './sandbox-client.js'\nimport { runWithConcurrency } from './concurrency.js'\nimport { MFS_FILE_SIZE_LIMIT_BYTES, MFS_FILE_SIZE_LIMIT_LABEL } from './sandbox-file.js'\nimport type { BatchTreesResponse, MfsTreeEntry, PresignUrlsResponse } from './sandbox-mfs-types.js'\nimport { listRepoEntries } from './sandbox-path.js'\nimport type { RepoEntry, SandboxRuntimeContext } from './runtime-context.js'\n\nconst MFS_FILE_TYPE_REGULAR = 1\nconst MAX_CONCURRENT_UPLOADS = 8\n\nexport interface PushSandboxWorkspaceOptions {\n message: string\n}\n\nexport interface PushSandboxWorkspaceResult {\n changes: Array<{ action: 'create' | 'update' | 'delete'; workspacePath: string }>\n sourceDir: string\n}\n\ninterface LocalFile {\n repo: RepoEntry\n repoPath: string\n workspacePath: string\n localPath: string\n contentHash: string\n size: number\n}\n\ninterface PlannedWriteChange extends LocalFile {\n action: 'create' | 'update'\n existing?: MfsTreeEntry\n}\n\ninterface PlannedDeleteChange {\n action: 'delete'\n repo: RepoEntry\n repoPath: string\n workspacePath: string\n fileId: string | null\n}\n\ntype PlannedChange = PlannedWriteChange | PlannedDeleteChange\n\ninterface ReconciledFile extends LocalFile {\n remote: MfsTreeEntry\n}\n\ninterface PushPlan {\n changes: PlannedChange[]\n reconciledFiles: ReconciledFile[]\n removedWorkspacePaths: string[]\n}\n\ninterface UnifiedPushResponse {\n repoVersions: Record<string, number>\n fileMap: Record<string, Record<string, string>>\n}\n\nexport class SandboxPushError extends Error {\n constructor(\n message: string,\n readonly code: 'invalid-path' | 'invalid-file' | 'remote' | 'too-large' | 'conflict',\n ) {\n super(message)\n this.name = 'SandboxPushError'\n }\n}\n\nexport async function pushSandboxWorkspace(\n context: SandboxRuntimeContext,\n sourceDir: string,\n options: PushSandboxWorkspaceOptions,\n): Promise<PushSandboxWorkspaceResult> {\n const resolvedSourceDir = resolve(sourceDir)\n await assertWorkspaceRoot(resolvedSourceDir)\n\n const repos = listRepoEntries(context.repoPayload)\n for (const repo of repos) {\n assertSafeRepoName(resolvedSourceDir, repo.name)\n }\n const state = await resolveCheckoutState(context, resolvedSourceDir, repos)\n const checkoutRepos = repos.filter(\n (repo) => state.repos[repo.repoId] && doesCheckoutPathIntersect(state, repo.name),\n )\n if (checkoutRepos.length === 0) {\n throw new SandboxPushError('Checkout state does not contain a pushable scope', 'invalid-path')\n }\n const tree = await fetchWorkspaceTree(context, checkoutRepos)\n const remoteEntries = indexRemoteEntries(tree, checkoutRepos)\n const localFiles = await collectLocalFiles(resolvedSourceDir, checkoutRepos, remoteEntries, state)\n const { changes, reconciledFiles, removedWorkspacePaths } = planChanges(\n localFiles,\n remoteEntries,\n state,\n checkoutRepos,\n )\n\n let pushResponse: UnifiedPushResponse | undefined\n if (changes.length > 0) {\n await uploadChangedFiles(context, changes)\n pushResponse = await pushChanges(context, checkoutRepos, changes, options.message)\n }\n if (changes.length > 0 || reconciledFiles.length > 0 || removedWorkspacePaths.length > 0) {\n await updateCheckoutState(state, changes, reconciledFiles, removedWorkspacePaths, pushResponse)\n }\n\n return {\n changes: changes.map((change) => ({ action: change.action, workspacePath: change.workspacePath })),\n sourceDir: resolvedSourceDir,\n }\n}\n\nasync function resolveCheckoutState(\n context: SandboxRuntimeContext,\n sourceDir: string,\n repos: RepoEntry[],\n): Promise<CheckoutState> {\n const state = await loadCheckoutState()\n if (!state) {\n throw new SandboxPushError('Checkout is not initialized. Run moxt pull first.', 'invalid-path')\n }\n if (state.workspaceId !== context.workspaceId) {\n throw new SandboxPushError(\n `Checkout state belongs to workspace ${state.workspaceId}, not ${context.workspaceId}`,\n 'invalid-path',\n )\n }\n if (state.checkoutRoot !== sourceDir) {\n throw new SandboxPushError(\n `Checkout root is ${state.checkoutRoot}, not ${sourceDir}`,\n 'invalid-path',\n )\n }\n\n const currentRepos = new Map(repos.map((repo) => [repo.repoId, repo.name]))\n for (const [repoId, repo] of Object.entries(state.repos)) {\n if (currentRepos.get(repoId) !== repo.name) {\n throw new SandboxPushError(`Checkout state contains unknown repo: ${repoId}`, 'invalid-path')\n }\n }\n for (const scope of state.checkedOutScopes) {\n const hasRepo = Object.values(state.repos).some(\n (repo) => scope === repo.name || scope.startsWith(`${repo.name}/`),\n )\n if (!hasRepo) throw new SandboxPushError(`Checkout state contains invalid scope: ${scope}`, 'invalid-path')\n }\n return state\n}\n\nasync function assertWorkspaceRoot(sourceDir: string): Promise<void> {\n const stats = await lstat(sourceDir).catch((error: unknown) => {\n if (isNodeError(error) && error.code === 'ENOENT') {\n throw new SandboxPushError(`Local workspace directory does not exist: ${sourceDir}`, 'invalid-path')\n }\n throw error\n })\n if (!stats.isDirectory()) {\n throw new SandboxPushError(`Local workspace path is not a directory: ${sourceDir}`, 'invalid-path')\n }\n}\n\nasync function fetchWorkspaceTree(context: SandboxRuntimeContext, repos: RepoEntry[]): Promise<BatchTreesResponse> {\n const client = new SandboxMoxtClient(context)\n const response = await client.request<BatchTreesResponse>(\n 'POST',\n '/agent/api/pipeline-sandbox/mfs-workspace/batch-trees',\n {\n repos: repos.map((repo) => ({ repoId: repo.repoId, prefix: repo.name })),\n },\n )\n return response.data\n}\n\nfunction indexRemoteEntries(tree: BatchTreesResponse, repos: RepoEntry[]): Map<string, MfsTreeEntry> {\n const knownRepoIds = new Set(repos.map((repo) => repo.repoId))\n const entries = new Map<string, MfsTreeEntry>()\n for (const entry of tree.entries) {\n if (!knownRepoIds.has(entry.repoId)) {\n throw new SandboxPushError(`Remote tree returned unknown repo: ${entry.repoId}`, 'remote')\n }\n const key = remoteEntryKey(entry.repoId, entry.path)\n if (entries.has(key)) {\n throw new SandboxPushError(`Remote tree returned duplicate path: ${entry.prefixedPath}`, 'remote')\n }\n entries.set(key, entry)\n }\n return entries\n}\n\nasync function collectLocalFiles(\n sourceDir: string,\n repos: RepoEntry[],\n remoteEntries: ReadonlyMap<string, MfsTreeEntry>,\n state: CheckoutState,\n): Promise<LocalFile[]> {\n const files: LocalFile[] = []\n for (const repo of repos) {\n const repoRoot = resolveSafeRepoRoot(sourceDir, repo.name)\n const stats = await lstat(repoRoot).catch((error: unknown) => {\n if (isNodeError(error) && error.code === 'ENOENT') return undefined\n throw error\n })\n if (!stats) continue\n if (!stats.isDirectory()) {\n throw new SandboxPushError(`Local repo path is not a directory: ${repo.name}`, 'invalid-path')\n }\n await collectRepoFiles(repoRoot, repo, '', remoteEntries, state, files)\n }\n return files\n}\n\nasync function collectRepoFiles(\n repoRoot: string,\n repo: RepoEntry,\n relativeDir: string,\n remoteEntries: ReadonlyMap<string, MfsTreeEntry>,\n state: CheckoutState,\n files: LocalFile[],\n): Promise<void> {\n const localDir = relativeDir ? join(repoRoot, ...relativeDir.split('/')) : repoRoot\n const entries = await readdir(localDir, { withFileTypes: true })\n entries.sort((a, b) => a.name.localeCompare(b.name))\n\n for (const entry of entries) {\n if (entry.name === '.git') continue\n\n const repoPath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name\n const workspacePath = `${repo.name}/${repoPath}`\n assertSafePathPart(entry.name, workspacePath)\n if (!doesCheckoutPathIntersect(state, workspacePath)) continue\n\n if (entry.isSymbolicLink()) {\n throw new SandboxPushError(`Refusing to push symbolic link: ${workspacePath}`, 'invalid-file')\n }\n if (entry.isDirectory()) {\n const remote = remoteEntries.get(remoteEntryKey(repo.repoId, repoPath))\n if (remote?.type === 'blob') {\n throw new SandboxPushError(`Local directory conflicts with remote file: ${workspacePath}`, 'invalid-file')\n }\n await collectRepoFiles(repoRoot, repo, repoPath, remoteEntries, state, files)\n continue\n }\n if (!entry.isFile()) {\n throw new SandboxPushError(`Refusing to push unsupported file: ${workspacePath}`, 'invalid-file')\n }\n\n const localPath = join(repoRoot, ...repoPath.split('/'))\n const stats = await lstat(localPath)\n if (!stats.isFile()) {\n const kind = stats.isSymbolicLink() ? 'symbolic link' : 'unsupported file'\n throw new SandboxPushError(`Refusing to push ${kind}: ${workspacePath}`, 'invalid-file')\n }\n if (stats.size > MFS_FILE_SIZE_LIMIT_BYTES) {\n throw new SandboxPushError(\n `File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${workspacePath}`,\n 'too-large',\n )\n }\n const content = await readFile(localPath)\n if (content.length > MFS_FILE_SIZE_LIMIT_BYTES) {\n throw new SandboxPushError(\n `File too large (max ${MFS_FILE_SIZE_LIMIT_LABEL}): ${workspacePath}`,\n 'too-large',\n )\n }\n if (!isCheckoutPathIncluded(state, workspacePath)) continue\n files.push({\n repo,\n repoPath,\n workspacePath,\n localPath,\n contentHash: createHash('sha256').update(content).digest('hex'),\n size: content.length,\n })\n }\n}\n\nfunction planChanges(\n localFiles: LocalFile[],\n remoteEntries: ReadonlyMap<string, MfsTreeEntry>,\n state: CheckoutState,\n repos: RepoEntry[],\n): PushPlan {\n const changes: PlannedChange[] = []\n const reconciledFiles: ReconciledFile[] = []\n const removedWorkspacePaths: string[] = []\n const localWorkspacePaths = new Set(localFiles.map((file) => file.workspacePath))\n const reposById = new Map(repos.map((repo) => [repo.repoId, repo]))\n for (const file of localFiles) {\n const baseline = state.files[file.workspacePath]\n if (baseline?.sha === file.contentHash) continue\n\n const existing = remoteEntries.get(remoteEntryKey(file.repo.repoId, file.repoPath))\n if (existing?.type === 'tree') {\n throw new SandboxPushError(`Local file conflicts with remote directory: ${file.workspacePath}`, 'invalid-file')\n }\n if (existing?.sha === file.contentHash) {\n reconciledFiles.push({ ...file, remote: existing })\n continue\n }\n if (existing && !existing.sha) {\n throw new SandboxPushError(`${file.workspacePath} does not have a base content hash`, 'remote')\n }\n if (baseline && existing?.sha !== baseline.sha) {\n throw new SandboxPushError(`Remote file changed since checkout: ${file.workspacePath}`, 'conflict')\n }\n if (!baseline && existing) {\n throw new SandboxPushError(`Remote file changed since checkout: ${file.workspacePath}`, 'conflict')\n }\n changes.push({\n ...file,\n action: existing ? 'update' : 'create',\n ...(existing ? { existing } : {}),\n })\n }\n\n for (const [workspacePath, baseline] of Object.entries(state.files)) {\n if (localWorkspacePaths.has(workspacePath) || !isCheckoutPathIncluded(state, workspacePath)) continue\n\n const repo = reposById.get(baseline.repoId)\n if (!repo) continue\n const existing = remoteEntries.get(remoteEntryKey(baseline.repoId, baseline.repoPath))\n if (!existing) {\n removedWorkspacePaths.push(workspacePath)\n continue\n }\n if (existing.type !== 'blob' || existing.sha !== baseline.sha) {\n throw new SandboxPushError(`Remote file changed since checkout: ${workspacePath}`, 'conflict')\n }\n changes.push({\n action: 'delete',\n repo,\n repoPath: baseline.repoPath,\n workspacePath,\n fileId: validFileId(existing.fileId) ?? baseline.fileId,\n })\n }\n\n return { changes, reconciledFiles, removedWorkspacePaths }\n}\n\nasync function uploadChangedFiles(context: SandboxRuntimeContext, changes: PlannedChange[]): Promise<void> {\n const writeChanges = changes.filter(isWriteChange)\n if (writeChanges.length === 0) return\n\n const client = new SandboxMoxtClient(context)\n const changesByRepo = groupChangesByRepo(writeChanges)\n const uploadUrlsByRepo = await Promise.all(\n [...changesByRepo].map(async ([repoId, repoChanges]) => {\n const hashes = [...new Set(repoChanges.map((change) => change.contentHash))]\n const response = await client.request<PresignUrlsResponse>(\n 'POST',\n `/agent/api/pipeline-sandbox/mfs/${encodeURIComponent(repoId)}/presign-upload`,\n { hashes },\n )\n return [repoId, response.data.urls] as const\n }),\n )\n const uploadUrls = new Map(uploadUrlsByRepo)\n\n await runWithConcurrency(writeChanges, MAX_CONCURRENT_UPLOADS, async (change) => {\n const uploadUrl = uploadUrls.get(change.repo.repoId)?.[change.contentHash]\n if (!uploadUrl) {\n throw new SandboxPushError(`No upload URL returned for ${change.workspacePath}`, 'remote')\n }\n const content = await readFile(change.localPath)\n const currentHash = createHash('sha256').update(content).digest('hex')\n if (content.length !== change.size || currentHash !== change.contentHash) {\n throw new SandboxPushError(`Local file changed while pushing: ${change.workspacePath}`, 'invalid-file')\n }\n const upload = await fetch(uploadUrl, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/octet-stream' },\n body: new Uint8Array(content),\n })\n if (!upload.ok) {\n throw new SandboxPushError(`Upload failed [${upload.status}]: ${change.workspacePath}`, 'remote')\n }\n })\n}\n\nasync function pushChanges(\n context: SandboxRuntimeContext,\n repos: RepoEntry[],\n changes: PlannedChange[],\n message: string,\n): Promise<UnifiedPushResponse> {\n const client = new SandboxMoxtClient(context)\n const changesByRepo = groupChangesByRepo(changes)\n const response = await client.request<UnifiedPushResponse>(\n 'POST',\n '/agent/api/pipeline-sandbox/mfs-workspace/unified-push',\n {\n message,\n repoPushes: repos.flatMap((repo) => {\n const repoChanges = changesByRepo.get(repo.repoId)\n if (!repoChanges) return []\n return [{\n repoId: repo.repoId,\n changes: repoChanges.map((change) => {\n if (change.action === 'delete') {\n return {\n action: change.action,\n ...(change.fileId ? { fileId: change.fileId } : {}),\n path: change.repoPath,\n }\n }\n return {\n action: change.action,\n ...(change.existing?.fileId ? { fileId: change.existing.fileId } : {}),\n path: change.repoPath,\n contentHash: change.contentHash,\n ...(change.existing?.sha ? { baseContentHash: change.existing.sha } : {}),\n size: change.size,\n fileType: MFS_FILE_TYPE_REGULAR,\n }\n }),\n }]\n }),\n crossRepoMoves: [],\n },\n )\n return response.data\n}\n\nasync function updateCheckoutState(\n state: CheckoutState,\n changes: PlannedChange[],\n reconciledFiles: ReconciledFile[],\n removedWorkspacePaths: string[],\n response: UnifiedPushResponse | undefined,\n): Promise<void> {\n const files = { ...state.files }\n for (const workspacePath of removedWorkspacePaths) delete files[workspacePath]\n for (const file of reconciledFiles) {\n files[file.workspacePath] = checkoutStateFile(\n file,\n validFileId(file.remote.fileId),\n validFileType(file.remote.fileType),\n )\n }\n for (const change of changes) {\n if (change.action === 'delete') {\n delete files[change.workspacePath]\n continue\n }\n const returnedFileId = validFileId(response?.fileMap?.[change.repo.repoId]?.[change.repoPath])\n const fileId = returnedFileId ?? change.existing?.fileId ?? state.files[change.workspacePath]?.fileId ?? null\n files[change.workspacePath] = checkoutStateFile(change, validFileId(fileId), validFileType(change.existing?.fileType))\n }\n await saveCheckoutState({ ...state, files })\n}\n\nfunction isWriteChange(change: PlannedChange): change is PlannedWriteChange {\n return change.action !== 'delete'\n}\n\nfunction checkoutStateFile(\n file: LocalFile,\n fileId: string | null,\n fileType: number | null | undefined,\n): CheckoutStateFile {\n return {\n repoId: file.repo.repoId,\n repoPath: file.repoPath,\n fileId,\n sha: file.contentHash,\n size: file.size,\n fileType: fileType ?? MFS_FILE_TYPE_REGULAR,\n }\n}\n\nfunction validFileId(fileId: unknown): string | null {\n return typeof fileId === 'string' && fileId.length > 0 ? fileId : null\n}\n\nfunction validFileType(fileType: unknown): number | null {\n return typeof fileType === 'number' && Number.isInteger(fileType) && fileType >= 0 ? fileType : null\n}\n\nfunction groupChangesByRepo<T extends PlannedChange>(changes: T[]): Map<string, T[]> {\n const result = new Map<string, T[]>()\n for (const change of changes) {\n const repoChanges = result.get(change.repo.repoId) ?? []\n repoChanges.push(change)\n result.set(change.repo.repoId, repoChanges)\n }\n return result\n}\n\nfunction remoteEntryKey(repoId: string, repoPath: string): string {\n return `${repoId}\\0${repoPath}`\n}\n\nfunction assertSafePathPart(part: string, workspacePath: string): void {\n if (part === '.' || part === '..' || part.includes('/') || part.includes('\\\\') || part.includes('\\0')) {\n throw new SandboxPushError(`Local path is unsafe: ${workspacePath}`, 'invalid-path')\n }\n}\n\nfunction assertSafeRepoName(sourceDir: string, repoName: string): void {\n resolveSafeRepoRoot(sourceDir, repoName)\n}\n\nfunction resolveSafeRepoRoot(sourceDir: string, repoName: string): string {\n assertSafePathPart(repoName, repoName)\n const repoRoot = resolve(sourceDir, repoName)\n const relativePath = relative(sourceDir, repoRoot)\n if (relativePath.startsWith('..') || isAbsolute(relativePath)) {\n throw new SandboxPushError(`Repo path escapes local workspace: ${repoName}`, 'invalid-path')\n }\n return repoRoot\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && 'code' in error\n}\n","export async function runWithConcurrency<T>(\n items: readonly T[],\n concurrency: number,\n action: (item: T) => Promise<void>,\n): Promise<void> {\n if (!Number.isInteger(concurrency) || concurrency < 1) {\n throw new RangeError('Concurrency must be a positive integer')\n }\n\n let nextIndex = 0\n async function worker(): Promise<void> {\n while (nextIndex < items.length) {\n const item = items[nextIndex]\n nextIndex += 1\n await action(item)\n }\n }\n\n const workerCount = Math.min(concurrency, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n}\n","import { Command } from 'commander'\nimport { print, printError } from '../utils/output.js'\nimport { resolveRuntimeContext, RuntimeContextError, type SandboxRuntimeContext } from '../utils/runtime-context.js'\nimport { pushSandboxWorkspace } from '../utils/sandbox-push.js'\n\nexport function registerPushCommand(program: Command): void {\n program\n .command('push')\n .description('Push local workspace files to the sandbox workspace')\n .argument('[dir]', 'Local workspace directory', '.')\n .option('-m, --message <message>', 'Push message', 'moxt push')\n .action(async (sourceDir: string, options: { message: string }) => {\n const context = resolveSandboxRuntimeContextOrExit()\n\n try {\n const result = await pushSandboxWorkspace(context, sourceDir, { message: options.message })\n for (const change of result.changes) {\n print(`${change.action} ${change.workspacePath}`)\n }\n if (result.changes.length === 0) {\n print('No changes to push')\n return\n }\n\n const fileLabel = result.changes.length === 1 ? 'file' : 'files'\n print(`Pushed ${result.changes.length} ${fileLabel} from ${result.sourceDir}`)\n } catch (error) {\n handlePushError(error)\n }\n })\n}\n\nfunction resolveSandboxRuntimeContextOrExit(): SandboxRuntimeContext {\n let context\n try {\n context = resolveRuntimeContext()\n } catch (error) {\n if (error instanceof RuntimeContextError) {\n printError(error.message)\n process.exit(1)\n }\n throw error\n }\n\n if (context.mode !== 'sandbox') {\n printError('moxt push is only available in sandbox mode')\n process.exit(1)\n }\n return context\n}\n\nfunction handlePushError(error: unknown): never {\n if (error instanceof Error) {\n printError(error.message)\n process.exit(1)\n }\n throw error\n}\n","import { createHash } from 'node:crypto'\nimport { createReadStream } from 'node:fs'\nimport { lstat, readdir } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport {\n doesCheckoutPathIntersect,\n isCheckoutPathIncluded,\n type CheckoutState,\n} from './checkout-state.js'\n\nexport type CheckoutChangeAction = 'added' | 'modified' | 'deleted'\n\nexport interface CheckoutChange {\n action: CheckoutChangeAction\n path: string\n}\n\nexport class CheckoutStatusError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CheckoutStatusError'\n }\n}\n\nexport async function inspectCheckoutStatus(state: CheckoutState): Promise<CheckoutChange[]> {\n await requireCheckoutDirectory(state.checkoutRoot)\n const localFiles = new Map<string, string>()\n\n for (const repo of Object.values(state.repos)) {\n await scanDirectory(state, repo.name, join(state.checkoutRoot, repo.name), localFiles)\n }\n\n const changes: CheckoutChange[] = []\n for (const [path, sha] of localFiles) {\n const baseline = state.files[path]\n if (!baseline) changes.push({ action: 'added', path })\n else if (baseline.sha !== sha) changes.push({ action: 'modified', path })\n }\n for (const path of Object.keys(state.files)) {\n if (isCheckoutPathIncluded(state, path) && !localFiles.has(path)) changes.push({ action: 'deleted', path })\n }\n return changes.sort((left, right) => left.path.localeCompare(right.path))\n}\n\nasync function requireCheckoutDirectory(checkoutRoot: string): Promise<void> {\n let stats\n try {\n stats = await lstat(checkoutRoot)\n } catch (error) {\n throw new CheckoutStatusError(`Checkout root is not available: ${errorMessage(error)}`)\n }\n if (stats.isSymbolicLink()) throw new CheckoutStatusError(`Refusing to inspect symbolic link: ${checkoutRoot}`)\n if (!stats.isDirectory()) throw new CheckoutStatusError(`Checkout root is not a directory: ${checkoutRoot}`)\n}\n\nasync function scanDirectory(\n state: CheckoutState,\n workspacePath: string,\n localPath: string,\n files: Map<string, string>,\n): Promise<void> {\n let entries\n try {\n entries = await readdir(localPath, { withFileTypes: true })\n } catch (error) {\n if (isNodeError(error) && error.code === 'ENOENT') return\n throw new CheckoutStatusError(`Failed to inspect ${workspacePath}: ${errorMessage(error)}`)\n }\n\n for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {\n if (entry.name === '.git') continue\n const childWorkspacePath = `${workspacePath}/${entry.name}`\n if (!doesCheckoutPathIntersect(state, childWorkspacePath)) continue\n const childLocalPath = join(localPath, entry.name)\n const stats = await lstat(childLocalPath)\n if (stats.isSymbolicLink()) {\n throw new CheckoutStatusError(`Refusing to inspect symbolic link: ${childWorkspacePath}`)\n }\n if (stats.isDirectory()) {\n await scanDirectory(state, childWorkspacePath, childLocalPath, files)\n } else if (stats.isFile() && isCheckoutPathIncluded(state, childWorkspacePath)) {\n files.set(childWorkspacePath, await hashFile(childLocalPath))\n }\n }\n}\n\nasync function hashFile(path: string): Promise<string> {\n const hash = createHash('sha256')\n const stream = createReadStream(path)\n for await (const chunk of stream) hash.update(chunk)\n return hash.digest('hex')\n}\n\nfunction isNodeError(error: unknown): error is NodeJS.ErrnoException {\n return error instanceof Error && 'code' in error\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n","import { Command } from 'commander'\nimport { colors, print, printError } from '../utils/output.js'\nimport { resolveRuntimeContext, RuntimeContextError, type SandboxRuntimeContext } from '../utils/runtime-context.js'\nimport { listRepoEntries } from '../utils/sandbox-path.js'\nimport { loadCheckoutState, type CheckoutMode, type CheckoutState } from '../utils/checkout-state.js'\nimport { inspectCheckoutStatus, type CheckoutChange } from '../utils/checkout-status.js'\n\ninterface UninitializedStatusJson {\n mode: 'sandbox'\n workspaceId: string\n checkout: {\n mode: 'not_initialized'\n checkedOutScopes: string[]\n localChangesTracked: boolean\n }\n repos: Array<{\n name: string\n repoId: string\n }>\n}\n\ninterface InitializedStatusJson {\n mode: 'sandbox'\n workspaceId: string\n checkout: {\n mode: CheckoutMode\n root: string\n checkedOutScopes: string[]\n localChangesTracked: true\n changes: CheckoutChange[]\n }\n repos: Array<{\n name: string\n repoId: string\n }>\n}\n\ntype StatusJson = UninitializedStatusJson | InitializedStatusJson\n\nexport function registerStatusCommand(program: Command): void {\n program\n .command('status')\n .description('Show Moxt workspace checkout status')\n .option('--json', 'Print machine-readable status')\n .action(async (options: { json?: boolean }) => {\n const context = resolveRuntimeContextOrExit()\n if (context.mode !== 'sandbox') {\n printError('moxt status is only available in sandbox mode')\n process.exit(1)\n }\n\n const status = await buildSandboxStatusOrExit(context)\n if (options.json) {\n print(JSON.stringify(status, null, 2))\n return\n }\n\n print(`${colors.bold}Workspace${colors.reset}: ${status.workspaceId}`)\n print(`${colors.bold}Mode${colors.reset}: sandbox`)\n print(`${colors.bold}Checkout${colors.reset}: ${formatCheckoutMode(status.checkout.mode)}`)\n if (status.checkout.mode !== 'not_initialized') {\n print(`${colors.bold}Root${colors.reset}: ${status.checkout.root}`)\n }\n print('')\n print(`${colors.bold}Repos${colors.reset}:`)\n const repoNameWidth = status.repos.reduce((width, repo) => Math.max(width, repo.name.length), 0)\n for (const repo of status.repos) {\n print(` ${repo.name.padEnd(repoNameWidth)} ${repo.repoId}`)\n }\n print('')\n if (status.checkout.mode === 'not_initialized') {\n print(`${colors.bold}Checked out scopes${colors.reset}: none`)\n print(`${colors.bold}Local changes${colors.reset}: not tracked`)\n return\n }\n\n print(`${colors.bold}Checked out scopes${colors.reset}:`)\n for (const scope of status.checkout.checkedOutScopes) print(` ${scope}`)\n print(`${colors.bold}Local changes${colors.reset}:${status.checkout.changes.length === 0 ? ' none' : ''}`)\n for (const change of status.checkout.changes) {\n print(` ${change.action.padEnd(8)} ${change.path}`)\n }\n })\n}\n\nasync function buildSandboxStatusOrExit(context: SandboxRuntimeContext): Promise<StatusJson> {\n const repos = listRepoEntries(context.repoPayload).map((repo) => ({\n name: repo.name,\n repoId: repo.repoId,\n }))\n try {\n const state = await loadCheckoutState()\n if (!state) return buildUninitializedStatus(context.workspaceId, repos)\n validateStateContext(state, context)\n return {\n mode: 'sandbox',\n workspaceId: context.workspaceId,\n checkout: {\n mode: state.mode,\n root: state.checkoutRoot,\n checkedOutScopes: state.checkedOutScopes,\n localChangesTracked: true,\n changes: await inspectCheckoutStatus(state),\n },\n repos,\n }\n } catch (error) {\n printError(error instanceof Error ? error.message : String(error))\n process.exit(1)\n }\n}\n\nfunction buildUninitializedStatus(\n workspaceId: string,\n repos: UninitializedStatusJson['repos'],\n): UninitializedStatusJson {\n return {\n mode: 'sandbox',\n workspaceId,\n checkout: {\n mode: 'not_initialized',\n checkedOutScopes: [],\n localChangesTracked: false,\n },\n repos,\n }\n}\n\nfunction validateStateContext(state: CheckoutState, context: SandboxRuntimeContext): void {\n if (state.workspaceId !== context.workspaceId) {\n throw new Error(`Checkout state belongs to workspace ${state.workspaceId}, not ${context.workspaceId}`)\n }\n const currentRepos = new Map(listRepoEntries(context.repoPayload).map((repo) => [repo.repoId, repo.name]))\n for (const [repoId, repo] of Object.entries(state.repos)) {\n const currentName = currentRepos.get(repoId)\n if (!currentName) throw new Error(`Checkout state contains unknown repo: ${repoId}`)\n if (currentName !== repo.name) {\n throw new Error(`Checkout state repo name does not match current workspace: ${repo.name}`)\n }\n }\n}\n\nfunction resolveRuntimeContextOrExit() {\n try {\n return resolveRuntimeContext()\n } catch (error) {\n if (error instanceof RuntimeContextError) {\n printError(error.message)\n process.exit(1)\n }\n throw error\n }\n}\n\nfunction formatCheckoutMode(mode: StatusJson['checkout']['mode']): string {\n return mode === 'not_initialized' ? 'not initialized' : `${mode} checkout`\n}\n","import * as fs from 'node:fs'\nimport * as os from 'node:os'\nimport * as path from 'node:path'\n\nexport interface TelemetryConfig {\n disabled?: boolean\n noticeShown?: boolean\n}\n\nfunction getConfigPath(): string {\n return path.join(os.homedir(), '.moxt', 'config.json')\n}\n\nexport function readTelemetryConfig(): TelemetryConfig {\n try {\n const raw = fs.readFileSync(getConfigPath(), 'utf8')\n const parsed = JSON.parse(raw) as { telemetry?: TelemetryConfig }\n return parsed.telemetry ?? {}\n } catch {\n return {}\n }\n}\n\nexport function writeTelemetryConfig(update: Partial<TelemetryConfig>): void {\n const configPath = getConfigPath()\n let existing: Record<string, unknown> = {}\n try {\n existing = JSON.parse(fs.readFileSync(configPath, 'utf8')) as Record<string, unknown>\n } catch {\n existing = {}\n }\n const currentTelemetry = (existing.telemetry as TelemetryConfig | undefined) ?? {}\n const next = { ...existing, telemetry: { ...currentTelemetry, ...update } }\n fs.mkdirSync(path.dirname(configPath), { recursive: true })\n fs.writeFileSync(configPath, JSON.stringify(next, null, 2))\n}\n","import { readTelemetryConfig } from './config.js'\n\nexport function isCiEnvironment(): boolean {\n return process.env.CI === 'true' || process.env.CI === '1'\n}\n\nexport function isTelemetryDisabled(): boolean {\n if (process.env.MOXT_TELEMETRY_DISABLED === '1' || process.env.MOXT_TELEMETRY_DISABLED === 'true') {\n return true\n }\n if (process.env.DO_NOT_TRACK === '1' || process.env.DO_NOT_TRACK === 'true') {\n return true\n }\n return readTelemetryConfig().disabled === true\n}\n","import { Command } from 'commander'\nimport { readTelemetryConfig, writeTelemetryConfig } from '../telemetry/config.js'\nimport { isTelemetryDisabled } from '../telemetry/opt-out.js'\nimport { print } from '../utils/output.js'\n\nexport function registerTelemetryCommand(program: Command): void {\n const telemetry = program.command('telemetry').description('Manage Moxt CLI telemetry')\n\n telemetry\n .command('status')\n .description('Show telemetry status')\n .action(() => {\n const cfg = readTelemetryConfig()\n const envOverride =\n process.env.MOXT_TELEMETRY_DISABLED === '1' ||\n process.env.MOXT_TELEMETRY_DISABLED === 'true' ||\n process.env.DO_NOT_TRACK === '1' ||\n process.env.DO_NOT_TRACK === 'true'\n\n const state = isTelemetryDisabled() ? 'disabled' : 'enabled'\n print(`telemetry: ${state}`)\n if (envOverride) {\n print('(disabled via environment variable)')\n } else if (cfg.disabled) {\n print('(disabled via config file)')\n }\n })\n\n telemetry\n .command('enable')\n .description('Enable telemetry')\n .action(() => {\n writeTelemetryConfig({ disabled: false })\n print('telemetry: enabled')\n })\n\n telemetry\n .command('disable')\n .description('Disable telemetry')\n .action(() => {\n writeTelemetryConfig({ disabled: true })\n print('telemetry: disabled')\n })\n}\n","import { Command } from 'commander'\nimport { httpGet } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WhoamiResponse {\n nickname: string\n email: string\n}\n\nexport function registerWhoamiCommand(program: Command): void {\n program\n .command('whoami')\n .description('Show current user information')\n .action(async () => {\n startSpinner('Fetching user info...')\n const response = await httpGet<WhoamiResponse>('/users/whoami')\n\n if (response.ok) {\n stopSpinner(true, 'Done')\n print(`${colors.bold}Nickname${colors.reset}: ${response.data.nickname}`)\n print(`${colors.bold}Email${colors.reset}: ${response.data.email}`)\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n}\n","import { Command } from 'commander'\nimport { httpGet, httpDelete } from '../utils/http.js'\nimport { colors, print, printError } from '../utils/output.js'\nimport { startSpinner, stopSpinner } from '../utils/spinner.js'\n\ninterface WorkspaceItem {\n workspaceId: string\n name: string\n}\n\ninterface WorkspaceListResponse {\n workspaces: WorkspaceItem[]\n}\n\ninterface MemberItem {\n userId: number\n email: string\n displayName: string | null\n role: string\n}\n\ninterface MembersResponse {\n members: MemberItem[]\n}\n\ninterface SpaceItem {\n type: 'personal' | 'team' | 'teammate'\n name: string\n teamSpaceId: string | null\n agentId: number | null\n}\n\n// Email regex (same as web/src/utils/email.ts)\nconst emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/\n\nfunction isValidEmail(email: string): boolean {\n return emailRegex.test(email)\n}\n\nexport function registerWorkspaceCommand(program: Command): void {\n const workspace = program.command('workspace').description('Workspace management')\n\n workspace\n .command('list')\n .description('List all workspaces you belong to')\n .action(async () => {\n startSpinner('Fetching workspaces...')\n const response = await httpGet<WorkspaceListResponse>('/workspaces')\n\n if (response.ok) {\n const { workspaces } = response.data\n if (workspaces.length === 0) {\n stopSpinner(true, 'No workspaces found.')\n return\n }\n\n stopSpinner(true, `Found ${workspaces.length} workspace(s)`)\n\n for (const ws of workspaces) {\n print(`${colors.bold}${ws.workspaceId}${colors.reset}\\t${ws.name}`)\n }\n } else {\n stopSpinner(false, 'Failed')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n })\n\n const members = program.command('members').description('Manage workspace members')\n\n members\n .command('list')\n .description('List all members in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching workspace members...')\n const response = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { members } = response.data\n if (members.length === 0) {\n stopSpinner(true, 'No members found.')\n return\n }\n\n stopSpinner(true, `Found ${members.length} member(s)`)\n\n for (const member of members) {\n const name = member.displayName || '-'\n print(`${colors.bold}${member.email}${colors.reset}\\t${name}\\t${member.role}`)\n }\n })\n\n members\n .command('remove')\n .description('Remove members from a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .argument('<emails>', 'Emails to remove (comma-separated)')\n .action(async (emailsArg: string, options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n const emails = emailsArg.split(',').map((e) => e.trim()).filter(Boolean)\n if (emails.length === 0) {\n printError('No valid emails provided')\n process.exit(1)\n }\n\n // Validate email format\n const invalidEmails = emails.filter((e) => !isValidEmail(e))\n if (invalidEmails.length > 0) {\n for (const email of invalidEmails) {\n printError(`Invalid email format: ${email}`)\n }\n process.exit(1)\n }\n\n // Fetch members to get userId by email\n startSpinner('Fetching workspace members...')\n const membersResponse = await httpGet<MembersResponse>(`/workspaces/${workspaceId}/members`)\n\n if (!membersResponse.ok) {\n stopSpinner(false, 'Failed to fetch members')\n printError(`Error [${membersResponse.status}]: ${JSON.stringify(membersResponse.data)}`)\n process.exit(1)\n }\n\n stopSpinner(true, 'Members fetched')\n\n const { members } = membersResponse.data\n const emailToMember = new Map(members.map((m) => [m.email.toLowerCase(), m]))\n\n // Remove each member\n for (const email of emails) {\n const member = emailToMember.get(email.toLowerCase())\n if (!member) {\n print(`${colors.red}✗${colors.reset} ${email} - not found in workspace`)\n continue\n }\n\n const deleteResponse = await httpDelete(`/workspaces/${workspaceId}/members/${member.userId}`)\n\n if (deleteResponse.ok) {\n print(`${colors.green}✓${colors.reset} ${email} - removed`)\n } else {\n print(`${colors.red}✗${colors.reset} ${email} - failed: ${JSON.stringify(deleteResponse.data)}`)\n }\n }\n })\n\n const space = program.command('space').description('Manage spaces')\n\n space\n .command('list')\n .description('List accessible spaces in a workspace')\n .requiredOption('-w, --workspace <workspaceId>', 'Workspace ID')\n .action(async (options: { workspace: string }) => {\n const { workspace: workspaceId } = options\n\n startSpinner('Fetching spaces...')\n const response = await httpGet<{ spaces: SpaceItem[] }>(`/workspaces/${workspaceId}/spaces`)\n\n if (!response.ok) {\n stopSpinner(false, 'Failed to fetch spaces')\n printError(`Error [${response.status}]: ${JSON.stringify(response.data)}`)\n process.exit(1)\n }\n\n const { spaces } = response.data\n if (spaces.length === 0) {\n stopSpinner(true, 'No spaces found.')\n return\n }\n\n stopSpinner(true, `Found ${spaces.length} space(s)`)\n\n print(\n `${colors.bold}TYPE${colors.reset}\\t${colors.bold}TEAM_SPACE_ID${colors.reset}\\t${colors.bold}TEAMMATE_ID${colors.reset}\\t${colors.bold}NAME${colors.reset}`,\n )\n for (const s of spaces) {\n const teamSpaceId = s.teamSpaceId ?? ''\n const teammateId = s.agentId != null ? String(s.agentId) : ''\n print(`${s.type}\\t${teamSpaceId}\\t${teammateId}\\t${s.name}`)\n }\n })\n\n}\n","import { arch, platform } from 'node:os'\nimport { getApiBaseUrl, getApiKeyOrUndefined } from '../utils/config.js'\nimport { isCiEnvironment, isTelemetryDisabled } from './opt-out.js'\n\ndeclare const __CLI_VERSION__: string\n\nexport type MetricType = 'counter' | 'gauge' | 'histogram'\n\nexport interface MetricRecord {\n metric_id: string\n metric_type: MetricType\n value: number\n extra_label_name_2_value?: Record<string, string>\n}\n\nconst buffer: MetricRecord[] = []\nconst FLUSH_TIMEOUT_MS = 3000\nconst MAX_BATCH_SIZE = 100\n\nfunction commonLabels(): Record<string, string> {\n return {\n cli_version: __CLI_VERSION__,\n node_version: process.versions.node,\n os: platform(),\n arch: arch(),\n is_ci: isCiEnvironment() ? 'true' : 'false',\n }\n}\n\nexport function record(metric: MetricRecord): void {\n if (isTelemetryDisabled()) {\n debugLog(`record: disabled, dropping ${metric.metric_id}`)\n return\n }\n if (!getApiKeyOrUndefined()) {\n debugLog(`record: no API key, dropping ${metric.metric_id}`)\n return\n }\n buffer.push({\n ...metric,\n extra_label_name_2_value: {\n ...commonLabels(),\n ...(metric.extra_label_name_2_value ?? {}),\n },\n })\n debugLog(`record: buffered ${metric.metric_id} (buffer=${buffer.length})`)\n}\n\nfunction isDebug(): boolean {\n return process.env.MOXT_TELEMETRY_DEBUG === '1' || process.env.MOXT_TELEMETRY_DEBUG === 'true'\n}\n\nfunction debugLog(msg: string, detail?: unknown): void {\n if (!isDebug()) return\n process.stderr.write(`[telemetry] ${msg}${detail !== undefined ? ` ${JSON.stringify(detail)}` : ''}\\n`)\n}\n\nexport async function flush(): Promise<void> {\n if (buffer.length === 0) {\n debugLog('flush: buffer empty, skipping')\n return\n }\n const apiKey = getApiKeyOrUndefined()\n if (!apiKey) {\n debugLog('flush: no API key, dropping buffer')\n buffer.length = 0\n return\n }\n\n const batch = buffer.splice(0, MAX_BATCH_SIZE)\n const payload = {\n release_id: __CLI_VERSION__,\n client_type: 'cli',\n metric_data_list: batch.map((m) => ({\n profile: 'cli',\n metric_id: m.metric_id,\n metric_type: m.metric_type,\n value: m.value,\n extra_label_name_2_value: m.extra_label_name_2_value,\n })),\n }\n\n const url = `${getApiBaseUrl()}/cli-metrics`\n debugLog(`flush: POST ${url} with ${batch.length} metrics`, payload)\n\n try {\n const controller = new AbortController()\n const timeout = setTimeout(() => {\n controller.abort()\n }, FLUSH_TIMEOUT_MS)\n try {\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n })\n debugLog(`flush: response status=${res.status}`)\n } finally {\n clearTimeout(timeout)\n }\n } catch (err) {\n debugLog('flush: failed', err instanceof Error ? err.message : String(err))\n // fire-and-forget — never surface telemetry failures to the user\n }\n}\n","import { readTelemetryConfig, writeTelemetryConfig } from './config.js'\nimport { isCiEnvironment, isTelemetryDisabled } from './opt-out.js'\n\nconst NOTICE = [\n '',\n 'Attention: Moxt CLI now collects anonymous telemetry regarding usage.',\n \"This information is used to shape Moxt CLI's roadmap and prioritize features.\",\n '',\n 'You may opt out by setting MOXT_TELEMETRY_DISABLED=1 in your env',\n 'or by running `moxt telemetry disable`.',\n 'Details: https://www.npmjs.com/package/@moxt-ai/cli#telemetry',\n '',\n]\n\nexport function maybeShowTelemetryNotice(): void {\n if (isTelemetryDisabled()) return\n if (isCiEnvironment()) return\n if (readTelemetryConfig().noticeShown) return\n\n for (const line of NOTICE) {\n process.stderr.write(`${line}\\n`)\n }\n\n try {\n writeTelemetryConfig({ noticeShown: true })\n } catch {\n // persistence failure is not user-visible — we'll just show the notice again next run\n }\n}\n","import type { Command } from 'commander'\nimport { flush, record } from './client.js'\nimport { maybeShowTelemetryNotice } from './notice.js'\n\ninterface RunningCommand {\n name: string\n subcommand?: string\n startedAt: number\n}\n\nlet current: RunningCommand | null = null\n\nfunction commandPath(cmd: Command): { command: string; subcommand?: string } {\n const names: string[] = []\n let node: Command | null = cmd\n while (node && node.parent) {\n names.unshift(node.name())\n node = node.parent\n }\n if (names.length === 0) return { command: 'unknown' }\n if (names.length === 1) return { command: names[0] }\n return { command: names[0], subcommand: names.slice(1).join(' ') }\n}\n\nexport function instrumentProgram(program: Command): void {\n program.hook('preAction', (_thisCommand, actionCommand) => {\n const { command, subcommand } = commandPath(actionCommand)\n if (command !== 'telemetry') {\n maybeShowTelemetryNotice()\n }\n current = { name: command, subcommand, startedAt: Date.now() }\n record({\n metric_id: 'client.cli.command_invocation.count',\n metric_type: 'counter',\n value: 1,\n extra_label_name_2_value: {\n command,\n ...(subcommand ? { subcommand } : {}),\n status: 'started',\n },\n })\n })\n\n program.hook('postAction', async () => {\n await reportOutcome('success')\n })\n}\n\nasync function reportOutcome(status: 'success' | 'error', errorCode?: string): Promise<void> {\n if (!current) return\n const { name, subcommand, startedAt } = current\n const durationSeconds = (Date.now() - startedAt) / 1000\n\n record({\n metric_id: 'client.cli.command_duration_seconds',\n metric_type: 'histogram',\n value: durationSeconds,\n extra_label_name_2_value: {\n command: name,\n ...(subcommand ? { subcommand } : {}),\n status,\n },\n })\n\n if (status === 'error') {\n record({\n metric_id: 'client.cli.command_error.count',\n metric_type: 'counter',\n value: 1,\n extra_label_name_2_value: {\n command: name,\n ...(subcommand ? { subcommand } : {}),\n ...(errorCode ? { error_code: errorCode } : {}),\n },\n })\n }\n\n current = null\n await flush()\n}\n\n/**\n * Wire a final error/exit hook. Call before program.parseAsync so we can capture\n * failures routed through process.exit or unhandled rejections.\n *\n * Best-effort only: `reportOutcome` is fire-and-forget, and the subsequent\n * `process.exit(1)` terminates the process before `flush()` can complete — so\n * the error metric recorded here will typically be dropped. Reliable crash\n * reporting belongs to Sentry/APM, not this telemetry path.\n */\nexport function installExitHandler(): void {\n const handleError = (errorCode: string): void => {\n void reportOutcome('error', errorCode)\n }\n\n process.on('uncaughtException', () => {\n handleError('uncaught_exception')\n process.exit(1)\n })\n process.on('unhandledRejection', () => {\n handleError('unhandled_rejection')\n process.exit(1)\n })\n}\n"],"mappings":";;;AAAA,OAAO,oBAAoB;;;ACA3B,SAAS,WAAAA,gBAAe;;;ACCjB,IAAM,SAAS;AAAA,EAClB,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,KAAK;AAAA,EACL,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO;AACX;AAEO,SAAS,MAAM,SAAuB;AACzC,UAAQ,IAAI,OAAO;AACvB;AAEO,SAAS,WAAW,SAAuB;AAC9C,UAAQ,MAAM,GAAG,OAAO,GAAG,GAAG,OAAO,GAAG,OAAO,KAAK,EAAE;AAC1D;;;ACUA,IAAM,oBAAoB;AACnB,IAAM,mBAAmB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ;AAEO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC3C,YAAY,SAAiB;AACzB,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EAChB;AACJ;AAEO,SAAS,sBAAsB,MAAyB,QAAQ,KAAqB;AACxF,MAAI,iBAAiB,GAAG,GAAG;AACvB,WAAO,6BAA6B,GAAG;AAAA,EAC3C;AAEA,QAAM,SAAS,gBAAgB,KAAK,cAAc;AAClD,MAAI,QAAQ;AACR,WAAO;AAAA,MACH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KAAK,YAAY;AACd,QAAM,MAAM;AAChB,CAAC,EACA,MAAM,OAAO,QAAiB;AAC3B,UAAQ,MAAM,cAAc,GAAG;AAC/B,QAAM,MAAM;AACZ,UAAQ,KAAK,CAAC;AAClB,CAAC;","names":["Command","path","record","program","fs","path","buffer","path","path","program","path","content","response","action","buffer","program","path","runOrExit","path","program","isAbsolute","createHash","mkdir","readFile","rm","writeFile","dirname","isAbsolute","path","rm","mkdir","path","createHash","isNodeError","readFile","dirname","writeFile","isAbsolute","program","resolveSandboxRuntimeContextOrExit","isAbsolute","createHash","lstat","readFile","isAbsolute","join","relative","resolve","MFS_FILE_TYPE_REGULAR","resolve","fetchWorkspaceTree","lstat","isNodeError","join","readFile","createHash","relative","isAbsolute","program","resolveSandboxRuntimeContextOrExit","createHash","lstat","readdir","join","join","path","lstat","errorMessage","readdir","isNodeError","createHash","program","resolveRuntimeContextOrExit","fs","program","program","program","members","program","Command","arch","platform","platform","arch","program"]}
|