@dev-anywhere/proxy 0.7.0 → 0.8.1

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.
Files changed (44) hide show
  1. package/README.md +23 -4
  2. package/dist/{chunk-6D4UN567.js → chunk-2FVY2JAS.js} +1 -1
  3. package/dist/chunk-2FVY2JAS.js.map +1 -0
  4. package/dist/{chunk-SOBI2VPD.js → chunk-43VZTEDR.js} +2 -2
  5. package/dist/{chunk-WX3ZHKAW.js → chunk-AQPTQ44T.js} +84 -3
  6. package/dist/chunk-AQPTQ44T.js.map +1 -0
  7. package/dist/{chunk-QM6EGEYM.js → chunk-FJHCP2HS.js} +4 -3
  8. package/dist/chunk-FJHCP2HS.js.map +1 -0
  9. package/dist/{chunk-S52EXNTW.js → chunk-HIZNGFB5.js} +2 -2
  10. package/dist/chunk-HIZNGFB5.js.map +1 -0
  11. package/dist/{chunk-YB72FEQG.js → chunk-JU6MVCCD.js} +67 -22
  12. package/dist/chunk-JU6MVCCD.js.map +1 -0
  13. package/dist/{chunk-3HKHB7MD.js → chunk-MSIZBFLV.js} +31 -9
  14. package/dist/chunk-MSIZBFLV.js.map +1 -0
  15. package/dist/{chunk-JMAOONB2.js → chunk-OWPHJ5LA.js} +2 -2
  16. package/dist/{chunk-RM7QJPMR.js → chunk-T2RI7YUO.js} +5 -5
  17. package/dist/{chunk-CN7UT6KW.js → chunk-WC3KEY7N.js} +16 -1
  18. package/dist/chunk-WC3KEY7N.js.map +1 -0
  19. package/dist/index.js +203 -18
  20. package/dist/index.js.map +1 -1
  21. package/dist/{quick-tunnel-P2EMAYTU.js → quick-tunnel-C2WILO6I.js} +2 -2
  22. package/dist/{relay-token-YW37VD4D.js → relay-token-V6EA4HPM.js} +5 -5
  23. package/dist/serve.js +683 -77
  24. package/dist/serve.js.map +1 -1
  25. package/dist/session-worker.js +764 -23
  26. package/dist/session-worker.js.map +1 -1
  27. package/dist/{terminal-JLLMGMXN.js → terminal-NWKJTN2R.js} +15 -12
  28. package/dist/terminal-NWKJTN2R.js.map +1 -0
  29. package/dist/terminal-worker.js +7 -7
  30. package/dist/update-runner.js +3 -3
  31. package/package.json +4 -3
  32. package/dist/chunk-3HKHB7MD.js.map +0 -1
  33. package/dist/chunk-6D4UN567.js.map +0 -1
  34. package/dist/chunk-CN7UT6KW.js.map +0 -1
  35. package/dist/chunk-QM6EGEYM.js.map +0 -1
  36. package/dist/chunk-S52EXNTW.js.map +0 -1
  37. package/dist/chunk-WX3ZHKAW.js.map +0 -1
  38. package/dist/chunk-YB72FEQG.js.map +0 -1
  39. package/dist/terminal-JLLMGMXN.js.map +0 -1
  40. /package/dist/{chunk-SOBI2VPD.js.map → chunk-43VZTEDR.js.map} +0 -0
  41. /package/dist/{chunk-JMAOONB2.js.map → chunk-OWPHJ5LA.js.map} +0 -0
  42. /package/dist/{chunk-RM7QJPMR.js.map → chunk-T2RI7YUO.js.map} +0 -0
  43. /package/dist/{quick-tunnel-P2EMAYTU.js.map → quick-tunnel-C2WILO6I.js.map} +0 -0
  44. /package/dist/{relay-token-YW37VD4D.js.map → relay-token-V6EA4HPM.js.map} +0 -0
@@ -3,24 +3,29 @@ import {
3
3
  ControlRequestEventSchema,
4
4
  SeqCounter,
5
5
  createApprovalRequestIdFactory
6
- } from "./chunk-SOBI2VPD.js";
6
+ } from "./chunk-43VZTEDR.js";
7
+ import {
8
+ PROXY_VERSION
9
+ } from "./chunk-EGNWMOPC.js";
7
10
  import {
8
11
  CLAUDE_PROVIDER,
9
12
  CODEX_PROVIDER,
10
- resolveCodexPermissionPolicy
11
- } from "./chunk-WX3ZHKAW.js";
13
+ KIMI_PROVIDER,
14
+ resolveCodexPermissionPolicy,
15
+ resolveKimiAcpMode
16
+ } from "./chunk-AQPTQ44T.js";
12
17
  import {
13
18
  ControlErrorCode,
14
19
  LineBuffer,
15
20
  createWorkerReader,
16
21
  serializeWorkerMsg
17
- } from "./chunk-YB72FEQG.js";
22
+ } from "./chunk-JU6MVCCD.js";
18
23
  import {
19
24
  classifyCodexActiveWriterError,
20
25
  sanitizeProviderErrorTail
21
26
  } from "./chunk-J5V2TKSV.js";
22
27
  import "./chunk-NQDJ6QAM.js";
23
- import "./chunk-S52EXNTW.js";
28
+ import "./chunk-HIZNGFB5.js";
24
29
 
25
30
  // src/session-worker.ts
26
31
  import { createServer } from "net";
@@ -675,6 +680,612 @@ function toError(err) {
675
680
  return err instanceof Error ? err : new Error(String(err));
676
681
  }
677
682
 
