acpx 0.19.1 → 0.19.2

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.
@@ -1,4 +1,4 @@
1
- import { $ as measurePerf, A as findGitRepositoryRoot, B as writeSessionRecord, Bt as PermissionDeniedError, C as getUnsupportedPromptContentMessage, D as textPrompt, Dt as OUTPUT_ERROR_ORIGINS, E as promptToDisplayText, Et as OUTPUT_ERROR_CODES, Ft as AgentStartupError, G as normalizeAgentSessionId, Gt as SessionModelReplayError, Ht as QueueConnectionError, I as normalizeName, It as AuthPolicyError, Jt as UnsupportedPromptContentError, K as SESSION_JOURNAL_SCHEMA, Lt as ClaudeAcpSessionCreateTimeoutError, M as findSessionByDirectoryWalk, Mt as AcpxOperationalError, N as isoNow$1, Nt as AgentDisconnectedError, Pt as AgentSpawnError, Q as incrementPerfCounter, Rt as CopilotAcpUnsupportedError, St as isAcpResourceNotFoundError, Ut as SessionConfigOptionReplayError, Vt as PermissionPromptUnavailableError, W as extractAgentSessionId, Wt as SessionModeReplayError, X as formatPerfMetric, Z as getPerfMetricsSnapshot, _ as waitMs$1, a as trySetModelOnRunningOwner, at as isAcpJsonRpcMessage, b as lockOwnerPid, bt as extractAcpError, c as queueRequestExceedsLimit, et as recordPerfDuration, f as refreshQueueOwnerLease, ft as defaultSessionEventLog, g as tryAcquireQueueOwnerLease, gt as sessionEventSegmentPath, h as terminateQueueOwnerForSession, ht as sessionEventLockPath, i as trySetModeOnRunningOwner, k as absolutePath, l as parseQueueRequest, m as terminateProcess, mt as sessionEventActivePath, n as tryCloseSessionOnRunningOwner, nt as setPerfGauge, o as trySubmitToRunningOwner, ot as isAcpMessageObject, p as releaseQueueOwnerLease, pt as sessionBaseDir, q as SessionJournalReader, qt as SessionResumeRequiredError, r as trySetConfigOptionOnRunningOwner, rt as startPerfTimer, s as queueRequestByteLimit, st as isSessionUpdateNotification, t as tryCancelOnRunningOwner, tt as resetPerfMetrics, v as QueueLeaseGuardSettlementError, wt as EXIT_CODES, x as ProcessDescendants, xt as formatUnknownErrorMessage, y as createLockOwner, yt as isProcessAlive, z as resolveSessionRecord, zt as GeminiAcpStartupTimeoutError } from "./ipc-DAApJ5mi.js";
1
+ import { $ as resetPerfMetrics, Bt as PermissionDeniedError, Ct as extractAcpError, E as textPrompt, F as normalizeName, Ft as AgentStartupError, G as SESSION_JOURNAL_SCHEMA, Gt as SessionModelReplayError, Ht as QueueConnectionError, It as AuthPolicyError, Jt as UnsupportedPromptContentError, K as SessionJournalReader, Lt as ClaudeAcpSessionCreateTimeoutError, M as isoNow$1, Mt as AcpxOperationalError, Nt as AgentDisconnectedError, O as absolutePath, Pt as AgentSpawnError, Q as measurePerf, R as resolveSessionRecord, Rt as CopilotAcpUnsupportedError, S as getUnsupportedPromptContentMessage, St as normalizeOutputError, T as promptToDisplayText, U as extractAgentSessionId, Ut as SessionConfigOptionReplayError, Vt as PermissionPromptUnavailableError, W as normalizeAgentSessionId, Wt as SessionModeReplayError, X as getPerfMetricsSnapshot, Y as formatPerfMetric, Z as incrementPerfCounter, _ as createLockOwner, _t as isProcessAlive, a as trySetModelOnRunningOwner, at as isSessionUpdateNotification, bt as isAcpQueryClosedBeforeResponseError, d as releaseQueueOwnerLease, dt as sessionBaseDir, et as setPerfGauge, f as terminateProcess, ft as sessionEventActivePath, g as QueueLeaseGuardSettlementError, h as waitMs$1, i as trySetModeOnRunningOwner, it as isAcpMessageObject, j as findSessionByDirectoryWalk, k as findGitRepositoryRoot, m as tryAcquireQueueOwnerLease, mt as sessionEventSegmentPath, n as tryCloseSessionOnRunningOwner, o as trySubmitToRunningOwner, p as terminateQueueOwnerForSession, pt as sessionEventLockPath, qt as SessionResumeRequiredError, r as trySetConfigOptionOnRunningOwner, rt as isAcpJsonRpcMessage, s as SessionQueueOwner, t as tryCancelOnRunningOwner, tt as startPerfTimer, u as refreshQueueOwnerLease, ut as defaultSessionEventLog, v as lockOwnerPid, wt as isAcpResourceNotFoundError, xt as isRetryablePromptError, y as ProcessDescendants, yt as formatErrorMessage, z as writeSessionRecord, zt as GeminiAcpStartupTimeoutError } from "./ipc-D0ZMQ0q9.js";
2
2
  import { A as requireAgentStdio, C as PROCESS_HELPER_TIMEOUT_MS, D as isoNow$2, E as isChildProcessRunning, F as waitForChildExit, I as waitForSpawn, M as resolveAgentSessionCwd, N as runTimedExecFile, P as splitCommandLine, T as basenameToken, _ as buildSpawnCommandOptions, b as readWindowsEnvValue, f as resolveBuiltInAgentLaunch, g as buildAgentSpawnCommand, j as resolveAgentCommandParts, v as buildTerminalShellSpawnCommand, w as asAbsoluteCwd, x as resolveWindowsExecutablePath, y as buildTerminalSpawnCommand } from "./agent-registry-DWlx5BQ4.js";
