ycodium-acp-executor 0.2.5634 → 0.2.5854
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/_private/ycodium-jsonl-stream/appendedJsonl.d.ts +47 -0
- package/dist/_private/ycodium-jsonl-stream/appendedJsonl.js +172 -0
- package/dist/_private/ycodium-jsonl-stream/claudeSessions.d.ts +63 -0
- package/dist/_private/ycodium-jsonl-stream/claudeSessions.js +220 -0
- package/dist/_private/ycodium-jsonl-stream/codexSessions.d.ts +41 -0
- package/dist/_private/ycodium-jsonl-stream/codexSessions.js +197 -0
- package/dist/_private/ycodium-jsonl-stream/history.d.ts +6 -0
- package/dist/_private/ycodium-jsonl-stream/history.js +389 -0
- package/dist/_private/ycodium-jsonl-stream/historyErrors.d.ts +6 -0
- package/dist/_private/ycodium-jsonl-stream/historyErrors.js +6 -0
- package/dist/_private/ycodium-jsonl-stream/historyFile.d.ts +19 -0
- package/dist/_private/ycodium-jsonl-stream/historyFile.js +117 -0
- package/dist/_private/ycodium-jsonl-stream/historyRecord.d.ts +31 -0
- package/dist/_private/ycodium-jsonl-stream/historyRecord.js +144 -0
- package/dist/_private/ycodium-jsonl-stream/historyWaiting.d.ts +8 -0
- package/dist/_private/ycodium-jsonl-stream/historyWaiting.js +142 -0
- package/dist/_private/ycodium-jsonl-stream/jsonObjectLine.d.ts +5 -0
- package/dist/_private/ycodium-jsonl-stream/jsonObjectLine.js +18 -0
- package/dist/_private/ycodium-jsonl-stream/jsonlStream.d.ts +79 -0
- package/dist/_private/ycodium-jsonl-stream/jsonlStream.js +603 -0
- package/dist/_private/ycodium-jsonl-stream/scanCache.d.ts +69 -0
- package/dist/_private/ycodium-jsonl-stream/scanCache.js +106 -0
- package/dist/_private/ycodium-jsonl-stream/sessionDirectory.d.ts +5 -0
- package/dist/_private/ycodium-jsonl-stream/sessionDirectory.js +32 -0
- package/dist/_private/ycodium-jsonl-stream/usageFields.d.ts +5 -0
- package/dist/_private/ycodium-jsonl-stream/usageFields.js +11 -0
- package/dist/_private/ycodium-workspace-path/directoryScope.d.ts +5 -0
- package/dist/_private/ycodium-workspace-path/directoryScope.js +28 -0
- package/dist/_private/ycodium-workspace-path/workspacePath.d.ts +19 -0
- package/dist/_private/ycodium-workspace-path/workspacePath.js +90 -0
- package/dist/adapter-support.d.ts.map +1 -1
- package/dist/adapter-support.js.map +1 -1
- package/dist/apply-effort.d.ts.map +1 -1
- package/dist/apply-effort.js.map +1 -1
- package/dist/approvals.d.ts.map +1 -1
- package/dist/approvals.js.map +1 -1
- package/dist/artifacts.d.ts.map +1 -1
- package/dist/artifacts.js.map +1 -1
- package/dist/card-defaults.d.ts.map +1 -1
- package/dist/card-defaults.js.map +1 -1
- package/dist/config-option-wiring.d.ts.map +1 -1
- package/dist/config-option-wiring.js.map +1 -1
- package/dist/config-options.d.ts.map +1 -1
- package/dist/config-options.js.map +1 -1
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js.map +1 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js.map +1 -1
- package/dist/event-stream.d.ts.map +1 -1
- package/dist/event-stream.js.map +1 -1
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/executor/child-sessions.d.ts.map +1 -1
- package/dist/executor/child-sessions.js.map +1 -1
- package/dist/executor/lifecycle.d.ts.map +1 -1
- package/dist/executor/lifecycle.js +2 -1
- package/dist/executor/lifecycle.js.map +1 -1
- package/dist/executor/prompt-results.d.ts.map +1 -1
- package/dist/executor/prompt-results.js.map +1 -1
- package/dist/executor/prompt.d.ts.map +1 -1
- package/dist/executor/prompt.js.map +1 -1
- package/dist/executor/requests.d.ts.map +1 -1
- package/dist/executor/requests.js.map +1 -1
- package/dist/executor/runtime.d.ts.map +1 -1
- package/dist/executor/runtime.js.map +1 -1
- package/dist/executor/session.d.ts.map +1 -1
- package/dist/executor/session.js +17 -1
- package/dist/executor/session.js.map +1 -1
- package/dist/executor/settlement.d.ts.map +1 -1
- package/dist/executor/settlement.js.map +1 -1
- package/dist/executor/subagent-sessions.d.ts.map +1 -1
- package/dist/executor/subagent-sessions.js.map +1 -1
- package/dist/executor/support.d.ts +1 -1
- package/dist/executor/support.d.ts.map +1 -1
- package/dist/executor/support.js.map +1 -1
- package/dist/executor/updates.d.ts.map +1 -1
- package/dist/executor/updates.js +21 -6
- package/dist/executor/updates.js.map +1 -1
- package/dist/executor.d.ts.map +1 -1
- package/dist/executor.js.map +1 -1
- package/dist/failureCategory.d.ts.map +1 -1
- package/dist/failureCategory.js.map +1 -1
- package/dist/handshake.d.ts.map +1 -1
- package/dist/handshake.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/instance-kit.d.ts.map +1 -1
- package/dist/instance-kit.js.map +1 -1
- package/dist/jsonrpc.d.ts.map +1 -1
- package/dist/jsonrpc.js.map +1 -1
- package/dist/line-buffer.d.ts.map +1 -1
- package/dist/line-buffer.js.map +1 -1
- package/dist/mcp-servers.d.ts +26 -4
- package/dist/mcp-servers.d.ts.map +1 -1
- package/dist/mcp-servers.js +25 -4
- package/dist/mcp-servers.js.map +1 -1
- package/dist/model-selection.d.ts.map +1 -1
- package/dist/model-selection.js.map +1 -1
- package/dist/model-send.d.ts.map +1 -1
- package/dist/model-send.js.map +1 -1
- package/dist/mutex.d.ts.map +1 -1
- package/dist/mutex.js.map +1 -1
- package/dist/native-session-transcript.d.ts.map +1 -1
- package/dist/native-session-transcript.js.map +1 -1
- package/dist/native-sessions.d.ts.map +1 -1
- package/dist/native-sessions.js.map +1 -1
- package/dist/openCommands.d.ts.map +1 -1
- package/dist/openCommands.js.map +1 -1
- package/dist/permission-statement.d.ts.map +1 -1
- package/dist/permission-statement.js.map +1 -1
- package/dist/probe-process.d.ts.map +1 -1
- package/dist/probe-process.js.map +1 -1
- package/dist/probe-session.d.ts.map +1 -1
- package/dist/probe-session.js.map +1 -1
- package/dist/probe.d.ts.map +1 -1
- package/dist/probe.js.map +1 -1
- package/dist/prompt-dispatch.d.ts.map +1 -1
- package/dist/prompt-dispatch.js.map +1 -1
- package/dist/protocol-log.d.ts.map +1 -1
- package/dist/protocol-log.js.map +1 -1
- package/dist/protocol.d.ts.map +1 -1
- package/dist/protocol.js.map +1 -1
- package/dist/refreshDeadline.d.ts.map +1 -1
- package/dist/refreshDeadline.js.map +1 -1
- package/dist/runtime-mode.d.ts.map +1 -1
- package/dist/runtime-mode.js.map +1 -1
- package/dist/runtime-model.d.ts +2 -2
- package/dist/runtime-model.d.ts.map +1 -1
- package/dist/runtime-model.js +4 -4
- package/dist/runtime-model.js.map +1 -1
- package/dist/session-cleanup.d.ts.map +1 -1
- package/dist/session-cleanup.js.map +1 -1
- package/dist/session-registry.d.ts.map +1 -1
- package/dist/session-registry.js.map +1 -1
- package/dist/session-update.d.ts.map +1 -1
- package/dist/session-update.js.map +1 -1
- package/dist/sessionProcess.d.ts.map +1 -1
- package/dist/sessionProcess.js.map +1 -1
- package/dist/source/_private/ycodium-executor-common/catalogModel.ts +40 -0
- package/dist/source/_private/ycodium-executor-common/eventTypes.ts +97 -0
- package/dist/source/_private/ycodium-executor-common/modelSelection.ts +24 -0
- package/dist/source/_private/ycodium-executor-common/nodeStreams.ts +212 -0
- package/dist/source/_private/ycodium-executor-common/raceAbort.ts +25 -0
- package/dist/source/_private/ycodium-executor-common/reasoningLevelFallback.ts +28 -0
- package/dist/source/_private/ycodium-executor-common/stderrTail.ts +27 -0
- package/dist/source/_private/ycodium-executor-common/toolPresentation.ts +268 -0
- package/dist/source/_private/ycodium-jsonl-stream/appendedJsonl.ts +222 -0
- package/dist/source/_private/ycodium-jsonl-stream/claudeSessions.ts +263 -0
- package/dist/source/_private/ycodium-jsonl-stream/codexSessions.ts +254 -0
- package/dist/source/_private/ycodium-jsonl-stream/history.ts +492 -0
- package/dist/source/_private/ycodium-jsonl-stream/historyErrors.ts +6 -0
- package/dist/source/_private/ycodium-jsonl-stream/historyFile.ts +139 -0
- package/dist/source/_private/ycodium-jsonl-stream/historyRecord.ts +180 -0
- package/dist/source/_private/ycodium-jsonl-stream/historyWaiting.ts +140 -0
- package/dist/source/_private/ycodium-jsonl-stream/jsonObjectLine.ts +15 -0
- package/dist/source/_private/ycodium-jsonl-stream/jsonlStream.ts +650 -0
- package/dist/source/_private/ycodium-jsonl-stream/scanCache.ts +163 -0
- package/dist/source/_private/ycodium-jsonl-stream/sessionDirectory.ts +39 -0
- package/dist/source/_private/ycodium-jsonl-stream/sessionTranscript.ts +136 -0
- package/dist/source/_private/ycodium-jsonl-stream/usageFields.ts +13 -0
- package/dist/source/_private/ycodium-workspace-path/directoryScope.ts +34 -0
- package/dist/source/_private/ycodium-workspace-path/workspacePath.ts +110 -0
- package/dist/source/adapter-support.ts +115 -0
- package/dist/source/apply-effort.ts +66 -0
- package/dist/source/approvals.ts +94 -0
- package/dist/source/artifacts.ts +88 -0
- package/dist/source/card-defaults.ts +25 -0
- package/dist/source/config-option-wiring.ts +119 -0
- package/dist/source/config-options.ts +270 -0
- package/dist/source/connection.ts +553 -0
- package/dist/source/errors.ts +207 -0
- package/dist/source/event-stream.ts +91 -0
- package/dist/source/events.ts +341 -0
- package/dist/source/executor/child-sessions.ts +87 -0
- package/dist/source/executor/lifecycle.ts +283 -0
- package/dist/source/executor/prompt-results.ts +123 -0
- package/dist/source/executor/prompt.ts +606 -0
- package/dist/source/executor/requests.ts +323 -0
- package/dist/source/executor/runtime.ts +137 -0
- package/dist/source/executor/session.ts +553 -0
- package/dist/source/executor/settlement.ts +92 -0
- package/dist/source/executor/subagent-sessions.ts +183 -0
- package/dist/source/executor/support.ts +129 -0
- package/dist/source/executor/updates.ts +446 -0
- package/dist/source/executor.ts +537 -0
- package/dist/source/failureCategory.ts +74 -0
- package/dist/source/handshake.ts +66 -0
- package/dist/source/index.ts +210 -0
- package/dist/source/instance-kit.ts +478 -0
- package/dist/source/jsonrpc.ts +59 -0
- package/dist/source/line-buffer.ts +54 -0
- package/dist/source/mcp-servers.ts +83 -0
- package/dist/source/model-selection.ts +138 -0
- package/dist/source/model-send.ts +80 -0
- package/dist/source/mutex.ts +47 -0
- package/dist/source/native-session-transcript.ts +167 -0
- package/dist/source/native-sessions.ts +271 -0
- package/dist/source/openCommands.ts +39 -0
- package/dist/source/permission-statement.ts +49 -0
- package/dist/source/probe-process.ts +95 -0
- package/dist/source/probe-session.ts +81 -0
- package/dist/source/probe.ts +261 -0
- package/dist/source/prompt-dispatch.ts +42 -0
- package/dist/source/protocol-log.ts +143 -0
- package/dist/source/protocol.ts +36 -0
- package/dist/source/refreshDeadline.ts +2 -0
- package/dist/source/runtime-mode.ts +125 -0
- package/dist/source/runtime-model.ts +598 -0
- package/dist/source/session-cleanup.ts +82 -0
- package/dist/source/session-registry.ts +62 -0
- package/dist/source/session-update.ts +88 -0
- package/dist/source/sessionProcess.ts +29 -0
- package/dist/source/start-abort.ts +19 -0
- package/dist/source/thread-operations.ts +145 -0
- package/dist/source/tool-call-state.ts +322 -0
- package/dist/source/tool-presentation.ts +20 -0
- package/dist/source/tool-subagents.ts +491 -0
- package/dist/source/turn-usage.ts +88 -0
- package/dist/source/types.ts +146 -0
- package/dist/source/user-input-pending.ts +31 -0
- package/dist/source/util.ts +38 -0
- package/dist/source/vendor-hooks.ts +395 -0
- package/dist/start-abort.d.ts.map +1 -1
- package/dist/start-abort.js.map +1 -1
- package/dist/thread-operations.d.ts.map +1 -1
- package/dist/thread-operations.js.map +1 -1
- package/dist/tool-call-state.d.ts.map +1 -1
- package/dist/tool-call-state.js.map +1 -1
- package/dist/tool-presentation.d.ts.map +1 -1
- package/dist/tool-presentation.js.map +1 -1
- package/dist/tool-subagents.d.ts +1 -0
- package/dist/tool-subagents.d.ts.map +1 -1
- package/dist/tool-subagents.js +2 -0
- package/dist/tool-subagents.js.map +1 -1
- package/dist/turn-usage.d.ts.map +1 -1
- package/dist/turn-usage.js +12 -1
- package/dist/turn-usage.js.map +1 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/user-input-pending.d.ts.map +1 -1
- package/dist/user-input-pending.js.map +1 -1
- package/dist/util.d.ts.map +1 -1
- package/dist/util.js.map +1 -1
- package/dist/vendor-hooks.d.ts +11 -1
- package/dist/vendor-hooks.d.ts.map +1 -1
- package/dist/vendor-hooks.js.map +1 -1
- package/package.json +5 -2
|
@@ -0,0 +1,553 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ndJsonStream,
|
|
3
|
+
RequestError,
|
|
4
|
+
type AgentRequestMethod,
|
|
5
|
+
type AgentRequestParamsByMethod,
|
|
6
|
+
type AgentRequestResponsesByMethod,
|
|
7
|
+
type AnyMessage,
|
|
8
|
+
type JsonRpcId,
|
|
9
|
+
type SessionNotification,
|
|
10
|
+
} from "@agentclientprotocol/sdk";
|
|
11
|
+
import * as NodeStream from "node:stream";
|
|
12
|
+
|
|
13
|
+
import { AcpConnectionClosedError } from "./errors.ts";
|
|
14
|
+
import {
|
|
15
|
+
isNotificationMessage,
|
|
16
|
+
isRequestMessage,
|
|
17
|
+
isResponseMessage,
|
|
18
|
+
readJsonRpcError,
|
|
19
|
+
} from "./jsonrpc.ts";
|
|
20
|
+
import { LineBuffer } from "./line-buffer.ts";
|
|
21
|
+
import { decodeSessionUpdate } from "./session-update.ts";
|
|
22
|
+
|
|
23
|
+
export type AcpProtocolLogEvent = {
|
|
24
|
+
readonly direction: "incoming" | "outgoing";
|
|
25
|
+
readonly stage: "raw" | "decoded" | "decode_failed";
|
|
26
|
+
readonly payload: unknown;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export type AcpIncomingNotification =
|
|
30
|
+
| {
|
|
31
|
+
readonly method: "session/update";
|
|
32
|
+
readonly params: SessionNotification;
|
|
33
|
+
readonly delivery: "decoded" | "raw";
|
|
34
|
+
}
|
|
35
|
+
| {
|
|
36
|
+
readonly method: string;
|
|
37
|
+
readonly params: unknown;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
type AcpRequest = {
|
|
41
|
+
readonly method: string;
|
|
42
|
+
readonly promptId?: string;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export type AcpConnectionOptions = {
|
|
46
|
+
readonly readable: NodeStream.Readable;
|
|
47
|
+
readonly writable: NodeStream.Writable;
|
|
48
|
+
readonly onNotification?: (notification: AcpIncomingNotification) => void | Promise<void>;
|
|
49
|
+
readonly onRequest?: (method: string, params: unknown) => unknown | Promise<unknown>;
|
|
50
|
+
/**
|
|
51
|
+
* 对端的应答(成功或错误)落定的那一刻、按到达顺序同步调一次,先于任何排在它后面的帧。
|
|
52
|
+
* 靠请求方 await 之后再标记「应答已到」不行:紧跟其后的通知可能先于那段续体被派发。
|
|
53
|
+
*/
|
|
54
|
+
readonly onResponse?: (
|
|
55
|
+
request: AcpRequest,
|
|
56
|
+
outcome: { readonly result: unknown } | { readonly error: unknown },
|
|
57
|
+
) => void;
|
|
58
|
+
readonly logger?: (event: AcpProtocolLogEvent) => void;
|
|
59
|
+
/** 入站任务(分发请求、写应答)失败、连接随即收掉时调;连接已经在收尾时不调。 */
|
|
60
|
+
readonly onInboundFailure?: (error: unknown) => void;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
type PendingRequest = AcpRequest & {
|
|
64
|
+
readonly onArrival?: () => void;
|
|
65
|
+
readonly resolve: (value: unknown) => void;
|
|
66
|
+
readonly reject: (error: unknown) => void;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const textDecoder = new TextDecoder();
|
|
70
|
+
const textEncoder = new TextEncoder();
|
|
71
|
+
|
|
72
|
+
function asBytes(chunk: unknown): Uint8Array {
|
|
73
|
+
if (typeof chunk === "string") {
|
|
74
|
+
return textEncoder.encode(chunk);
|
|
75
|
+
}
|
|
76
|
+
if (chunk instanceof Uint8Array) {
|
|
77
|
+
return chunk;
|
|
78
|
+
}
|
|
79
|
+
throw new TypeError("ACP readable produced a non-byte chunk");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Same filter `ndJsonStream` uses before `controller.enqueue`.
|
|
84
|
+
* Empty / invalid / non-object lines are not enqueued; counting them would
|
|
85
|
+
* deadlock the inbound drain.
|
|
86
|
+
*/
|
|
87
|
+
function isEnqueueableLine(lineBytes: Uint8Array): boolean {
|
|
88
|
+
const trimmed = textDecoder.decode(lineBytes).trim();
|
|
89
|
+
if (!trimmed) {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const parsed: unknown = JSON.parse(trimmed);
|
|
94
|
+
return typeof parsed === "object" && parsed !== null;
|
|
95
|
+
} catch {
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
type AcpPendingRequest<T> = {
|
|
101
|
+
readonly written: Promise<void>;
|
|
102
|
+
readonly response: Promise<T>;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
export type AcpConnection = {
|
|
106
|
+
request<Method extends AgentRequestMethod>(
|
|
107
|
+
method: Method,
|
|
108
|
+
params: AgentRequestParamsByMethod[Method],
|
|
109
|
+
): Promise<AgentRequestResponsesByMethod[Method]>;
|
|
110
|
+
request<T = unknown>(method: string, params?: unknown): Promise<T>;
|
|
111
|
+
/**
|
|
112
|
+
* 同 `request`,但把两个时刻分开交出:`written` 在这条请求写进对端 stdin 后落定(写失败或
|
|
113
|
+
* 连接先关就 reject),`response` 等对端应答。连接已关时同步抛错。
|
|
114
|
+
*/
|
|
115
|
+
/** `onArrival` 在应答帧到达的那一刻同步调一次,先于排在它后面的帧(与 `onResponse` 同一时刻)。 */
|
|
116
|
+
begin<T = unknown>(
|
|
117
|
+
method: string,
|
|
118
|
+
params?: unknown,
|
|
119
|
+
promptId?: string,
|
|
120
|
+
onArrival?: () => void,
|
|
121
|
+
): AcpPendingRequest<T>;
|
|
122
|
+
notify(method: string, params?: unknown): Promise<void>;
|
|
123
|
+
awaitInboundIdle(): Promise<void>;
|
|
124
|
+
/**
|
|
125
|
+
* 丢掉还在等的请求,不关连接。刷新期限到了用它:晚到的应答没有等待方,直接忽略。
|
|
126
|
+
*/
|
|
127
|
+
abandonPending(error: unknown): void;
|
|
128
|
+
close(error?: unknown): Promise<void>;
|
|
129
|
+
readonly closed: Promise<void>;
|
|
130
|
+
/** 连接因什么关的;还开着时是 undefined。 */
|
|
131
|
+
closeError(): unknown;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export function createAcpConnection(options: AcpConnectionOptions): AcpConnection {
|
|
135
|
+
const byteBridge = new TransformStream<Uint8Array, Uint8Array>();
|
|
136
|
+
const byteWriter = byteBridge.writable.getWriter();
|
|
137
|
+
const stream = ndJsonStream(
|
|
138
|
+
NodeStream.Writable.toWeb(options.writable) as WritableStream<Uint8Array>,
|
|
139
|
+
byteBridge.readable,
|
|
140
|
+
);
|
|
141
|
+
const incoming = stream.readable.getReader();
|
|
142
|
+
const outgoing = stream.writable.getWriter();
|
|
143
|
+
const lineBuffer = new LineBuffer();
|
|
144
|
+
const pending = new Map<string, PendingRequest>();
|
|
145
|
+
const idleWaiters: Array<() => void> = [];
|
|
146
|
+
|
|
147
|
+
let nextRequestId = 1;
|
|
148
|
+
let inboundBatches = 0;
|
|
149
|
+
let closing: Promise<void> | undefined;
|
|
150
|
+
let closedError: unknown | undefined;
|
|
151
|
+
let inboundTail = Promise.resolve();
|
|
152
|
+
|
|
153
|
+
const { resolve: resolveClosed, promise: closed } = Promise.withResolvers<void>();
|
|
154
|
+
|
|
155
|
+
const rejectPending = (error: unknown) => {
|
|
156
|
+
const entries = [...pending.values()];
|
|
157
|
+
pending.clear();
|
|
158
|
+
for (const entry of entries) {
|
|
159
|
+
entry.reject(error);
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const releaseIdleWaiters = () => {
|
|
164
|
+
if (idleWaiters.length === 0) {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const waiters = idleWaiters.splice(0);
|
|
168
|
+
for (const waiter of waiters) {
|
|
169
|
+
waiter();
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const beginInboundBatch = () => {
|
|
174
|
+
inboundBatches += 1;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const endInboundBatch = () => {
|
|
178
|
+
inboundBatches = Math.max(0, inboundBatches - 1);
|
|
179
|
+
if (inboundBatches === 0) {
|
|
180
|
+
releaseIdleWaiters();
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const log = (event: AcpProtocolLogEvent) => {
|
|
185
|
+
options.logger?.(event);
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const writeMessage = async (message: AnyMessage) => {
|
|
189
|
+
log({ direction: "outgoing", stage: "decoded", payload: message });
|
|
190
|
+
await outgoing.write(message);
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const failIfClosed = () => {
|
|
194
|
+
if (closedError !== undefined) {
|
|
195
|
+
throw closedError;
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const shutdown = (error: unknown) => {
|
|
200
|
+
if (closing) {
|
|
201
|
+
return closing;
|
|
202
|
+
}
|
|
203
|
+
closedError = error;
|
|
204
|
+
closing = (async () => {
|
|
205
|
+
rejectPending(error);
|
|
206
|
+
releaseIdleWaiters();
|
|
207
|
+
options.readable.off("data", onData);
|
|
208
|
+
options.readable.off("end", onEnd);
|
|
209
|
+
options.readable.off("error", onError);
|
|
210
|
+
options.writable.off("error", onWritableError);
|
|
211
|
+
try {
|
|
212
|
+
await byteWriter.close();
|
|
213
|
+
} catch {
|
|
214
|
+
// Already closed with the peer.
|
|
215
|
+
}
|
|
216
|
+
try {
|
|
217
|
+
await incoming.cancel();
|
|
218
|
+
} catch {
|
|
219
|
+
// Reader may already be closed by ndJsonStream.
|
|
220
|
+
}
|
|
221
|
+
try {
|
|
222
|
+
await outgoing.close();
|
|
223
|
+
} catch {
|
|
224
|
+
// The peer may already have ended stdin.
|
|
225
|
+
}
|
|
226
|
+
resolveClosed();
|
|
227
|
+
})();
|
|
228
|
+
return closing;
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
const dispatchNotification = async (method: string, params: unknown) => {
|
|
232
|
+
if (method === "session/update") {
|
|
233
|
+
const decoded = decodeSessionUpdate(params);
|
|
234
|
+
if (decoded.status === "dropped") {
|
|
235
|
+
log({
|
|
236
|
+
direction: "incoming",
|
|
237
|
+
stage: "decode_failed",
|
|
238
|
+
payload: {
|
|
239
|
+
operation: "decode-notification-payload",
|
|
240
|
+
method,
|
|
241
|
+
outcome: "dropped",
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
if (decoded.status === "raw") {
|
|
247
|
+
log({
|
|
248
|
+
direction: "incoming",
|
|
249
|
+
stage: "decode_failed",
|
|
250
|
+
payload: {
|
|
251
|
+
operation: "decode-notification-payload",
|
|
252
|
+
method,
|
|
253
|
+
outcome: "delivered",
|
|
254
|
+
},
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
const notification: AcpIncomingNotification = {
|
|
258
|
+
method: "session/update",
|
|
259
|
+
params: decoded.params,
|
|
260
|
+
delivery: decoded.status === "decoded" ? "decoded" : "raw",
|
|
261
|
+
};
|
|
262
|
+
try {
|
|
263
|
+
await options.onNotification?.(notification);
|
|
264
|
+
} catch {
|
|
265
|
+
// A bad handler must not tear the connection down.
|
|
266
|
+
}
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
try {
|
|
271
|
+
await options.onNotification?.({ method, params });
|
|
272
|
+
} catch {
|
|
273
|
+
// Same as session/update: keep the connection.
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
const dispatchRequest = async (id: JsonRpcId, method: string, params: unknown) => {
|
|
278
|
+
try {
|
|
279
|
+
if (!options.onRequest) {
|
|
280
|
+
throw RequestError.methodNotFound(method);
|
|
281
|
+
}
|
|
282
|
+
const result = await options.onRequest(method, params);
|
|
283
|
+
await writeMessage({ jsonrpc: "2.0", id, result: result ?? null });
|
|
284
|
+
} catch (error) {
|
|
285
|
+
const rpcError =
|
|
286
|
+
error instanceof RequestError
|
|
287
|
+
? error
|
|
288
|
+
: RequestError.internalError(error instanceof Error ? error.message : String(error));
|
|
289
|
+
await writeMessage({ jsonrpc: "2.0", id, error: rpcError.toErrorResponse() });
|
|
290
|
+
}
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
const dispatchResponse = (id: JsonRpcId, message: Record<string, unknown>) => {
|
|
294
|
+
const key = String(id);
|
|
295
|
+
const waiter = pending.get(key);
|
|
296
|
+
if (!waiter) {
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
pending.delete(key);
|
|
300
|
+
try {
|
|
301
|
+
options.onResponse?.(
|
|
302
|
+
waiter,
|
|
303
|
+
Object.hasOwn(message, "error")
|
|
304
|
+
? { error: message["error"] }
|
|
305
|
+
: { result: message["result"] },
|
|
306
|
+
);
|
|
307
|
+
} catch {
|
|
308
|
+
// 观察钩子出错不许挡住应答。
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
waiter.onArrival?.();
|
|
312
|
+
} catch {
|
|
313
|
+
// 同上。
|
|
314
|
+
}
|
|
315
|
+
if (Object.hasOwn(message, "error")) {
|
|
316
|
+
const rpcError = readJsonRpcError(message["error"]);
|
|
317
|
+
waiter.reject(
|
|
318
|
+
rpcError
|
|
319
|
+
? rpcError.data === undefined
|
|
320
|
+
? new RequestError(rpcError.code, rpcError.message)
|
|
321
|
+
: new RequestError(rpcError.code, rpcError.message, rpcError.data)
|
|
322
|
+
: RequestError.internalError("Malformed JSON-RPC error response"),
|
|
323
|
+
);
|
|
324
|
+
return;
|
|
325
|
+
}
|
|
326
|
+
waiter.resolve(message["result"]);
|
|
327
|
+
};
|
|
328
|
+
|
|
329
|
+
const dispatchMessage = async (message: unknown) => {
|
|
330
|
+
log({ direction: "incoming", stage: "decoded", payload: message });
|
|
331
|
+
if (isResponseMessage(message)) {
|
|
332
|
+
dispatchResponse(message.id, message);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
if (isNotificationMessage(message)) {
|
|
336
|
+
await dispatchNotification(message.method, message.params);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (isRequestMessage(message)) {
|
|
340
|
+
await dispatchRequest(message.id, message.method, message.params);
|
|
341
|
+
}
|
|
342
|
+
};
|
|
343
|
+
|
|
344
|
+
const dispatchWire = async (value: AnyMessage | readonly unknown[]) => {
|
|
345
|
+
if (Array.isArray(value)) {
|
|
346
|
+
for (const item of value) {
|
|
347
|
+
await dispatchMessage(item);
|
|
348
|
+
}
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
await dispatchMessage(value);
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
const pullEnqueued = async (count: number) => {
|
|
355
|
+
for (let i = 0; i < count; i += 1) {
|
|
356
|
+
const { value, done } = await incoming.read();
|
|
357
|
+
if (done || value === undefined) {
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
await dispatchWire(value);
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
const handleChunk = async (bytes: Uint8Array) => {
|
|
365
|
+
const lines = lineBuffer.push(bytes);
|
|
366
|
+
for (const line of lines) {
|
|
367
|
+
const trimmed = textDecoder.decode(line).trim();
|
|
368
|
+
if (trimmed) {
|
|
369
|
+
log({ direction: "incoming", stage: "raw", payload: trimmed });
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const expected = lines.filter(isEnqueueableLine).length;
|
|
373
|
+
await byteWriter.write(bytes);
|
|
374
|
+
if (expected === 0) {
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
beginInboundBatch();
|
|
378
|
+
try {
|
|
379
|
+
await pullEnqueued(expected);
|
|
380
|
+
} finally {
|
|
381
|
+
endInboundBatch();
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
// 入站任务的失败在这里接住:多半是应答连同错误应答都写不出去,出站已经坏了,连接不能再用。
|
|
386
|
+
// 不接的话这条链上的拒绝没人接,后面不一定还有入站任务排上来。连接已经在收尾时,应答写
|
|
387
|
+
// 不出去是收尾的结果,不是新故障,不报。
|
|
388
|
+
const failInbound = (error: unknown): void => {
|
|
389
|
+
if (closedError !== undefined) return;
|
|
390
|
+
options.onInboundFailure?.(error);
|
|
391
|
+
void shutdown(
|
|
392
|
+
new AcpConnectionClosedError(
|
|
393
|
+
`ACP inbound handling failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
394
|
+
{ reason: "inbound-failed" },
|
|
395
|
+
),
|
|
396
|
+
);
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const enqueueInbound = (work: () => Promise<void>) => {
|
|
400
|
+
inboundTail = inboundTail.then(work).catch(failInbound);
|
|
401
|
+
};
|
|
402
|
+
|
|
403
|
+
const onData = (chunk: unknown) => {
|
|
404
|
+
if (closedError !== undefined) {
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
enqueueInbound(() => handleChunk(asBytes(chunk)));
|
|
408
|
+
};
|
|
409
|
+
|
|
410
|
+
const onEnd = () => {
|
|
411
|
+
enqueueInbound(async () => {
|
|
412
|
+
const last = lineBuffer.flush();
|
|
413
|
+
if (last) {
|
|
414
|
+
const trimmed = textDecoder.decode(last).trim();
|
|
415
|
+
if (trimmed) {
|
|
416
|
+
log({ direction: "incoming", stage: "raw", payload: trimmed });
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
const expected = last && isEnqueueableLine(last) ? 1 : 0;
|
|
420
|
+
try {
|
|
421
|
+
await byteWriter.close();
|
|
422
|
+
} catch {
|
|
423
|
+
// Already closed.
|
|
424
|
+
}
|
|
425
|
+
beginInboundBatch();
|
|
426
|
+
try {
|
|
427
|
+
if (expected > 0) {
|
|
428
|
+
await pullEnqueued(expected);
|
|
429
|
+
}
|
|
430
|
+
while (true) {
|
|
431
|
+
const { value, done } = await incoming.read();
|
|
432
|
+
if (done) {
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
if (value !== undefined) {
|
|
436
|
+
await dispatchWire(value);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
} catch {
|
|
440
|
+
// Reader cancelled by close().
|
|
441
|
+
} finally {
|
|
442
|
+
endInboundBatch();
|
|
443
|
+
}
|
|
444
|
+
await shutdown(
|
|
445
|
+
new AcpConnectionClosedError("ACP input stream ended", { reason: "input-ended" }),
|
|
446
|
+
);
|
|
447
|
+
});
|
|
448
|
+
};
|
|
449
|
+
|
|
450
|
+
const onError = (error: unknown) => {
|
|
451
|
+
enqueueInbound(async () => {
|
|
452
|
+
await shutdown(
|
|
453
|
+
error instanceof Error
|
|
454
|
+
? error
|
|
455
|
+
: new AcpConnectionClosedError("ACP input stream error", { reason: "stream-error" }),
|
|
456
|
+
);
|
|
457
|
+
});
|
|
458
|
+
};
|
|
459
|
+
|
|
460
|
+
// 出站写坏了以 Node 流自己的 'error' 为准收掉连接:Node 24.20 的 Writable.toWeb 在 write()
|
|
461
|
+
// 同步出错、又不是背压时,让这次 write 直接 resolve,错误只落到流上(24.13 还会让它 reject)。
|
|
462
|
+
// 不在这里收,请求就当帧已经写出去,一直等一个不会来的应答。
|
|
463
|
+
const onWritableError = (error: unknown) => {
|
|
464
|
+
void shutdown(
|
|
465
|
+
error instanceof Error
|
|
466
|
+
? error
|
|
467
|
+
: new AcpConnectionClosedError("ACP output stream error", { reason: "stream-error" }),
|
|
468
|
+
);
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
options.readable.on("data", onData);
|
|
472
|
+
options.readable.on("end", onEnd);
|
|
473
|
+
options.readable.on("error", onError);
|
|
474
|
+
options.writable.once("error", onWritableError);
|
|
475
|
+
|
|
476
|
+
const begin = <T>(
|
|
477
|
+
method: string,
|
|
478
|
+
params?: unknown,
|
|
479
|
+
promptId?: string,
|
|
480
|
+
onArrival?: () => void,
|
|
481
|
+
): AcpPendingRequest<T> => {
|
|
482
|
+
failIfClosed();
|
|
483
|
+
const id = nextRequestId;
|
|
484
|
+
nextRequestId += 1;
|
|
485
|
+
const { promise, resolve, reject } = Promise.withResolvers<unknown>();
|
|
486
|
+
// 提前收口后 RPC 可能永不应答;只能留标量关联号,不能留住正文、结果记录或其 finish 闭包。
|
|
487
|
+
pending.set(String(id), {
|
|
488
|
+
method,
|
|
489
|
+
...(promptId === undefined ? {} : { promptId }),
|
|
490
|
+
...(onArrival === undefined ? {} : { onArrival }),
|
|
491
|
+
resolve,
|
|
492
|
+
reject,
|
|
493
|
+
});
|
|
494
|
+
const message: AnyMessage =
|
|
495
|
+
params === undefined
|
|
496
|
+
? { jsonrpc: "2.0", id, method }
|
|
497
|
+
: { jsonrpc: "2.0", id, method, params };
|
|
498
|
+
// 写还挂着时 shutdown 会先拒掉 promise:与写一起等,先落定的算数。只等写的话,
|
|
499
|
+
// 这次拒绝和写失败时下面那次 reject 都没人接,写又可能永远不落定。
|
|
500
|
+
const written = Promise.race([writeMessage(message), promise]).then(
|
|
501
|
+
() => undefined,
|
|
502
|
+
(error: unknown) => {
|
|
503
|
+
if (pending.delete(String(id))) {
|
|
504
|
+
reject(error);
|
|
505
|
+
}
|
|
506
|
+
throw error;
|
|
507
|
+
},
|
|
508
|
+
);
|
|
509
|
+
return { written, response: promise as Promise<T> };
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
const request = (async (method: string, params?: unknown) => {
|
|
513
|
+
const { written, response } = begin(method, params);
|
|
514
|
+
await written;
|
|
515
|
+
return response;
|
|
516
|
+
}) as AcpConnection["request"];
|
|
517
|
+
|
|
518
|
+
const notify = async (method: string, params?: unknown) => {
|
|
519
|
+
failIfClosed();
|
|
520
|
+
const message: AnyMessage =
|
|
521
|
+
params === undefined ? { jsonrpc: "2.0", method } : { jsonrpc: "2.0", method, params };
|
|
522
|
+
await writeMessage(message);
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
const awaitInboundIdle = async () => {
|
|
526
|
+
if (inboundBatches === 0) {
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
await new Promise<void>((resolve) => {
|
|
530
|
+
idleWaiters.push(resolve);
|
|
531
|
+
if (inboundBatches === 0) {
|
|
532
|
+
releaseIdleWaiters();
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
const close = (error?: unknown) => shutdown(error ?? new AcpConnectionClosedError());
|
|
538
|
+
|
|
539
|
+
const abandonPending = (error: unknown) => {
|
|
540
|
+
rejectPending(error);
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
return {
|
|
544
|
+
request,
|
|
545
|
+
begin,
|
|
546
|
+
notify,
|
|
547
|
+
awaitInboundIdle,
|
|
548
|
+
abandonPending,
|
|
549
|
+
close,
|
|
550
|
+
closed,
|
|
551
|
+
closeError: () => closedError,
|
|
552
|
+
};
|
|
553
|
+
}
|