@dev-anywhere/proxy 0.9.20 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -4
- package/dist/{autostart-VGHJZS6V.js → autostart-MLJRJC2J.js} +5 -5
- package/dist/{chunk-CFPY2A6Q.js → chunk-44IM5SVF.js} +2 -2
- package/dist/{chunk-PLWNR3X4.js → chunk-4QJ24E5S.js} +5 -5
- package/dist/{chunk-FNZ5X2VZ.js → chunk-5OJFDJ65.js} +108 -9
- package/dist/chunk-5OJFDJ65.js.map +1 -0
- package/dist/{chunk-SKKPJULC.js → chunk-7BNZO6DB.js} +4 -2
- package/dist/chunk-7BNZO6DB.js.map +1 -0
- package/dist/{chunk-ZKMCE4JY.js → chunk-E6NHFBCU.js} +110 -11
- package/dist/chunk-E6NHFBCU.js.map +1 -0
- package/dist/{chunk-Z2KUJ6SW.js → chunk-EMWUDUL4.js} +2 -2
- package/dist/{chunk-HPNB53V4.js → chunk-GK3WHOWF.js} +2 -2
- package/dist/{chunk-4IX5R5X3.js → chunk-GTG6VONI.js} +12 -8
- package/dist/chunk-GTG6VONI.js.map +1 -0
- package/dist/{chunk-CZPY2BFR.js → chunk-GUNXL4C5.js} +10 -6
- package/dist/chunk-GUNXL4C5.js.map +1 -0
- package/dist/chunk-LNSWARRW.js +30 -0
- package/dist/chunk-LNSWARRW.js.map +1 -0
- package/dist/{chunk-4EIUH7CQ.js → chunk-RQKKZC5T.js} +23 -9
- package/dist/chunk-RQKKZC5T.js.map +1 -0
- package/dist/{chunk-WTCJIDDT.js → chunk-RW32NTSD.js} +3 -2
- package/dist/chunk-RW32NTSD.js.map +1 -0
- package/dist/{chunk-4KUJOGCV.js → chunk-SGVG4V66.js} +27 -6
- package/dist/chunk-SGVG4V66.js.map +1 -0
- package/dist/{chunk-5RESCDN4.js → chunk-V3JJ352Q.js} +1 -1
- package/dist/chunk-V3JJ352Q.js.map +1 -0
- package/dist/{chunk-KM62ELKK.js → chunk-Z6HCYOPJ.js} +25 -1
- package/dist/chunk-Z6HCYOPJ.js.map +1 -0
- package/dist/index.js +10 -9
- package/dist/index.js.map +1 -1
- package/dist/{logger-6MR4NSOC.js → logger-U5XYVVXY.js} +3 -3
- package/dist/preview-worker.js +5 -5
- package/dist/{relay-token-KHOXKEF2.js → relay-token-LFUK2JW6.js} +4 -4
- package/dist/serve.js +1024 -124
- package/dist/serve.js.map +1 -1
- package/dist/{service-host-FAPIR5IX.js → service-host-XIAWRF4P.js} +3 -3
- package/dist/session-worker.js +1019 -81
- package/dist/session-worker.js.map +1 -1
- package/dist/{terminal-HA5PIFVP.js → terminal-LJSUWZ7X.js} +14 -12
- package/dist/terminal-LJSUWZ7X.js.map +1 -0
- package/dist/terminal-worker.js +10 -10
- package/dist/update-runner.js +22 -2
- package/dist/update-runner.js.map +1 -1
- package/package.json +4 -4
- package/dist/chunk-4EIUH7CQ.js.map +0 -1
- package/dist/chunk-4IX5R5X3.js.map +0 -1
- package/dist/chunk-4KUJOGCV.js.map +0 -1
- package/dist/chunk-5RESCDN4.js.map +0 -1
- package/dist/chunk-CZPY2BFR.js.map +0 -1
- package/dist/chunk-FNZ5X2VZ.js.map +0 -1
- package/dist/chunk-KM62ELKK.js.map +0 -1
- package/dist/chunk-SKKPJULC.js.map +0 -1
- package/dist/chunk-WTCJIDDT.js.map +0 -1
- package/dist/chunk-ZKMCE4JY.js.map +0 -1
- package/dist/terminal-HA5PIFVP.js.map +0 -1
- /package/dist/{autostart-VGHJZS6V.js.map → autostart-MLJRJC2J.js.map} +0 -0
- /package/dist/{chunk-CFPY2A6Q.js.map → chunk-44IM5SVF.js.map} +0 -0
- /package/dist/{chunk-PLWNR3X4.js.map → chunk-4QJ24E5S.js.map} +0 -0
- /package/dist/{chunk-Z2KUJ6SW.js.map → chunk-EMWUDUL4.js.map} +0 -0
- /package/dist/{chunk-HPNB53V4.js.map → chunk-GK3WHOWF.js.map} +0 -0
- /package/dist/{logger-6MR4NSOC.js.map → logger-U5XYVVXY.js.map} +0 -0
- /package/dist/{relay-token-KHOXKEF2.js.map → relay-token-LFUK2JW6.js.map} +0 -0
- /package/dist/{service-host-FAPIR5IX.js.map → service-host-XIAWRF4P.js.map} +0 -0
package/dist/session-worker.js
CHANGED
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
ControlRequestEventSchema,
|
|
4
4
|
SeqCounter,
|
|
5
5
|
createApprovalRequestIdFactory
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-44IM5SVF.js";
|
|
7
7
|
import {
|
|
8
8
|
acceptCurrentWorkerSocketMessage,
|
|
9
9
|
readWorkerConnection,
|
|
@@ -14,20 +14,23 @@ import "./chunk-NQDJ6QAM.js";
|
|
|
14
14
|
import {
|
|
15
15
|
CLAUDE_PROVIDER,
|
|
16
16
|
CODEX_PROVIDER,
|
|
17
|
+
CURSOR_PROVIDER,
|
|
17
18
|
KIMI_PROVIDER,
|
|
19
|
+
cursorAcpAutoApprovesPermissions,
|
|
18
20
|
resolveCodexPermissionPolicy,
|
|
21
|
+
resolveCursorAcpMode,
|
|
19
22
|
resolveKimiAcpMode
|
|
20
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-5OJFDJ65.js";
|
|
21
24
|
import {
|
|
22
25
|
WORKER_IPC_PROTOCOL_VERSION,
|
|
23
26
|
createWorkerReader,
|
|
24
27
|
serializeWorkerMsg
|
|
25
|
-
} from "./chunk-
|
|
26
|
-
import "./chunk-
|
|
28
|
+
} from "./chunk-GUNXL4C5.js";
|
|
29
|
+
import "./chunk-V3JJ352Q.js";
|
|
27
30
|
import {
|
|
28
31
|
ControlErrorCode,
|
|
29
32
|
LineBuffer
|
|
30
|
-
} from "./chunk-
|
|
33
|
+
} from "./chunk-E6NHFBCU.js";
|
|
31
34
|
import {
|
|
32
35
|
prepareLocalIpcEndpoint,
|
|
33
36
|
removeLocalIpcEndpoint,
|
|
@@ -47,7 +50,7 @@ import {
|
|
|
47
50
|
spawnCommand
|
|
48
51
|
} from "./chunk-EWIHC4BK.js";
|
|
49
52
|
import "./chunk-HJOYOYGB.js";
|
|
50
|
-
import "./chunk-
|
|
53
|
+
import "./chunk-7BNZO6DB.js";
|
|
51
54
|
|
|
52
55
|
// src/session-worker.ts
|
|
53
56
|
import { createServer } from "net";
|
|
@@ -700,39 +703,872 @@ function toError(err) {
|
|
|
700
703
|
return err instanceof Error ? err : new Error(String(err));
|
|
701
704
|
}
|
|
702
705
|
|
|
706
|
+
// src/worker/cursor-acp-session.ts
|
|
707
|
+
var CLIENT_INFO2 = {
|
|
708
|
+
name: "dev-anywhere",
|
|
709
|
+
title: "Dev Anywhere",
|
|
710
|
+
version: PROXY_VERSION
|
|
711
|
+
};
|
|
712
|
+
var DEFAULT_REQUEST_TIMEOUT_MS2 = 1e4;
|
|
713
|
+
var DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS = 2e3;
|
|
714
|
+
var STDERR_TAIL_LIMIT3 = 8192;
|
|
715
|
+
var CANCELLED_RESPONSE_TOMBSTONE_LIMIT = 128;
|
|
716
|
+
var CURSOR_ACP_AUTH_REQUIRED_MESSAGE = "Cursor CLI \u672A\u767B\u5F55\u3002\u8BF7\u5728\u672C\u673A\u8FD0\u884C Cursor CLI \u7684 `agent login`\uFF0C\u6216\u8BBE\u7F6E CURSOR_API_KEY / CURSOR_AUTH_TOKEN\u3002";
|
|
717
|
+
var denyPermission = () => ({
|
|
718
|
+
behavior: "deny",
|
|
719
|
+
message: "Tool use denied by default policy. Remote approval is not configured."
|
|
720
|
+
});
|
|
721
|
+
var cancelExtension = () => ({
|
|
722
|
+
cancelled: true,
|
|
723
|
+
answer: { type: "ask_question", outcome: "cancelled" }
|
|
724
|
+
});
|
|
725
|
+
function isRecord2(value) {
|
|
726
|
+
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
727
|
+
}
|
|
728
|
+
function toError2(error) {
|
|
729
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
730
|
+
}
|
|
731
|
+
function normalizeApprovalInput2(value) {
|
|
732
|
+
if (!isRecord2(value)) return {};
|
|
733
|
+
const input = { ...value };
|
|
734
|
+
if (Array.isArray(input.command)) {
|
|
735
|
+
input.command = input.command.map((part) => String(part)).join(" ");
|
|
736
|
+
}
|
|
737
|
+
return input;
|
|
738
|
+
}
|
|
739
|
+
function normalizePermissionKind(kind) {
|
|
740
|
+
return kind.replace(/-/g, "_");
|
|
741
|
+
}
|
|
742
|
+
function parsePermissionOptions(value) {
|
|
743
|
+
if (!Array.isArray(value)) return [];
|
|
744
|
+
const options = [];
|
|
745
|
+
for (const candidate of value) {
|
|
746
|
+
if (!isRecord2(candidate) || typeof candidate.optionId !== "string") continue;
|
|
747
|
+
const rawKind = typeof candidate.kind === "string" ? candidate.kind : "";
|
|
748
|
+
options.push({
|
|
749
|
+
...candidate,
|
|
750
|
+
optionId: candidate.optionId,
|
|
751
|
+
name: typeof candidate.name === "string" ? candidate.name : candidate.optionId,
|
|
752
|
+
kind: normalizePermissionKind(rawKind) || rawKind
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
return options;
|
|
756
|
+
}
|
|
757
|
+
function normalizedOptionText(option) {
|
|
758
|
+
return `${option.optionId} ${option.name}`.toLowerCase().replace(/[^a-z0-9]+/g, " ");
|
|
759
|
+
}
|
|
760
|
+
function isAllowOption(option) {
|
|
761
|
+
const text = normalizedOptionText(option);
|
|
762
|
+
const kind = normalizePermissionKind(option.kind);
|
|
763
|
+
return kind.startsWith("allow") || /\b(allow|approve|accept)\b/.test(text);
|
|
764
|
+
}
|
|
765
|
+
function isAlwaysOption(option) {
|
|
766
|
+
const text = normalizedOptionText(option);
|
|
767
|
+
const kind = normalizePermissionKind(option.kind);
|
|
768
|
+
return kind === "allow_always" || /\b(always|session|persist)\b/.test(text);
|
|
769
|
+
}
|
|
770
|
+
function isDenyOption(option) {
|
|
771
|
+
const text = normalizedOptionText(option);
|
|
772
|
+
const kind = normalizePermissionKind(option.kind);
|
|
773
|
+
return kind.startsWith("reject") || /\b(reject|deny|decline|cancel|skip)\b/.test(text);
|
|
774
|
+
}
|
|
775
|
+
function optionMatchesBehavior(option, behavior) {
|
|
776
|
+
if (behavior === "deny") return isDenyOption(option);
|
|
777
|
+
if (behavior === "allow_always") {
|
|
778
|
+
return isAllowOption(option) && isAlwaysOption(option);
|
|
779
|
+
}
|
|
780
|
+
return isAllowOption(option) && !isAlwaysOption(option);
|
|
781
|
+
}
|
|
782
|
+
function selectPermissionOption(options, behavior) {
|
|
783
|
+
if (behavior === "deny") {
|
|
784
|
+
return options.find((option) => normalizePermissionKind(option.kind).startsWith("reject")) ?? options.find(isDenyOption);
|
|
785
|
+
}
|
|
786
|
+
if (behavior === "allow_always") {
|
|
787
|
+
return options.find((option) => normalizePermissionKind(option.kind) === "allow_always") ?? options.find((option) => isAllowOption(option) && isAlwaysOption(option)) ?? options.find((option) => normalizePermissionKind(option.kind) === "allow_once") ?? options.find((option) => isAllowOption(option) && !isAlwaysOption(option));
|
|
788
|
+
}
|
|
789
|
+
return options.find((option) => normalizePermissionKind(option.kind) === "allow_once") ?? options.find((option) => isAllowOption(option) && !isAlwaysOption(option));
|
|
790
|
+
}
|
|
791
|
+
function promptResult(value) {
|
|
792
|
+
return isRecord2(value) ? value : {};
|
|
793
|
+
}
|
|
794
|
+
function responseErrorMessage(error) {
|
|
795
|
+
return typeof error.message === "string" ? error.message : "Cursor ACP request failed";
|
|
796
|
+
}
|
|
797
|
+
function advertisedAuthMethods(result) {
|
|
798
|
+
if (!isRecord2(result) || !Array.isArray(result.authMethods)) return [];
|
|
799
|
+
return result.authMethods.flatMap((candidate) => {
|
|
800
|
+
if (typeof candidate === "string") return [candidate];
|
|
801
|
+
if (isRecord2(candidate) && typeof candidate.id === "string") return [candidate.id];
|
|
802
|
+
return [];
|
|
803
|
+
});
|
|
804
|
+
}
|
|
805
|
+
function parseAskQuestionPrompt(params) {
|
|
806
|
+
if (!Array.isArray(params.questions)) return null;
|
|
807
|
+
const questions = params.questions.flatMap((candidate) => {
|
|
808
|
+
if (!isRecord2(candidate) || typeof candidate.id !== "string" || typeof candidate.prompt !== "string") {
|
|
809
|
+
return [];
|
|
810
|
+
}
|
|
811
|
+
if (!Array.isArray(candidate.options)) return [];
|
|
812
|
+
const options = candidate.options.flatMap((option) => {
|
|
813
|
+
if (!isRecord2(option) || typeof option.id !== "string" || typeof option.label !== "string") {
|
|
814
|
+
return [];
|
|
815
|
+
}
|
|
816
|
+
return [{ id: option.id, label: option.label }];
|
|
817
|
+
});
|
|
818
|
+
if (options.length === 0) return [];
|
|
819
|
+
return [
|
|
820
|
+
{
|
|
821
|
+
id: candidate.id,
|
|
822
|
+
prompt: candidate.prompt,
|
|
823
|
+
options,
|
|
824
|
+
...candidate.allowMultiple === true ? { allowMultiple: true } : {}
|
|
825
|
+
}
|
|
826
|
+
];
|
|
827
|
+
});
|
|
828
|
+
if (questions.length === 0) return null;
|
|
829
|
+
return {
|
|
830
|
+
type: "ask_question",
|
|
831
|
+
...typeof params.toolCallId === "string" ? { toolCallId: params.toolCallId } : {},
|
|
832
|
+
...typeof params.title === "string" ? { title: params.title } : {},
|
|
833
|
+
questions
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
function parseTodoStatus(value) {
|
|
837
|
+
if (value === "pending" || value === "in_progress" || value === "completed" || value === "cancelled") {
|
|
838
|
+
return value;
|
|
839
|
+
}
|
|
840
|
+
return "pending";
|
|
841
|
+
}
|
|
842
|
+
function parseTodos(value) {
|
|
843
|
+
if (!Array.isArray(value)) return void 0;
|
|
844
|
+
const todos = value.flatMap((candidate) => {
|
|
845
|
+
if (!isRecord2(candidate) || typeof candidate.id !== "string" || typeof candidate.content !== "string") {
|
|
846
|
+
return [];
|
|
847
|
+
}
|
|
848
|
+
return [
|
|
849
|
+
{ id: candidate.id, content: candidate.content, status: parseTodoStatus(candidate.status) }
|
|
850
|
+
];
|
|
851
|
+
});
|
|
852
|
+
return todos.length ? todos : void 0;
|
|
853
|
+
}
|
|
854
|
+
function parseCreatePlanPrompt(params) {
|
|
855
|
+
if (typeof params.plan !== "string") return null;
|
|
856
|
+
const todos = parseTodos(params.todos);
|
|
857
|
+
const phases = Array.isArray(params.phases) ? params.phases.flatMap((candidate) => {
|
|
858
|
+
if (!isRecord2(candidate) || typeof candidate.name !== "string") return [];
|
|
859
|
+
const phaseTodos = parseTodos(candidate.todos);
|
|
860
|
+
return phaseTodos ? [{ name: candidate.name, todos: phaseTodos }] : [];
|
|
861
|
+
}) : void 0;
|
|
862
|
+
return {
|
|
863
|
+
type: "create_plan",
|
|
864
|
+
...typeof params.toolCallId === "string" ? { toolCallId: params.toolCallId } : {},
|
|
865
|
+
...typeof params.name === "string" ? { name: params.name } : {},
|
|
866
|
+
...typeof params.overview === "string" ? { overview: params.overview } : {},
|
|
867
|
+
plan: params.plan,
|
|
868
|
+
...todos ? { todos } : {},
|
|
869
|
+
...typeof params.isProject === "boolean" ? { isProject: params.isProject } : {},
|
|
870
|
+
...phases?.length ? { phases } : {}
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
function wrapAuthError(error) {
|
|
874
|
+
const message = error.message.toLowerCase();
|
|
875
|
+
if (message.includes("auth") || message.includes("login") || message.includes("unauthor") || message.includes("token") || message.includes("api key")) {
|
|
876
|
+
return new Error(`${CURSOR_ACP_AUTH_REQUIRED_MESSAGE} (${error.message})`);
|
|
877
|
+
}
|
|
878
|
+
return new Error(`${CURSOR_ACP_AUTH_REQUIRED_MESSAGE} (${error.message})`);
|
|
879
|
+
}
|
|
880
|
+
var CursorAcpRpcError = class extends Error {
|
|
881
|
+
constructor(method, code, message, data) {
|
|
882
|
+
super(`Cursor ACP ${method} failed${code === void 0 ? "" : ` (${code})`}: ${message}`);
|
|
883
|
+
this.method = method;
|
|
884
|
+
this.code = code;
|
|
885
|
+
this.data = data;
|
|
886
|
+
this.name = "CursorAcpRpcError";
|
|
887
|
+
}
|
|
888
|
+
method;
|
|
889
|
+
code;
|
|
890
|
+
data;
|
|
891
|
+
};
|
|
892
|
+
var CursorAcpProtocolError = class extends Error {
|
|
893
|
+
constructor(message, payload) {
|
|
894
|
+
super(message);
|
|
895
|
+
this.payload = payload;
|
|
896
|
+
this.name = "CursorAcpProtocolError";
|
|
897
|
+
}
|
|
898
|
+
payload;
|
|
899
|
+
};
|
|
900
|
+
var CursorAcpSession = class {
|
|
901
|
+
child = null;
|
|
902
|
+
stderrTail = "";
|
|
903
|
+
nextRequestId = 1;
|
|
904
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
905
|
+
pendingPermissions = /* @__PURE__ */ new Map();
|
|
906
|
+
pendingExtensions = /* @__PURE__ */ new Map();
|
|
907
|
+
cancelledResponseIds = /* @__PURE__ */ new Set();
|
|
908
|
+
toolCalls = /* @__PURE__ */ new Map();
|
|
909
|
+
sessionReady;
|
|
910
|
+
resolveSessionReady = () => {
|
|
911
|
+
};
|
|
912
|
+
rejectSessionReady = () => {
|
|
913
|
+
};
|
|
914
|
+
sessionReadySettled = false;
|
|
915
|
+
exitReported = false;
|
|
916
|
+
closed = false;
|
|
917
|
+
transportFailure = null;
|
|
918
|
+
sessionId = null;
|
|
919
|
+
activePrompt = null;
|
|
920
|
+
promptQueue = Promise.resolve();
|
|
921
|
+
workDir;
|
|
922
|
+
resumeSessionId;
|
|
923
|
+
acpMode;
|
|
924
|
+
autoApprovePermissions;
|
|
925
|
+
requestTimeoutMs;
|
|
926
|
+
promptTimeoutMs;
|
|
927
|
+
cancelAcknowledgeTimeoutMs;
|
|
928
|
+
onUpdate;
|
|
929
|
+
onNotification;
|
|
930
|
+
onPermissionRequest;
|
|
931
|
+
onExtensionRequest;
|
|
932
|
+
onPromptStart;
|
|
933
|
+
onPromptComplete;
|
|
934
|
+
onPromptError;
|
|
935
|
+
onSessionId;
|
|
936
|
+
onProtocolError;
|
|
937
|
+
onProcessError;
|
|
938
|
+
onExitCb;
|
|
939
|
+
constructor(options = {}) {
|
|
940
|
+
this.workDir = options.cwd ?? options.workDir ?? process.cwd();
|
|
941
|
+
this.resumeSessionId = options.resumeSessionId;
|
|
942
|
+
this.acpMode = resolveCursorAcpMode(options.permissionMode);
|
|
943
|
+
this.autoApprovePermissions = cursorAcpAutoApprovesPermissions(options.permissionMode);
|
|
944
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS2;
|
|
945
|
+
this.promptTimeoutMs = options.promptTimeoutMs ?? 0;
|
|
946
|
+
this.cancelAcknowledgeTimeoutMs = options.cancelAcknowledgeTimeoutMs ?? DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS;
|
|
947
|
+
this.onUpdate = options.onUpdate;
|
|
948
|
+
this.onNotification = options.onNotification;
|
|
949
|
+
this.onPermissionRequest = options.onPermissionRequest ?? denyPermission;
|
|
950
|
+
this.onExtensionRequest = options.onExtensionRequest;
|
|
951
|
+
this.onPromptStart = options.onPromptStart;
|
|
952
|
+
this.onPromptComplete = options.onPromptComplete;
|
|
953
|
+
this.onPromptError = options.onPromptError;
|
|
954
|
+
this.onSessionId = options.onSessionId;
|
|
955
|
+
this.onProtocolError = options.onProtocolError;
|
|
956
|
+
this.onProcessError = options.onProcessError;
|
|
957
|
+
this.onExitCb = options.onExit;
|
|
958
|
+
this.sessionReady = new Promise((resolve, reject) => {
|
|
959
|
+
this.resolveSessionReady = resolve;
|
|
960
|
+
this.rejectSessionReady = reject;
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
getCursorSessionId() {
|
|
964
|
+
return this.sessionId;
|
|
965
|
+
}
|
|
966
|
+
getPendingPermission(requestId) {
|
|
967
|
+
return this.pendingPermissions.get(requestId)?.request;
|
|
968
|
+
}
|
|
969
|
+
start() {
|
|
970
|
+
if (this.child) throw new Error("Cursor ACP session has already been started");
|
|
971
|
+
const command = CURSOR_PROVIDER.buildJsonCommand({ cwd: this.workDir }, process.env);
|
|
972
|
+
this.child = spawnCommand(command.command, command.args, {
|
|
973
|
+
cwd: this.workDir,
|
|
974
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
975
|
+
env: command.env
|
|
976
|
+
});
|
|
977
|
+
this.setupStdoutParsing();
|
|
978
|
+
this.setupStderrCollection();
|
|
979
|
+
this.setupExitHandler();
|
|
980
|
+
void this.initializeSession().catch((error) => this.rejectSessionReadyOnce(toError2(error)));
|
|
981
|
+
if (!this.child.pid) throw new Error("Cursor ACP failed to start: missing child pid");
|
|
982
|
+
return this.child.pid;
|
|
983
|
+
}
|
|
984
|
+
waitUntilReady() {
|
|
985
|
+
return this.sessionReady;
|
|
986
|
+
}
|
|
987
|
+
sendMessage(content) {
|
|
988
|
+
this.promptQueue = this.promptQueue.then(() => this.runPrompt(content));
|
|
989
|
+
}
|
|
990
|
+
async interruptCurrentTurn() {
|
|
991
|
+
const activePrompt = this.activePrompt;
|
|
992
|
+
if (!activePrompt || activePrompt.cancelled || !this.sessionId) return false;
|
|
993
|
+
activePrompt.cancelled = true;
|
|
994
|
+
if (!this.writeLine({
|
|
995
|
+
jsonrpc: "2.0",
|
|
996
|
+
method: "session/cancel",
|
|
997
|
+
params: { sessionId: this.sessionId }
|
|
998
|
+
})) {
|
|
999
|
+
activePrompt.cancelled = false;
|
|
1000
|
+
return false;
|
|
1001
|
+
}
|
|
1002
|
+
this.cancelPendingPermissions();
|
|
1003
|
+
this.cancelPendingExtensions();
|
|
1004
|
+
if (this.cancelAcknowledgeTimeoutMs <= 0) {
|
|
1005
|
+
this.abortUnacknowledgedCancellation(activePrompt);
|
|
1006
|
+
} else {
|
|
1007
|
+
activePrompt.cancelSettleTimer = setTimeout(
|
|
1008
|
+
() => this.abortUnacknowledgedCancellation(activePrompt),
|
|
1009
|
+
this.cancelAcknowledgeTimeoutMs
|
|
1010
|
+
);
|
|
1011
|
+
activePrompt.cancelSettleTimer.unref?.();
|
|
1012
|
+
}
|
|
1013
|
+
return true;
|
|
1014
|
+
}
|
|
1015
|
+
async close() {
|
|
1016
|
+
if (this.closed) return;
|
|
1017
|
+
if (!this.child) throw new Error("Cursor ACP session has not been started");
|
|
1018
|
+
const sessionId2 = this.sessionId ?? await this.sessionReady;
|
|
1019
|
+
await this.request("session/close", { sessionId: sessionId2 });
|
|
1020
|
+
this.closed = true;
|
|
1021
|
+
}
|
|
1022
|
+
async stop(gracePeriodMs = 5e3) {
|
|
1023
|
+
const child = this.child;
|
|
1024
|
+
if (!child || !this.isAlive()) return;
|
|
1025
|
+
if (this.activePrompt) await this.interruptCurrentTurn();
|
|
1026
|
+
if (this.sessionId && !this.closed) {
|
|
1027
|
+
try {
|
|
1028
|
+
await this.close();
|
|
1029
|
+
} catch (error) {
|
|
1030
|
+
this.appendStderr(`Cursor ACP close failed: ${toError2(error).message}
|
|
1031
|
+
`);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
terminateOwnedProcessTree(child, "SIGTERM");
|
|
1035
|
+
const startedAt = Date.now();
|
|
1036
|
+
while (Date.now() - startedAt < gracePeriodMs) {
|
|
1037
|
+
if (!this.isChildAlive(child)) return;
|
|
1038
|
+
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
1039
|
+
}
|
|
1040
|
+
if (this.isChildAlive(child)) terminateOwnedProcessTree(child, "SIGKILL");
|
|
1041
|
+
}
|
|
1042
|
+
isAlive() {
|
|
1043
|
+
return this.child ? this.isChildAlive(this.child) : false;
|
|
1044
|
+
}
|
|
1045
|
+
getStderr() {
|
|
1046
|
+
return this.stderrTail;
|
|
1047
|
+
}
|
|
1048
|
+
isChildAlive(child) {
|
|
1049
|
+
if (!child.pid) return false;
|
|
1050
|
+
try {
|
|
1051
|
+
process.kill(child.pid, 0);
|
|
1052
|
+
return true;
|
|
1053
|
+
} catch {
|
|
1054
|
+
return false;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
async initializeSession() {
|
|
1058
|
+
const initializeResult = await this.request("initialize", {
|
|
1059
|
+
protocolVersion: 1,
|
|
1060
|
+
clientCapabilities: {
|
|
1061
|
+
fs: { readTextFile: false, writeTextFile: false },
|
|
1062
|
+
terminal: false
|
|
1063
|
+
},
|
|
1064
|
+
clientInfo: CLIENT_INFO2
|
|
1065
|
+
});
|
|
1066
|
+
const authMethods = advertisedAuthMethods(initializeResult);
|
|
1067
|
+
if (authMethods.includes("cursor_login") || authMethods.length === 0) {
|
|
1068
|
+
try {
|
|
1069
|
+
await this.request("authenticate", { methodId: "cursor_login" });
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
if (authMethods.includes("cursor_login") || this.looksLikeAuthFailure(error)) {
|
|
1072
|
+
throw wrapAuthError(toError2(error));
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
let sessionId2;
|
|
1077
|
+
if (this.resumeSessionId) {
|
|
1078
|
+
try {
|
|
1079
|
+
await this.request("session/load", {
|
|
1080
|
+
sessionId: this.resumeSessionId,
|
|
1081
|
+
cwd: this.workDir,
|
|
1082
|
+
mcpServers: []
|
|
1083
|
+
});
|
|
1084
|
+
} catch (error) {
|
|
1085
|
+
throw new Error(`\u65E0\u6CD5\u6062\u590D Cursor \u4F1A\u8BDD ${this.resumeSessionId}\uFF1A${toError2(error).message}`, {
|
|
1086
|
+
cause: error
|
|
1087
|
+
});
|
|
1088
|
+
}
|
|
1089
|
+
sessionId2 = this.resumeSessionId;
|
|
1090
|
+
} else {
|
|
1091
|
+
const created = await this.request("session/new", {
|
|
1092
|
+
cwd: this.workDir,
|
|
1093
|
+
mcpServers: []
|
|
1094
|
+
});
|
|
1095
|
+
sessionId2 = this.sessionIdFromResult(created);
|
|
1096
|
+
}
|
|
1097
|
+
if (!sessionId2) throw new Error("Cursor ACP session/new did not return a session id");
|
|
1098
|
+
await this.request("session/set_mode", { sessionId: sessionId2, modeId: this.acpMode });
|
|
1099
|
+
this.sessionId = sessionId2;
|
|
1100
|
+
this.onSessionId?.(sessionId2);
|
|
1101
|
+
this.resolveSessionReadyOnce(sessionId2);
|
|
1102
|
+
}
|
|
1103
|
+
looksLikeAuthFailure(error) {
|
|
1104
|
+
const message = toError2(error).message.toLowerCase();
|
|
1105
|
+
return message.includes("auth") || message.includes("login") || message.includes("unauthor") || message.includes("token") || message.includes("api key");
|
|
1106
|
+
}
|
|
1107
|
+
sessionIdFromResult(result) {
|
|
1108
|
+
if (!isRecord2(result)) return null;
|
|
1109
|
+
return typeof result.sessionId === "string" ? result.sessionId : null;
|
|
1110
|
+
}
|
|
1111
|
+
async runPrompt(content) {
|
|
1112
|
+
let prompt = null;
|
|
1113
|
+
try {
|
|
1114
|
+
const sessionId2 = await this.sessionReady;
|
|
1115
|
+
if (this.transportFailure) throw this.transportFailure;
|
|
1116
|
+
const currentPrompt = { cancelled: false };
|
|
1117
|
+
prompt = currentPrompt;
|
|
1118
|
+
this.activePrompt = currentPrompt;
|
|
1119
|
+
this.invokeCallback(() => this.onPromptStart?.(), "session/prompt start callback failed");
|
|
1120
|
+
const result = await this.request(
|
|
1121
|
+
"session/prompt",
|
|
1122
|
+
{
|
|
1123
|
+
sessionId: sessionId2,
|
|
1124
|
+
prompt: [{ type: "text", text: content }]
|
|
1125
|
+
},
|
|
1126
|
+
this.promptTimeoutMs,
|
|
1127
|
+
(requestId) => {
|
|
1128
|
+
if (this.activePrompt === currentPrompt) currentPrompt.requestId = requestId;
|
|
1129
|
+
}
|
|
1130
|
+
);
|
|
1131
|
+
if (!prompt.cancelled) {
|
|
1132
|
+
this.invokeCallback(
|
|
1133
|
+
() => this.onPromptComplete?.(promptResult(result)),
|
|
1134
|
+
"session/prompt completion callback failed"
|
|
1135
|
+
);
|
|
1136
|
+
}
|
|
1137
|
+
} catch (error) {
|
|
1138
|
+
if (!prompt?.cancelled) {
|
|
1139
|
+
this.invokeCallback(
|
|
1140
|
+
() => this.onPromptError?.(toError2(error)),
|
|
1141
|
+
"session/prompt error callback failed"
|
|
1142
|
+
);
|
|
1143
|
+
}
|
|
1144
|
+
} finally {
|
|
1145
|
+
if (prompt?.cancelSettleTimer) clearTimeout(prompt.cancelSettleTimer);
|
|
1146
|
+
if (this.activePrompt === prompt) this.activePrompt = null;
|
|
1147
|
+
this.toolCalls.clear();
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
request(method, params, timeoutMs = this.requestTimeoutMs, onRequestId) {
|
|
1151
|
+
const id = this.nextRequestId++;
|
|
1152
|
+
onRequestId?.(id);
|
|
1153
|
+
const payload = { jsonrpc: "2.0", id, method, params };
|
|
1154
|
+
return new Promise((resolve, reject) => {
|
|
1155
|
+
const timeout = timeoutMs > 0 ? setTimeout(() => {
|
|
1156
|
+
this.pendingRequests.delete(id);
|
|
1157
|
+
reject(new Error(`Cursor ACP request ${method} timed out after ${timeoutMs}ms`));
|
|
1158
|
+
}, timeoutMs) : void 0;
|
|
1159
|
+
timeout?.unref?.();
|
|
1160
|
+
this.pendingRequests.set(id, { method, resolve, reject, timeout });
|
|
1161
|
+
if (!this.writeLine(payload)) {
|
|
1162
|
+
if (timeout) clearTimeout(timeout);
|
|
1163
|
+
this.pendingRequests.delete(id);
|
|
1164
|
+
reject(new Error(`Cursor ACP stdin is not writable for ${method}`));
|
|
1165
|
+
}
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
1168
|
+
writeLine(payload) {
|
|
1169
|
+
if (this.transportFailure || !this.child?.stdin?.writable) return false;
|
|
1170
|
+
try {
|
|
1171
|
+
this.child.stdin.write(`${JSON.stringify(payload)}
|
|
1172
|
+
`);
|
|
1173
|
+
return true;
|
|
1174
|
+
} catch (error) {
|
|
1175
|
+
this.reportProtocolError(
|
|
1176
|
+
new CursorAcpProtocolError("Failed to write Cursor ACP message", error)
|
|
1177
|
+
);
|
|
1178
|
+
return false;
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
setupStdoutParsing() {
|
|
1182
|
+
const child = this.child;
|
|
1183
|
+
if (!child?.stdout) return;
|
|
1184
|
+
const lineBuffer = new LineBuffer();
|
|
1185
|
+
child.stdout.pipe(lineBuffer);
|
|
1186
|
+
lineBuffer.on("data", (line) => {
|
|
1187
|
+
const text = typeof line === "string" ? line : line.toString();
|
|
1188
|
+
let message;
|
|
1189
|
+
try {
|
|
1190
|
+
message = JSON.parse(text);
|
|
1191
|
+
} catch (error) {
|
|
1192
|
+
this.reportProtocolError(
|
|
1193
|
+
new CursorAcpProtocolError(`Invalid Cursor ACP JSON: ${toError2(error).message}`, text),
|
|
1194
|
+
text
|
|
1195
|
+
);
|
|
1196
|
+
return;
|
|
1197
|
+
}
|
|
1198
|
+
this.handleAcpMessage(message);
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
handleAcpMessage(message) {
|
|
1202
|
+
if (!isRecord2(message)) {
|
|
1203
|
+
this.reportProtocolError(
|
|
1204
|
+
new CursorAcpProtocolError("Cursor ACP message must be an object", message)
|
|
1205
|
+
);
|
|
1206
|
+
return;
|
|
1207
|
+
}
|
|
1208
|
+
const id = message.id;
|
|
1209
|
+
const method = message.method;
|
|
1210
|
+
if (typeof method === "string" && (typeof id === "string" || typeof id === "number")) {
|
|
1211
|
+
this.handleServerRequest({ id, method, params: message.params });
|
|
1212
|
+
return;
|
|
1213
|
+
}
|
|
1214
|
+
if (typeof method === "string") {
|
|
1215
|
+
this.handleNotification(method, message.params);
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
if (typeof id === "string" || typeof id === "number") {
|
|
1219
|
+
this.handleResponse(id, message);
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
this.reportProtocolError(
|
|
1223
|
+
new CursorAcpProtocolError("Unrecognized Cursor ACP message", message)
|
|
1224
|
+
);
|
|
1225
|
+
}
|
|
1226
|
+
handleResponse(id, message) {
|
|
1227
|
+
const pending = this.pendingRequests.get(id);
|
|
1228
|
+
if (!pending) {
|
|
1229
|
+
if (this.cancelledResponseIds.delete(id)) return;
|
|
1230
|
+
this.reportProtocolError(
|
|
1231
|
+
new CursorAcpProtocolError(`Unexpected Cursor ACP response id: ${String(id)}`, message)
|
|
1232
|
+
);
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
this.pendingRequests.delete(id);
|
|
1236
|
+
if (pending.timeout) clearTimeout(pending.timeout);
|
|
1237
|
+
if (isRecord2(message.error)) {
|
|
1238
|
+
pending.reject(
|
|
1239
|
+
new CursorAcpRpcError(
|
|
1240
|
+
pending.method,
|
|
1241
|
+
typeof message.error.code === "number" ? message.error.code : void 0,
|
|
1242
|
+
responseErrorMessage(message.error),
|
|
1243
|
+
message.error.data
|
|
1244
|
+
)
|
|
1245
|
+
);
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
pending.resolve(message.result);
|
|
1249
|
+
}
|
|
1250
|
+
abortUnacknowledgedCancellation(prompt) {
|
|
1251
|
+
const requestId = prompt.requestId;
|
|
1252
|
+
if (requestId === void 0) return;
|
|
1253
|
+
const pending = this.pendingRequests.get(requestId);
|
|
1254
|
+
if (!pending || pending.method !== "session/prompt") return;
|
|
1255
|
+
const error = new Error(
|
|
1256
|
+
`Cursor ACP did not acknowledge session/cancel within ${this.cancelAcknowledgeTimeoutMs}ms; terminating the unsafe transport`
|
|
1257
|
+
);
|
|
1258
|
+
this.transportFailure = error;
|
|
1259
|
+
this.pendingRequests.delete(requestId);
|
|
1260
|
+
if (pending.timeout) clearTimeout(pending.timeout);
|
|
1261
|
+
this.cancelledResponseIds.add(requestId);
|
|
1262
|
+
if (this.cancelledResponseIds.size > CANCELLED_RESPONSE_TOMBSTONE_LIMIT) {
|
|
1263
|
+
const oldest = this.cancelledResponseIds.values().next().value;
|
|
1264
|
+
if (oldest !== void 0) this.cancelledResponseIds.delete(oldest);
|
|
1265
|
+
}
|
|
1266
|
+
this.appendStderr(`${error.message}
|
|
1267
|
+
`);
|
|
1268
|
+
this.cancelPendingPermissions();
|
|
1269
|
+
this.cancelPendingExtensions();
|
|
1270
|
+
pending.reject(error);
|
|
1271
|
+
if (this.child) terminateOwnedProcessTree(this.child, "SIGKILL");
|
|
1272
|
+
}
|
|
1273
|
+
handleNotification(method, rawParams) {
|
|
1274
|
+
const params = isRecord2(rawParams) ? rawParams : {};
|
|
1275
|
+
if (method === "session/update") {
|
|
1276
|
+
this.trackToolCall(params);
|
|
1277
|
+
this.invokeCallback(() => this.onUpdate?.(params), "session/update callback failed");
|
|
1278
|
+
}
|
|
1279
|
+
this.invokeCallback(
|
|
1280
|
+
() => this.onNotification?.(method, params),
|
|
1281
|
+
`${method} notification callback failed`
|
|
1282
|
+
);
|
|
1283
|
+
}
|
|
1284
|
+
trackToolCall(params) {
|
|
1285
|
+
if (!isRecord2(params.update) || typeof params.update.toolCallId !== "string") return;
|
|
1286
|
+
const previous = this.toolCalls.get(params.update.toolCallId) ?? {};
|
|
1287
|
+
const next = { ...previous, ...params.update };
|
|
1288
|
+
if (next.status === "completed" || next.status === "failed") {
|
|
1289
|
+
this.toolCalls.delete(params.update.toolCallId);
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
this.toolCalls.set(params.update.toolCallId, next);
|
|
1293
|
+
}
|
|
1294
|
+
handleServerRequest(request) {
|
|
1295
|
+
if (request.method === "session/request_permission") {
|
|
1296
|
+
void this.handlePermissionRequest(request.id, request.params);
|
|
1297
|
+
return;
|
|
1298
|
+
}
|
|
1299
|
+
if (request.method === "cursor/ask_question" || request.method === "cursor/create_plan") {
|
|
1300
|
+
void this.handleExtensionRequest(request.id, request.method, request.params);
|
|
1301
|
+
return;
|
|
1302
|
+
}
|
|
1303
|
+
this.writeLine({
|
|
1304
|
+
jsonrpc: "2.0",
|
|
1305
|
+
id: request.id,
|
|
1306
|
+
error: { code: -32601, message: `Unsupported Cursor ACP client request: ${request.method}` }
|
|
1307
|
+
});
|
|
1308
|
+
}
|
|
1309
|
+
async handlePermissionRequest(id, rawParams) {
|
|
1310
|
+
const params = isRecord2(rawParams) ? rawParams : {};
|
|
1311
|
+
const incomingToolCall = isRecord2(params.toolCall) ? params.toolCall : {};
|
|
1312
|
+
const toolCallId = typeof incomingToolCall.toolCallId === "string" ? incomingToolCall.toolCallId : void 0;
|
|
1313
|
+
const trackedToolCall = toolCallId ? this.toolCalls.get(toolCallId) ?? {} : {};
|
|
1314
|
+
const toolCall = { ...trackedToolCall, ...incomingToolCall };
|
|
1315
|
+
const rawInput = isRecord2(incomingToolCall.rawInput) ? incomingToolCall.rawInput : trackedToolCall.rawInput;
|
|
1316
|
+
const request = {
|
|
1317
|
+
requestId: id,
|
|
1318
|
+
sessionId: typeof params.sessionId === "string" ? params.sessionId : this.sessionId ?? "",
|
|
1319
|
+
toolName: typeof incomingToolCall.title === "string" ? incomingToolCall.title : typeof trackedToolCall.title === "string" ? trackedToolCall.title : "Tool",
|
|
1320
|
+
input: normalizeApprovalInput2(rawInput),
|
|
1321
|
+
rawToolCall: incomingToolCall,
|
|
1322
|
+
toolCall,
|
|
1323
|
+
options: parsePermissionOptions(params.options),
|
|
1324
|
+
rawParams: params
|
|
1325
|
+
};
|
|
1326
|
+
if (this.transportFailure || this.activePrompt?.cancelled) {
|
|
1327
|
+
this.writeLine({
|
|
1328
|
+
jsonrpc: "2.0",
|
|
1329
|
+
id,
|
|
1330
|
+
result: { outcome: { outcome: "cancelled" } }
|
|
1331
|
+
});
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
if (this.autoApprovePermissions) {
|
|
1335
|
+
const option2 = selectPermissionOption(request.options, "allow_always");
|
|
1336
|
+
this.writeLine({
|
|
1337
|
+
jsonrpc: "2.0",
|
|
1338
|
+
id,
|
|
1339
|
+
result: option2 ? { outcome: { outcome: "selected", optionId: option2.optionId } } : { outcome: { outcome: "selected", optionId: "allow-always" } }
|
|
1340
|
+
});
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
const pending = { request, responded: false };
|
|
1344
|
+
this.pendingPermissions.set(id, pending);
|
|
1345
|
+
let decision;
|
|
1346
|
+
try {
|
|
1347
|
+
decision = await this.onPermissionRequest(request);
|
|
1348
|
+
} catch (error) {
|
|
1349
|
+
decision = { behavior: "deny", message: toError2(error).message };
|
|
1350
|
+
}
|
|
1351
|
+
if (pending.responded) return;
|
|
1352
|
+
pending.responded = true;
|
|
1353
|
+
this.pendingPermissions.delete(id);
|
|
1354
|
+
const requestedOptionId = typeof decision.optionId === "string" && decision.optionId.trim().length > 0 ? decision.optionId : void 0;
|
|
1355
|
+
const explicitOption = requestedOptionId ? request.options.find((candidate) => candidate.optionId === requestedOptionId) : void 0;
|
|
1356
|
+
const cancelled = decision.cancelled === true || decision.behavior === "cancel";
|
|
1357
|
+
const behavior = decision.behavior === "allow_once" || decision.behavior === "allow_always" || decision.behavior === "deny" ? decision.behavior : void 0;
|
|
1358
|
+
const validExplicitOption = explicitOption && (!behavior || optionMatchesBehavior(explicitOption, behavior)) ? explicitOption : void 0;
|
|
1359
|
+
const option = cancelled || requestedOptionId || !behavior ? void 0 : selectPermissionOption(request.options, behavior);
|
|
1360
|
+
const selectedOptionId = cancelled ? void 0 : validExplicitOption?.optionId || option?.optionId;
|
|
1361
|
+
const outcome = selectedOptionId ? { outcome: "selected", optionId: selectedOptionId } : { outcome: "cancelled" };
|
|
1362
|
+
if (!this.writeLine({ jsonrpc: "2.0", id, result: { outcome } })) {
|
|
1363
|
+
this.reportProtocolError(
|
|
1364
|
+
new CursorAcpProtocolError(`Failed to respond to permission request ${String(id)}`)
|
|
1365
|
+
);
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
async handleExtensionRequest(id, method, rawParams) {
|
|
1369
|
+
const params = isRecord2(rawParams) ? rawParams : {};
|
|
1370
|
+
const prompt = method === "cursor/ask_question" ? parseAskQuestionPrompt(params) : parseCreatePlanPrompt(params);
|
|
1371
|
+
const cancelledResult = method === "cursor/ask_question" ? { outcome: { outcome: "cancelled" } } : { outcome: { outcome: "cancelled" } };
|
|
1372
|
+
if (!prompt) {
|
|
1373
|
+
this.writeLine({
|
|
1374
|
+
jsonrpc: "2.0",
|
|
1375
|
+
id,
|
|
1376
|
+
result: cancelledResult
|
|
1377
|
+
});
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
if (this.transportFailure || this.activePrompt?.cancelled) {
|
|
1381
|
+
this.writeLine({ jsonrpc: "2.0", id, result: cancelledResult });
|
|
1382
|
+
return;
|
|
1383
|
+
}
|
|
1384
|
+
const request = {
|
|
1385
|
+
requestId: id,
|
|
1386
|
+
sessionId: typeof params.sessionId === "string" ? params.sessionId : this.sessionId ?? "",
|
|
1387
|
+
prompt
|
|
1388
|
+
};
|
|
1389
|
+
const pending = { request, responded: false };
|
|
1390
|
+
this.pendingExtensions.set(id, pending);
|
|
1391
|
+
let decision;
|
|
1392
|
+
try {
|
|
1393
|
+
decision = this.onExtensionRequest ? await this.onExtensionRequest(request) : cancelExtension();
|
|
1394
|
+
} catch (error) {
|
|
1395
|
+
decision = {
|
|
1396
|
+
cancelled: true,
|
|
1397
|
+
answer: method === "cursor/ask_question" ? { type: "ask_question", outcome: "cancelled", reason: toError2(error).message } : { type: "create_plan", outcome: "cancelled", reason: toError2(error).message }
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
if (pending.responded) return;
|
|
1401
|
+
pending.responded = true;
|
|
1402
|
+
this.pendingExtensions.delete(id);
|
|
1403
|
+
const result = this.extensionResult(method, decision);
|
|
1404
|
+
if (!this.writeLine({ jsonrpc: "2.0", id, result })) {
|
|
1405
|
+
this.reportProtocolError(
|
|
1406
|
+
new CursorAcpProtocolError(`Failed to respond to ${method} ${String(id)}`)
|
|
1407
|
+
);
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
extensionResult(method, decision) {
|
|
1411
|
+
if (decision.cancelled) {
|
|
1412
|
+
return { outcome: { outcome: "cancelled" } };
|
|
1413
|
+
}
|
|
1414
|
+
const answer = decision.answer;
|
|
1415
|
+
if (method === "cursor/ask_question") {
|
|
1416
|
+
if (answer?.type !== "ask_question") return { outcome: { outcome: "cancelled" } };
|
|
1417
|
+
if (answer.outcome === "answered") {
|
|
1418
|
+
return {
|
|
1419
|
+
outcome: {
|
|
1420
|
+
outcome: "answered",
|
|
1421
|
+
answers: answer.answers ?? []
|
|
1422
|
+
}
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
return {
|
|
1426
|
+
outcome: {
|
|
1427
|
+
outcome: answer.outcome,
|
|
1428
|
+
...answer.reason ? { reason: answer.reason } : {}
|
|
1429
|
+
}
|
|
1430
|
+
};
|
|
1431
|
+
}
|
|
1432
|
+
if (answer?.type !== "create_plan") return { outcome: { outcome: "cancelled" } };
|
|
1433
|
+
return {
|
|
1434
|
+
outcome: {
|
|
1435
|
+
outcome: answer.outcome,
|
|
1436
|
+
...answer.reason ? { reason: answer.reason } : {}
|
|
1437
|
+
}
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
cancelPendingPermissions() {
|
|
1441
|
+
for (const [id, pending] of this.pendingPermissions) {
|
|
1442
|
+
if (pending.responded) continue;
|
|
1443
|
+
pending.responded = true;
|
|
1444
|
+
this.writeLine({
|
|
1445
|
+
jsonrpc: "2.0",
|
|
1446
|
+
id,
|
|
1447
|
+
result: { outcome: { outcome: "cancelled" } }
|
|
1448
|
+
});
|
|
1449
|
+
}
|
|
1450
|
+
this.pendingPermissions.clear();
|
|
1451
|
+
}
|
|
1452
|
+
cancelPendingExtensions() {
|
|
1453
|
+
for (const [id, pending] of this.pendingExtensions) {
|
|
1454
|
+
if (pending.responded) continue;
|
|
1455
|
+
pending.responded = true;
|
|
1456
|
+
this.writeLine({
|
|
1457
|
+
jsonrpc: "2.0",
|
|
1458
|
+
id,
|
|
1459
|
+
result: { outcome: { outcome: "cancelled" } }
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
this.pendingExtensions.clear();
|
|
1463
|
+
}
|
|
1464
|
+
setupStderrCollection() {
|
|
1465
|
+
const child = this.child;
|
|
1466
|
+
if (!child?.stderr) return;
|
|
1467
|
+
child.stderr.on("data", (chunk) => {
|
|
1468
|
+
this.appendStderr(typeof chunk === "string" ? chunk : chunk.toString());
|
|
1469
|
+
});
|
|
1470
|
+
}
|
|
1471
|
+
setupExitHandler() {
|
|
1472
|
+
const child = this.child;
|
|
1473
|
+
if (!child) return;
|
|
1474
|
+
child.on("error", (error) => {
|
|
1475
|
+
const wrapped = new Error(`Cursor ACP failed to start: ${error.message}`);
|
|
1476
|
+
this.appendStderr(`${wrapped.message}
|
|
1477
|
+
`);
|
|
1478
|
+
this.rejectAllPendingRequests(wrapped);
|
|
1479
|
+
this.rejectSessionReadyOnce(wrapped);
|
|
1480
|
+
this.onProcessError?.(wrapped);
|
|
1481
|
+
this.reportExit(1);
|
|
1482
|
+
});
|
|
1483
|
+
child.on("exit", (code) => {
|
|
1484
|
+
const exitCode = code ?? 1;
|
|
1485
|
+
const error = new Error(
|
|
1486
|
+
this.sessionReadySettled ? `Cursor ACP exited (code ${exitCode})` : `Cursor ACP exited before ready (code ${exitCode})`
|
|
1487
|
+
);
|
|
1488
|
+
this.rejectAllPendingRequests(error);
|
|
1489
|
+
this.pendingPermissions.clear();
|
|
1490
|
+
this.pendingExtensions.clear();
|
|
1491
|
+
this.rejectSessionReadyOnce(error);
|
|
1492
|
+
if (exitCode !== 0) this.onProcessError?.(error);
|
|
1493
|
+
this.reportExit(exitCode);
|
|
1494
|
+
});
|
|
1495
|
+
}
|
|
1496
|
+
invokeCallback(callback, message) {
|
|
1497
|
+
try {
|
|
1498
|
+
callback();
|
|
1499
|
+
} catch (error) {
|
|
1500
|
+
this.reportProtocolError(new CursorAcpProtocolError(`${message}: ${toError2(error).message}`));
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
reportProtocolError(error, line) {
|
|
1504
|
+
this.appendStderr(`${error.message}
|
|
1505
|
+
`);
|
|
1506
|
+
try {
|
|
1507
|
+
this.onProtocolError?.(error, line);
|
|
1508
|
+
} catch {
|
|
1509
|
+
}
|
|
1510
|
+
}
|
|
1511
|
+
appendStderr(chunk) {
|
|
1512
|
+
this.stderrTail = `${this.stderrTail}${chunk}`.slice(-STDERR_TAIL_LIMIT3);
|
|
1513
|
+
}
|
|
1514
|
+
resolveSessionReadyOnce(sessionId2) {
|
|
1515
|
+
if (this.sessionReadySettled) return;
|
|
1516
|
+
this.sessionReadySettled = true;
|
|
1517
|
+
this.resolveSessionReady(sessionId2);
|
|
1518
|
+
}
|
|
1519
|
+
rejectSessionReadyOnce(error) {
|
|
1520
|
+
if (this.sessionReadySettled) return;
|
|
1521
|
+
this.sessionReadySettled = true;
|
|
1522
|
+
this.rejectSessionReady(error);
|
|
1523
|
+
}
|
|
1524
|
+
rejectAllPendingRequests(error) {
|
|
1525
|
+
for (const pending of this.pendingRequests.values()) {
|
|
1526
|
+
if (pending.timeout) clearTimeout(pending.timeout);
|
|
1527
|
+
pending.reject(error);
|
|
1528
|
+
}
|
|
1529
|
+
this.pendingRequests.clear();
|
|
1530
|
+
this.cancelledResponseIds.clear();
|
|
1531
|
+
}
|
|
1532
|
+
reportExit(code) {
|
|
1533
|
+
if (this.exitReported) return;
|
|
1534
|
+
this.exitReported = true;
|
|
1535
|
+
this.onExitCb?.(code);
|
|
1536
|
+
}
|
|
1537
|
+
};
|
|
1538
|
+
|
|
703
1539
|
// src/worker/kimi-acp-session.ts
|
|
704
|
-
var
|
|
1540
|
+
var CLIENT_INFO3 = {
|
|
705
1541
|
name: "dev-anywhere",
|
|
706
1542
|
title: "Dev Anywhere",
|
|
707
1543
|
version: PROXY_VERSION
|
|
708
1544
|
};
|
|
709
|
-
var
|
|
710
|
-
var
|
|
711
|
-
var
|
|
712
|
-
var
|
|
713
|
-
var
|
|
1545
|
+
var DEFAULT_REQUEST_TIMEOUT_MS3 = 1e4;
|
|
1546
|
+
var DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS2 = 2e3;
|
|
1547
|
+
var STDERR_TAIL_LIMIT4 = 8192;
|
|
1548
|
+
var CANCELLED_RESPONSE_TOMBSTONE_LIMIT2 = 128;
|
|
1549
|
+
var denyPermission2 = () => ({
|
|
714
1550
|
behavior: "deny",
|
|
715
1551
|
message: "Tool use denied by default policy. Remote approval is not configured."
|
|
716
1552
|
});
|
|
717
|
-
function
|
|
1553
|
+
function isRecord3(value) {
|
|
718
1554
|
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
719
1555
|
}
|
|
720
|
-
function
|
|
1556
|
+
function toError3(error) {
|
|
721
1557
|
return error instanceof Error ? error : new Error(String(error));
|
|
722
1558
|
}
|
|
723
|
-
function
|
|
724
|
-
if (!
|
|
1559
|
+
function normalizeApprovalInput3(value) {
|
|
1560
|
+
if (!isRecord3(value)) return {};
|
|
725
1561
|
const input = { ...value };
|
|
726
1562
|
if (Array.isArray(input.command)) {
|
|
727
1563
|
input.command = input.command.map((part) => String(part)).join(" ");
|
|
728
1564
|
}
|
|
729
1565
|
return input;
|
|
730
1566
|
}
|
|
731
|
-
function
|
|
1567
|
+
function parsePermissionOptions2(value) {
|
|
732
1568
|
if (!Array.isArray(value)) return [];
|
|
733
1569
|
const options = [];
|
|
734
1570
|
for (const candidate of value) {
|
|
735
|
-
if (!
|
|
1571
|
+
if (!isRecord3(candidate) || typeof candidate.optionId !== "string") continue;
|
|
736
1572
|
options.push({
|
|
737
1573
|
...candidate,
|
|
738
1574
|
optionId: candidate.optionId,
|
|
@@ -742,43 +1578,43 @@ function parsePermissionOptions(value) {
|
|
|
742
1578
|
}
|
|
743
1579
|
return options;
|
|
744
1580
|
}
|
|
745
|
-
function
|
|
1581
|
+
function normalizedOptionText2(option) {
|
|
746
1582
|
return `${option.optionId} ${option.name}`.toLowerCase().replace(/[^a-z0-9]+/g, " ");
|
|
747
1583
|
}
|
|
748
|
-
function
|
|
749
|
-
const text =
|
|
1584
|
+
function isAllowOption2(option) {
|
|
1585
|
+
const text = normalizedOptionText2(option);
|
|
750
1586
|
return option.kind.startsWith("allow") || /\b(allow|approve|accept)\b/.test(text);
|
|
751
1587
|
}
|
|
752
|
-
function
|
|
753
|
-
const text =
|
|
1588
|
+
function isAlwaysOption2(option) {
|
|
1589
|
+
const text = normalizedOptionText2(option);
|
|
754
1590
|
return option.kind === "allow_always" || /\b(always|session|persist)\b/.test(text);
|
|
755
1591
|
}
|
|
756
|
-
function
|
|
757
|
-
const text =
|
|
1592
|
+
function isDenyOption2(option) {
|
|
1593
|
+
const text = normalizedOptionText2(option);
|
|
758
1594
|
return option.kind.startsWith("reject") || /\b(reject|deny|decline|cancel|skip)\b/.test(text);
|
|
759
1595
|
}
|
|
760
|
-
function
|
|
761
|
-
if (behavior === "deny") return
|
|
1596
|
+
function optionMatchesBehavior2(option, behavior) {
|
|
1597
|
+
if (behavior === "deny") return isDenyOption2(option);
|
|
762
1598
|
if (behavior === "allow_always") {
|
|
763
|
-
return
|
|
1599
|
+
return isAllowOption2(option) && isAlwaysOption2(option);
|
|
764
1600
|
}
|
|
765
|
-
return
|
|
1601
|
+
return isAllowOption2(option) && !isAlwaysOption2(option);
|
|
766
1602
|
}
|
|
767
|
-
function
|
|
1603
|
+
function selectPermissionOption2(options, behavior) {
|
|
768
1604
|
if (behavior === "deny") {
|
|
769
|
-
return options.find((option) => option.kind.startsWith("reject")) ?? options.find(
|
|
1605
|
+
return options.find((option) => option.kind.startsWith("reject")) ?? options.find(isDenyOption2);
|
|
770
1606
|
}
|
|
771
1607
|
if (behavior === "allow_always") {
|
|
772
|
-
return options.find((option) => option.kind === "allow_always") ?? options.find((option) =>
|
|
1608
|
+
return options.find((option) => option.kind === "allow_always") ?? options.find((option) => isAllowOption2(option) && isAlwaysOption2(option)) ?? // Never upgrade a one-shot decision, but safely downgrade a persistent allow when the
|
|
773
1609
|
// provider only advertises allow-once.
|
|
774
|
-
options.find((option) => option.kind === "allow_once") ?? options.find((option) =>
|
|
1610
|
+
options.find((option) => option.kind === "allow_once") ?? options.find((option) => isAllowOption2(option) && !isAlwaysOption2(option));
|
|
775
1611
|
}
|
|
776
|
-
return options.find((option) => option.kind === "allow_once") ?? options.find((option) =>
|
|
1612
|
+
return options.find((option) => option.kind === "allow_once") ?? options.find((option) => isAllowOption2(option) && !isAlwaysOption2(option));
|
|
777
1613
|
}
|
|
778
|
-
function
|
|
779
|
-
return
|
|
1614
|
+
function promptResult2(value) {
|
|
1615
|
+
return isRecord3(value) ? value : {};
|
|
780
1616
|
}
|
|
781
|
-
function
|
|
1617
|
+
function responseErrorMessage2(error) {
|
|
782
1618
|
return typeof error.message === "string" ? error.message : "Kimi ACP request failed";
|
|
783
1619
|
}
|
|
784
1620
|
var KimiAcpRpcError = class extends Error {
|
|
@@ -841,12 +1677,12 @@ var KimiAcpSession = class {
|
|
|
841
1677
|
this.workDir = options.cwd ?? options.workDir ?? process.cwd();
|
|
842
1678
|
this.resumeSessionId = options.resumeSessionId;
|
|
843
1679
|
this.acpMode = resolveKimiAcpMode(options.permissionMode);
|
|
844
|
-
this.requestTimeoutMs = options.requestTimeoutMs ??
|
|
1680
|
+
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS3;
|
|
845
1681
|
this.promptTimeoutMs = options.promptTimeoutMs ?? 0;
|
|
846
|
-
this.cancelAcknowledgeTimeoutMs = options.cancelAcknowledgeTimeoutMs ??
|
|
1682
|
+
this.cancelAcknowledgeTimeoutMs = options.cancelAcknowledgeTimeoutMs ?? DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS2;
|
|
847
1683
|
this.onUpdate = options.onUpdate;
|
|
848
1684
|
this.onNotification = options.onNotification;
|
|
849
|
-
this.onPermissionRequest = options.onPermissionRequest ??
|
|
1685
|
+
this.onPermissionRequest = options.onPermissionRequest ?? denyPermission2;
|
|
850
1686
|
this.onPromptStart = options.onPromptStart;
|
|
851
1687
|
this.onPromptComplete = options.onPromptComplete;
|
|
852
1688
|
this.onPromptError = options.onPromptError;
|
|
@@ -876,7 +1712,7 @@ var KimiAcpSession = class {
|
|
|
876
1712
|
this.setupStdoutParsing();
|
|
877
1713
|
this.setupStderrCollection();
|
|
878
1714
|
this.setupExitHandler();
|
|
879
|
-
void this.initializeSession().catch((error) => this.rejectSessionReadyOnce(
|
|
1715
|
+
void this.initializeSession().catch((error) => this.rejectSessionReadyOnce(toError3(error)));
|
|
880
1716
|
if (!this.child.pid) throw new Error("Kimi ACP failed to start: missing child pid");
|
|
881
1717
|
return this.child.pid;
|
|
882
1718
|
}
|
|
@@ -925,7 +1761,7 @@ var KimiAcpSession = class {
|
|
|
925
1761
|
try {
|
|
926
1762
|
await this.close();
|
|
927
1763
|
} catch (error) {
|
|
928
|
-
this.appendStderr(`Kimi ACP close failed: ${
|
|
1764
|
+
this.appendStderr(`Kimi ACP close failed: ${toError3(error).message}
|
|
929
1765
|
`);
|
|
930
1766
|
}
|
|
931
1767
|
}
|
|
@@ -959,7 +1795,7 @@ var KimiAcpSession = class {
|
|
|
959
1795
|
fs: { readTextFile: false, writeTextFile: false },
|
|
960
1796
|
terminal: false
|
|
961
1797
|
},
|
|
962
|
-
clientInfo:
|
|
1798
|
+
clientInfo: CLIENT_INFO3
|
|
963
1799
|
});
|
|
964
1800
|
const result = this.resumeSessionId ? await this.request("session/resume", {
|
|
965
1801
|
sessionId: this.resumeSessionId,
|
|
@@ -977,7 +1813,7 @@ var KimiAcpSession = class {
|
|
|
977
1813
|
this.resolveSessionReadyOnce(sessionId2);
|
|
978
1814
|
}
|
|
979
1815
|
sessionIdFromResult(result) {
|
|
980
|
-
if (!
|
|
1816
|
+
if (!isRecord3(result)) return null;
|
|
981
1817
|
return typeof result.sessionId === "string" ? result.sessionId : null;
|
|
982
1818
|
}
|
|
983
1819
|
async runPrompt(content) {
|
|
@@ -1002,14 +1838,14 @@ var KimiAcpSession = class {
|
|
|
1002
1838
|
);
|
|
1003
1839
|
if (!prompt.cancelled) {
|
|
1004
1840
|
this.invokeCallback(
|
|
1005
|
-
() => this.onPromptComplete?.(
|
|
1841
|
+
() => this.onPromptComplete?.(promptResult2(result)),
|
|
1006
1842
|
"session/prompt completion callback failed"
|
|
1007
1843
|
);
|
|
1008
1844
|
}
|
|
1009
1845
|
} catch (error) {
|
|
1010
1846
|
if (!prompt?.cancelled) {
|
|
1011
1847
|
this.invokeCallback(
|
|
1012
|
-
() => this.onPromptError?.(
|
|
1848
|
+
() => this.onPromptError?.(toError3(error)),
|
|
1013
1849
|
"session/prompt error callback failed"
|
|
1014
1850
|
);
|
|
1015
1851
|
}
|
|
@@ -1060,7 +1896,7 @@ var KimiAcpSession = class {
|
|
|
1060
1896
|
message = JSON.parse(text);
|
|
1061
1897
|
} catch (error) {
|
|
1062
1898
|
this.reportProtocolError(
|
|
1063
|
-
new KimiAcpProtocolError(`Invalid Kimi ACP JSON: ${
|
|
1899
|
+
new KimiAcpProtocolError(`Invalid Kimi ACP JSON: ${toError3(error).message}`, text),
|
|
1064
1900
|
text
|
|
1065
1901
|
);
|
|
1066
1902
|
return;
|
|
@@ -1069,7 +1905,7 @@ var KimiAcpSession = class {
|
|
|
1069
1905
|
});
|
|
1070
1906
|
}
|
|
1071
1907
|
handleAcpMessage(message) {
|
|
1072
|
-
if (!
|
|
1908
|
+
if (!isRecord3(message)) {
|
|
1073
1909
|
this.reportProtocolError(
|
|
1074
1910
|
new KimiAcpProtocolError("Kimi ACP message must be an object", message)
|
|
1075
1911
|
);
|
|
@@ -1102,12 +1938,12 @@ var KimiAcpSession = class {
|
|
|
1102
1938
|
}
|
|
1103
1939
|
this.pendingRequests.delete(id);
|
|
1104
1940
|
if (pending.timeout) clearTimeout(pending.timeout);
|
|
1105
|
-
if (
|
|
1941
|
+
if (isRecord3(message.error)) {
|
|
1106
1942
|
pending.reject(
|
|
1107
1943
|
new KimiAcpRpcError(
|
|
1108
1944
|
pending.method,
|
|
1109
1945
|
typeof message.error.code === "number" ? message.error.code : void 0,
|
|
1110
|
-
|
|
1946
|
+
responseErrorMessage2(message.error),
|
|
1111
1947
|
message.error.data
|
|
1112
1948
|
)
|
|
1113
1949
|
);
|
|
@@ -1127,7 +1963,7 @@ var KimiAcpSession = class {
|
|
|
1127
1963
|
this.pendingRequests.delete(requestId);
|
|
1128
1964
|
if (pending.timeout) clearTimeout(pending.timeout);
|
|
1129
1965
|
this.cancelledResponseIds.add(requestId);
|
|
1130
|
-
if (this.cancelledResponseIds.size >
|
|
1966
|
+
if (this.cancelledResponseIds.size > CANCELLED_RESPONSE_TOMBSTONE_LIMIT2) {
|
|
1131
1967
|
const oldest = this.cancelledResponseIds.values().next().value;
|
|
1132
1968
|
if (oldest !== void 0) this.cancelledResponseIds.delete(oldest);
|
|
1133
1969
|
}
|
|
@@ -1138,7 +1974,7 @@ var KimiAcpSession = class {
|
|
|
1138
1974
|
if (this.child) terminateOwnedProcessTree(this.child, "SIGKILL");
|
|
1139
1975
|
}
|
|
1140
1976
|
handleNotification(method, rawParams) {
|
|
1141
|
-
const params =
|
|
1977
|
+
const params = isRecord3(rawParams) ? rawParams : {};
|
|
1142
1978
|
if (method === "session/update") {
|
|
1143
1979
|
this.trackToolCall(params);
|
|
1144
1980
|
this.invokeCallback(() => this.onUpdate?.(params), "session/update callback failed");
|
|
@@ -1149,7 +1985,7 @@ var KimiAcpSession = class {
|
|
|
1149
1985
|
);
|
|
1150
1986
|
}
|
|
1151
1987
|
trackToolCall(params) {
|
|
1152
|
-
if (!
|
|
1988
|
+
if (!isRecord3(params.update) || typeof params.update.toolCallId !== "string") return;
|
|
1153
1989
|
const previous = this.toolCalls.get(params.update.toolCallId) ?? {};
|
|
1154
1990
|
const next = { ...previous, ...params.update };
|
|
1155
1991
|
if (next.status === "completed" || next.status === "failed") {
|
|
@@ -1170,20 +2006,20 @@ var KimiAcpSession = class {
|
|
|
1170
2006
|
});
|
|
1171
2007
|
}
|
|
1172
2008
|
async handlePermissionRequest(id, rawParams) {
|
|
1173
|
-
const params =
|
|
1174
|
-
const incomingToolCall =
|
|
2009
|
+
const params = isRecord3(rawParams) ? rawParams : {};
|
|
2010
|
+
const incomingToolCall = isRecord3(params.toolCall) ? params.toolCall : {};
|
|
1175
2011
|
const toolCallId = typeof incomingToolCall.toolCallId === "string" ? incomingToolCall.toolCallId : void 0;
|
|
1176
2012
|
const trackedToolCall = toolCallId ? this.toolCalls.get(toolCallId) ?? {} : {};
|
|
1177
2013
|
const toolCall = { ...trackedToolCall, ...incomingToolCall };
|
|
1178
|
-
const rawInput =
|
|
2014
|
+
const rawInput = isRecord3(incomingToolCall.rawInput) ? incomingToolCall.rawInput : trackedToolCall.rawInput;
|
|
1179
2015
|
const request = {
|
|
1180
2016
|
requestId: id,
|
|
1181
2017
|
sessionId: typeof params.sessionId === "string" ? params.sessionId : this.sessionId ?? "",
|
|
1182
2018
|
toolName: typeof incomingToolCall.title === "string" ? incomingToolCall.title : typeof trackedToolCall.title === "string" ? trackedToolCall.title : "Tool",
|
|
1183
|
-
input:
|
|
2019
|
+
input: normalizeApprovalInput3(rawInput),
|
|
1184
2020
|
rawToolCall: incomingToolCall,
|
|
1185
2021
|
toolCall,
|
|
1186
|
-
options:
|
|
2022
|
+
options: parsePermissionOptions2(params.options),
|
|
1187
2023
|
rawParams: params
|
|
1188
2024
|
};
|
|
1189
2025
|
if (this.transportFailure || this.activePrompt?.cancelled) {
|
|
@@ -1200,7 +2036,7 @@ var KimiAcpSession = class {
|
|
|
1200
2036
|
try {
|
|
1201
2037
|
decision = await this.onPermissionRequest(request);
|
|
1202
2038
|
} catch (error) {
|
|
1203
|
-
decision = { behavior: "deny", message:
|
|
2039
|
+
decision = { behavior: "deny", message: toError3(error).message };
|
|
1204
2040
|
}
|
|
1205
2041
|
if (pending.responded) return;
|
|
1206
2042
|
pending.responded = true;
|
|
@@ -1209,8 +2045,8 @@ var KimiAcpSession = class {
|
|
|
1209
2045
|
const explicitOption = requestedOptionId ? request.options.find((candidate) => candidate.optionId === requestedOptionId) : void 0;
|
|
1210
2046
|
const cancelled = decision.cancelled === true || decision.behavior === "cancel";
|
|
1211
2047
|
const behavior = decision.behavior === "allow_once" || decision.behavior === "allow_always" || decision.behavior === "deny" ? decision.behavior : void 0;
|
|
1212
|
-
const validExplicitOption = explicitOption && (!behavior ||
|
|
1213
|
-
const option = cancelled || requestedOptionId || !behavior ? void 0 :
|
|
2048
|
+
const validExplicitOption = explicitOption && (!behavior || optionMatchesBehavior2(explicitOption, behavior)) ? explicitOption : void 0;
|
|
2049
|
+
const option = cancelled || requestedOptionId || !behavior ? void 0 : selectPermissionOption2(request.options, behavior);
|
|
1214
2050
|
const selectedOptionId = cancelled ? void 0 : validExplicitOption?.optionId || option?.optionId;
|
|
1215
2051
|
const outcome = selectedOptionId ? { outcome: "selected", optionId: selectedOptionId } : { outcome: "cancelled" };
|
|
1216
2052
|
if (!this.writeLine({ jsonrpc: "2.0", id, result: { outcome } })) {
|
|
@@ -1266,7 +2102,7 @@ var KimiAcpSession = class {
|
|
|
1266
2102
|
try {
|
|
1267
2103
|
callback();
|
|
1268
2104
|
} catch (error) {
|
|
1269
|
-
this.reportProtocolError(new KimiAcpProtocolError(`${message}: ${
|
|
2105
|
+
this.reportProtocolError(new KimiAcpProtocolError(`${message}: ${toError3(error).message}`));
|
|
1270
2106
|
}
|
|
1271
2107
|
}
|
|
1272
2108
|
reportProtocolError(error, line) {
|
|
@@ -1278,7 +2114,7 @@ var KimiAcpSession = class {
|
|
|
1278
2114
|
}
|
|
1279
2115
|
}
|
|
1280
2116
|
appendStderr(chunk) {
|
|
1281
|
-
this.stderrTail = `${this.stderrTail}${chunk}`.slice(-
|
|
2117
|
+
this.stderrTail = `${this.stderrTail}${chunk}`.slice(-STDERR_TAIL_LIMIT4);
|
|
1282
2118
|
}
|
|
1283
2119
|
resolveSessionReadyOnce(sessionId2) {
|
|
1284
2120
|
if (this.sessionReadySettled) return;
|
|
@@ -1342,7 +2178,7 @@ if (!sessionId || !sockPath) {
|
|
|
1342
2178
|
console.error("Usage: session-worker <sessionId> <socketPath> [-- claudeArgs...]");
|
|
1343
2179
|
process.exit(1);
|
|
1344
2180
|
}
|
|
1345
|
-
if (providerArg !== "claude" && providerArg !== "codex" && providerArg !== "kimi") {
|
|
2181
|
+
if (providerArg !== "claude" && providerArg !== "codex" && providerArg !== "kimi" && providerArg !== "cursor") {
|
|
1346
2182
|
console.error(
|
|
1347
2183
|
providerArg === void 0 ? "JSON worker provider is required" : `Unsupported JSON worker provider: ${providerArg}`
|
|
1348
2184
|
);
|
|
@@ -1362,13 +2198,18 @@ var latestKimiCommandEvent = null;
|
|
|
1362
2198
|
var readyMessage = null;
|
|
1363
2199
|
var providerReady = false;
|
|
1364
2200
|
var exiting = false;
|
|
1365
|
-
var
|
|
2201
|
+
var acpTurnActive = false;
|
|
1366
2202
|
var seqCounter = new SeqCounter(sessionId);
|
|
1367
2203
|
var whitelist = new ToolWhitelist();
|
|
1368
2204
|
var nextApprovalRequestId = createApprovalRequestIdFactory(sessionId);
|
|
1369
2205
|
var pendingApprovals = /* @__PURE__ */ new Map();
|
|
2206
|
+
function isAcpProvider(value) {
|
|
2207
|
+
return value === "kimi" || value === "cursor";
|
|
2208
|
+
}
|
|
1370
2209
|
function isKimiCommandEvent(msg) {
|
|
1371
|
-
if (msg.type !== "worker_event" || msg.event.type !== "kimi_acp")
|
|
2210
|
+
if (msg.type !== "worker_event" || msg.event.type !== "kimi_acp" && msg.event.type !== "cursor_acp") {
|
|
2211
|
+
return false;
|
|
2212
|
+
}
|
|
1372
2213
|
const params = msg.event.params;
|
|
1373
2214
|
if (!params || typeof params !== "object" || Array.isArray(params)) return false;
|
|
1374
2215
|
const update = params.update;
|
|
@@ -1412,7 +2253,7 @@ function replayServeState(socket) {
|
|
|
1412
2253
|
const queuedKimiTurnStart = queuedServeMessages.some(
|
|
1413
2254
|
(message) => message.type === "worker_turn_started"
|
|
1414
2255
|
);
|
|
1415
|
-
if (provider
|
|
2256
|
+
if (isAcpProvider(provider) && acpTurnActive && !queuedKimiTurnStart) {
|
|
1416
2257
|
socket.write(serializeWorkerMsg({ type: "worker_turn_started" }));
|
|
1417
2258
|
}
|
|
1418
2259
|
flushQueuedServeMessages();
|
|
@@ -1426,21 +2267,23 @@ function replayServeState(socket) {
|
|
|
1426
2267
|
requestId,
|
|
1427
2268
|
toolName: pending.toolName,
|
|
1428
2269
|
input: pending.input,
|
|
1429
|
-
...pending.options ? { options: pending.options } : {}
|
|
2270
|
+
...pending.options ? { options: pending.options } : {},
|
|
2271
|
+
...pending.cursorPrompt ? { cursorPrompt: pending.cursorPrompt } : {}
|
|
1430
2272
|
})
|
|
1431
2273
|
);
|
|
1432
2274
|
}
|
|
1433
2275
|
}
|
|
1434
|
-
var forwardToRelay = async (toolName, input, options) => {
|
|
2276
|
+
var forwardToRelay = async (toolName, input, options, cursorPrompt) => {
|
|
1435
2277
|
return new Promise((resolve) => {
|
|
1436
2278
|
const requestId = nextApprovalRequestId();
|
|
1437
|
-
pendingApprovals.set(requestId, { resolve, toolName, input, options });
|
|
2279
|
+
pendingApprovals.set(requestId, { resolve, toolName, input, options, cursorPrompt });
|
|
1438
2280
|
sendToServe({
|
|
1439
2281
|
type: "worker_approval_request",
|
|
1440
2282
|
requestId,
|
|
1441
2283
|
toolName,
|
|
1442
2284
|
input,
|
|
1443
|
-
...options ? { options } : {}
|
|
2285
|
+
...options ? { options } : {},
|
|
2286
|
+
...cursorPrompt ? { cursorPrompt } : {}
|
|
1444
2287
|
});
|
|
1445
2288
|
});
|
|
1446
2289
|
};
|
|
@@ -1463,12 +2306,16 @@ function handleProviderEvent(event) {
|
|
|
1463
2306
|
function handleKimiEvent(method, params) {
|
|
1464
2307
|
handleProviderEvent({ type: "kimi_acp", method, params });
|
|
1465
2308
|
}
|
|
2309
|
+
function handleCursorEvent(method, params) {
|
|
2310
|
+
handleProviderEvent({ type: "cursor_acp", method, params });
|
|
2311
|
+
}
|
|
1466
2312
|
function workerApprovalOptions(options) {
|
|
1467
2313
|
return options.flatMap((option) => {
|
|
1468
|
-
|
|
2314
|
+
const kind = option.kind.replace(/-/g, "_");
|
|
2315
|
+
if (kind !== "allow_once" && kind !== "allow_always" && kind !== "reject_once" && kind !== "reject_always") {
|
|
1469
2316
|
return [];
|
|
1470
2317
|
}
|
|
1471
|
-
return [{ optionId: option.optionId, name: option.name, kind
|
|
2318
|
+
return [{ optionId: option.optionId, name: option.name, kind }];
|
|
1472
2319
|
});
|
|
1473
2320
|
}
|
|
1474
2321
|
async function handleKimiPermissionRequest(request) {
|
|
@@ -1486,10 +2333,47 @@ async function handleKimiPermissionRequest(request) {
|
|
|
1486
2333
|
...decision.optionId ? { optionId: decision.optionId } : {}
|
|
1487
2334
|
};
|
|
1488
2335
|
}
|
|
2336
|
+
async function handleCursorPermissionRequest(request) {
|
|
2337
|
+
if (whitelist.has(request.toolName)) return { behavior: "allow_always" };
|
|
2338
|
+
const options = workerApprovalOptions(request.options);
|
|
2339
|
+
const decision = await forwardToRelay(
|
|
2340
|
+
request.toolName,
|
|
2341
|
+
request.input,
|
|
2342
|
+
options.length > 0 ? options : void 0
|
|
2343
|
+
);
|
|
2344
|
+
if (decision.cancelled) return { cancelled: true };
|
|
2345
|
+
return {
|
|
2346
|
+
behavior: decision.behavior === "deny" ? "deny" : decision.remember ? "allow_always" : "allow_once",
|
|
2347
|
+
...decision.message ? { message: decision.message } : {},
|
|
2348
|
+
...decision.optionId ? { optionId: decision.optionId } : {}
|
|
2349
|
+
};
|
|
2350
|
+
}
|
|
2351
|
+
async function handleCursorExtensionRequest(request) {
|
|
2352
|
+
const toolName = request.prompt.type === "ask_question" ? "AskQuestion" : "CreatePlan";
|
|
2353
|
+
const decision = await forwardToRelay(toolName, {}, void 0, request.prompt);
|
|
2354
|
+
if (decision.cancelled) return { cancelled: true };
|
|
2355
|
+
if (decision.cursorAnswer) return { answer: decision.cursorAnswer };
|
|
2356
|
+
if (request.prompt.type === "create_plan") {
|
|
2357
|
+
return {
|
|
2358
|
+
answer: {
|
|
2359
|
+
type: "create_plan",
|
|
2360
|
+
outcome: decision.behavior === "deny" ? "rejected" : "accepted",
|
|
2361
|
+
...decision.message ? { reason: decision.message } : {}
|
|
2362
|
+
}
|
|
2363
|
+
};
|
|
2364
|
+
}
|
|
2365
|
+
return {
|
|
2366
|
+
answer: {
|
|
2367
|
+
type: "ask_question",
|
|
2368
|
+
outcome: decision.behavior === "deny" ? "skipped" : "cancelled",
|
|
2369
|
+
...decision.message ? { reason: decision.message } : {}
|
|
2370
|
+
}
|
|
2371
|
+
};
|
|
2372
|
+
}
|
|
1489
2373
|
function handleProviderExit(code) {
|
|
1490
2374
|
if (exiting) return;
|
|
1491
2375
|
exiting = true;
|
|
1492
|
-
|
|
2376
|
+
acpTurnActive = false;
|
|
1493
2377
|
whitelist.clear();
|
|
1494
2378
|
const errorTail = code === 0 ? "" : sanitizeProviderErrorTail(session.getStderr());
|
|
1495
2379
|
sendToServe({
|
|
@@ -1521,15 +2405,15 @@ var session = provider === "codex" ? new CodexAppServerSession({
|
|
|
1521
2405
|
onUpdate: (params) => handleKimiEvent("session/update", params),
|
|
1522
2406
|
onPermissionRequest: handleKimiPermissionRequest,
|
|
1523
2407
|
onPromptStart: () => {
|
|
1524
|
-
|
|
2408
|
+
acpTurnActive = true;
|
|
1525
2409
|
sendToServe({ type: "worker_turn_started" });
|
|
1526
2410
|
},
|
|
1527
2411
|
onPromptComplete: (result) => {
|
|
1528
|
-
|
|
2412
|
+
acpTurnActive = false;
|
|
1529
2413
|
handleKimiEvent("session/prompt/result", { response: result });
|
|
1530
2414
|
},
|
|
1531
2415
|
onPromptError: (error) => {
|
|
1532
|
-
|
|
2416
|
+
acpTurnActive = false;
|
|
1533
2417
|
handleKimiEvent("session/prompt/error", {
|
|
1534
2418
|
message: sanitizeProviderErrorTail(error.message) || "Kimi ACP prompt failed"
|
|
1535
2419
|
});
|
|
@@ -1544,6 +2428,40 @@ var session = provider === "codex" ? new CodexAppServerSession({
|
|
|
1544
2428
|
onProtocolError: (error) => console.error(`[worker] ${error.message}`),
|
|
1545
2429
|
onProcessError: (error) => console.error(`[worker] ${error.message}`),
|
|
1546
2430
|
onExit: handleProviderExit
|
|
2431
|
+
}) : provider === "cursor" ? new CursorAcpSession({
|
|
2432
|
+
cwd: workerCwd,
|
|
2433
|
+
resumeSessionId: workerResume,
|
|
2434
|
+
permissionMode: workerPermissionMode,
|
|
2435
|
+
onUpdate: (params) => handleCursorEvent("session/update", params),
|
|
2436
|
+
onNotification: (method, params) => {
|
|
2437
|
+
if (method !== "session/update") handleCursorEvent(method, params);
|
|
2438
|
+
},
|
|
2439
|
+
onPermissionRequest: handleCursorPermissionRequest,
|
|
2440
|
+
onExtensionRequest: handleCursorExtensionRequest,
|
|
2441
|
+
onPromptStart: () => {
|
|
2442
|
+
acpTurnActive = true;
|
|
2443
|
+
sendToServe({ type: "worker_turn_started" });
|
|
2444
|
+
},
|
|
2445
|
+
onPromptComplete: (result) => {
|
|
2446
|
+
acpTurnActive = false;
|
|
2447
|
+
handleCursorEvent("session/prompt/result", { response: result });
|
|
2448
|
+
},
|
|
2449
|
+
onPromptError: (error) => {
|
|
2450
|
+
acpTurnActive = false;
|
|
2451
|
+
handleCursorEvent("session/prompt/error", {
|
|
2452
|
+
message: sanitizeProviderErrorTail(error.message) || "Cursor ACP prompt failed"
|
|
2453
|
+
});
|
|
2454
|
+
},
|
|
2455
|
+
onSessionId: (cursorSessionId) => {
|
|
2456
|
+
sendToServe({
|
|
2457
|
+
type: "worker_native_session_id",
|
|
2458
|
+
provider: "cursor",
|
|
2459
|
+
sessionId: cursorSessionId
|
|
2460
|
+
});
|
|
2461
|
+
},
|
|
2462
|
+
onProtocolError: (error) => console.error(`[worker] ${error.message}`),
|
|
2463
|
+
onProcessError: (error) => console.error(`[worker] ${error.message}`),
|
|
2464
|
+
onExit: handleProviderExit
|
|
1547
2465
|
}) : new JsonSession({
|
|
1548
2466
|
claudeArgs: providerArgs,
|
|
1549
2467
|
cwd: workerCwd,
|
|
@@ -1584,14 +2502,14 @@ function handleServeConnection(socket) {
|
|
|
1584
2502
|
session.sendMessage(msg.content);
|
|
1585
2503
|
break;
|
|
1586
2504
|
case "worker_interrupt":
|
|
1587
|
-
if (provider
|
|
2505
|
+
if (isAcpProvider(provider)) {
|
|
1588
2506
|
void session.interruptCurrentTurn().then((interrupted) => {
|
|
1589
2507
|
if (interrupted) {
|
|
1590
|
-
|
|
2508
|
+
acpTurnActive = false;
|
|
1591
2509
|
rejectAllPendingApprovals("Turn interrupted", true);
|
|
1592
2510
|
sendToServe({ type: "worker_interrupted" });
|
|
1593
2511
|
} else {
|
|
1594
|
-
console.error(
|
|
2512
|
+
console.error(`[worker] interrupt requested but ${provider} had no active turn`);
|
|
1595
2513
|
}
|
|
1596
2514
|
});
|
|
1597
2515
|
} else {
|
|
@@ -1612,7 +2530,8 @@ function handleServeConnection(socket) {
|
|
|
1612
2530
|
behavior: msg.behavior,
|
|
1613
2531
|
...msg.message ? { message: msg.message } : {},
|
|
1614
2532
|
...msg.remember ? { remember: true } : {},
|
|
1615
|
-
...msg.optionId ? { optionId: msg.optionId } : {}
|
|
2533
|
+
...msg.optionId ? { optionId: msg.optionId } : {},
|
|
2534
|
+
...msg.cursorAnswer ? { cursorAnswer: msg.cursorAnswer } : {}
|
|
1616
2535
|
});
|
|
1617
2536
|
pendingApprovals.delete(msg.requestId);
|
|
1618
2537
|
}
|
|
@@ -1719,6 +2638,25 @@ ${session.getStderr()}`) || "Kimi ACP \u521D\u59CB\u5316\u5931\u8D25";
|
|
|
1719
2638
|
console.error(`[worker] Kimi ACP failed to initialize: ${diagnostic}`);
|
|
1720
2639
|
void session.stop(0).finally(() => handleProviderExit(1));
|
|
1721
2640
|
});
|
|
2641
|
+
} else if (provider === "cursor" && session instanceof CursorAcpSession) {
|
|
2642
|
+
void session.waitUntilReady().then((cursorSessionId) => {
|
|
2643
|
+
reportReady({
|
|
2644
|
+
type: "worker_ready",
|
|
2645
|
+
pid,
|
|
2646
|
+
nativeSession: { provider: "cursor", sessionId: cursorSessionId }
|
|
2647
|
+
});
|
|
2648
|
+
}).catch((err) => {
|
|
2649
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
2650
|
+
const diagnostic = sanitizeProviderErrorTail(`${message}
|
|
2651
|
+
${session.getStderr()}`) || "Cursor ACP \u521D\u59CB\u5316\u5931\u8D25";
|
|
2652
|
+
sendToServe({
|
|
2653
|
+
type: "worker_startup_error",
|
|
2654
|
+
provider: "cursor",
|
|
2655
|
+
message: diagnostic
|
|
2656
|
+
});
|
|
2657
|
+
console.error(`[worker] Cursor ACP failed to initialize: ${diagnostic}`);
|
|
2658
|
+
void session.stop(0).finally(() => handleProviderExit(1));
|
|
2659
|
+
});
|
|
1722
2660
|
} else {
|
|
1723
2661
|
reportReady({ type: "worker_ready", pid });
|
|
1724
2662
|
}
|