3
3
  import fs, { readFileSync, realpathSync } from "node:fs";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -16,137 +16,6 @@ import { root } from "@openclaw/fs-safe/root";
16
16
  import readline from "node:readline/promises";
17
17
  import { isHardlinkFallbackError } from "@openclaw/fs-safe/durability";
18
18
  import { acquireFileLock } from "@openclaw/fs-safe/file-lock";
19
- import net from "node:net";
20
- //#region src/acp/error-normalization.ts
21
- const AUTH_REQUIRED_ACP_CODES = /* @__PURE__ */ new Set([-32e3]);
22
- const QUERY_CLOSED_BEFORE_RESPONSE_DETAIL = "query closed before response received";
23
- function asRecord$3(value) {
24
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
25
- return value;
26
- }
27
- function isAuthRequiredMessage(value) {
28
- if (!value) return false;
29
- const normalized = value.toLowerCase();
30
- return [
31
- "auth required",
32
- "authentication required",
33
- "authorization required",
34
- "credential required",
35
- "credentials required",
36
- "token required",
37
- "login required"
38
- ].some((needle) => normalized.includes(needle));
39
- }
40
- function isAcpAuthRequiredPayload(acp) {
41
- if (!acp) return false;
42
- if (!AUTH_REQUIRED_ACP_CODES.has(acp.code)) return false;
43
- if (isAuthRequiredMessage(acp.message)) return true;
44
- const data = asRecord$3(acp.data);
45
- if (!data) return false;
46
- return hasAuthRequiredData(data);
47
- }
48
- function hasAuthRequiredData(data) {
49
- return data.authRequired === true || hasNonEmptyString(data.methodId) || hasNonEmptyArray(data.methods);
50
- }
51
- function hasNonEmptyString(value) {
52
- return typeof value === "string" && value.trim().length > 0;
53
- }
54
- function hasNonEmptyArray(value) {
55
- return Array.isArray(value) && value.length > 0;
56
- }
57
- function isOutputErrorCode(value) {
58
- return typeof value === "string" && OUTPUT_ERROR_CODES.includes(value);
59
- }
60
- function isOutputErrorOrigin(value) {
61
- return typeof value === "string" && OUTPUT_ERROR_ORIGINS.includes(value);
62
- }
63
- function readOutputErrorMeta(error) {
64
- const record = asRecord$3(error);
65
- if (!record) return {};
66
- return {
67
- outputCode: isOutputErrorCode(record.outputCode) ? record.outputCode : void 0,
68
- detailCode: typeof record.detailCode === "string" && record.detailCode.trim().length > 0 ? record.detailCode : void 0,
69
- origin: isOutputErrorOrigin(record.origin) ? record.origin : void 0,
70
- retryable: typeof record.retryable === "boolean" ? record.retryable : void 0,
71
- acp: extractAcpError(record.acp)
72
- };
73
- }
74
- function isTimeoutLike(error) {
75
- return error instanceof Error && error.name === "TimeoutError";
76
- }
77
- function isNoSessionLike(error) {
78
- return error instanceof Error && error.name === "NoSessionError";
79
- }
80
- function isUsageLike(error) {
81
- if (!(error instanceof Error)) return false;
82
- return error.name === "CommanderError" || error.name === "InvalidArgumentError" || asRecord$3(error)?.code === "commander.invalidArgument";
83
- }
84
- function formatErrorMessage(error) {
85
- return formatUnknownErrorMessage(error);
86
- }
87
- function isAcpQueryClosedBeforeResponseError(error) {
88
- const acp = extractAcpError(error);
89
- if (!acp || acp.code !== -32603) return false;
90
- const details = asRecord$3(acp.data)?.details;
91
- if (typeof details !== "string") return false;
92
- return details.toLowerCase().includes(QUERY_CLOSED_BEFORE_RESPONSE_DETAIL);
93
- }
94
- function mapErrorCode(error) {
95
- if (error instanceof PermissionPromptUnavailableError) return "PERMISSION_PROMPT_UNAVAILABLE";
96
- if (error instanceof PermissionDeniedError) return "PERMISSION_DENIED";
97
- if (isTimeoutLike(error)) return "TIMEOUT";
98
- if (isNoSessionLike(error) || isAcpResourceNotFoundError(error)) return "NO_SESSION";
99
- if (isUsageLike(error)) return "USAGE";
100
- }
101
- function normalizeOutputError(error, options = {}) {
102
- const meta = readOutputErrorMeta(error);
103
- const code = resolveOutputErrorCode(error, options, meta);
104
- const acp = options.acp ?? meta.acp ?? extractAcpError(error);
105
- return {
106
- code,
107
- message: formatErrorMessage(error),
108
- detailCode: resolveDetailCode(error, acp, options, meta),
109
- origin: meta.origin ?? options.origin,
110
- retryable: meta.retryable ?? options.retryable,
111
- acp
112
- };
113
- }
114
- function resolveOutputErrorCode(error, options, meta) {
115
- const code = meta.outputCode ?? mapErrorCode(error) ?? options.defaultCode ?? "RUNTIME";
116
- if (code === "RUNTIME" && isAcpResourceNotFoundError(error)) return "NO_SESSION";
117
- return code;
118
- }
119
- function resolveDetailCode(error, acp, options, meta) {
120
- return meta.detailCode ?? options.detailCode ?? (error instanceof AuthPolicyError || isAcpAuthRequiredPayload(acp) ? "AUTH_REQUIRED" : void 0);
121
- }
122
- /**
123
- * Returns true when an error from `client.prompt()` looks transient and
124
- * can reasonably be retried (e.g. model-API 400/500, network hiccups that
125
- * surface as ACP internal errors).
126
- *
127
- * Errors that are definitively non-recoverable (auth, missing session,
128
- * invalid params, timeout, permission) return false.
129
- */
130
- function isRetryablePromptError(error) {
131
- if (isNonRetryablePromptError(error)) return false;
132
- const acp = extractAcpError(error);
133
- if (!acp) return false;
134
- return acp.code === -32603 || acp.code === -32700;
135
- }
136
- function isNonRetryablePromptError(error) {
137
- return error instanceof PermissionDeniedError || error instanceof PermissionPromptUnavailableError || isTimeoutLike(error) || isNoSessionLike(error) || isUsageLike(error);
138
- }
139
- function exitCodeForOutputErrorCode(code) {
140
- switch (code) {
141
- case "USAGE": return EXIT_CODES.USAGE;
142
- case "TIMEOUT": return EXIT_CODES.TIMEOUT;
143
- case "NO_SESSION": return EXIT_CODES.NO_SESSION;
144
- case "PERMISSION_DENIED":
145
- case "PERMISSION_PROMPT_UNAVAILABLE": return EXIT_CODES.PERMISSION_DENIED;
146
- default: return EXIT_CODES.ERROR;
147
- }
148
- }
149
- //#endregion
150
19
  //#region src/async-control.ts