683
+ // src/worker/kimi-acp-session.ts
684
+ import { spawn as spawn3 } from "child_process";
685
+ var CLIENT_INFO2 = {
686
+ name: "dev-anywhere",
687
+ title: "Dev Anywhere",
688
+ version: PROXY_VERSION
689
+ };
690
+ var DEFAULT_REQUEST_TIMEOUT_MS2 = 1e4;
691
+ var DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS = 2e3;
692
+ var STDERR_TAIL_LIMIT3 = 8192;
693
+ var CANCELLED_RESPONSE_TOMBSTONE_LIMIT = 128;
694
+ var denyPermission = () => ({
695
+ behavior: "deny",
696
+ message: "Tool use denied by default policy. Remote approval is not configured."
697
+ });
698
+ function isRecord2(value) {
699
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
700
+ }
701
+ function toError2(error) {
702
+ return error instanceof Error ? error : new Error(String(error));
703
+ }
704
+ function normalizeApprovalInput2(value) {
705
+ if (!isRecord2(value)) return {};
706
+ const input = { ...value };
707
+ if (Array.isArray(input.command)) {
708
+ input.command = input.command.map((part) => String(part)).join(" ");
709
+ }
710
+ return input;
711
+ }
712
+ function parsePermissionOptions(value) {
713
+ if (!Array.isArray(value)) return [];
714
+ const options = [];
715
+ for (const candidate of value) {
716
+ if (!isRecord2(candidate) || typeof candidate.optionId !== "string") continue;
717
+ options.push({
718
+ ...candidate,
719
+ optionId: candidate.optionId,
720
+ name: typeof candidate.name === "string" ? candidate.name : candidate.optionId,
721
+ kind: typeof candidate.kind === "string" ? candidate.kind : ""
722
+ });
723
+ }
724
+ return options;
725
+ }
726
+ function normalizedOptionText(option) {
727
+ return `${option.optionId} ${option.name}`.toLowerCase().replace(/[^a-z0-9]+/g, " ");
728
+ }
729
+ function isAllowOption(option) {
730
+ const text = normalizedOptionText(option);
731
+ return option.kind.startsWith("allow") || /\b(allow|approve|accept)\b/.test(text);
732
+ }
733
+ function isAlwaysOption(option) {
734
+ const text = normalizedOptionText(option);
735
+ return option.kind === "allow_always" || /\b(always|session|persist)\b/.test(text);
736
+ }
737
+ function isDenyOption(option) {
738
+ const text = normalizedOptionText(option);
739
+ return option.kind.startsWith("reject") || /\b(reject|deny|decline|cancel|skip)\b/.test(text);
740
+ }
741
+ function optionMatchesBehavior(option, behavior) {
742
+ if (behavior === "deny") return isDenyOption(option);
743
+ if (behavior === "allow_always") {
744
+ return isAllowOption(option) && isAlwaysOption(option);
745
+ }
746
+ return isAllowOption(option) && !isAlwaysOption(option);
747
+ }
748
+ function selectPermissionOption(options, behavior) {
749
+ if (behavior === "deny") {
750
+ return options.find((option) => option.kind.startsWith("reject")) ?? options.find(isDenyOption);
751
+ }
752
+ if (behavior === "allow_always") {
753
+ return options.find((option) => option.kind === "allow_always") ?? options.find((option) => isAllowOption(option) && isAlwaysOption(option)) ?? // Never upgrade a one-shot decision, but safely downgrade a persistent allow when the
754
+ // provider only advertises allow-once.
755
+ options.find((option) => option.kind === "allow_once") ?? options.find((option) => isAllowOption(option) && !isAlwaysOption(option));
756
+ }
757
+ return options.find((option) => option.kind === "allow_once") ?? options.find((option) => isAllowOption(option) && !isAlwaysOption(option));
758
+ }
759
+ function promptResult(value) {
760
+ return isRecord2(value) ? value : {};
761
+ }
762
+ function responseErrorMessage(error) {
763
+ return typeof error.message === "string" ? error.message : "Kimi ACP request failed";
764
+ }
765
+ var KimiAcpRpcError = class extends Error {
766
+ constructor(method, code, message, data) {
767
+ super(`Kimi ACP ${method} failed${code === void 0 ? "" : ` (${code})`}: ${message}`);
768
+ this.method = method;
769
+ this.code = code;
770
+ this.data = data;
771
+ this.name = "KimiAcpRpcError";
772
+ }
773
+ method;
774
+ code;
775
+ data;
776
+ };
777
+ var KimiAcpProtocolError = class extends Error {
778
+ constructor(message, payload) {
779
+ super(message);
780
+ this.payload = payload;
781
+ this.name = "KimiAcpProtocolError";
782
+ }
783
+ payload;
784
+ };
785
+ var KimiAcpSession = class {
786
+ child = null;
787
+ stderrTail = "";
788
+ nextRequestId = 1;
789
+ pendingRequests = /* @__PURE__ */ new Map();
790
+ pendingPermissions = /* @__PURE__ */ new Map();
791
+ cancelledResponseIds = /* @__PURE__ */ new Set();
792
+ toolCalls = /* @__PURE__ */ new Map();
793
+ sessionReady;
794
+ resolveSessionReady = () => {
795
+ };
796
+ rejectSessionReady = () => {
797
+ };
798
+ sessionReadySettled = false;
799
+ exitReported = false;
800
+ closed = false;
801
+ transportFailure = null;
802
+ sessionId = null;
803
+ activePrompt = null;
804
+ promptQueue = Promise.resolve();
805
+ workDir;
806
+ resumeSessionId;
807
+ acpMode;
808
+ requestTimeoutMs;
809
+ promptTimeoutMs;
810
+ cancelAcknowledgeTimeoutMs;
811
+ onUpdate;
812
+ onNotification;
813
+ onPermissionRequest;
814
+ onPromptStart;
815
+ onPromptComplete;
816
+ onPromptError;
817
+ onSessionId;
818
+ onProtocolError;
819
+ onProcessError;
820
+ onExitCb;
821
+ constructor(options = {}) {
822
+ this.workDir = options.cwd ?? options.workDir ?? process.cwd();
823
+ this.resumeSessionId = options.resumeSessionId;
824
+ this.acpMode = resolveKimiAcpMode(options.permissionMode);
825
+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS2;
826
+ this.promptTimeoutMs = options.promptTimeoutMs ?? 0;
827
+ this.cancelAcknowledgeTimeoutMs = options.cancelAcknowledgeTimeoutMs ?? DEFAULT_CANCEL_ACKNOWLEDGE_TIMEOUT_MS;
828
+ this.onUpdate = options.onUpdate;
829
+ this.onNotification = options.onNotification;
830
+ this.onPermissionRequest = options.onPermissionRequest ?? denyPermission;
831
+ this.onPromptStart = options.onPromptStart;
832
+ this.onPromptComplete = options.onPromptComplete;
833
+ this.onPromptError = options.onPromptError;
834
+ this.onSessionId = options.onSessionId;
835
+ this.onProtocolError = options.onProtocolError;
836
+ this.onProcessError = options.onProcessError;
837
+ this.onExitCb = options.onExit;
838
+ this.sessionReady = new Promise((resolve, reject) => {
839
+ this.resolveSessionReady = resolve;
840
+ this.rejectSessionReady = reject;
841
+ });
842
+ }
843
+ getKimiSessionId() {
844
+ return this.sessionId;
845
+ }
846
+ getPendingPermission(requestId) {
847
+ return this.pendingPermissions.get(requestId)?.request;
848
+ }
849
+ start() {
850
+ if (this.child) throw new Error("Kimi ACP session has already been started");
851
+ const command = KIMI_PROVIDER.buildJsonCommand({}, process.env);
852
+ this.child = spawn3(command.command, command.args, {
853
+ cwd: this.workDir,
854
+ stdio: ["pipe", "pipe", "pipe"],
855
+ env: command.env
856
+ });
857
+ this.setupStdoutParsing();
858
+ this.setupStderrCollection();
859
+ this.setupExitHandler();
860
+ void this.initializeSession().catch((error) => this.rejectSessionReadyOnce(toError2(error)));
861
+ if (!this.child.pid) throw new Error("Kimi ACP failed to start: missing child pid");
862
+ return this.child.pid;
863
+ }
864
+ waitUntilReady() {
865
+ return this.sessionReady;
866
+ }
867
+ sendMessage(content) {
868
+ this.promptQueue = this.promptQueue.then(() => this.runPrompt(content));
869
+ }
870
+ async interruptCurrentTurn() {
871
+ const activePrompt = this.activePrompt;
872
+ if (!activePrompt || activePrompt.cancelled || !this.sessionId) return false;
873
+ activePrompt.cancelled = true;
874
+ if (!this.writeLine({
875
+ jsonrpc: "2.0",
876
+ method: "session/cancel",
877
+ params: { sessionId: this.sessionId }
878
+ })) {
879
+ activePrompt.cancelled = false;
880
+ return false;
881
+ }
882
+ this.cancelPendingPermissions();
883
+ if (this.cancelAcknowledgeTimeoutMs <= 0) {
884
+ this.abortUnacknowledgedCancellation(activePrompt);
885
+ } else {
886
+ activePrompt.cancelSettleTimer = setTimeout(
887
+ () => this.abortUnacknowledgedCancellation(activePrompt),
888
+ this.cancelAcknowledgeTimeoutMs
889
+ );
890
+ activePrompt.cancelSettleTimer.unref?.();
891
+ }
892
+ return true;
893
+ }
894
+ async close() {
895
+ if (this.closed) return;
896
+ if (!this.child) throw new Error("Kimi ACP session has not been started");
897
+ const sessionId2 = this.sessionId ?? await this.sessionReady;
898
+ await this.request("session/close", { sessionId: sessionId2 });
899
+ this.closed = true;
900
+ }
901
+ async stop(gracePeriodMs = 5e3) {
902
+ const child = this.child;
903
+ if (!child || !this.isAlive()) return;
904
+ if (this.activePrompt) await this.interruptCurrentTurn();
905
+ if (this.sessionId && !this.closed) {
906
+ try {
907
+ await this.close();
908
+ } catch (error) {
909
+ this.appendStderr(`Kimi ACP close failed: ${toError2(error).message}
910
+ `);
911
+ }
912
+ }
913
+ child.kill("SIGTERM");
914
+ const startedAt = Date.now();
915
+ while (Date.now() - startedAt < gracePeriodMs) {
916
+ if (!this.isChildAlive(child)) return;
917
+ await new Promise((resolve) => setTimeout(resolve, 200));
918
+ }
919
+ if (this.isChildAlive(child)) child.kill("SIGKILL");
920
+ }
921
+ isAlive() {
922
+ return this.child ? this.isChildAlive(this.child) : false;
923
+ }
924
+ getStderr() {
925
+ return this.stderrTail;
926
+ }
927
+ isChildAlive(child) {
928
+ if (!child.pid) return false;
929
+ try {
930
+ process.kill(child.pid, 0);
931
+ return true;
932
+ } catch {
933
+ return false;
934
+ }
935
+ }
936
+ async initializeSession() {
937
+ await this.request("initialize", {
938
+ protocolVersion: 1,
939
+ clientCapabilities: {
940
+ fs: { readTextFile: false, writeTextFile: false },
941
+ terminal: false
942
+ },
943
+ clientInfo: CLIENT_INFO2
944
+ });
945
+ const result = this.resumeSessionId ? await this.request("session/resume", {
946
+ sessionId: this.resumeSessionId,
947
+ cwd: this.workDir,
948
+ mcpServers: []
949
+ }) : await this.request("session/new", {
950
+ cwd: this.workDir,
951
+ mcpServers: []
952
+ });
953
+ const sessionId2 = this.resumeSessionId ?? this.sessionIdFromResult(result);
954
+ if (!sessionId2) throw new Error("Kimi ACP session/new did not return a session id");
955
+ await this.request("session/set_mode", { sessionId: sessionId2, modeId: this.acpMode });
956
+ this.sessionId = sessionId2;
957
+ this.onSessionId?.(sessionId2);
958
+ this.resolveSessionReadyOnce(sessionId2);
959
+ }
960
+ sessionIdFromResult(result) {
961
+ if (!isRecord2(result)) return null;
962
+ return typeof result.sessionId === "string" ? result.sessionId : null;
963
+ }
964
+ async runPrompt(content) {
965
+ let prompt = null;
966
+ try {
967
+ const sessionId2 = await this.sessionReady;
968
+ if (this.transportFailure) throw this.transportFailure;
969
+ const currentPrompt = { cancelled: false };
970
+ prompt = currentPrompt;
971
+ this.activePrompt = currentPrompt;
972
+ this.invokeCallback(() => this.onPromptStart?.(), "session/prompt start callback failed");
973
+ const result = await this.request(
974
+ "session/prompt",
975
+ {
976
+ sessionId: sessionId2,
977
+ prompt: [{ type: "text", text: content }]
978
+ },
979
+ this.promptTimeoutMs,
980
+ (requestId) => {
981
+ if (this.activePrompt === currentPrompt) currentPrompt.requestId = requestId;
982
+ }
983
+ );
984
+ if (!prompt.cancelled) {
985
+ this.invokeCallback(
986
+ () => this.onPromptComplete?.(promptResult(result)),
987
+ "session/prompt completion callback failed"
988
+ );
989
+ }
990
+ } catch (error) {
991
+ if (!prompt?.cancelled) {
992
+ this.invokeCallback(
993
+ () => this.onPromptError?.(toError2(error)),
994
+ "session/prompt error callback failed"
995
+ );
996
+ }
997
+ } finally {
998
+ if (prompt?.cancelSettleTimer) clearTimeout(prompt.cancelSettleTimer);
999
+ if (this.activePrompt === prompt) this.activePrompt = null;
1000
+ this.toolCalls.clear();
1001
+ }
1002
+ }
1003
+ request(method, params, timeoutMs = this.requestTimeoutMs, onRequestId) {
1004
+ const id = this.nextRequestId++;
1005
+ onRequestId?.(id);
1006
+ const payload = { jsonrpc: "2.0", id, method, params };
1007
+ return new Promise((resolve, reject) => {
1008
+ const timeout = timeoutMs > 0 ? setTimeout(() => {
1009
+ this.pendingRequests.delete(id);
1010
+ reject(new Error(`Kimi ACP request ${method} timed out after ${timeoutMs}ms`));
1011
+ }, timeoutMs) : void 0;
1012
+ timeout?.unref?.();
1013
+ this.pendingRequests.set(id, { method, resolve, reject, timeout });
1014
+ if (!this.writeLine(payload)) {
1015
+ if (timeout) clearTimeout(timeout);
1016
+ this.pendingRequests.delete(id);
1017
+ reject(new Error(`Kimi ACP stdin is not writable for ${method}`));
1018
+ }
1019
+ });
1020
+ }
1021
+ writeLine(payload) {
1022
+ if (this.transportFailure || !this.child?.stdin?.writable) return false;
1023
+ try {
1024
+ this.child.stdin.write(`${JSON.stringify(payload)}
1025
+ `);
1026
+ return true;
1027
+ } catch (error) {
1028
+ this.reportProtocolError(new KimiAcpProtocolError("Failed to write Kimi ACP message", error));
1029
+ return false;
1030
+ }
1031
+ }
1032
+ setupStdoutParsing() {
1033
+ const child = this.child;
1034
+ if (!child?.stdout) return;
1035
+ const lineBuffer = new LineBuffer();
1036
+ child.stdout.pipe(lineBuffer);
1037
+ lineBuffer.on("data", (line) => {
1038
+ const text = typeof line === "string" ? line : line.toString();
1039
+ let message;
1040
+ try {
1041
+ message = JSON.parse(text);
1042
+ } catch (error) {
1043
+ this.reportProtocolError(
1044
+ new KimiAcpProtocolError(`Invalid Kimi ACP JSON: ${toError2(error).message}`, text),
1045
+ text
1046
+ );
1047
+ return;
1048
+ }
1049
+ this.handleAcpMessage(message);
1050
+ });
1051
+ }
1052
+ handleAcpMessage(message) {
1053
+ if (!isRecord2(message)) {
1054
+ this.reportProtocolError(
1055
+ new KimiAcpProtocolError("Kimi ACP message must be an object", message)
1056
+ );
1057
+ return;
1058
+ }
1059
+ const id = message.id;
1060
+ const method = message.method;
1061
+ if (typeof method === "string" && (typeof id === "string" || typeof id === "number")) {
1062
+ this.handleServerRequest({ id, method, params: message.params });
1063
+ return;
1064
+ }
1065
+ if (typeof method === "string") {
1066
+ this.handleNotification(method, message.params);
1067
+ return;
1068
+ }
1069
+ if (typeof id === "string" || typeof id === "number") {
1070
+ this.handleResponse(id, message);
1071
+ return;
1072
+ }
1073
+ this.reportProtocolError(new KimiAcpProtocolError("Unrecognized Kimi ACP message", message));
1074
+ }
1075
+ handleResponse(id, message) {
1076
+ const pending = this.pendingRequests.get(id);
1077
+ if (!pending) {
1078
+ if (this.cancelledResponseIds.delete(id)) return;
1079
+ this.reportProtocolError(
1080
+ new KimiAcpProtocolError(`Unexpected Kimi ACP response id: ${String(id)}`, message)
1081
+ );
1082
+ return;
1083
+ }
1084
+ this.pendingRequests.delete(id);
1085
+ if (pending.timeout) clearTimeout(pending.timeout);
1086
+ if (isRecord2(message.error)) {
1087
+ pending.reject(
1088
+ new KimiAcpRpcError(
1089
+ pending.method,
1090
+ typeof message.error.code === "number" ? message.error.code : void 0,
1091
+ responseErrorMessage(message.error),
1092
+ message.error.data
1093
+ )
1094
+ );
1095
+ return;
1096
+ }
1097
+ pending.resolve(message.result);
1098
+ }
1099
+ abortUnacknowledgedCancellation(prompt) {
1100
+ const requestId = prompt.requestId;
1101
+ if (requestId === void 0) return;
1102
+ const pending = this.pendingRequests.get(requestId);
1103
+ if (!pending || pending.method !== "session/prompt") return;
1104
+ const error = new Error(
1105
+ `Kimi ACP did not acknowledge session/cancel within ${this.cancelAcknowledgeTimeoutMs}ms; terminating the unsafe transport`
1106
+ );
1107
+ this.transportFailure = error;
1108
+ this.pendingRequests.delete(requestId);
1109
+ if (pending.timeout) clearTimeout(pending.timeout);
1110
+ this.cancelledResponseIds.add(requestId);
1111
+ if (this.cancelledResponseIds.size > CANCELLED_RESPONSE_TOMBSTONE_LIMIT) {
1112
+ const oldest = this.cancelledResponseIds.values().next().value;
1113
+ if (oldest !== void 0) this.cancelledResponseIds.delete(oldest);
1114
+ }
1115
+ this.appendStderr(`${error.message}
1116
+ `);
1117
+ this.cancelPendingPermissions();
1118
+ pending.reject(error);
1119
+ this.child?.kill("SIGKILL");
1120
+ }
1121
+ handleNotification(method, rawParams) {
1122
+ const params = isRecord2(rawParams) ? rawParams : {};
1123
+ if (method === "session/update") {
1124
+ this.trackToolCall(params);
1125
+ this.invokeCallback(() => this.onUpdate?.(params), "session/update callback failed");
1126
+ }
1127
+ this.invokeCallback(
1128
+ () => this.onNotification?.(method, params),
1129
+ `${method} notification callback failed`
1130
+ );
1131
+ }
1132
+ trackToolCall(params) {
1133
+ if (!isRecord2(params.update) || typeof params.update.toolCallId !== "string") return;
1134
+ const previous = this.toolCalls.get(params.update.toolCallId) ?? {};
1135
+ const next = { ...previous, ...params.update };
1136
+ if (next.status === "completed" || next.status === "failed") {
1137
+ this.toolCalls.delete(params.update.toolCallId);
1138
+ return;
1139
+ }
1140
+ this.toolCalls.set(params.update.toolCallId, next);
1141
+ }
1142
+ handleServerRequest(request) {
1143
+ if (request.method === "session/request_permission") {
1144
+ void this.handlePermissionRequest(request.id, request.params);
1145
+ return;
1146
+ }
1147
+ this.writeLine({
1148
+ jsonrpc: "2.0",
1149
+ id: request.id,
1150
+ error: { code: -32601, message: `Unsupported Kimi ACP client request: ${request.method}` }
1151
+ });
1152
+ }
1153
+ async handlePermissionRequest(id, rawParams) {
1154
+ const params = isRecord2(rawParams) ? rawParams : {};
1155
+ const incomingToolCall = isRecord2(params.toolCall) ? params.toolCall : {};
1156
+ const toolCallId = typeof incomingToolCall.toolCallId === "string" ? incomingToolCall.toolCallId : void 0;
1157
+ const trackedToolCall = toolCallId ? this.toolCalls.get(toolCallId) ?? {} : {};
1158
+ const toolCall = { ...trackedToolCall, ...incomingToolCall };
1159
+ const rawInput = isRecord2(incomingToolCall.rawInput) ? incomingToolCall.rawInput : trackedToolCall.rawInput;
1160
+ const request = {
1161
+ requestId: id,
1162
+ sessionId: typeof params.sessionId === "string" ? params.sessionId : this.sessionId ?? "",
1163
+ toolName: typeof incomingToolCall.title === "string" ? incomingToolCall.title : typeof trackedToolCall.title === "string" ? trackedToolCall.title : "Tool",
1164
+ input: normalizeApprovalInput2(rawInput),
1165
+ rawToolCall: incomingToolCall,
1166
+ toolCall,
1167
+ options: parsePermissionOptions(params.options),
1168
+ rawParams: params
1169
+ };
1170
+ if (this.transportFailure || this.activePrompt?.cancelled) {
1171
+ this.writeLine({
1172
+ jsonrpc: "2.0",
1173
+ id,
1174
+ result: { outcome: { outcome: "cancelled" } }
1175
+ });
1176
+ return;
1177
+ }
1178
+ const pending = { request, responded: false };
1179
+ this.pendingPermissions.set(id, pending);
1180
+ let decision;
1181
+ try {
1182
+ decision = await this.onPermissionRequest(request);
1183
+ } catch (error) {
1184
+ decision = { behavior: "deny", message: toError2(error).message };
1185
+ }
1186
+ if (pending.responded) return;
1187
+ pending.responded = true;
1188
+ this.pendingPermissions.delete(id);
1189
+ const requestedOptionId = typeof decision.optionId === "string" && decision.optionId.trim().length > 0 ? decision.optionId : void 0;
1190
+ const explicitOption = requestedOptionId ? request.options.find((candidate) => candidate.optionId === requestedOptionId) : void 0;
1191
+ const cancelled = decision.cancelled === true || decision.behavior === "cancel";
1192
+ const behavior = decision.behavior === "allow_once" || decision.behavior === "allow_always" || decision.behavior === "deny" ? decision.behavior : void 0;
1193
+ const validExplicitOption = explicitOption && (!behavior || optionMatchesBehavior(explicitOption, behavior)) ? explicitOption : void 0;
1194
+ const option = cancelled || requestedOptionId || !behavior ? void 0 : selectPermissionOption(request.options, behavior);
1195
+ const selectedOptionId = cancelled ? void 0 : validExplicitOption?.optionId || option?.optionId;
1196
+ const outcome = selectedOptionId ? { outcome: "selected", optionId: selectedOptionId } : { outcome: "cancelled" };
1197
+ if (!this.writeLine({ jsonrpc: "2.0", id, result: { outcome } })) {
1198
+ this.reportProtocolError(
1199
+ new KimiAcpProtocolError(`Failed to respond to permission request ${String(id)}`)
1200
+ );
1201
+ }
1202
+ }
1203
+ cancelPendingPermissions() {
1204
+ for (const [id, pending] of this.pendingPermissions) {
1205
+ if (pending.responded) continue;
1206
+ pending.responded = true;
1207
+ this.writeLine({
1208
+ jsonrpc: "2.0",
1209
+ id,
1210
+ result: { outcome: { outcome: "cancelled" } }
1211
+ });
1212
+ }
1213
+ this.pendingPermissions.clear();
1214
+ }
1215
+ setupStderrCollection() {
1216
+ const child = this.child;
1217
+ if (!child?.stderr) return;
1218
+ child.stderr.on("data", (chunk) => {
1219
+ this.appendStderr(typeof chunk === "string" ? chunk : chunk.toString());
1220
+ });
1221
+ }
1222
+ setupExitHandler() {
1223
+ const child = this.child;
1224
+ if (!child) return;
1225
+ child.on("error", (error) => {
1226
+ const wrapped = new Error(`Kimi ACP failed to start: ${error.message}`);
1227
+ this.appendStderr(`${wrapped.message}
1228
+ `);
1229
+ this.rejectAllPendingRequests(wrapped);
1230
+ this.rejectSessionReadyOnce(wrapped);
1231
+ this.onProcessError?.(wrapped);
1232
+ this.reportExit(1);
1233
+ });
1234
+ child.on("exit", (code) => {
1235
+ const exitCode = code ?? 1;
1236
+ const error = new Error(
1237
+ this.sessionReadySettled ? `Kimi ACP exited (code ${exitCode})` : `Kimi ACP exited before ready (code ${exitCode})`
1238
+ );
1239
+ this.rejectAllPendingRequests(error);
1240
+ this.pendingPermissions.clear();
1241
+ this.rejectSessionReadyOnce(error);
1242
+ if (exitCode !== 0) this.onProcessError?.(error);
1243
+ this.reportExit(exitCode);
1244
+ });
1245
+ }
1246
+ invokeCallback(callback, message) {
1247
+ try {
1248
+ callback();
1249
+ } catch (error) {
1250
+ this.reportProtocolError(new KimiAcpProtocolError(`${message}: ${toError2(error).message}`));
1251
+ }
1252
+ }
1253
+ reportProtocolError(error, line) {
1254
+ this.appendStderr(`${error.message}
1255
+ `);
1256
+ try {
1257
+ this.onProtocolError?.(error, line);
1258
+ } catch {
1259
+ }
1260
+ }
1261
+ appendStderr(chunk) {
1262
+ this.stderrTail = `${this.stderrTail}${chunk}`.slice(-STDERR_TAIL_LIMIT3);
1263
+ }
1264
+ resolveSessionReadyOnce(sessionId2) {
1265
+ if (this.sessionReadySettled) return;
1266
+ this.sessionReadySettled = true;
1267
+ this.resolveSessionReady(sessionId2);
1268
+ }
1269
+ rejectSessionReadyOnce(error) {
1270
+ if (this.sessionReadySettled) return;
1271
+ this.sessionReadySettled = true;
1272
+ this.rejectSessionReady(error);
1273
+ }
1274
+ rejectAllPendingRequests(error) {
1275
+ for (const pending of this.pendingRequests.values()) {
1276
+ if (pending.timeout) clearTimeout(pending.timeout);
1277
+ pending.reject(error);
1278
+ }
1279
+ this.pendingRequests.clear();
1280
+ this.cancelledResponseIds.clear();
1281
+ }
1282
+ reportExit(code) {
1283
+ if (this.exitReported) return;
1284
+ this.exitReported = true;
1285
+ this.onExitCb?.(code);
1286
+ }
1287
+ };
1288
+
678
1289
  // src/worker/serve-socket-takeover.ts
