acpx 0.1.16 → 0.2.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/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +13 -13
- package/dist/cli.js.map +1 -1
- package/dist/{output-render-C_rsjEYP.js → output-render-Cvz0eKSb.js} +2 -2
- package/dist/{output-render-C_rsjEYP.js.map → output-render-Cvz0eKSb.js.map} +1 -1
- package/dist/{queue-ipc-CEetz4_7.js → queue-ipc-C8StWiZt.js} +306 -254
- package/dist/queue-ipc-C8StWiZt.js.map +1 -0
- package/dist/{session-BARXiu6-.js → session-C6nyqSfk.js} +16 -15
- package/dist/session-C6nyqSfk.js.map +1 -0
- package/package.json +1 -4
- package/dist/queue-ipc-CEetz4_7.js.map +0 -1
- package/dist/session-BARXiu6-.js.map +0 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "acpx",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Headless CLI client for the Agent Client Protocol (ACP) — talk to coding agents from the command line",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"acp",
|
|
@@ -46,8 +46,6 @@
|
|
|
46
46
|
"precommit": "pnpm exec lint-staged && pnpm run -s build",
|
|
47
47
|
"prepack": "pnpm run build",
|
|
48
48
|
"prepare": "husky",
|
|
49
|
-
"release": "release-it",
|
|
50
|
-
"release:ci": "release-it --ci",
|
|
51
49
|
"test": "pnpm run build:test && node --test dist-test/test/*.test.js",
|
|
52
50
|
"test:coverage": "pnpm run build:test && node --experimental-test-coverage --test-coverage-lines=83 --test-coverage-branches=76 --test-coverage-functions=86 --test dist-test/test/*.test.js",
|
|
53
51
|
"typecheck": "tsgo --noEmit",
|
|
@@ -67,7 +65,6 @@
|
|
|
67
65
|
"oxfmt": "^0.36.0",
|
|
68
66
|
"oxlint": "^1.51.0",
|
|
69
67
|
"oxlint-tsgolint": "^0.16.0",
|
|
70
|
-
"release-it": "^19.2.4",
|
|
71
68
|
"tsdown": "^0.21.0-beta.2",
|
|
72
69
|
"tsx": "^4.0.0",
|
|
73
70
|
"typescript": "^5.7.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"queue-ipc-CEetz4_7.js","names":["asRecord","isOutputErrorCode","isOutputErrorOrigin"],"sources":["../src/errors.ts","../src/types.ts","../src/error-normalization.ts","../src/perf-metrics.ts","../src/queue-paths.ts","../src/queue-lease-store.ts","../src/queue-messages.ts","../src/queue-ipc-server.ts","../src/queue-ipc.ts"],"sourcesContent":["import type { OutputErrorAcpPayload, OutputErrorCode, OutputErrorOrigin } from \"./types.js\";\n\ntype AcpxErrorOptions = ErrorOptions & {\n outputCode?: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n outputAlreadyEmitted?: boolean;\n};\n\nexport class AcpxOperationalError extends Error {\n readonly outputCode?: OutputErrorCode;\n readonly detailCode?: string;\n readonly origin?: OutputErrorOrigin;\n readonly retryable?: boolean;\n readonly acp?: OutputErrorAcpPayload;\n readonly outputAlreadyEmitted?: boolean;\n\n constructor(message: string, options?: AcpxErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n this.outputCode = options?.outputCode;\n this.detailCode = options?.detailCode;\n this.origin = options?.origin;\n this.retryable = options?.retryable;\n this.acp = options?.acp;\n this.outputAlreadyEmitted = options?.outputAlreadyEmitted;\n }\n}\n\nexport class SessionNotFoundError extends AcpxOperationalError {\n readonly sessionId: string;\n\n constructor(sessionId: string) {\n super(`Session not found: ${sessionId}`);\n this.sessionId = sessionId;\n }\n}\n\nexport class SessionResolutionError extends AcpxOperationalError {}\n\nexport class AgentSpawnError extends AcpxOperationalError {\n readonly agentCommand: string;\n\n constructor(agentCommand: string, cause?: unknown) {\n super(`Failed to spawn agent command: ${agentCommand}`, {\n cause: cause instanceof Error ? cause : undefined,\n });\n this.agentCommand = agentCommand;\n }\n}\n\nexport class GeminiAcpStartupTimeoutError extends AcpxOperationalError {\n constructor(message: string, options?: AcpxErrorOptions) {\n super(message, {\n outputCode: \"TIMEOUT\",\n detailCode: \"GEMINI_ACP_STARTUP_TIMEOUT\",\n origin: \"acp\",\n ...options,\n });\n }\n}\n\nexport class SessionModeReplayError extends AcpxOperationalError {\n constructor(message: string, options?: AcpxErrorOptions) {\n super(message, {\n outputCode: \"RUNTIME\",\n detailCode: \"SESSION_MODE_REPLAY_FAILED\",\n origin: \"acp\",\n ...options,\n });\n }\n}\n\nexport class ClaudeAcpSessionCreateTimeoutError extends AcpxOperationalError {\n constructor(message: string, options?: AcpxErrorOptions) {\n super(message, {\n outputCode: \"TIMEOUT\",\n detailCode: \"CLAUDE_ACP_SESSION_CREATE_TIMEOUT\",\n origin: \"acp\",\n ...options,\n });\n }\n}\n\nexport class CopilotAcpUnsupportedError extends AcpxOperationalError {\n constructor(message: string, options?: AcpxErrorOptions) {\n super(message, {\n outputCode: \"RUNTIME\",\n detailCode: \"COPILOT_ACP_UNSUPPORTED\",\n origin: \"acp\",\n ...options,\n });\n }\n}\n\nexport class AuthPolicyError extends AcpxOperationalError {\n constructor(message: string, options?: AcpxErrorOptions) {\n super(message, {\n outputCode: \"RUNTIME\",\n detailCode: \"AUTH_REQUIRED\",\n origin: \"acp\",\n ...options,\n });\n }\n}\n\nexport class QueueConnectionError extends AcpxOperationalError {}\n\nexport class QueueProtocolError extends AcpxOperationalError {}\n\nexport class PermissionDeniedError extends AcpxOperationalError {}\n\nexport class PermissionPromptUnavailableError extends AcpxOperationalError {\n constructor() {\n super(\"Permission prompt unavailable in non-interactive mode\");\n }\n}\n","import type {\n AgentCapabilities,\n AnyMessage,\n McpServer,\n SessionNotification,\n SessionConfigOption,\n SetSessionConfigOptionResponse,\n StopReason,\n} from \"@agentclientprotocol/sdk\";\nexport type { McpServer } from \"@agentclientprotocol/sdk\";\n\nexport const EXIT_CODES = {\n SUCCESS: 0,\n ERROR: 1,\n USAGE: 2,\n TIMEOUT: 3,\n NO_SESSION: 4,\n PERMISSION_DENIED: 5,\n INTERRUPTED: 130,\n} as const;\n\nexport type ExitCode = (typeof EXIT_CODES)[keyof typeof EXIT_CODES];\n\nexport const OUTPUT_FORMATS = [\"text\", \"json\", \"quiet\"] as const;\nexport type OutputFormat = (typeof OUTPUT_FORMATS)[number];\n\nexport const PERMISSION_MODES = [\"approve-all\", \"approve-reads\", \"deny-all\"] as const;\nexport type PermissionMode = (typeof PERMISSION_MODES)[number];\n\nexport const AUTH_POLICIES = [\"skip\", \"fail\"] as const;\nexport type AuthPolicy = (typeof AUTH_POLICIES)[number];\n\nexport const NON_INTERACTIVE_PERMISSION_POLICIES = [\"deny\", \"fail\"] as const;\nexport type NonInteractivePermissionPolicy = (typeof NON_INTERACTIVE_PERMISSION_POLICIES)[number];\n\nexport const OUTPUT_STREAMS = [\"prompt\", \"control\"] as const;\nexport type OutputStream = (typeof OUTPUT_STREAMS)[number];\nexport type AcpJsonRpcMessage = AnyMessage;\nexport type AcpMessageDirection = \"outbound\" | \"inbound\";\n\nexport const OUTPUT_ERROR_CODES = [\n \"NO_SESSION\",\n \"TIMEOUT\",\n \"PERMISSION_DENIED\",\n \"PERMISSION_PROMPT_UNAVAILABLE\",\n \"RUNTIME\",\n \"USAGE\",\n] as const;\nexport type OutputErrorCode = (typeof OUTPUT_ERROR_CODES)[number];\n\nexport const OUTPUT_ERROR_ORIGINS = [\"cli\", \"runtime\", \"queue\", \"acp\"] as const;\nexport type OutputErrorOrigin = (typeof OUTPUT_ERROR_ORIGINS)[number];\n\nexport const QUEUE_ERROR_DETAIL_CODES = [\n \"QUEUE_OWNER_CLOSED\",\n \"QUEUE_OWNER_SHUTTING_DOWN\",\n \"QUEUE_OWNER_OVERLOADED\",\n \"QUEUE_OWNER_GENERATION_MISMATCH\",\n \"QUEUE_REQUEST_INVALID\",\n \"QUEUE_REQUEST_PAYLOAD_INVALID_JSON\",\n \"QUEUE_ACK_MISSING\",\n \"QUEUE_DISCONNECTED_BEFORE_ACK\",\n \"QUEUE_DISCONNECTED_BEFORE_COMPLETION\",\n \"QUEUE_PROTOCOL_INVALID_JSON\",\n \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n \"QUEUE_PROTOCOL_UNEXPECTED_RESPONSE\",\n \"QUEUE_NOT_ACCEPTING_REQUESTS\",\n \"QUEUE_CONTROL_REQUEST_FAILED\",\n \"QUEUE_RUNTIME_PROMPT_FAILED\",\n] as const;\nexport type QueueErrorDetailCode = (typeof QUEUE_ERROR_DETAIL_CODES)[number];\n\nexport type OutputErrorAcpPayload = {\n code: number;\n message: string;\n data?: unknown;\n};\n\nexport type PermissionStats = {\n requested: number;\n approved: number;\n denied: number;\n cancelled: number;\n};\n\nexport type ClientOperationMethod =\n | \"fs/read_text_file\"\n | \"fs/write_text_file\"\n | \"terminal/create\"\n | \"terminal/output\"\n | \"terminal/wait_for_exit\"\n | \"terminal/kill\"\n | \"terminal/release\";\n\nexport type ClientOperationStatus = \"running\" | \"completed\" | \"failed\";\n\nexport type ClientOperation = {\n method: ClientOperationMethod;\n status: ClientOperationStatus;\n summary: string;\n details?: string;\n timestamp: string;\n};\n\nexport type SessionEventLog = {\n active_path: string;\n segment_count: number;\n max_segment_bytes: number;\n max_segments: number;\n last_write_at?: string;\n last_write_error?: string | null;\n};\n\nexport type PerfMetricSummary = {\n count: number;\n totalMs: number;\n maxMs: number;\n};\n\nexport type PerfMetricsSnapshot = {\n counters: Record<string, number>;\n timings: Record<string, PerfMetricSummary>;\n gauges: Record<string, number>;\n};\n\nexport type OutputFormatterContext = {\n sessionId: string;\n};\n\nexport type OutputPolicy = {\n format: OutputFormat;\n jsonStrict: boolean;\n suppressNonJsonStderr: boolean;\n queueErrorAlreadyEmitted: boolean;\n suppressSdkConsoleErrors: boolean;\n};\n\nexport type OutputErrorEmissionPolicy = {\n queueErrorAlreadyEmitted: boolean;\n};\n\nexport interface OutputFormatter {\n setContext(context: OutputFormatterContext): void;\n onAcpMessage(message: AcpJsonRpcMessage): void;\n onError(params: {\n code: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n message: string;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n timestamp?: string;\n }): void;\n flush(): void;\n}\n\nexport type AcpClientOptions = {\n agentCommand: string;\n cwd: string;\n mcpServers?: McpServer[];\n permissionMode: PermissionMode;\n nonInteractivePermissions?: NonInteractivePermissionPolicy;\n authCredentials?: Record<string, string>;\n authPolicy?: AuthPolicy;\n suppressSdkConsoleErrors?: boolean;\n verbose?: boolean;\n sessionOptions?: {\n model?: string;\n allowedTools?: string[];\n maxTurns?: number;\n };\n onAcpMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;\n onAcpOutputMessage?: (direction: AcpMessageDirection, message: AcpJsonRpcMessage) => void;\n onSessionUpdate?: (notification: SessionNotification) => void;\n onClientOperation?: (operation: ClientOperation) => void;\n};\n\nexport const SESSION_RECORD_SCHEMA = \"acpx.session.v1\" as const;\nexport type SessionMessageImage = {\n source: string;\n size?: {\n width: number;\n height: number;\n } | null;\n};\n\nexport type SessionUserContent =\n | {\n Text: string;\n }\n | {\n Mention: {\n uri: string;\n content: string;\n };\n }\n | {\n Image: SessionMessageImage;\n };\n\nexport type SessionToolUse = {\n id: string;\n name: string;\n raw_input: string;\n input: unknown;\n is_input_complete: boolean;\n thought_signature?: string | null;\n};\n\nexport type SessionToolResultContent =\n | {\n Text: string;\n }\n | {\n Image: SessionMessageImage;\n };\n\nexport type SessionToolResult = {\n tool_use_id: string;\n tool_name: string;\n is_error: boolean;\n content: SessionToolResultContent;\n output?: unknown;\n};\n\nexport type SessionAgentContent =\n | {\n Text: string;\n }\n | {\n Thinking: {\n text: string;\n signature?: string | null;\n };\n }\n | {\n RedactedThinking: string;\n }\n | {\n ToolUse: SessionToolUse;\n };\n\nexport type SessionUserMessage = {\n id: string;\n content: SessionUserContent[];\n};\n\nexport type SessionAgentMessage = {\n content: SessionAgentContent[];\n tool_results: Record<string, SessionToolResult>;\n reasoning_details?: unknown;\n};\n\nexport type SessionMessage =\n | {\n User: SessionUserMessage;\n }\n | {\n Agent: SessionAgentMessage;\n }\n | \"Resume\";\n\nexport type SessionTokenUsage = {\n input_tokens?: number;\n output_tokens?: number;\n cache_creation_input_tokens?: number;\n cache_read_input_tokens?: number;\n};\n\nexport type SessionConversation = {\n title?: string | null;\n messages: SessionMessage[];\n updated_at: string;\n cumulative_token_usage: SessionTokenUsage;\n request_token_usage: Record<string, SessionTokenUsage>;\n};\n\nexport type SessionAcpxState = {\n current_mode_id?: string;\n desired_mode_id?: string;\n available_commands?: string[];\n config_options?: SessionConfigOption[];\n};\n\nexport type SessionRecord = {\n schema: typeof SESSION_RECORD_SCHEMA;\n acpxRecordId: string;\n acpSessionId: string;\n agentSessionId?: string;\n agentCommand: string;\n cwd: string;\n name?: string;\n createdAt: string;\n lastUsedAt: string;\n lastSeq: number;\n lastRequestId?: string;\n eventLog: SessionEventLog;\n closed?: boolean;\n closedAt?: string;\n pid?: number;\n agentStartedAt?: string;\n lastPromptAt?: string;\n lastAgentExitCode?: number | null;\n lastAgentExitSignal?: NodeJS.Signals | null;\n lastAgentExitAt?: string;\n lastAgentDisconnectReason?: string;\n protocolVersion?: number;\n agentCapabilities?: AgentCapabilities;\n title?: string | null;\n messages: SessionMessage[];\n updated_at: string;\n cumulative_token_usage: SessionTokenUsage;\n request_token_usage: Record<string, SessionTokenUsage>;\n acpx?: SessionAcpxState;\n};\n\nexport type RunPromptResult = {\n stopReason: StopReason;\n permissionStats: PermissionStats;\n sessionId: string;\n};\n\nexport type SessionSendResult = RunPromptResult & {\n record: SessionRecord;\n resumed: boolean;\n loadError?: string;\n};\n\nexport type SessionSetModeResult = {\n record: SessionRecord;\n resumed: boolean;\n loadError?: string;\n};\n\nexport type SessionSetConfigOptionResult = {\n record: SessionRecord;\n response: SetSessionConfigOptionResponse;\n resumed: boolean;\n loadError?: string;\n};\n\nexport type SessionEnsureResult = {\n record: SessionRecord;\n created: boolean;\n};\n\nexport type SessionEnqueueResult = {\n queued: true;\n sessionId: string;\n requestId: string;\n};\n\nexport type SessionSendOutcome = SessionSendResult | SessionEnqueueResult;\n","import {\n AuthPolicyError,\n PermissionDeniedError,\n PermissionPromptUnavailableError,\n} from \"./errors.js\";\nimport {\n EXIT_CODES,\n OUTPUT_ERROR_CODES,\n OUTPUT_ERROR_ORIGINS,\n type ExitCode,\n type OutputErrorAcpPayload,\n type OutputErrorCode,\n type OutputErrorOrigin,\n} from \"./types.js\";\n\nconst RESOURCE_NOT_FOUND_ACP_CODES = new Set([-32002]);\nconst AUTH_REQUIRED_ACP_CODES = new Set([-32000]);\nconst QUERY_CLOSED_BEFORE_RESPONSE_DETAIL = \"query closed before response received\";\n\ntype ErrorMeta = {\n outputCode?: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n};\n\nexport type NormalizedOutputError = {\n code: OutputErrorCode;\n message: string;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n};\n\nexport type NormalizeOutputErrorOptions = {\n defaultCode?: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n};\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n return value as Record<string, unknown>;\n}\n\nfunction isAuthRequiredMessage(value: string | undefined): boolean {\n if (!value) {\n return false;\n }\n const normalized = value.toLowerCase();\n return (\n normalized.includes(\"auth required\") ||\n normalized.includes(\"authentication required\") ||\n normalized.includes(\"authorization required\") ||\n normalized.includes(\"credential required\") ||\n normalized.includes(\"credentials required\") ||\n normalized.includes(\"token required\") ||\n normalized.includes(\"login required\")\n );\n}\n\nfunction isAcpAuthRequiredPayload(acp: OutputErrorAcpPayload | undefined): boolean {\n if (!acp) {\n return false;\n }\n if (!AUTH_REQUIRED_ACP_CODES.has(acp.code)) {\n return false;\n }\n if (isAuthRequiredMessage(acp.message)) {\n return true;\n }\n\n const data = asRecord(acp.data);\n if (!data) {\n return false;\n }\n\n if (data.authRequired === true) {\n return true;\n }\n\n const methodId = data.methodId;\n if (typeof methodId === \"string\" && methodId.trim().length > 0) {\n return true;\n }\n\n const methods = data.methods;\n if (Array.isArray(methods) && methods.length > 0) {\n return true;\n }\n\n return false;\n}\n\nfunction isOutputErrorCode(value: unknown): value is OutputErrorCode {\n return typeof value === \"string\" && OUTPUT_ERROR_CODES.includes(value as OutputErrorCode);\n}\n\nfunction isOutputErrorOrigin(value: unknown): value is OutputErrorOrigin {\n return typeof value === \"string\" && OUTPUT_ERROR_ORIGINS.includes(value as OutputErrorOrigin);\n}\n\nfunction readOutputErrorMeta(error: unknown): ErrorMeta {\n const record = asRecord(error);\n if (!record) {\n return {};\n }\n\n const outputCode = isOutputErrorCode(record.outputCode) ? record.outputCode : undefined;\n const detailCode =\n typeof record.detailCode === \"string\" && record.detailCode.trim().length > 0\n ? record.detailCode\n : undefined;\n const origin = isOutputErrorOrigin(record.origin) ? record.origin : undefined;\n const retryable = typeof record.retryable === \"boolean\" ? record.retryable : undefined;\n\n const acp = toAcpErrorPayload(record.acp);\n return {\n outputCode,\n detailCode,\n origin,\n retryable,\n acp,\n };\n}\n\nfunction toAcpErrorPayload(value: unknown): OutputErrorAcpPayload | undefined {\n const record = asRecord(value);\n if (!record) {\n return undefined;\n }\n\n if (typeof record.code !== \"number\" || !Number.isFinite(record.code)) {\n return undefined;\n }\n if (typeof record.message !== \"string\" || record.message.length === 0) {\n return undefined;\n }\n\n return {\n code: record.code,\n message: record.message,\n data: record.data,\n };\n}\n\nfunction extractAcpErrorInternal(value: unknown, depth: number): OutputErrorAcpPayload | undefined {\n if (depth > 5) {\n return undefined;\n }\n\n const direct = toAcpErrorPayload(value);\n if (direct) {\n return direct;\n }\n\n const record = asRecord(value);\n if (!record) {\n return undefined;\n }\n\n if (\"error\" in record) {\n const nested = extractAcpErrorInternal(record.error, depth + 1);\n if (nested) {\n return nested;\n }\n }\n\n if (\"cause\" in record) {\n const nested = extractAcpErrorInternal(record.cause, depth + 1);\n if (nested) {\n return nested;\n }\n }\n\n return undefined;\n}\n\nfunction isTimeoutLike(error: unknown): boolean {\n return error instanceof Error && error.name === \"TimeoutError\";\n}\n\nfunction isNoSessionLike(error: unknown): boolean {\n return error instanceof Error && error.name === \"NoSessionError\";\n}\n\nfunction isUsageLike(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n return (\n error.name === \"CommanderError\" ||\n error.name === \"InvalidArgumentError\" ||\n asRecord(error)?.code === \"commander.invalidArgument\"\n );\n}\n\nexport function formatErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (error && typeof error === \"object\") {\n const maybeMessage = (error as { message?: unknown }).message;\n if (typeof maybeMessage === \"string\" && maybeMessage.length > 0) {\n return maybeMessage;\n }\n\n try {\n return JSON.stringify(error);\n } catch {\n // fall through\n }\n }\n\n return String(error);\n}\n\nexport function extractAcpError(error: unknown): OutputErrorAcpPayload | undefined {\n return extractAcpErrorInternal(error, 0);\n}\n\nexport function isAcpResourceNotFoundError(error: unknown): boolean {\n const acp = extractAcpError(error);\n return Boolean(acp && RESOURCE_NOT_FOUND_ACP_CODES.has(acp.code));\n}\n\nexport function isAcpQueryClosedBeforeResponseError(error: unknown): boolean {\n const acp = extractAcpError(error);\n if (!acp || acp.code !== -32603) {\n return false;\n }\n\n const data = asRecord(acp.data);\n const details = data?.details;\n if (typeof details !== \"string\") {\n return false;\n }\n\n return details.toLowerCase().includes(QUERY_CLOSED_BEFORE_RESPONSE_DETAIL);\n}\n\nfunction mapErrorCode(error: unknown): OutputErrorCode | undefined {\n if (error instanceof PermissionPromptUnavailableError) {\n return \"PERMISSION_PROMPT_UNAVAILABLE\";\n }\n if (error instanceof PermissionDeniedError) {\n return \"PERMISSION_DENIED\";\n }\n if (isTimeoutLike(error)) {\n return \"TIMEOUT\";\n }\n if (isNoSessionLike(error) || isAcpResourceNotFoundError(error)) {\n return \"NO_SESSION\";\n }\n if (isUsageLike(error)) {\n return \"USAGE\";\n }\n return undefined;\n}\n\nexport function normalizeOutputError(\n error: unknown,\n options: NormalizeOutputErrorOptions = {},\n): NormalizedOutputError {\n const meta = readOutputErrorMeta(error);\n const mapped = mapErrorCode(error);\n let code = mapped ?? options.defaultCode ?? \"RUNTIME\";\n\n if (meta.outputCode) {\n code = meta.outputCode;\n }\n\n if (code === \"RUNTIME\" && isAcpResourceNotFoundError(error)) {\n code = \"NO_SESSION\";\n }\n\n const acp = options.acp ?? meta.acp ?? extractAcpError(error);\n const detailCode =\n meta.detailCode ??\n options.detailCode ??\n (error instanceof AuthPolicyError || isAcpAuthRequiredPayload(acp)\n ? \"AUTH_REQUIRED\"\n : undefined);\n return {\n code,\n message: formatErrorMessage(error),\n detailCode,\n origin: meta.origin ?? options.origin,\n retryable: meta.retryable ?? options.retryable,\n acp,\n };\n}\n\nexport function exitCodeForOutputErrorCode(code: OutputErrorCode): ExitCode {\n switch (code) {\n case \"USAGE\":\n return EXIT_CODES.USAGE;\n case \"TIMEOUT\":\n return EXIT_CODES.TIMEOUT;\n case \"NO_SESSION\":\n return EXIT_CODES.NO_SESSION;\n case \"PERMISSION_DENIED\":\n case \"PERMISSION_PROMPT_UNAVAILABLE\":\n return EXIT_CODES.PERMISSION_DENIED;\n case \"RUNTIME\":\n default:\n return EXIT_CODES.ERROR;\n }\n}\n","import type { PerfMetricsSnapshot } from \"./types.js\";\n\ntype TimingBucket = {\n count: number;\n totalMs: number;\n maxMs: number;\n};\n\nconst counters = new Map<string, number>();\nconst gauges = new Map<string, number>();\nconst timings = new Map<string, TimingBucket>();\n\nfunction hrNow(): bigint {\n return process.hrtime.bigint();\n}\n\nfunction durationMs(start: bigint): number {\n return Number(process.hrtime.bigint() - start) / 1_000_000;\n}\n\nfunction roundMetric(value: number): number {\n return Number(value.toFixed(3));\n}\n\nexport function incrementPerfCounter(name: string, delta = 1): void {\n counters.set(name, (counters.get(name) ?? 0) + delta);\n}\n\nexport function setPerfGauge(name: string, value: number): void {\n gauges.set(name, value);\n}\n\nexport function recordPerfDuration(name: string, durationMsValue: number): void {\n const next = timings.get(name) ?? {\n count: 0,\n totalMs: 0,\n maxMs: 0,\n };\n next.count += 1;\n next.totalMs += durationMsValue;\n next.maxMs = Math.max(next.maxMs, durationMsValue);\n timings.set(name, next);\n}\n\nexport async function measurePerf<T>(name: string, run: () => Promise<T>): Promise<T> {\n const startedAt = hrNow();\n try {\n return await run();\n } finally {\n recordPerfDuration(name, durationMs(startedAt));\n }\n}\n\nexport function startPerfTimer(name: string): () => number {\n const startedAt = hrNow();\n return () => {\n const elapsedMs = durationMs(startedAt);\n recordPerfDuration(name, elapsedMs);\n return elapsedMs;\n };\n}\n\nexport function getPerfMetricsSnapshot(): PerfMetricsSnapshot {\n return {\n counters: Object.fromEntries(counters.entries()),\n gauges: Object.fromEntries(gauges.entries()),\n timings: Object.fromEntries(\n [...timings.entries()].map(([name, bucket]) => [\n name,\n {\n count: bucket.count,\n totalMs: roundMetric(bucket.totalMs),\n maxMs: roundMetric(bucket.maxMs),\n },\n ]),\n ),\n };\n}\n\nexport function resetPerfMetrics(): void {\n counters.clear();\n gauges.clear();\n timings.clear();\n}\n\nexport function formatPerfMetric(name: string, durationMsValue: number): string {\n return `${name}=${roundMetric(durationMsValue)}ms`;\n}\n","import { createHash } from \"node:crypto\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nfunction shortHash(value: string, length: number): string {\n return createHash(\"sha256\").update(value).digest(\"hex\").slice(0, length);\n}\n\nexport function queueKeyForSession(sessionId: string): string {\n return shortHash(sessionId, 24);\n}\n\nexport function queueBaseDir(homeDir: string = os.homedir()): string {\n return path.join(homeDir, \".acpx\", \"queues\");\n}\n\nexport function queueSocketBaseDir(homeDir: string = os.homedir()): string | undefined {\n if (process.platform === \"win32\") {\n return undefined;\n }\n return path.join(\"/tmp\", `acpx-${shortHash(homeDir, 10)}`);\n}\n\nexport function queueLockFilePath(sessionId: string, homeDir: string = os.homedir()): string {\n return path.join(queueBaseDir(homeDir), `${queueKeyForSession(sessionId)}.lock`);\n}\n\nexport function queueSocketPath(sessionId: string, homeDir: string = os.homedir()): string {\n const key = queueKeyForSession(sessionId);\n if (process.platform === \"win32\") {\n return `\\\\\\\\.\\\\pipe\\\\acpx-${key}`;\n }\n return path.join(queueSocketBaseDir(homeDir) ?? \"/tmp\", `${key}.sock`);\n}\n","import fs from \"node:fs/promises\";\nimport {\n queueBaseDir,\n queueLockFilePath,\n queueSocketBaseDir,\n queueSocketPath,\n} from \"./queue-paths.js\";\n\nconst PROCESS_EXIT_GRACE_MS = 1_500;\nconst PROCESS_POLL_MS = 50;\nconst QUEUE_OWNER_STALE_HEARTBEAT_MS = 15_000;\n\nexport type QueueOwnerRecord = {\n pid: number;\n sessionId: string;\n socketPath: string;\n createdAt: string;\n heartbeatAt: string;\n ownerGeneration: number;\n queueDepth: number;\n};\n\nexport type QueueOwnerLease = {\n sessionId: string;\n lockPath: string;\n socketPath: string;\n createdAt: string;\n ownerGeneration: number;\n};\n\nexport type QueueOwnerStatus = {\n pid: number;\n socketPath: string;\n heartbeatAt: string;\n ownerGeneration: number;\n queueDepth: number;\n alive: boolean;\n stale: boolean;\n};\n\nfunction parseQueueOwnerRecord(raw: unknown): QueueOwnerRecord | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return null;\n }\n const record = raw as Record<string, unknown>;\n\n if (\n !Number.isInteger(record.pid) ||\n (record.pid as number) <= 0 ||\n typeof record.sessionId !== \"string\" ||\n typeof record.socketPath !== \"string\" ||\n typeof record.createdAt !== \"string\" ||\n typeof record.heartbeatAt !== \"string\" ||\n !Number.isInteger(record.ownerGeneration) ||\n (record.ownerGeneration as number) <= 0 ||\n !Number.isInteger(record.queueDepth) ||\n (record.queueDepth as number) < 0\n ) {\n return null;\n }\n\n return {\n pid: record.pid as number,\n sessionId: record.sessionId,\n socketPath: record.socketPath,\n createdAt: record.createdAt,\n heartbeatAt: record.heartbeatAt,\n ownerGeneration: record.ownerGeneration as number,\n queueDepth: record.queueDepth as number,\n };\n}\n\nfunction createOwnerGeneration(): number {\n return Date.now() * 1_000 + Math.floor(Math.random() * 1_000);\n}\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\n\nfunction isQueueOwnerHeartbeatStale(owner: QueueOwnerRecord): boolean {\n const heartbeatMs = Date.parse(owner.heartbeatAt);\n if (!Number.isFinite(heartbeatMs)) {\n return true;\n }\n return Date.now() - heartbeatMs > QUEUE_OWNER_STALE_HEARTBEAT_MS;\n}\n\nasync function ensureQueueDir(): Promise<void> {\n await fs.mkdir(queueBaseDir(), { recursive: true });\n const socketDir = queueSocketBaseDir();\n if (socketDir) {\n await fs.mkdir(socketDir, { recursive: true });\n }\n}\n\nasync function removeSocketFile(socketPath: string): Promise<void> {\n if (process.platform === \"win32\") {\n return;\n }\n\n try {\n await fs.unlink(socketPath);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n }\n}\n\nasync function waitForProcessExit(pid: number, timeoutMs: number): Promise<boolean> {\n const deadline = Date.now() + Math.max(0, timeoutMs);\n while (Date.now() <= deadline) {\n if (!isProcessAlive(pid)) {\n return true;\n }\n await waitMs(PROCESS_POLL_MS);\n }\n\n return !isProcessAlive(pid);\n}\n\nasync function cleanupStaleQueueOwner(\n sessionId: string,\n owner: QueueOwnerRecord | undefined,\n): Promise<void> {\n const lockPath = queueLockFilePath(sessionId);\n const socketPath = owner?.socketPath ?? queueSocketPath(sessionId);\n\n await removeSocketFile(socketPath).catch(() => {\n // ignore stale socket cleanup failures\n });\n\n await fs.unlink(lockPath).catch((error) => {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n });\n}\n\nexport async function readQueueOwnerRecord(\n sessionId: string,\n): Promise<QueueOwnerRecord | undefined> {\n const lockPath = queueLockFilePath(sessionId);\n try {\n const payload = await fs.readFile(lockPath, \"utf8\");\n const parsed = parseQueueOwnerRecord(JSON.parse(payload));\n return parsed ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport function isProcessAlive(pid: number | undefined): boolean {\n if (!pid || !Number.isInteger(pid) || pid <= 0 || pid === process.pid) {\n return false;\n }\n\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\nexport async function terminateProcess(pid: number): Promise<boolean> {\n if (!isProcessAlive(pid)) {\n return false;\n }\n\n try {\n process.kill(pid, \"SIGTERM\");\n } catch {\n return false;\n }\n\n if (await waitForProcessExit(pid, PROCESS_EXIT_GRACE_MS)) {\n return true;\n }\n\n try {\n process.kill(pid, \"SIGKILL\");\n } catch {\n return false;\n }\n\n await waitForProcessExit(pid, PROCESS_EXIT_GRACE_MS);\n return true;\n}\n\nexport async function ensureOwnerIsUsable(\n sessionId: string,\n owner: QueueOwnerRecord,\n): Promise<boolean> {\n const alive = isProcessAlive(owner.pid);\n const stale = isQueueOwnerHeartbeatStale(owner);\n if (alive && !stale) {\n return true;\n }\n\n if (alive) {\n await terminateProcess(owner.pid).catch(() => {\n // best effort stale owner termination\n });\n }\n await cleanupStaleQueueOwner(sessionId, owner);\n return false;\n}\n\nexport async function readQueueOwnerStatus(\n sessionId: string,\n): Promise<QueueOwnerStatus | undefined> {\n const owner = await readQueueOwnerRecord(sessionId);\n if (!owner) {\n return undefined;\n }\n\n const alive = await ensureOwnerIsUsable(sessionId, owner);\n if (!alive) {\n return undefined;\n }\n\n return {\n pid: owner.pid,\n socketPath: owner.socketPath,\n heartbeatAt: owner.heartbeatAt,\n ownerGeneration: owner.ownerGeneration,\n queueDepth: owner.queueDepth,\n alive,\n stale: isQueueOwnerHeartbeatStale(owner),\n };\n}\n\nexport async function tryAcquireQueueOwnerLease(\n sessionId: string,\n nowIsoFactory: () => string = nowIso,\n): Promise<QueueOwnerLease | undefined> {\n await ensureQueueDir();\n const lockPath = queueLockFilePath(sessionId);\n const socketPath = queueSocketPath(sessionId);\n const createdAt = nowIsoFactory();\n const ownerGeneration = createOwnerGeneration();\n const payload = JSON.stringify(\n {\n pid: process.pid,\n sessionId,\n socketPath,\n createdAt,\n heartbeatAt: createdAt,\n ownerGeneration,\n queueDepth: 0,\n },\n null,\n 2,\n );\n\n try {\n await fs.writeFile(lockPath, `${payload}\\n`, {\n encoding: \"utf8\",\n flag: \"wx\",\n });\n await removeSocketFile(socketPath).catch(() => {\n // best-effort stale socket cleanup after ownership is acquired\n });\n return {\n sessionId,\n lockPath,\n socketPath,\n createdAt,\n ownerGeneration,\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") {\n throw error;\n }\n\n const owner = await readQueueOwnerRecord(sessionId);\n if (!owner) {\n await cleanupStaleQueueOwner(sessionId, owner);\n return undefined;\n }\n\n if (!isProcessAlive(owner.pid) || isQueueOwnerHeartbeatStale(owner)) {\n if (isProcessAlive(owner.pid)) {\n await terminateProcess(owner.pid).catch(() => {\n // best effort stale owner termination\n });\n }\n await cleanupStaleQueueOwner(sessionId, owner);\n }\n return undefined;\n }\n}\n\nexport async function refreshQueueOwnerLease(\n lease: QueueOwnerLease,\n options: {\n queueDepth: number;\n },\n nowIsoFactory: () => string = nowIso,\n): Promise<void> {\n const payload = JSON.stringify(\n {\n pid: process.pid,\n sessionId: lease.sessionId,\n socketPath: lease.socketPath,\n createdAt: lease.createdAt,\n heartbeatAt: nowIsoFactory(),\n ownerGeneration: lease.ownerGeneration,\n queueDepth: Math.max(0, Math.round(options.queueDepth)),\n },\n null,\n 2,\n );\n await fs.writeFile(lease.lockPath, `${payload}\\n`, {\n encoding: \"utf8\",\n });\n}\n\nexport async function releaseQueueOwnerLease(lease: QueueOwnerLease): Promise<void> {\n await removeSocketFile(lease.socketPath).catch(() => {\n // ignore best-effort cleanup failures\n });\n\n await fs.unlink(lease.lockPath).catch((error) => {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") {\n throw error;\n }\n });\n}\n\nexport async function terminateQueueOwnerForSession(sessionId: string): Promise<void> {\n const owner = await readQueueOwnerRecord(sessionId);\n if (!owner) {\n return;\n }\n\n if (isProcessAlive(owner.pid)) {\n await terminateProcess(owner.pid);\n }\n\n await cleanupStaleQueueOwner(sessionId, owner);\n}\n\nexport async function waitMs(ms: number): Promise<void> {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","import type { SetSessionConfigOptionResponse } from \"@agentclientprotocol/sdk\";\nimport { isAcpJsonRpcMessage } from \"./acp-jsonrpc.js\";\nimport {\n OUTPUT_ERROR_CODES,\n OUTPUT_ERROR_ORIGINS,\n type OutputErrorAcpPayload,\n type OutputErrorCode,\n type OutputErrorOrigin,\n} from \"./types.js\";\nimport type {\n AcpJsonRpcMessage,\n NonInteractivePermissionPolicy,\n PermissionMode,\n SessionSendResult,\n} from \"./types.js\";\n\nexport type QueueSubmitRequest = {\n type: \"submit_prompt\";\n requestId: string;\n ownerGeneration?: number;\n message: string;\n permissionMode: PermissionMode;\n nonInteractivePermissions?: NonInteractivePermissionPolicy;\n timeoutMs?: number;\n suppressSdkConsoleErrors?: boolean;\n waitForCompletion: boolean;\n};\n\nexport type QueueCancelRequest = {\n type: \"cancel_prompt\";\n requestId: string;\n ownerGeneration?: number;\n};\n\nexport type QueueSetModeRequest = {\n type: \"set_mode\";\n requestId: string;\n ownerGeneration?: number;\n modeId: string;\n timeoutMs?: number;\n};\n\nexport type QueueSetConfigOptionRequest = {\n type: \"set_config_option\";\n requestId: string;\n ownerGeneration?: number;\n configId: string;\n value: string;\n timeoutMs?: number;\n};\n\nexport type QueueRequest =\n | QueueSubmitRequest\n | QueueCancelRequest\n | QueueSetModeRequest\n | QueueSetConfigOptionRequest;\n\nexport type QueueOwnerAcceptedMessage = {\n type: \"accepted\";\n requestId: string;\n ownerGeneration?: number;\n};\n\nexport type QueueOwnerEventMessage = {\n type: \"event\";\n requestId: string;\n ownerGeneration?: number;\n message: AcpJsonRpcMessage;\n};\n\nexport type QueueOwnerResultMessage = {\n type: \"result\";\n requestId: string;\n ownerGeneration?: number;\n result: SessionSendResult;\n};\n\nexport type QueueOwnerCancelResultMessage = {\n type: \"cancel_result\";\n requestId: string;\n ownerGeneration?: number;\n cancelled: boolean;\n};\n\nexport type QueueOwnerSetModeResultMessage = {\n type: \"set_mode_result\";\n requestId: string;\n ownerGeneration?: number;\n modeId: string;\n};\n\nexport type QueueOwnerSetConfigOptionResultMessage = {\n type: \"set_config_option_result\";\n requestId: string;\n ownerGeneration?: number;\n response: SetSessionConfigOptionResponse;\n};\n\nexport type QueueOwnerErrorMessage = {\n type: \"error\";\n requestId: string;\n ownerGeneration?: number;\n code?: OutputErrorCode;\n detailCode?: string;\n origin?: OutputErrorOrigin;\n message: string;\n retryable?: boolean;\n acp?: OutputErrorAcpPayload;\n outputAlreadyEmitted?: boolean;\n};\n\nexport type QueueOwnerMessage =\n | QueueOwnerAcceptedMessage\n | QueueOwnerEventMessage\n | QueueOwnerResultMessage\n | QueueOwnerCancelResultMessage\n | QueueOwnerSetModeResultMessage\n | QueueOwnerSetConfigOptionResultMessage\n | QueueOwnerErrorMessage;\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n return undefined;\n }\n return value as Record<string, unknown>;\n}\n\nfunction isPermissionMode(value: unknown): value is PermissionMode {\n return value === \"approve-all\" || value === \"approve-reads\" || value === \"deny-all\";\n}\n\nfunction isNonInteractivePermissionPolicy(value: unknown): value is NonInteractivePermissionPolicy {\n return value === \"deny\" || value === \"fail\";\n}\n\nfunction isOutputErrorCode(value: unknown): value is OutputErrorCode {\n return typeof value === \"string\" && OUTPUT_ERROR_CODES.includes(value as OutputErrorCode);\n}\n\nfunction isOutputErrorOrigin(value: unknown): value is OutputErrorOrigin {\n return typeof value === \"string\" && OUTPUT_ERROR_ORIGINS.includes(value as OutputErrorOrigin);\n}\n\nfunction parseAcpError(value: unknown): OutputErrorAcpPayload | undefined {\n const record = asRecord(value);\n if (!record) {\n return undefined;\n }\n if (typeof record.code !== \"number\" || !Number.isFinite(record.code)) {\n return undefined;\n }\n if (typeof record.message !== \"string\" || record.message.length === 0) {\n return undefined;\n }\n\n return {\n code: record.code,\n message: record.message,\n data: record.data,\n };\n}\n\nfunction parseOwnerGeneration(value: unknown): number | undefined | null {\n if (value == null) {\n return undefined;\n }\n if (typeof value !== \"number\" || !Number.isInteger(value) || value <= 0) {\n return null;\n }\n return value;\n}\n\nexport function parseQueueRequest(raw: unknown): QueueRequest | null {\n const request = asRecord(raw);\n if (!request) {\n return null;\n }\n\n if (typeof request.type !== \"string\" || typeof request.requestId !== \"string\") {\n return null;\n }\n const ownerGeneration = parseOwnerGeneration(request.ownerGeneration);\n if (ownerGeneration === null) {\n return null;\n }\n\n const timeoutRaw = request.timeoutMs;\n const timeoutMs =\n typeof timeoutRaw === \"number\" && Number.isFinite(timeoutRaw) && timeoutRaw > 0\n ? Math.round(timeoutRaw)\n : undefined;\n\n if (request.type === \"submit_prompt\") {\n const nonInteractivePermissions =\n request.nonInteractivePermissions == null\n ? undefined\n : isNonInteractivePermissionPolicy(request.nonInteractivePermissions)\n ? request.nonInteractivePermissions\n : null;\n const suppressSdkConsoleErrors =\n request.suppressSdkConsoleErrors == null\n ? undefined\n : typeof request.suppressSdkConsoleErrors === \"boolean\"\n ? request.suppressSdkConsoleErrors\n : null;\n\n if (\n typeof request.message !== \"string\" ||\n !isPermissionMode(request.permissionMode) ||\n nonInteractivePermissions === null ||\n suppressSdkConsoleErrors === null ||\n typeof request.waitForCompletion !== \"boolean\"\n ) {\n return null;\n }\n\n return {\n type: \"submit_prompt\",\n requestId: request.requestId,\n ownerGeneration,\n message: request.message,\n permissionMode: request.permissionMode,\n nonInteractivePermissions,\n timeoutMs,\n ...(suppressSdkConsoleErrors !== undefined ? { suppressSdkConsoleErrors } : {}),\n waitForCompletion: request.waitForCompletion,\n };\n }\n\n if (request.type === \"cancel_prompt\") {\n return {\n type: \"cancel_prompt\",\n requestId: request.requestId,\n ownerGeneration,\n };\n }\n\n if (request.type === \"set_mode\") {\n if (typeof request.modeId !== \"string\" || request.modeId.trim().length === 0) {\n return null;\n }\n return {\n type: \"set_mode\",\n requestId: request.requestId,\n ownerGeneration,\n modeId: request.modeId,\n timeoutMs,\n };\n }\n\n if (request.type === \"set_config_option\") {\n if (\n typeof request.configId !== \"string\" ||\n request.configId.trim().length === 0 ||\n typeof request.value !== \"string\" ||\n request.value.trim().length === 0\n ) {\n return null;\n }\n return {\n type: \"set_config_option\",\n requestId: request.requestId,\n ownerGeneration,\n configId: request.configId,\n value: request.value,\n timeoutMs,\n };\n }\n\n return null;\n}\n\nfunction parseSessionSendResult(raw: unknown): SessionSendResult | null {\n const result = asRecord(raw);\n if (!result) {\n return null;\n }\n\n if (\n typeof result.stopReason !== \"string\" ||\n typeof result.sessionId !== \"string\" ||\n typeof result.resumed !== \"boolean\"\n ) {\n return null;\n }\n\n const permissionStats = asRecord(result.permissionStats);\n const record = asRecord(result.record);\n if (!permissionStats || !record) {\n return null;\n }\n\n const statsValid =\n typeof permissionStats.requested === \"number\" &&\n typeof permissionStats.approved === \"number\" &&\n typeof permissionStats.denied === \"number\" &&\n typeof permissionStats.cancelled === \"number\";\n if (!statsValid) {\n return null;\n }\n\n const recordValid =\n typeof record.acpxRecordId === \"string\" &&\n typeof record.acpSessionId === \"string\" &&\n typeof record.agentCommand === \"string\" &&\n typeof record.cwd === \"string\" &&\n typeof record.createdAt === \"string\" &&\n typeof record.lastUsedAt === \"string\" &&\n Array.isArray(record.messages) &&\n typeof record.updated_at === \"string\" &&\n typeof record.lastSeq === \"number\" &&\n Number.isInteger(record.lastSeq) &&\n !!record.eventLog &&\n typeof record.eventLog === \"object\";\n if (!recordValid) {\n return null;\n }\n\n return result as SessionSendResult;\n}\n\nexport function parseQueueOwnerMessage(raw: unknown): QueueOwnerMessage | null {\n const message = asRecord(raw);\n if (!message || typeof message.type !== \"string\") {\n return null;\n }\n\n if (typeof message.requestId !== \"string\") {\n return null;\n }\n const ownerGeneration = parseOwnerGeneration(message.ownerGeneration);\n if (ownerGeneration === null) {\n return null;\n }\n\n if (message.type === \"accepted\") {\n return {\n type: \"accepted\",\n requestId: message.requestId,\n ownerGeneration,\n };\n }\n\n if (message.type === \"event\") {\n if (!isAcpJsonRpcMessage(message.message)) {\n return null;\n }\n\n return {\n type: \"event\",\n requestId: message.requestId,\n ownerGeneration,\n message: message.message,\n };\n }\n\n if (message.type === \"result\") {\n const parsedResult = parseSessionSendResult(message.result);\n if (!parsedResult) {\n return null;\n }\n return {\n type: \"result\",\n requestId: message.requestId,\n ownerGeneration,\n result: parsedResult,\n };\n }\n\n if (message.type === \"cancel_result\") {\n if (typeof message.cancelled !== \"boolean\") {\n return null;\n }\n return {\n type: \"cancel_result\",\n requestId: message.requestId,\n ownerGeneration,\n cancelled: message.cancelled,\n };\n }\n\n if (message.type === \"set_mode_result\") {\n if (typeof message.modeId !== \"string\") {\n return null;\n }\n return {\n type: \"set_mode_result\",\n requestId: message.requestId,\n ownerGeneration,\n modeId: message.modeId,\n };\n }\n\n if (message.type === \"set_config_option_result\") {\n const response = asRecord(message.response);\n if (!response || !Array.isArray(response.configOptions)) {\n return null;\n }\n return {\n type: \"set_config_option_result\",\n requestId: message.requestId,\n ownerGeneration,\n response: response as SetSessionConfigOptionResponse,\n };\n }\n\n if (message.type === \"error\") {\n if (\n typeof message.message !== \"string\" ||\n !isOutputErrorCode(message.code) ||\n !isOutputErrorOrigin(message.origin)\n ) {\n return null;\n }\n\n const detailCode =\n typeof message.detailCode === \"string\" && message.detailCode.trim().length > 0\n ? message.detailCode\n : undefined;\n const retryable = typeof message.retryable === \"boolean\" ? message.retryable : undefined;\n const acp = parseAcpError(message.acp);\n const outputAlreadyEmitted =\n typeof message.outputAlreadyEmitted === \"boolean\" ? message.outputAlreadyEmitted : undefined;\n\n return {\n type: \"error\",\n requestId: message.requestId,\n ownerGeneration,\n code: message.code,\n detailCode,\n origin: message.origin,\n message: message.message,\n retryable,\n acp,\n ...(outputAlreadyEmitted === undefined ? {} : { outputAlreadyEmitted }),\n };\n }\n\n return null;\n}\n","import net from \"node:net\";\nimport type { SetSessionConfigOptionResponse } from \"@agentclientprotocol/sdk\";\nimport { normalizeOutputError } from \"./error-normalization.js\";\nimport { recordPerfDuration } from \"./perf-metrics.js\";\nimport {\n parseQueueRequest,\n type QueueOwnerErrorMessage,\n type QueueOwnerMessage,\n} from \"./queue-messages.js\";\nimport type { NonInteractivePermissionPolicy, PermissionMode } from \"./types.js\";\n\ntype QueueOwnerSocketLease = {\n socketPath: string;\n ownerGeneration?: number;\n};\n\nfunction makeQueueOwnerError(\n requestId: string,\n message: string,\n detailCode: string,\n options: {\n retryable?: boolean;\n } = {},\n): QueueOwnerErrorMessage {\n return {\n type: \"error\",\n requestId,\n ownerGeneration: undefined,\n code: \"RUNTIME\",\n detailCode,\n origin: \"queue\",\n retryable: options.retryable,\n message,\n };\n}\n\nfunction makeQueueOwnerErrorFromUnknown(\n requestId: string,\n error: unknown,\n detailCode: string,\n options: {\n retryable?: boolean;\n } = {},\n): QueueOwnerErrorMessage {\n const normalized = normalizeOutputError(error, {\n defaultCode: \"RUNTIME\",\n origin: \"queue\",\n detailCode,\n retryable: options.retryable,\n });\n\n return {\n type: \"error\",\n requestId,\n code: normalized.code,\n detailCode: normalized.detailCode,\n origin: normalized.origin,\n message: normalized.message,\n retryable: normalized.retryable,\n acp: normalized.acp,\n };\n}\n\nfunction writeQueueMessage(socket: net.Socket, message: QueueOwnerMessage): void {\n if (socket.destroyed || !socket.writable) {\n return;\n }\n socket.write(`${JSON.stringify(message)}\\n`);\n}\n\nexport type QueueTask = {\n requestId: string;\n message: string;\n permissionMode: PermissionMode;\n nonInteractivePermissions?: NonInteractivePermissionPolicy;\n timeoutMs?: number;\n suppressSdkConsoleErrors?: boolean;\n waitForCompletion: boolean;\n enqueuedAt: number;\n send: (message: QueueOwnerMessage) => void;\n close: () => void;\n};\n\nexport type QueueOwnerControlHandlers = {\n cancelPrompt: () => Promise<boolean>;\n setSessionMode: (modeId: string, timeoutMs?: number) => Promise<void>;\n setSessionConfigOption: (\n configId: string,\n value: string,\n timeoutMs?: number,\n ) => Promise<SetSessionConfigOptionResponse>;\n};\n\ntype SessionQueueOwnerOptions = {\n maxQueueDepth: number;\n onQueueDepthChanged?: (queueDepth: number) => void;\n};\n\nexport class SessionQueueOwner {\n private readonly server: net.Server;\n private readonly controlHandlers: QueueOwnerControlHandlers;\n private readonly ownerGeneration?: number;\n private readonly maxQueueDepth: number;\n private readonly onQueueDepthChanged?: (queueDepth: number) => void;\n private readonly pending: QueueTask[] = [];\n private readonly waiters: Array<(task: QueueTask | undefined) => void> = [];\n private closed = false;\n\n private constructor(\n server: net.Server,\n controlHandlers: QueueOwnerControlHandlers,\n lease: QueueOwnerSocketLease,\n options: SessionQueueOwnerOptions,\n ) {\n this.server = server;\n this.controlHandlers = controlHandlers;\n this.ownerGeneration = lease.ownerGeneration;\n this.maxQueueDepth = Math.max(1, Math.round(options.maxQueueDepth));\n this.onQueueDepthChanged = options.onQueueDepthChanged;\n }\n\n static async start(\n lease: QueueOwnerSocketLease,\n controlHandlers: QueueOwnerControlHandlers,\n options: SessionQueueOwnerOptions = {\n maxQueueDepth: 16,\n },\n ): Promise<SessionQueueOwner> {\n const ownerRef: { current: SessionQueueOwner | undefined } = { current: undefined };\n const server = net.createServer((socket) => {\n ownerRef.current?.handleConnection(socket);\n });\n ownerRef.current = new SessionQueueOwner(server, controlHandlers, lease, options);\n\n await new Promise<void>((resolve, reject) => {\n const onListening = () => {\n server.off(\"error\", onError);\n resolve();\n };\n const onError = (error: Error) => {\n server.off(\"listening\", onListening);\n reject(error);\n };\n\n server.once(\"listening\", onListening);\n server.once(\"error\", onError);\n server.listen(lease.socketPath);\n });\n\n return ownerRef.current;\n }\n\n async close(): Promise<void> {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n for (const waiter of this.waiters.splice(0)) {\n waiter(undefined);\n }\n\n for (const task of this.pending.splice(0)) {\n if (task.waitForCompletion) {\n task.send(\n makeQueueOwnerError(\n task.requestId,\n \"Queue owner shutting down before prompt execution\",\n \"QUEUE_OWNER_SHUTTING_DOWN\",\n {\n retryable: true,\n },\n ),\n );\n }\n task.close();\n }\n this.emitQueueDepth();\n\n await new Promise<void>((resolve) => {\n this.server.close(() => resolve());\n });\n }\n\n async nextTask(timeoutMs?: number): Promise<QueueTask | undefined> {\n if (this.pending.length > 0) {\n const task = this.pending.shift();\n this.emitQueueDepth();\n if (task) {\n recordPerfDuration(\"queue.owner.wait_ms\", Date.now() - task.enqueuedAt);\n }\n return task;\n }\n if (this.closed) {\n return undefined;\n }\n\n return await new Promise<QueueTask | undefined>((resolve) => {\n const shouldTimeout = timeoutMs != null;\n const timer =\n shouldTimeout &&\n setTimeout(\n () => {\n const index = this.waiters.indexOf(waiter);\n if (index >= 0) {\n this.waiters.splice(index, 1);\n }\n resolve(undefined);\n },\n Math.max(0, timeoutMs),\n );\n\n const waiter = (task: QueueTask | undefined) => {\n if (timer) {\n clearTimeout(timer);\n }\n resolve(task);\n };\n\n this.waiters.push(waiter);\n });\n }\n\n queueDepth(): number {\n return this.pending.length;\n }\n\n private emitQueueDepth(): void {\n this.onQueueDepthChanged?.(this.pending.length);\n }\n\n private enqueue(task: QueueTask): void {\n if (this.closed) {\n if (task.waitForCompletion) {\n task.send(\n makeQueueOwnerError(\n task.requestId,\n \"Queue owner is shutting down\",\n \"QUEUE_OWNER_SHUTTING_DOWN\",\n {\n retryable: true,\n },\n ),\n );\n }\n task.close();\n return;\n }\n\n const waiter = this.waiters.shift();\n if (waiter) {\n waiter(task);\n return;\n }\n\n if (this.pending.length >= this.maxQueueDepth) {\n if (task.waitForCompletion) {\n task.send({\n ...makeQueueOwnerError(\n task.requestId,\n `Queue owner is overloaded (${this.pending.length}/${this.maxQueueDepth} queued)`,\n \"QUEUE_OWNER_OVERLOADED\",\n {\n retryable: true,\n },\n ),\n ownerGeneration: this.ownerGeneration,\n });\n }\n task.close();\n return;\n }\n\n this.pending.push(task);\n this.emitQueueDepth();\n }\n\n private handleConnection(socket: net.Socket): void {\n socket.setEncoding(\"utf8\");\n\n if (this.closed) {\n writeQueueMessage(\n socket,\n makeQueueOwnerError(\"unknown\", \"Queue owner is closed\", \"QUEUE_OWNER_CLOSED\", {\n retryable: true,\n }),\n );\n socket.end();\n return;\n }\n\n let buffer = \"\";\n let handled = false;\n\n const fail = (requestId: string, message: string, detailCode: string): void => {\n writeQueueMessage(socket, {\n ...makeQueueOwnerError(requestId, message, detailCode, {\n retryable: false,\n }),\n ownerGeneration: this.ownerGeneration,\n });\n socket.end();\n };\n\n const processLine = (line: string): void => {\n if (handled) {\n return;\n }\n handled = true;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n fail(\"unknown\", \"Invalid queue request payload\", \"QUEUE_REQUEST_PAYLOAD_INVALID_JSON\");\n return;\n }\n\n const request = parseQueueRequest(parsed);\n if (!request) {\n fail(\"unknown\", \"Invalid queue request\", \"QUEUE_REQUEST_INVALID\");\n return;\n }\n\n if (\n request.ownerGeneration !== undefined &&\n this.ownerGeneration !== undefined &&\n request.ownerGeneration !== this.ownerGeneration\n ) {\n fail(\n request.requestId,\n \"Queue request targeted a stale queue owner generation\",\n \"QUEUE_OWNER_GENERATION_MISMATCH\",\n );\n return;\n }\n\n if (request.type === \"cancel_prompt\") {\n writeQueueMessage(socket, {\n type: \"accepted\",\n requestId: request.requestId,\n ownerGeneration: this.ownerGeneration,\n });\n void this.controlHandlers\n .cancelPrompt()\n .then((cancelled) => {\n writeQueueMessage(socket, {\n type: \"cancel_result\",\n requestId: request.requestId,\n ownerGeneration: this.ownerGeneration,\n cancelled,\n });\n })\n .catch((error) => {\n writeQueueMessage(socket, {\n ...makeQueueOwnerErrorFromUnknown(\n request.requestId,\n error,\n \"QUEUE_CONTROL_REQUEST_FAILED\",\n ),\n ownerGeneration: this.ownerGeneration,\n });\n })\n .finally(() => {\n if (!socket.destroyed) {\n socket.end();\n }\n });\n return;\n }\n\n if (request.type === \"set_mode\") {\n writeQueueMessage(socket, {\n type: \"accepted\",\n requestId: request.requestId,\n ownerGeneration: this.ownerGeneration,\n });\n void this.controlHandlers\n .setSessionMode(request.modeId, request.timeoutMs)\n .then(() => {\n writeQueueMessage(socket, {\n type: \"set_mode_result\",\n requestId: request.requestId,\n ownerGeneration: this.ownerGeneration,\n modeId: request.modeId,\n });\n })\n .catch((error) => {\n writeQueueMessage(socket, {\n ...makeQueueOwnerErrorFromUnknown(\n request.requestId,\n error,\n \"QUEUE_CONTROL_REQUEST_FAILED\",\n ),\n ownerGeneration: this.ownerGeneration,\n });\n })\n .finally(() => {\n if (!socket.destroyed) {\n socket.end();\n }\n });\n return;\n }\n\n if (request.type === \"set_config_option\") {\n writeQueueMessage(socket, {\n type: \"accepted\",\n requestId: request.requestId,\n ownerGeneration: this.ownerGeneration,\n });\n void this.controlHandlers\n .setSessionConfigOption(request.configId, request.value, request.timeoutMs)\n .then((response) => {\n writeQueueMessage(socket, {\n type: \"set_config_option_result\",\n requestId: request.requestId,\n ownerGeneration: this.ownerGeneration,\n response,\n });\n })\n .catch((error) => {\n writeQueueMessage(socket, {\n ...makeQueueOwnerErrorFromUnknown(\n request.requestId,\n error,\n \"QUEUE_CONTROL_REQUEST_FAILED\",\n ),\n ownerGeneration: this.ownerGeneration,\n });\n })\n .finally(() => {\n if (!socket.destroyed) {\n socket.end();\n }\n });\n return;\n }\n\n const task: QueueTask = {\n requestId: request.requestId,\n message: request.message,\n permissionMode: request.permissionMode,\n nonInteractivePermissions: request.nonInteractivePermissions,\n timeoutMs: request.timeoutMs,\n suppressSdkConsoleErrors: request.suppressSdkConsoleErrors,\n waitForCompletion: request.waitForCompletion,\n enqueuedAt: Date.now(),\n send: (message) => {\n writeQueueMessage(socket, {\n ...message,\n ownerGeneration: this.ownerGeneration,\n });\n },\n close: () => {\n if (!socket.destroyed) {\n socket.end();\n }\n },\n };\n\n writeQueueMessage(socket, {\n type: \"accepted\",\n requestId: request.requestId,\n ownerGeneration: this.ownerGeneration,\n });\n\n if (!request.waitForCompletion) {\n task.close();\n }\n\n this.enqueue(task);\n };\n\n socket.on(\"data\", (chunk: string) => {\n buffer += chunk;\n\n let index = buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = buffer.slice(0, index).trim();\n buffer = buffer.slice(index + 1);\n\n if (line.length > 0) {\n processLine(line);\n }\n\n index = buffer.indexOf(\"\\n\");\n }\n });\n\n socket.on(\"error\", () => {\n // no-op: queue processing continues even if client disconnects\n });\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport net from \"node:net\";\nimport type { SetSessionConfigOptionResponse } from \"@agentclientprotocol/sdk\";\nimport { QueueConnectionError, QueueProtocolError } from \"./errors.js\";\nimport { incrementPerfCounter, measurePerf } from \"./perf-metrics.js\";\nimport {\n type QueueOwnerLease,\n type QueueOwnerRecord,\n isProcessAlive,\n readQueueOwnerRecord,\n readQueueOwnerStatus,\n releaseQueueOwnerLease,\n terminateProcess,\n terminateQueueOwnerForSession,\n tryAcquireQueueOwnerLease,\n waitMs,\n} from \"./queue-lease-store.js\";\nimport {\n parseQueueOwnerMessage,\n type QueueCancelRequest,\n type QueueOwnerCancelResultMessage,\n type QueueOwnerMessage,\n type QueueOwnerSetConfigOptionResultMessage,\n type QueueOwnerSetModeResultMessage,\n type QueueRequest,\n type QueueSetConfigOptionRequest,\n type QueueSetModeRequest,\n type QueueSubmitRequest,\n} from \"./queue-messages.js\";\nimport type {\n NonInteractivePermissionPolicy,\n OutputErrorEmissionPolicy,\n OutputFormatter,\n PermissionMode,\n SessionEnqueueResult,\n SessionSendOutcome,\n} from \"./types.js\";\n\nconst QUEUE_CONNECT_ATTEMPTS = 40;\nexport const QUEUE_CONNECT_RETRY_MS = 50;\nexport {\n isProcessAlive,\n releaseQueueOwnerLease,\n terminateProcess,\n terminateQueueOwnerForSession,\n tryAcquireQueueOwnerLease,\n waitMs,\n} from \"./queue-lease-store.js\";\nexport type { QueueOwnerLease } from \"./queue-lease-store.js\";\n\nconst STALE_OWNER_PROTOCOL_DETAIL_CODES = new Set([\n \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n \"QUEUE_PROTOCOL_UNEXPECTED_RESPONSE\",\n]);\n\nasync function maybeRecoverStaleOwnerAfterProtocolMismatch(params: {\n sessionId: string;\n owner: QueueOwnerRecord;\n error: unknown;\n verbose?: boolean;\n}): Promise<boolean> {\n if (!(params.error instanceof QueueProtocolError)) {\n return false;\n }\n\n const detailCode = params.error.detailCode;\n if (!detailCode || !STALE_OWNER_PROTOCOL_DETAIL_CODES.has(detailCode)) {\n return false;\n }\n\n await terminateQueueOwnerForSession(params.sessionId).catch(() => {\n // Preserve existing behavior if cleanup fails.\n });\n incrementPerfCounter(\"queue.owner.stale_recovered\");\n\n if (params.verbose) {\n process.stderr.write(\n `[acpx] dropped stale queue owner metadata after protocol mismatch for session ${params.sessionId} (${detailCode})\\n`,\n );\n }\n\n return true;\n}\nexport type QueueOwnerHealth = {\n sessionId: string;\n hasLease: boolean;\n healthy: boolean;\n socketReachable: boolean;\n pidAlive: boolean;\n pid?: number;\n socketPath?: string;\n ownerGeneration?: number;\n queueDepth?: number;\n};\n\nexport type { QueueOwnerMessage, QueueSubmitRequest } from \"./queue-messages.js\";\nexport type { QueueOwnerControlHandlers, QueueTask } from \"./queue-ipc-server.js\";\nexport { SessionQueueOwner } from \"./queue-ipc-server.js\";\n\nfunction shouldRetryQueueConnect(error: unknown): boolean {\n const code = (error as NodeJS.ErrnoException).code;\n return code === \"ENOENT\" || code === \"ECONNREFUSED\";\n}\n\nasync function connectToSocket(socketPath: string): Promise<net.Socket> {\n return await new Promise<net.Socket>((resolve, reject) => {\n const socket = net.createConnection(socketPath);\n\n const onConnect = () => {\n socket.off(\"error\", onError);\n resolve(socket);\n };\n const onError = (error: Error) => {\n socket.off(\"connect\", onConnect);\n reject(error);\n };\n\n socket.once(\"connect\", onConnect);\n socket.once(\"error\", onError);\n });\n}\n\nasync function connectToQueueOwner(\n owner: QueueOwnerRecord,\n maxAttempts = QUEUE_CONNECT_ATTEMPTS,\n): Promise<net.Socket | undefined> {\n let lastError: unknown;\n\n const attempts = Math.max(1, Math.trunc(maxAttempts));\n for (let attempt = 0; attempt < attempts; attempt += 1) {\n try {\n return await measurePerf(\n \"queue.connect\",\n async () => await connectToSocket(owner.socketPath),\n );\n } catch (error) {\n lastError = error;\n if (!shouldRetryQueueConnect(error)) {\n throw error;\n }\n await waitMs(QUEUE_CONNECT_RETRY_MS);\n }\n }\n\n if (lastError && !shouldRetryQueueConnect(lastError)) {\n throw lastError;\n }\n\n return undefined;\n}\n\nexport async function probeQueueOwnerHealth(sessionId: string): Promise<QueueOwnerHealth> {\n const ownerRecord = await readQueueOwnerRecord(sessionId);\n if (!ownerRecord) {\n return {\n sessionId,\n hasLease: false,\n healthy: false,\n socketReachable: false,\n pidAlive: false,\n };\n }\n\n const owner = await readQueueOwnerStatus(sessionId);\n if (!owner) {\n return {\n sessionId,\n hasLease: false,\n healthy: false,\n socketReachable: false,\n pidAlive: false,\n };\n }\n\n const pidAlive = owner.alive;\n let socketReachable = false;\n try {\n const socket = await connectToQueueOwner(ownerRecord, 2);\n if (socket) {\n socketReachable = true;\n if (!socket.destroyed) {\n socket.end();\n }\n }\n } catch {\n socketReachable = false;\n }\n\n return {\n sessionId,\n hasLease: true,\n healthy: socketReachable,\n socketReachable,\n pidAlive,\n pid: owner.pid,\n socketPath: owner.socketPath,\n ownerGeneration: owner.ownerGeneration,\n queueDepth: owner.queueDepth,\n };\n}\n\nfunction assertOwnerGeneration(\n owner: QueueOwnerRecord,\n message: QueueOwnerMessage,\n): QueueOwnerMessage {\n if (\n owner.ownerGeneration !== undefined &&\n message.ownerGeneration !== undefined &&\n message.ownerGeneration !== owner.ownerGeneration\n ) {\n throw new QueueProtocolError(\"Queue owner returned mismatched generation\", {\n detailCode: \"QUEUE_OWNER_GENERATION_MISMATCH\",\n origin: \"queue\",\n retryable: true,\n });\n }\n return message;\n}\n\nexport type SubmitToQueueOwnerOptions = {\n sessionId: string;\n message: string;\n permissionMode: PermissionMode;\n nonInteractivePermissions?: NonInteractivePermissionPolicy;\n outputFormatter: OutputFormatter;\n errorEmissionPolicy?: OutputErrorEmissionPolicy;\n timeoutMs?: number;\n suppressSdkConsoleErrors?: boolean;\n waitForCompletion: boolean;\n verbose?: boolean;\n};\n\nasync function submitToQueueOwner(\n owner: QueueOwnerRecord,\n options: SubmitToQueueOwnerOptions,\n): Promise<SessionSendOutcome | undefined> {\n const socket = await connectToQueueOwner(owner);\n if (!socket) {\n return undefined;\n }\n\n socket.setEncoding(\"utf8\");\n const requestId = randomUUID();\n const request: QueueSubmitRequest = {\n type: \"submit_prompt\",\n requestId,\n ownerGeneration: owner.ownerGeneration,\n message: options.message,\n permissionMode: options.permissionMode,\n nonInteractivePermissions: options.nonInteractivePermissions,\n timeoutMs: options.timeoutMs,\n suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,\n waitForCompletion: options.waitForCompletion,\n };\n\n options.outputFormatter.setContext({\n sessionId: options.sessionId,\n });\n\n return await new Promise<SessionSendOutcome>((resolve, reject) => {\n let settled = false;\n let acknowledged = false;\n let buffer = \"\";\n\n const finishResolve = (result: SessionSendOutcome) => {\n if (settled) {\n return;\n }\n settled = true;\n socket.removeAllListeners();\n if (!socket.destroyed) {\n socket.end();\n }\n resolve(result);\n };\n\n const finishReject = (error: unknown) => {\n if (settled) {\n return;\n }\n settled = true;\n socket.removeAllListeners();\n if (!socket.destroyed) {\n socket.destroy();\n }\n reject(error);\n };\n\n const processLine = (line: string): void => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n finishReject(\n new QueueProtocolError(\"Queue owner sent invalid JSON payload\", {\n detailCode: \"QUEUE_PROTOCOL_INVALID_JSON\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n const parsedMessage = parseQueueOwnerMessage(parsed);\n if (!parsedMessage) {\n finishReject(\n new QueueProtocolError(\"Queue owner sent malformed message\", {\n detailCode: \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n const message = assertOwnerGeneration(owner, parsedMessage);\n if (message.requestId !== requestId) {\n finishReject(\n new QueueProtocolError(\"Queue owner sent malformed message\", {\n detailCode: \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n if (message.type === \"accepted\") {\n acknowledged = true;\n options.outputFormatter.setContext({\n sessionId: options.sessionId,\n });\n if (!options.waitForCompletion) {\n const queued: SessionEnqueueResult = {\n queued: true,\n sessionId: options.sessionId,\n requestId,\n };\n finishResolve(queued);\n }\n return;\n }\n\n if (message.type === \"error\") {\n options.outputFormatter.setContext({\n sessionId: options.sessionId,\n });\n\n const queueErrorAlreadyEmitted =\n options.errorEmissionPolicy?.queueErrorAlreadyEmitted ?? true;\n const outputAlreadyEmitted = message.outputAlreadyEmitted === true;\n const shouldEmitInFormatter = !outputAlreadyEmitted || !queueErrorAlreadyEmitted;\n if (shouldEmitInFormatter) {\n options.outputFormatter.onError({\n code: message.code ?? \"RUNTIME\",\n detailCode: message.detailCode,\n origin: message.origin ?? \"queue\",\n message: message.message,\n retryable: message.retryable,\n acp: message.acp,\n });\n options.outputFormatter.flush();\n }\n finishReject(\n new QueueConnectionError(message.message, {\n outputCode: message.code,\n detailCode: message.detailCode,\n origin: message.origin ?? \"queue\",\n retryable: message.retryable,\n acp: message.acp,\n ...(queueErrorAlreadyEmitted ? { outputAlreadyEmitted: true } : {}),\n }),\n );\n return;\n }\n\n if (!acknowledged) {\n finishReject(\n new QueueConnectionError(\"Queue owner did not acknowledge request\", {\n detailCode: \"QUEUE_ACK_MISSING\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n if (message.type === \"event\") {\n options.outputFormatter.onAcpMessage(message.message);\n return;\n }\n\n if (message.type === \"result\") {\n options.outputFormatter.flush();\n finishResolve(message.result);\n return;\n }\n\n finishReject(\n new QueueProtocolError(\"Queue owner returned unexpected response\", {\n detailCode: \"QUEUE_PROTOCOL_UNEXPECTED_RESPONSE\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n };\n\n socket.on(\"data\", (chunk: string) => {\n buffer += chunk;\n\n let index = buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = buffer.slice(0, index).trim();\n buffer = buffer.slice(index + 1);\n\n if (line.length > 0) {\n processLine(line);\n }\n\n index = buffer.indexOf(\"\\n\");\n }\n });\n\n socket.once(\"error\", (error: Error) => {\n finishReject(error);\n });\n\n socket.once(\"close\", () => {\n if (settled) {\n return;\n }\n\n if (!acknowledged) {\n finishReject(\n new QueueConnectionError(\"Queue owner disconnected before acknowledging request\", {\n detailCode: \"QUEUE_DISCONNECTED_BEFORE_ACK\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n if (!options.waitForCompletion) {\n const queued: SessionEnqueueResult = {\n queued: true,\n sessionId: options.sessionId,\n requestId,\n };\n finishResolve(queued);\n return;\n }\n\n finishReject(\n new QueueConnectionError(\"Queue owner disconnected before prompt completion\", {\n detailCode: \"QUEUE_DISCONNECTED_BEFORE_COMPLETION\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n });\n\n socket.write(`${JSON.stringify(request)}\\n`);\n });\n}\n\nasync function submitControlToQueueOwner<TResponse extends QueueOwnerMessage>(\n owner: QueueOwnerRecord,\n request: QueueRequest,\n isExpectedResponse: (message: QueueOwnerMessage) => message is TResponse,\n): Promise<TResponse | undefined> {\n const socket = await connectToQueueOwner(owner);\n if (!socket) {\n return undefined;\n }\n\n socket.setEncoding(\"utf8\");\n\n return await new Promise<TResponse>((resolve, reject) => {\n let settled = false;\n let acknowledged = false;\n let buffer = \"\";\n\n const finishResolve = (result: TResponse) => {\n if (settled) {\n return;\n }\n settled = true;\n socket.removeAllListeners();\n if (!socket.destroyed) {\n socket.end();\n }\n resolve(result);\n };\n\n const finishReject = (error: unknown) => {\n if (settled) {\n return;\n }\n settled = true;\n socket.removeAllListeners();\n if (!socket.destroyed) {\n socket.destroy();\n }\n reject(error);\n };\n\n const processLine = (line: string): void => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n finishReject(\n new QueueProtocolError(\"Queue owner sent invalid JSON payload\", {\n detailCode: \"QUEUE_PROTOCOL_INVALID_JSON\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n const parsedMessage = parseQueueOwnerMessage(parsed);\n if (!parsedMessage) {\n finishReject(\n new QueueProtocolError(\"Queue owner sent malformed message\", {\n detailCode: \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n const message = assertOwnerGeneration(owner, parsedMessage);\n if (message.requestId !== request.requestId) {\n finishReject(\n new QueueProtocolError(\"Queue owner sent malformed message\", {\n detailCode: \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n if (message.type === \"accepted\") {\n acknowledged = true;\n return;\n }\n\n if (message.type === \"error\") {\n finishReject(\n new QueueConnectionError(message.message, {\n outputCode: message.code,\n detailCode: message.detailCode,\n origin: message.origin ?? \"queue\",\n retryable: message.retryable,\n acp: message.acp,\n }),\n );\n return;\n }\n\n if (!acknowledged) {\n finishReject(\n new QueueConnectionError(\"Queue owner did not acknowledge request\", {\n detailCode: \"QUEUE_ACK_MISSING\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n if (!isExpectedResponse(message)) {\n finishReject(\n new QueueProtocolError(\"Queue owner returned unexpected response\", {\n detailCode: \"QUEUE_PROTOCOL_UNEXPECTED_RESPONSE\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n\n finishResolve(message);\n };\n\n socket.on(\"data\", (chunk: string) => {\n buffer += chunk;\n\n let index = buffer.indexOf(\"\\n\");\n while (index >= 0) {\n const line = buffer.slice(0, index).trim();\n buffer = buffer.slice(index + 1);\n\n if (line.length > 0) {\n processLine(line);\n }\n\n index = buffer.indexOf(\"\\n\");\n }\n });\n\n socket.once(\"error\", (error: Error) => {\n finishReject(error);\n });\n\n socket.once(\"close\", () => {\n if (settled) {\n return;\n }\n if (!acknowledged) {\n finishReject(\n new QueueConnectionError(\"Queue owner disconnected before acknowledging request\", {\n detailCode: \"QUEUE_DISCONNECTED_BEFORE_ACK\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n return;\n }\n finishReject(\n new QueueConnectionError(\"Queue owner disconnected before responding\", {\n detailCode: \"QUEUE_DISCONNECTED_BEFORE_COMPLETION\",\n origin: \"queue\",\n retryable: true,\n }),\n );\n });\n\n socket.write(`${JSON.stringify(request)}\\n`);\n });\n}\n\nasync function submitCancelToQueueOwner(owner: QueueOwnerRecord): Promise<boolean | undefined> {\n const request: QueueCancelRequest = {\n type: \"cancel_prompt\",\n requestId: randomUUID(),\n ownerGeneration: owner.ownerGeneration,\n };\n const response = await submitControlToQueueOwner(\n owner,\n request,\n (message): message is QueueOwnerCancelResultMessage => message.type === \"cancel_result\",\n );\n if (!response) {\n return undefined;\n }\n if (response.requestId !== request.requestId) {\n throw new QueueProtocolError(\"Queue owner returned mismatched cancel response\", {\n detailCode: \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n origin: \"queue\",\n retryable: true,\n });\n }\n return response.cancelled;\n}\n\nasync function submitSetModeToQueueOwner(\n owner: QueueOwnerRecord,\n modeId: string,\n timeoutMs?: number,\n): Promise<boolean | undefined> {\n const request: QueueSetModeRequest = {\n type: \"set_mode\",\n requestId: randomUUID(),\n ownerGeneration: owner.ownerGeneration,\n modeId,\n timeoutMs,\n };\n const response = await submitControlToQueueOwner(\n owner,\n request,\n (message): message is QueueOwnerSetModeResultMessage => message.type === \"set_mode_result\",\n );\n if (!response) {\n return undefined;\n }\n if (response.requestId !== request.requestId) {\n throw new QueueProtocolError(\"Queue owner returned mismatched set_mode response\", {\n detailCode: \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n origin: \"queue\",\n retryable: true,\n });\n }\n return true;\n}\n\nasync function submitSetConfigOptionToQueueOwner(\n owner: QueueOwnerRecord,\n configId: string,\n value: string,\n timeoutMs?: number,\n): Promise<SetSessionConfigOptionResponse | undefined> {\n const request: QueueSetConfigOptionRequest = {\n type: \"set_config_option\",\n requestId: randomUUID(),\n ownerGeneration: owner.ownerGeneration,\n configId,\n value,\n timeoutMs,\n };\n const response = await submitControlToQueueOwner(\n owner,\n request,\n (message): message is QueueOwnerSetConfigOptionResultMessage =>\n message.type === \"set_config_option_result\",\n );\n if (!response) {\n return undefined;\n }\n if (response.requestId !== request.requestId) {\n throw new QueueProtocolError(\"Queue owner returned mismatched set_config_option response\", {\n detailCode: \"QUEUE_PROTOCOL_MALFORMED_MESSAGE\",\n origin: \"queue\",\n retryable: true,\n });\n }\n return response.response;\n}\n\nexport async function trySubmitToRunningOwner(\n options: SubmitToQueueOwnerOptions,\n): Promise<SessionSendOutcome | undefined> {\n const owner = await readQueueOwnerRecord(options.sessionId);\n if (!owner) {\n return undefined;\n }\n\n let submitted: SessionSendOutcome | undefined;\n try {\n submitted = await submitToQueueOwner(owner, options);\n } catch (error) {\n const recovered = await maybeRecoverStaleOwnerAfterProtocolMismatch({\n sessionId: options.sessionId,\n owner,\n error,\n verbose: options.verbose,\n });\n if (recovered) {\n return undefined;\n }\n throw error;\n }\n if (submitted) {\n if (options.verbose) {\n process.stderr.write(\n `[acpx] queued prompt on active owner pid ${owner.pid} for session ${options.sessionId}\\n`,\n );\n }\n return submitted;\n }\n\n const health = await probeQueueOwnerHealth(options.sessionId);\n if (!health.hasLease) {\n return undefined;\n }\n\n throw new QueueConnectionError(\n \"Session queue owner is running but not accepting queue requests\",\n {\n detailCode: \"QUEUE_NOT_ACCEPTING_REQUESTS\",\n origin: \"queue\",\n retryable: true,\n },\n );\n}\n\nexport async function tryCancelOnRunningOwner(options: {\n sessionId: string;\n verbose?: boolean;\n}): Promise<boolean | undefined> {\n const owner = await readQueueOwnerRecord(options.sessionId);\n if (!owner) {\n return undefined;\n }\n\n const cancelled = await submitCancelToQueueOwner(owner);\n if (cancelled !== undefined) {\n if (options.verbose) {\n process.stderr.write(\n `[acpx] requested cancel on active owner pid ${owner.pid} for session ${options.sessionId}\\n`,\n );\n }\n return cancelled;\n }\n\n const health = await probeQueueOwnerHealth(options.sessionId);\n if (!health.hasLease) {\n return undefined;\n }\n\n throw new QueueConnectionError(\n \"Session queue owner is running but not accepting cancel requests\",\n {\n detailCode: \"QUEUE_NOT_ACCEPTING_REQUESTS\",\n origin: \"queue\",\n retryable: true,\n },\n );\n}\n\nexport async function trySetModeOnRunningOwner(\n sessionId: string,\n modeId: string,\n timeoutMs: number | undefined,\n verbose: boolean | undefined,\n): Promise<boolean | undefined> {\n const owner = await readQueueOwnerRecord(sessionId);\n if (!owner) {\n return undefined;\n }\n\n const submitted = await submitSetModeToQueueOwner(owner, modeId, timeoutMs);\n if (submitted) {\n if (verbose) {\n process.stderr.write(\n `[acpx] requested session/set_mode on owner pid ${owner.pid} for session ${sessionId}\\n`,\n );\n }\n return true;\n }\n\n const health = await probeQueueOwnerHealth(sessionId);\n if (!health.hasLease) {\n return undefined;\n }\n\n throw new QueueConnectionError(\n \"Session queue owner is running but not accepting set_mode requests\",\n {\n detailCode: \"QUEUE_NOT_ACCEPTING_REQUESTS\",\n origin: \"queue\",\n retryable: true,\n },\n );\n}\n\nexport async function trySetConfigOptionOnRunningOwner(\n sessionId: string,\n configId: string,\n value: string,\n timeoutMs: number | undefined,\n verbose: boolean | undefined,\n): Promise<SetSessionConfigOptionResponse | undefined> {\n const owner = await readQueueOwnerRecord(sessionId);\n if (!owner) {\n return undefined;\n }\n\n const response = await submitSetConfigOptionToQueueOwner(owner, configId, value, timeoutMs);\n if (response) {\n if (verbose) {\n process.stderr.write(\n `[acpx] requested session/set_config_option on owner pid ${owner.pid} for session ${sessionId}\\n`,\n );\n }\n return response;\n }\n\n const health = await probeQueueOwnerHealth(sessionId);\n if (!health.hasLease) {\n return undefined;\n }\n\n throw new QueueConnectionError(\n \"Session queue owner is running but not accepting set_config_option requests\",\n {\n detailCode: \"QUEUE_NOT_ACCEPTING_REQUESTS\",\n origin: \"queue\",\n retryable: true,\n },\n );\n}\n"],"mappings":";;;;;;;;;AAWA,IAAa,uBAAb,cAA0C,MAAM;CAC9C,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CACT,AAAS;CAET,YAAY,SAAiB,SAA4B;AACvD,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO,IAAI,OAAO;AACvB,OAAK,aAAa,SAAS;AAC3B,OAAK,aAAa,SAAS;AAC3B,OAAK,SAAS,SAAS;AACvB,OAAK,YAAY,SAAS;AAC1B,OAAK,MAAM,SAAS;AACpB,OAAK,uBAAuB,SAAS;;;AAIzC,IAAa,uBAAb,cAA0C,qBAAqB;CAC7D,AAAS;CAET,YAAY,WAAmB;AAC7B,QAAM,sBAAsB,YAAY;AACxC,OAAK,YAAY;;;AAIrB,IAAa,yBAAb,cAA4C,qBAAqB;AAEjE,IAAa,kBAAb,cAAqC,qBAAqB;CACxD,AAAS;CAET,YAAY,cAAsB,OAAiB;AACjD,QAAM,kCAAkC,gBAAgB,EACtD,OAAO,iBAAiB,QAAQ,QAAQ,QACzC,CAAC;AACF,OAAK,eAAe;;;AAIxB,IAAa,+BAAb,cAAkD,qBAAqB;CACrE,YAAY,SAAiB,SAA4B;AACvD,QAAM,SAAS;GACb,YAAY;GACZ,YAAY;GACZ,QAAQ;GACR,GAAG;GACJ,CAAC;;;AAIN,IAAa,yBAAb,cAA4C,qBAAqB;CAC/D,YAAY,SAAiB,SAA4B;AACvD,QAAM,SAAS;GACb,YAAY;GACZ,YAAY;GACZ,QAAQ;GACR,GAAG;GACJ,CAAC;;;AAIN,IAAa,qCAAb,cA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