151
20
  var TimeoutError = class extends Error {
152
21
  constructor(timeoutMs) {
@@ -4813,406 +4682,6 @@ function directExecutionError(error, signal) {
4813
4682
  return signal?.aborted && error instanceof AgentDisconnectedError ? signal.reason : error;
4814
4683
  }
4815
4684
  //#endregion
4816
- //#region src/session/queue/ipc-server.ts
4817
- const QUEUE_SOCKET_DRAIN_TIMEOUT_MS = 1e3;
4818
- function makeQueueOwnerError(requestId, message, detailCode, options = {}) {
4819
- return {
4820
- type: "error",
4821
- requestId,
4822
- ownerGeneration: void 0,
4823
- code: "RUNTIME",
4824
- detailCode,
4825
- origin: "queue",
4826
- retryable: options.retryable,
4827
- message
4828
- };
4829
- }
4830
- function makeQueueOwnerErrorFromUnknown(requestId, error, detailCode, options = {}) {
4831
- const normalized = normalizeOutputError(error, {
4832
- defaultCode: "RUNTIME",
4833
- origin: "queue",
4834
- detailCode,
4835
- retryable: options.retryable
4836
- });
4837
- return {
4838
- type: "error",
4839
- requestId,
4840
- code: normalized.code,
4841
- detailCode: normalized.detailCode,
4842
- origin: normalized.origin,
4843
- message: normalized.message,
4844
- retryable: normalized.retryable,
4845
- acp: normalized.acp
4846
- };
4847
- }
4848
- function armSocketDrainTimeout(socket) {
4849
- if (process.platform !== "win32") socket.setTimeout(QUEUE_SOCKET_DRAIN_TIMEOUT_MS);
4850
- }
4851
- function writeQueueMessage(socket, message) {
4852
- if (socket.destroyed || !socket.writable) return;
4853
- if (!socket.write(`${JSON.stringify(message)}\n`) && !socket.timeout) armSocketDrainTimeout(socket);
4854
- }
4855
- var SessionQueueOwner = class SessionQueueOwner {
4856
- server;
4857
- controlHandlers;
4858
- ownerGeneration;
4859
- maxQueueDepth;
4860
- maxRequestBytes;
4861
- onQueueDepthChanged;
4862
- pending = [];
4863
- activeTask;
4864
- waiters = [];
4865
- sockets = /* @__PURE__ */ new Set();
4866
- taskSockets = /* @__PURE__ */ new Set();
4867
- drainingSockets = /* @__PURE__ */ new Set();
4868
- closed = false;
4869
- constructor(server, controlHandlers, lease, options) {
4870
- this.server = server;
4871
- this.controlHandlers = controlHandlers;
4872
- this.ownerGeneration = lease.ownerGeneration;
4873
- this.maxQueueDepth = Math.max(1, Math.round(options.maxQueueDepth));
4874
- this.maxRequestBytes = queueRequestByteLimit(options.maxRequestBytes?.toString());
4875
- this.onQueueDepthChanged = options.onQueueDepthChanged;
4876
- }
4877
- static async start(lease, controlHandlers, options = { maxQueueDepth: 16 }) {
4878
- const ownerRef = { current: void 0 };
4879
- const server = net.createServer((socket) => {
4880
- ownerRef.current?.handleConnection(socket);
4881
- });
4882
- ownerRef.current = new SessionQueueOwner(server, controlHandlers, lease, options);
4883
- await new Promise((resolve, reject) => {
4884
- const onListening = () => {
4885
- server.off("error", onError);
4886
- resolve();
4887
- };
4888
- const onError = (error) => {
4889
- server.off("listening", onListening);
4890
- reject(error);
4891
- };
4892
- server.once("listening", onListening);
4893
- server.once("error", onError);
4894
- server.listen(lease.socketPath);
4895
- });
4896
- return ownerRef.current;
4897
- }
4898
- beginShutdown() {
4899
- if (this.closed) return;
4900
- this.closed = true;
4901
- for (const waiter of this.waiters.splice(0)) waiter(void 0);
4902
- for (const task of this.pending.splice(0)) {
4903
- if (task.waitForCompletion) task.send(makeQueueOwnerError(task.requestId, "Queue owner shutting down before prompt execution", "QUEUE_OWNER_SHUTTING_DOWN", { retryable: true }));
4904
- task.close();
4905
- }
4906
- for (const socket of this.sockets) if (!this.taskSockets.has(socket) && !this.drainingSockets.has(socket)) socket.destroy();
4907
- this.emitQueueDepth();
4908
- }
4909
- async close() {
4910
- this.beginShutdown();
4911
- await new Promise((resolve) => {
4912
- const forceCloseTimer = setTimeout(() => {
4913
- for (const socket of this.sockets) socket.destroy();
4914
- }, QUEUE_SOCKET_DRAIN_TIMEOUT_MS);
4915
- forceCloseTimer.unref();
4916
- this.server.close(() => {
4917
- clearTimeout(forceCloseTimer);
4918
- resolve();
4919
- });
4920
- });
4921
- }
4922
- async nextTask(timeoutMs) {
4923
- if (this.pending.length > 0) {
4924
- const task = this.pending.shift();
4925
- this.emitQueueDepth();
4926
- if (task) {
4927
- this.activeTask = task;
4928
- recordPerfDuration("queue.owner.wait_ms", Date.now() - task.enqueuedAt);
4929
- }
4930
- return task;
4931
- }
4932
- if (this.closed) return;
4933
- return await new Promise((resolve) => {
4934
- const timer = timeoutMs != null && setTimeout(() => {
4935
- const index = this.waiters.indexOf(waiter);
4936
- if (index >= 0) this.waiters.splice(index, 1);
4937
- resolve(void 0);
4938
- }, Math.max(0, timeoutMs));
4939
- const waiter = (task) => {
4940
- if (timer) clearTimeout(timer);
4941
- resolve(task);
4942
- };
4943
- this.waiters.push(waiter);
4944
- });
4945
- }
4946
- queueDepth() {
4947
- return this.pending.length;
4948
- }
4949
- completeTask(task) {
4950
- if (this.activeTask === task) this.activeTask = void 0;
4951
- }
4952
- async cancelPrompt(targetRequestId) {
4953
- if (targetRequestId === void 0) return await this.controlHandlers.cancelPrompt();
4954
- const index = this.pending.findIndex((task) => task.requestId === targetRequestId);
4955
- if (index >= 0) {
4956
- const [task] = this.pending.splice(index, 1);
4957
- task.send(makeQueueOwnerError(task.requestId, "Prompt cancelled before execution", "QUEUE_REQUEST_CANCELLED", { retryable: false }));
4958
- task.close();
4959
- this.emitQueueDepth();
4960
- return true;
4961
- }
4962
- return this.activeTask?.requestId === targetRequestId ? await this.controlHandlers.cancelPrompt() : false;
4963
- }
4964
- emitQueueDepth() {
4965
- this.onQueueDepthChanged?.(this.pending.length);
4966
- }
4967
- enqueue(task) {
4968
- if (this.closed) {
4969
- task.send(makeQueueOwnerError(task.requestId, "Queue owner is shutting down", "QUEUE_OWNER_SHUTTING_DOWN", { retryable: true }));
4970
- task.close();
4971
- return false;
4972
- }
4973
- if (this.activeTask?.requestId === task.requestId || this.pending.some((queued) => queued.requestId === task.requestId)) {
4974
- task.send(makeQueueOwnerError(task.requestId, "Request is already queued or active", "QUEUE_REQUEST_DUPLICATE", { retryable: false }));
4975
- task.close();
4976
- return false;
4977
- }
4978
- const waiter = this.waiters.shift();
4979
- if (waiter) {
4980
- this.activeTask = task;
4981
- waiter(task);
4982
- return true;
4983
- }
4984
- if (this.pending.length >= this.maxQueueDepth) {
4985
- task.send({
4986
- ...makeQueueOwnerError(task.requestId, `Queue owner is overloaded (${this.pending.length}/${this.maxQueueDepth} queued)`, "QUEUE_OWNER_OVERLOADED", { retryable: true }),
4987
- ownerGeneration: this.ownerGeneration
4988
- });
4989
- task.close();
4990
- return false;
4991
- }
4992
- this.pending.push(task);
4993
- this.emitQueueDepth();
4994
- return true;
4995
- }
4996
- handleControlRequest(options) {
4997
- this.taskSockets.add(options.socket);
4998
- writeQueueMessage(options.socket, {
4999
- type: "accepted",
5000
- requestId: options.requestId,
5001
- ownerGeneration: this.ownerGeneration
5002
- });
5003
- options.run().then((message) => {
5004
- writeQueueMessage(options.socket, {
5005
- ...message,
5006
- ownerGeneration: this.ownerGeneration
5007
- });
5008
- }).catch((error) => {
5009
- writeQueueMessage(options.socket, {
5010
- ...makeQueueOwnerErrorFromUnknown(options.requestId, error, "QUEUE_CONTROL_REQUEST_FAILED"),
5011
- ownerGeneration: this.ownerGeneration
5012
- });
5013
- }).finally(() => {
5014
- this.endSocket(options.socket);
5015
- });
5016
- }
5017
- endSocket(socket) {
5018
- if (socket.destroyed || this.drainingSockets.has(socket)) return;
5019
- this.taskSockets.delete(socket);
5020
- this.drainingSockets.add(socket);
5021
- armSocketDrainTimeout(socket);
5022
- socket.end(() => {
5023
- this.drainingSockets.delete(socket);
5024
- socket.destroy();
5025
- });
5026
- }
5027
- failRequest(socket, requestId, message, detailCode) {
5028
- writeQueueMessage(socket, {
5029
- ...makeQueueOwnerError(requestId, message, detailCode, { retryable: false }),
5030
- ownerGeneration: this.ownerGeneration
5031
- });
5032
- this.endSocket(socket);
5033
- }
5034
- parseRequestLine(socket, line) {
5035
- let parsed;
5036
- try {
5037
- parsed = JSON.parse(line);
5038
- } catch {
5039
- this.failRequest(socket, "unknown", "Invalid queue request payload", "QUEUE_REQUEST_PAYLOAD_INVALID_JSON");
5040
- return;
5041
- }
5042
- const request = parseQueueRequest(parsed);
5043
- if (!request) this.failRequest(socket, "unknown", "Invalid queue request", "QUEUE_REQUEST_INVALID");
5044
- return request ?? void 0;
5045
- }
5046
- rejectStaleOwnerGeneration(socket, request) {
5047
- if (request.ownerGeneration === void 0 || this.ownerGeneration === void 0 || request.ownerGeneration === this.ownerGeneration) return false;
5048
- this.failRequest(socket, request.requestId, "Queue request targeted a stale queue owner generation", "QUEUE_OWNER_GENERATION_MISMATCH");
5049
- return true;
5050
- }
5051
- rejectClosedOwner(socket, request) {
5052
- if (!this.closed) return false;
5053
- writeQueueMessage(socket, {
5054
- ...makeQueueOwnerError(request.requestId, "Queue owner is shutting down", "QUEUE_OWNER_CLOSED", { retryable: true }),
5055
- ownerGeneration: this.ownerGeneration
5056
- });
5057
- this.endSocket(socket);
5058
- return true;
5059
- }
5060
- handleControlQueueRequest(socket, request) {
5061
- if (request.type === "cancel_prompt") {
5062
- this.handleControlRequest({
5063
- socket,
5064
- requestId: request.requestId,
5065
- run: async () => ({
5066
- type: "cancel_result",
5067
- requestId: request.requestId,
5068
- cancelled: await this.cancelPrompt(request.targetRequestId)
5069
- })
5070
- });
5071
- return true;
5072
- }
5073
- if (request.type === "close_session") {
5074
- this.handleControlRequest({
5075
- socket,
5076
- requestId: request.requestId,
5077
- run: async () => ({
5078
- type: "close_session_result",
5079
- requestId: request.requestId,
5080
- closed: await this.controlHandlers.closeSession(request.timeoutMs)
5081
- })
5082
- });
5083
- return true;
5084
- }
5085
- return this.handleSessionControlQueueRequest(socket, request);
5086
- }
5087
- handleSessionControlQueueRequest(socket, request) {
5088
- if (request.type === "set_mode") {
5089
- this.handleControlRequest({
5090
- socket,
5091
- requestId: request.requestId,
5092
- run: async () => {
5093
- await this.controlHandlers.setSessionMode(request.modeId, request.timeoutMs);
5094
- return {
5095
- type: "set_mode_result",
5096
- requestId: request.requestId,
5097
- modeId: request.modeId
5098
- };
5099
- }
5100
- });
5101
- return true;
5102
- }
5103
- if (request.type === "set_model") {
5104
- this.handleControlRequest({
5105
- socket,
5106
- requestId: request.requestId,
5107
- run: async () => {
5108
- const response = await this.controlHandlers.setSessionModel(request.modelId, request.timeoutMs);
5109
- return {
5110
- type: "set_model_result",
5111
- requestId: request.requestId,
5112
- modelId: request.modelId,
5113
- response
5114
- };
5115
- }
5116
- });
5117
- return true;
5118
- }
5119
- if (request.type === "set_config_option") {
5120
- this.handleControlRequest({
5121
- socket,
5122
- requestId: request.requestId,
5123
- run: async () => ({
5124
- type: "set_config_option_result",
5125
- requestId: request.requestId,
5126
- response: await this.controlHandlers.setSessionConfigOption(request.configId, request.value, request.timeoutMs)
5127
- })
5128
- });
5129
- return true;
5130
- }
5131
- return false;
5132
- }
5133
- enqueuePromptRequest(socket, request) {
5134
- this.taskSockets.add(socket);
5135
- const task = {
5136
- requestId: request.requestId,
5137
- message: request.message,
5138
- prompt: request.prompt ?? textPrompt(request.message),
5139
- permissionMode: request.permissionMode,
5140
- resumePolicy: request.resumePolicy,
5141
- nonInteractivePermissions: request.nonInteractivePermissions,
5142
- permissionPolicy: request.permissionPolicy,
5143
- timeoutMs: request.timeoutMs,
5144
- suppressSdkConsoleErrors: request.suppressSdkConsoleErrors,
5145
- promptRetries: request.promptRetries,
5146
- sessionOptions: request.sessionOptions,
5147
- waitForCompletion: request.waitForCompletion,
5148
- reportPromptStarted: request.reportPromptStarted,
5149
- enqueuedAt: Date.now(),
5150
- send: (message) => {
5151
- writeQueueMessage(socket, {
5152
- ...message,
5153
- ownerGeneration: this.ownerGeneration
5154
- });
5155
- },
5156
- close: () => {
5157
- this.endSocket(socket);
5158
- }
5159
- };
5160
- if (!this.enqueue(task)) return;
5161
- writeQueueMessage(socket, {
5162
- type: "accepted",
5163
- requestId: request.requestId,
5164
- ownerGeneration: this.ownerGeneration
5165
- });
5166
- if (!request.waitForCompletion) task.close();
5167
- }
5168
- handleConnection(socket) {
5169
- this.sockets.add(socket);
5170
- socket.setEncoding("utf8");
5171
- socket.on("timeout", () => socket.destroy());
5172
- socket.on("drain", () => {
5173
- if (!socket.writableEnded) socket.setTimeout(0);
5174
- });
5175
- socket.once("close", () => {
5176
- this.sockets.delete(socket);
5177
- this.taskSockets.delete(socket);
5178
- this.drainingSockets.delete(socket);
5179
- });
5180
- let buffer = "";
5181
- let handled = false;
5182
- const processLine = (line) => {
5183
- if (handled) return;
5184
- handled = true;
5185
- const request = this.parseRequestLine(socket, line);
5186
- if (!request || this.rejectClosedOwner(socket, request) || this.rejectStaleOwnerGeneration(socket, request)) return;
5187
- if (this.handleControlQueueRequest(socket, request)) return;
5188
- if (request.type !== "submit_prompt") {
5189
- this.failRequest(socket, request.requestId, "Invalid queue request", "QUEUE_REQUEST_INVALID");
5190
- return;
5191
- }
5192
- this.enqueuePromptRequest(socket, request);
5193
- };
5194
- socket.on("data", (chunk) => {
5195
- buffer += chunk;
5196
- let index = buffer.indexOf("\n");
5197
- while (index >= 0) {
5198
- const rawLine = buffer.slice(0, index);
5199
- if (this.rejectOversizedRequest(socket, rawLine)) return;
5200
- const line = rawLine.trim();
5201
- buffer = buffer.slice(index + 1);
5202
- if (line.length > 0) processLine(line);
5203
- index = buffer.indexOf("\n");
5204
- }
5205
- this.rejectOversizedRequest(socket, buffer);
5206
- });
5207
- socket.on("error", () => {});
5208
- }
5209
- rejectOversizedRequest(socket, line) {
5210
- if (!queueRequestExceedsLimit(line, this.maxRequestBytes)) return false;
5211
- socket.destroy();
5212
- return true;
5213
- }
5214
- };
5215
- //#endregion
5216
4685
  //#region src/runtime/engine/reconnect.ts
5217
4686
  const SESSION_LOAD_UNSUPPORTED_CODES = /* @__PURE__ */ new Set([-32601, -32602]);
5218
4687
  function createReplayState(authority) {
@@ -5798,6 +5267,89 @@ async function runSessionSetConfigOptionDirect(options) {
5798
5267
  };
5799
5268
  }
5800
5269
  //#endregion
5270
+ //#region src/session/execution/windows-process-command.ts
5271
+ function skipSeparators(value) {
5272
+ return value.replace(/^[ \t]+/u, "");
5273
+ }
5274
+ function readQuote(commandLine, state, executable) {
5275
+ if (!executable && state.quoted && commandLine[state.index + 1] === "\"") {
5276
+ state.value += "\"";
5277
+ state.index += 2;
5278
+ } else {
5279
+ state.quoted = !state.quoted;
5280
+ state.index += 1;
5281
+ }
5282
+ }
5283
+ function readBackslashes(commandLine, state, executable) {
5284
+ const start = state.index;
5285
+ while (commandLine[state.index] === "\\") state.index += 1;
5286
+ const count = state.index - start;
5287
+ if (executable || commandLine[state.index] !== "\"") state.value += "\\".repeat(count);
5288
+ else {
5289
+ state.value += "\\".repeat(Math.floor(count / 2));
5290
+ if (count % 2 === 1) {
5291
+ state.value += "\"";
5292
+ state.index += 1;
5293
+ } else readQuote(commandLine, state, false);
5294
+ }
5295
+ }
5296
+ function readArgument(commandLine, start, executable) {
5297
+ const state = {
5298
+ value: "",
5299
+ index: start,
5300
+ quoted: false
5301
+ };
5302
+ while (state.index < commandLine.length) {
5303
+ const char = commandLine[state.index];
5304
+ if (!state.quoted && /[ \t]/u.test(char)) break;
5305
+ if (char === "\\") readBackslashes(commandLine, state, executable);
5306
+ else if (char === "\"") readQuote(commandLine, state, executable);
5307
+ else {
5308
+ state.value += char;
5309
+ state.index += 1;
5310
+ }
5311
+ }
5312
+ return state.quoted ? void 0 : state;
5313
+ }
5314
+ function readBatchCommand(commandLine) {
5315
+ const body = commandLine.match(/^[ \t]+\/d[ \t]+\/s[ \t]+\/c[ \t]+"([\s\S]*)"$/iu)?.[1];
5316
+ if (!body) return;
5317
+ return readBatchExecutable(body);
5318
+ }
5319
+ function readBatchExecutable(body) {
5320
+ let command = "";
5321
+ for (let index = 0; index < body.length; index += 1) {
5322
+ const char = body[index];
5323
+ if (char === "^") {
5324
+ index += 1;
5325
+ if (index === body.length) return;
5326
+ command += body[index];
5327
+ } else if (/[ \t]/u.test(char)) break;
5328
+ else if (/["\r\n]/u.test(char)) return;
5329
+ else command += char;
5330
+ }
5331
+ return /\.(?:cmd|bat)$/iu.test(command) ? command : void 0;
5332
+ }
5333
+ /** Decode process observations, not saved command identities or POSIX launch strings. */
5334
+ function splitWindowsProcessCommandLine(commandLine) {
5335
+ const line = skipSeparators(commandLine);
5336
+ const executable = readArgument(line, 0, true);
5337
+ if (!executable?.value) return [];
5338
+ const argv = [executable.value];
5339
+ if (path.win32.basename(executable.value).toLowerCase() === "cmd.exe") {
5340
+ const batch = readBatchCommand(line.slice(executable.index));
5341
+ return batch ? [...argv, batch] : argv;
5342
+ }
5343
+ let rest = skipSeparators(line.slice(executable.index));
5344
+ while (rest) {
5345
+ const argument = readArgument(rest, 0, false);
5346
+ if (!argument) return [];
5347
+ argv.push(argument.value);
5348
+ rest = skipSeparators(rest.slice(argument.index));
5349
+ }
5350
+ return argv;
5351
+ }
5352
+ //#endregion
5801
5353
  //#region src/session/execution/session-control.ts
5802
5354
  async function cancelSessionPrompt(options) {
5803
5355
  const cancelled = await tryCancelOnRunningOwner(options);
@@ -5907,15 +5459,16 @@ async function setSessionConfigOption(options) {
5907
5459
  verbose: options.verbose
5908
5460
  });
5909
5461
  }
5910
- function firstAgentCommandToken(command) {
5462
+ function firstAgentCommandToken(command, argv) {
5463
+ if (argv) return argv[0] || void 0;
5911
5464
  try {
5912
5465
  return splitCommandLine(command).command || void 0;
5913
5466
  } catch {
5914
5467
  return;
5915
5468
  }
5916
5469
  }
5917
- async function isLikelyMatchingProcess(pid, agentCommand) {
5918
- const expectedToken = firstAgentCommandToken(agentCommand);
5470
+ async function isLikelyMatchingProcess(pid, record) {
5471
+ const expectedToken = firstAgentCommandToken(record.agentCommand, record.agentArgv);
5919
5472
  if (!expectedToken) return false;
5920
5473
  const argv = await readProcessArgv(pid);
5921
5474
  if (argv.length === 0) return false;
@@ -5954,13 +5507,14 @@ async function readWindowsCommandLine(pid) {
5954
5507
  "-NonInteractive",
5955
5508
  "-Command",
5956
5509
  `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`
5957
- ], { windowsHide: true })).trim() || void 0;
5510
+ ], { windowsHide: true })).replace(/\r?\n$/u, "") || void 0;
5958
5511
  } catch {
5959
5512
  return;
5960
5513
  }