679
1290
  function takeoverServeSocket(prev, next) {
680
1291
  if (prev && prev !== next) {
@@ -685,6 +1296,11 @@ function takeoverServeSocket(prev, next) {
685
1296
  }
686
1297
  return next;
687
1298
  }
1299
+ function releaseServeSocket(current, closed, onCurrentClosed) {
1300
+ if (current !== closed) return current;
1301
+ onCurrentClosed();
1302
+ return null;
1303
+ }
688
1304
 
689
1305
  // src/session-worker.ts
690
1306
  var sessionId = process.argv[2];
@@ -712,7 +1328,7 @@ if (!sessionId || !sockPath) {
712
1328
  console.error("Usage: session-worker <sessionId> <socketPath> [-- claudeArgs...]");
713
1329
  process.exit(1);
714
1330
  }
715
- if (provider !== "claude" && provider !== "codex") {
1331
+ if (provider !== "claude" && provider !== "codex" && provider !== "kimi") {
716
1332
  console.error(`Unsupported JSON worker provider: ${provider}`);
717
1333
  process.exit(1);
718
1334
  }
@@ -725,16 +1341,29 @@ var workerHook = workerHookUrl && workerHookMarker && workerHookToken && workerH
725
1341
  } : void 0;
726
1342
  var serveSocket = null;
727
1343
  var queuedServeMessages = [];
1344
+ var latestKimiCommandEvent = null;
728
1345
  var exiting = false;
1346
+ var kimiTurnActive = false;
729
1347
  var seqCounter = new SeqCounter(sessionId);
730
1348
  var whitelist = new ToolWhitelist();
731
1349
  var nextApprovalRequestId = createApprovalRequestIdFactory(sessionId);
732
1350
  var pendingApprovals = /* @__PURE__ */ new Map();
1351
+ function isKimiCommandEvent(msg) {
1352
+ if (msg.type !== "worker_event" || msg.event.type !== "kimi_acp") return false;
1353
+ const params = msg.event.params;
1354
+ if (!params || typeof params !== "object" || Array.isArray(params)) return false;
1355
+ const update = params.update;
1356
+ return Boolean(
1357
+ update && typeof update === "object" && !Array.isArray(update) && update.sessionUpdate === "available_commands_update"
1358
+ );
1359
+ }
733
1360
  function sendToServe(msg) {
1361
+ if (isKimiCommandEvent(msg)) latestKimiCommandEvent = msg;
734
1362
  if (serveSocket?.writable) {
735
1363
  serveSocket.write(serializeWorkerMsg(msg));
736
1364
  return;
737
1365
  }
1366
+ if (isKimiCommandEvent(msg)) return;
738
1367
  if (msg.type !== "worker_approval_request") {
739
1368
  queuedServeMessages.push(msg);
740
1369
  }
@@ -746,15 +1375,16 @@ function flushQueuedServeMessages() {
746
1375
  if (msg) serveSocket.write(serializeWorkerMsg(msg));
747
1376
  }
748
1377
  }
749
- var forwardToRelay = async (toolName, input) => {
1378
+ var forwardToRelay = async (toolName, input, options) => {
750
1379
  return new Promise((resolve) => {
751
1380
  const requestId = nextApprovalRequestId();
752
- pendingApprovals.set(requestId, { resolve, toolName, input });
1381
+ pendingApprovals.set(requestId, { resolve, toolName, input, options });
753
1382
  sendToServe({
754
1383
  type: "worker_approval_request",
755
1384
  requestId,
756
1385
  toolName,
757
- input
1386
+ input,
1387
+ ...options ? { options } : {}
758
1388
  });
759
1389
  });
760
1390
  };
@@ -773,9 +1403,36 @@ function handleProviderEvent(event) {
773
1403
  event
774
1404
  });
775
1405
  }
1406
+ function handleKimiEvent(method, params) {
1407
+ handleProviderEvent({ type: "kimi_acp", method, params });
1408
+ }
1409
+ function workerApprovalOptions(options) {
1410
+ return options.flatMap((option) => {
1411
+ if (option.kind !== "allow_once" && option.kind !== "allow_always" && option.kind !== "reject_once" && option.kind !== "reject_always") {
1412
+ return [];
1413
+ }
1414
+ return [{ optionId: option.optionId, name: option.name, kind: option.kind }];
1415
+ });
1416
+ }
1417
+ async function handleKimiPermissionRequest(request) {
1418
+ if (whitelist.has(request.toolName)) return { behavior: "allow_always" };
1419
+ const options = workerApprovalOptions(request.options);
1420
+ const decision = await forwardToRelay(
1421
+ request.toolName,
1422
+ request.input,
1423
+ options.length > 0 ? options : void 0
1424
+ );
1425
+ if (decision.cancelled) return { cancelled: true };
1426
+ return {
1427
+ behavior: decision.behavior === "deny" ? "deny" : decision.remember ? "allow_always" : "allow_once",
1428
+ ...decision.message ? { message: decision.message } : {},
1429
+ ...decision.optionId ? { optionId: decision.optionId } : {}
1430
+ };
1431
+ }
776
1432
  function handleProviderExit(code) {
777
1433
  if (exiting) return;
778
1434
  exiting = true;
1435
+ kimiTurnActive = false;
779
1436
  whitelist.clear();
780
1437
  const errorTail = code === 0 ? "" : sanitizeProviderErrorTail(session.getStderr());
781
1438
  sendToServe({
@@ -800,6 +1457,36 @@ var session = provider === "codex" ? new CodexAppServerSession({
800
1457
  });
801
1458
  },
802
1459
  onExit: handleProviderExit
1460
+ }) : provider === "kimi" ? new KimiAcpSession({
1461
+ cwd: workerCwd,
1462
+ resumeSessionId: workerResume,
1463
+ permissionMode: workerPermissionMode,
1464
+ onUpdate: (params) => handleKimiEvent("session/update", params),
1465
+ onPermissionRequest: handleKimiPermissionRequest,
1466
+ onPromptStart: () => {
1467
+ kimiTurnActive = true;
1468
+ sendToServe({ type: "worker_turn_started" });
1469
+ },
1470
+ onPromptComplete: (result) => {
1471
+ kimiTurnActive = false;
1472
+ handleKimiEvent("session/prompt/result", { response: result });
1473
+ },
1474
+ onPromptError: (error) => {
1475
+ kimiTurnActive = false;
1476
+ handleKimiEvent("session/prompt/error", {
1477
+ message: sanitizeProviderErrorTail(error.message) || "Kimi ACP prompt failed"
1478
+ });
1479
+ },
1480
+ onSessionId: (kimiSessionId) => {
1481
+ sendToServe({
1482
+ type: "worker_native_session_id",
1483
+ provider: "kimi",
1484
+ sessionId: kimiSessionId
1485
+ });
1486
+ },
1487
+ onProtocolError: (error) => console.error(`[worker] ${error.message}`),
1488
+ onProcessError: (error) => console.error(`[worker] ${error.message}`),
1489
+ onExit: handleProviderExit
803
1490
  }) : new JsonSession({
804
1491
  claudeArgs: providerArgs,
805
1492
  cwd: workerCwd,
@@ -812,14 +1499,26 @@ var session = provider === "codex" ? new CodexAppServerSession({
812
1499
  onExit: handleProviderExit
813
1500
  });
814
1501
  function handleServeConnection(socket) {
815
- serveSocket = takeoverServeSocket(serveSocket, socket);
1502
+ const previousServeSocket = serveSocket;
1503
+ serveSocket = socket;
1504
+ takeoverServeSocket(previousServeSocket, socket);
1505
+ const queuedKimiTurnStart = queuedServeMessages.some(
1506
+ (message) => message.type === "worker_turn_started"
1507
+ );
1508
+ if (provider === "kimi" && kimiTurnActive && !queuedKimiTurnStart && serveSocket.writable) {
1509
+ serveSocket.write(serializeWorkerMsg({ type: "worker_turn_started" }));
1510
+ }
816
1511
  flushQueuedServeMessages();
1512
+ if (latestKimiCommandEvent && serveSocket.writable) {
1513
+ serveSocket.write(serializeWorkerMsg(latestKimiCommandEvent));
1514
+ }
817
1515
  for (const [requestId, pending] of pendingApprovals) {
818
1516
  sendToServe({
819
1517
  type: "worker_approval_request",
820
1518
  requestId,
821
1519
  toolName: pending.toolName,
822
- input: pending.input
1520
+ input: pending.input,
1521
+ ...pending.options ? { options: pending.options } : {}
823
1522
  });
824
1523
  }
825
1524
  createWorkerReader(
@@ -830,11 +1529,23 @@ function handleServeConnection(socket) {
830
1529
  session.sendMessage(msg.content);
831
1530
  break;
832
1531
  case "worker_interrupt":
833
- rejectAllPendingApprovals("Turn interrupted");
834
- void session.interruptCurrentTurn().then((interrupted) => {
835
- if (interrupted) sendToServe({ type: "worker_interrupted" });
836
- else console.error("[worker] interrupt requested but Claude child was not running");
837
- });
1532
+ if (provider === "kimi") {
1533
+ void session.interruptCurrentTurn().then((interrupted) => {
1534
+ if (interrupted) {
1535
+ kimiTurnActive = false;
1536
+ rejectAllPendingApprovals("Turn interrupted", true);
1537
+ sendToServe({ type: "worker_interrupted" });
1538
+ } else {
1539
+ console.error("[worker] interrupt requested but Kimi had no active turn");
1540
+ }
1541
+ });
1542
+ } else {
1543
+ rejectAllPendingApprovals("Turn interrupted");
1544
+ void session.interruptCurrentTurn().then((interrupted) => {
1545
+ if (interrupted) sendToServe({ type: "worker_interrupted" });
1546
+ else console.error("[worker] interrupt requested but provider child was not running");
1547
+ });
1548
+ }
838
1549
  break;
839
1550
  case "worker_stop":
840
1551
  session.stop();
@@ -842,7 +1553,12 @@ function handleServeConnection(socket) {
842
1553
  case "worker_approval_response": {
843
1554
  const pending = pendingApprovals.get(msg.requestId);
844
1555
  if (pending) {
845
- pending.resolve({ behavior: msg.behavior, message: msg.message });
1556
+ pending.resolve({
1557
+ behavior: msg.behavior,
1558
+ ...msg.message ? { message: msg.message } : {},
1559
+ ...msg.remember ? { remember: true } : {},
1560
+ ...msg.optionId ? { optionId: msg.optionId } : {}
1561
+ });
846
1562
  pendingApprovals.delete(msg.requestId);
847
1563
  }
848
1564
  break;
@@ -857,18 +1573,24 @@ function handleServeConnection(socket) {
857
1573
  }
858
1574
  );
859
1575
  socket.on("close", () => {
860
- serveSocket = null;
861
- rejectAllPendingApprovals("Serve connection closed");
1576
+ serveSocket = releaseServeSocket(serveSocket, socket, () => {
1577
+ rejectAllPendingApprovals("Serve connection closed");
1578
+ });
862
1579
  });
863
1580
  socket.on("error", () => {
864
- serveSocket = null;
865
- rejectAllPendingApprovals("Serve connection error");
1581
+ serveSocket = releaseServeSocket(serveSocket, socket, () => {
1582
+ rejectAllPendingApprovals("Serve connection error");
1583
+ });
866
1584
  });
867
1585
  }
868
- function rejectAllPendingApprovals(reason) {
1586
+ function rejectAllPendingApprovals(reason, cancelled = false) {
869
1587
  if (pendingApprovals.size === 0) return;
870
1588
  for (const [, pending] of pendingApprovals) {
871
- pending.resolve({ behavior: "deny", message: reason });
1589
+ pending.resolve({
1590
+ behavior: "deny",
1591
+ message: reason,
1592
+ ...cancelled ? { cancelled: true } : {}
1593
+ });
872
1594
  }
873
1595
  pendingApprovals.clear();
874
1596
  }
@@ -923,6 +1645,25 @@ ${session.getStderr()}`;
923
1645
  console.error(`[worker] Codex app-server failed to initialize: ${diagnostic}`);
924
1646
  void session.stop(0).finally(() => handleProviderExit(1));
925
1647
  });
1648
+ } else if (provider === "kimi" && session instanceof KimiAcpSession) {
1649
+ void session.waitUntilReady().then((kimiSessionId) => {
1650
+ sendToServe({
1651
+ type: "worker_ready",
1652
+ pid,
1653
+ nativeSession: { provider: "kimi", sessionId: kimiSessionId }
1654
+ });
1655
+ }).catch((err) => {
1656
+ const message = err instanceof Error ? err.message : String(err);
1657
+ const diagnostic = sanitizeProviderErrorTail(`${message}
1658
+ ${session.getStderr()}`) || "Kimi ACP \u521D\u59CB\u5316\u5931\u8D25";
1659
+ sendToServe({
1660
+ type: "worker_startup_error",
1661
+ provider: "kimi",
1662
+ message: diagnostic
1663
+ });
1664
+ console.error(`[worker] Kimi ACP failed to initialize: ${diagnostic}`);
1665
+ void session.stop(0).finally(() => handleProviderExit(1));
1666
+ });
926
1667
  } else {
927
1668
  sendToServe({ type: "worker_ready", pid });
928
1669
  }