5961
5514
  }
5962
- function splitCommandLineLike(commandLine) {
5515
+ function splitCommandLineLike(commandLine, platform = process.platform) {
5963
5516
  if (!commandLine) return [];
5517
+ if (platform === "win32") return splitWindowsProcessCommandLine(commandLine);
5964
5518
  try {
5965
5519
  const parsed = splitCommandLine(commandLine);
5966
5520
  return [parsed.command, ...parsed.args];
@@ -5982,7 +5536,7 @@ async function closeSession(sessionId) {
5982
5536
  }
5983
5537
  }).catch(() => {});
5984
5538
  if (selectedOwner) await terminateQueueOwnerForSession(record.acpxRecordId, selectedOwner);
5985
- if (record.pid != null && isProcessAlive(record.pid) && await isLikelyMatchingProcess(record.pid, record.agentCommand)) await terminateProcess(record.pid);
5539
+ if (record.pid != null && isProcessAlive(record.pid) && await isLikelyMatchingProcess(record.pid, record)) await terminateProcess(record.pid);
5986
5540
  const ownership = await acquireSessionTurn(record.acpxRecordId);
5987
5541
  try {
5988
5542
  const current = await resolveSessionRecord(record.acpxRecordId);
@@ -8304,6 +7858,6 @@ async function sendSession(options) {
8304
7858
  }
8305
7859
  const queueOwnerRuntimeTestInternals = { queueOwnerExitIsFatal };
8306
7860
  //#endregion
8307
- export { isRequestedModelUnsupportedError as $, applyInitialModelSelection as A, reconcileAgentSessionId as B, setSessionModeOnOwner as C, connectAndLoadSession as D, withConnectedSession as E, persistSessionOptions as F, recordPromptSubmission as G, cloneSessionConversation as H, sessionOptionsFromRecord as I, advertisedModelState as J, recordSessionUpdate as K, applyConversation as L, applyRequestedModelIfAdvertised as M, setDesiredModeId as N, applyConfigOptionSelection as O, normalizeSessionOptionShape as P, RequestedModelUnsupportedError as Q, applyLifecycleSnapshotToRecord as R, setSessionMode as S, setSessionModelOnOwner as T, createSessionConversation as U, cloneSessionAcpxState as V, recordClientOperation as W, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as X, AcpClient as Y, REQUESTED_MODEL_UNSUPPORTED_REASONS as Z, cancelSessionPrompt as _, runQueuedTask as a, isLegacyZedCodexAcpInvocation as at, setSessionConfigOption as b, LiveSessionCheckpoint as c, assertControlAuthority as ct, flushPerfMetricsCapture as d, exitCodeForOutputErrorCode as dt, getAcpxVersion as et, installPerfMetricsCapture as f, normalizeOutputError as ft, listAgentSessions as g, ensureSession as h, runOnce as i, listSessionEvents as it, applyModelSelection as j, applyConfigOptionsToRecord as k, runPromptTurn as l, withInterrupt as lt, createSessionWithClient as m, runSessionQueueOwner as n, DEFAULT_QUEUE_OWNER_TTL_MS as nt, sendSessionDirect as o, InterruptedError as ot, createSession as p, trimConversationForRuntime as q, sendSession as r, normalizeQueueOwnerTtlMs as rt, DISCARD_OUTPUT_FORMATTER as s, TimeoutError as st, queueOwnerRuntimeTestInternals as t, permissionModeSatisfies as tt, buildQueueOwnerArgOverride as u, withTimeout as ut, closeSession as v, setSessionModel as w, setSessionConfigOptionOnOwner as x, sessionControlTestInternals as y, createInitialSessionRecord as z };
7861
+ export { isRequestedModelUnsupportedError as $, applyInitialModelSelection as A, reconcileAgentSessionId as B, setSessionModeOnOwner as C, connectAndLoadSession as D, withConnectedSession as E, persistSessionOptions as F, recordPromptSubmission as G, cloneSessionConversation as H, sessionOptionsFromRecord as I, advertisedModelState as J, recordSessionUpdate as K, applyConversation as L, applyRequestedModelIfAdvertised as M, setDesiredModeId as N, applyConfigOptionSelection as O, normalizeSessionOptionShape as P, RequestedModelUnsupportedError as Q, applyLifecycleSnapshotToRecord as R, setSessionMode as S, setSessionModelOnOwner as T, createSessionConversation as U, cloneSessionAcpxState as V, recordClientOperation as W, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as X, AcpClient as Y, REQUESTED_MODEL_UNSUPPORTED_REASONS as Z, cancelSessionPrompt as _, runQueuedTask as a, isLegacyZedCodexAcpInvocation as at, setSessionConfigOption as b, LiveSessionCheckpoint as c, assertControlAuthority as ct, flushPerfMetricsCapture as d, getAcpxVersion as et, installPerfMetricsCapture as f, listAgentSessions as g, ensureSession as h, runOnce as i, listSessionEvents as it, applyModelSelection as j, applyConfigOptionsToRecord as k, runPromptTurn as l, withInterrupt as lt, createSessionWithClient as m, runSessionQueueOwner as n, DEFAULT_QUEUE_OWNER_TTL_MS as nt, sendSessionDirect as o, InterruptedError as ot, createSession as p, trimConversationForRuntime as q, sendSession as r, normalizeQueueOwnerTtlMs as rt, DISCARD_OUTPUT_FORMATTER as s, TimeoutError as st, queueOwnerRuntimeTestInternals as t, permissionModeSatisfies as tt, buildQueueOwnerArgOverride as u, withTimeout as ut, closeSession as v, setSessionModel as w, setSessionConfigOptionOnOwner as x, sessionControlTestInternals as y, createInitialSessionRecord as z };
8308
7862
 
8309
- //# sourceMappingURL=queue-owner-runtime-C4OOosbo.js.map
7863
+ //# sourceMappingURL=queue-owner-runtime-W0lly6ap.js.map