@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.
Files changed (63) hide show
  1. package/README.md +18 -4
  2. package/dist/{autostart-VGHJZS6V.js → autostart-MLJRJC2J.js} +5 -5
  3. package/dist/{chunk-CFPY2A6Q.js → chunk-44IM5SVF.js} +2 -2
  4. package/dist/{chunk-PLWNR3X4.js → chunk-4QJ24E5S.js} +5 -5
  5. package/dist/{chunk-FNZ5X2VZ.js → chunk-5OJFDJ65.js} +108 -9
  6. package/dist/chunk-5OJFDJ65.js.map +1 -0
  7. package/dist/{chunk-SKKPJULC.js → chunk-7BNZO6DB.js} +4 -2
  8. package/dist/chunk-7BNZO6DB.js.map +1 -0
  9. package/dist/{chunk-ZKMCE4JY.js → chunk-E6NHFBCU.js} +110 -11
  10. package/dist/chunk-E6NHFBCU.js.map +1 -0
  11. package/dist/{chunk-Z2KUJ6SW.js → chunk-EMWUDUL4.js} +2 -2
  12. package/dist/{chunk-HPNB53V4.js → chunk-GK3WHOWF.js} +2 -2
  13. package/dist/{chunk-4IX5R5X3.js → chunk-GTG6VONI.js} +12 -8
  14. package/dist/chunk-GTG6VONI.js.map +1 -0
  15. package/dist/{chunk-CZPY2BFR.js → chunk-GUNXL4C5.js} +10 -6
  16. package/dist/chunk-GUNXL4C5.js.map +1 -0
  17. package/dist/chunk-LNSWARRW.js +30 -0
  18. package/dist/chunk-LNSWARRW.js.map +1 -0
  19. package/dist/{chunk-4EIUH7CQ.js → chunk-RQKKZC5T.js} +23 -9
  20. package/dist/chunk-RQKKZC5T.js.map +1 -0
  21. package/dist/{chunk-WTCJIDDT.js → chunk-RW32NTSD.js} +3 -2
  22. package/dist/chunk-RW32NTSD.js.map +1 -0
  23. package/dist/{chunk-4KUJOGCV.js → chunk-SGVG4V66.js} +27 -6
  24. package/dist/chunk-SGVG4V66.js.map +1 -0
  25. package/dist/{chunk-5RESCDN4.js → chunk-V3JJ352Q.js} +1 -1
  26. package/dist/chunk-V3JJ352Q.js.map +1 -0
  27. package/dist/{chunk-KM62ELKK.js → chunk-Z6HCYOPJ.js} +25 -1
  28. package/dist/chunk-Z6HCYOPJ.js.map +1 -0
  29. package/dist/index.js +10 -9
  30. package/dist/index.js.map +1 -1
  31. package/dist/{logger-6MR4NSOC.js → logger-U5XYVVXY.js} +3 -3
  32. package/dist/preview-worker.js +5 -5
  33. package/dist/{relay-token-KHOXKEF2.js → relay-token-LFUK2JW6.js} +4 -4
  34. package/dist/serve.js +1024 -124
  35. package/dist/serve.js.map +1 -1
  36. package/dist/{service-host-FAPIR5IX.js → service-host-XIAWRF4P.js} +3 -3
  37. package/dist/session-worker.js +1019 -81
  38. package/dist/session-worker.js.map +1 -1
  39. package/dist/{terminal-HA5PIFVP.js → terminal-LJSUWZ7X.js} +14 -12
  40. package/dist/terminal-LJSUWZ7X.js.map +1 -0
  41. package/dist/terminal-worker.js +10 -10
  42. package/dist/update-runner.js +22 -2
  43. package/dist/update-runner.js.map +1 -1
  44. package/package.json +4 -4
  45. package/dist/chunk-4EIUH7CQ.js.map +0 -1
  46. package/dist/chunk-4IX5R5X3.js.map +0 -1
  47. package/dist/chunk-4KUJOGCV.js.map +0 -1
  48. package/dist/chunk-5RESCDN4.js.map +0 -1
  49. package/dist/chunk-CZPY2BFR.js.map +0 -1
  50. package/dist/chunk-FNZ5X2VZ.js.map +0 -1
  51. package/dist/chunk-KM62ELKK.js.map +0 -1
  52. package/dist/chunk-SKKPJULC.js.map +0 -1
  53. package/dist/chunk-WTCJIDDT.js.map +0 -1
  54. package/dist/chunk-ZKMCE4JY.js.map +0 -1
  55. package/dist/terminal-HA5PIFVP.js.map +0 -1
  56. /package/dist/{autostart-VGHJZS6V.js.map → autostart-MLJRJC2J.js.map} +0 -0
  57. /package/dist/{chunk-CFPY2A6Q.js.map → chunk-44IM5SVF.js.map} +0 -0
  58. /package/dist/{chunk-PLWNR3X4.js.map → chunk-4QJ24E5S.js.map} +0 -0
  59. /package/dist/{chunk-Z2KUJ6SW.js.map → chunk-EMWUDUL4.js.map} +0 -0
  60. /package/dist/{chunk-HPNB53V4.js.map → chunk-GK3WHOWF.js.map} +0 -0
  61. /package/dist/{logger-6MR4NSOC.js.map → logger-U5XYVVXY.js.map} +0 -0
  62. /package/dist/{relay-token-KHOXKEF2.js.map → relay-token-LFUK2JW6.js.map} +0 -0
  63. /package/dist/{service-host-FAPIR5IX.js.map → service-host-XIAWRF4P.js.map} +0 -0
package/dist/serve.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  buildProviderEnv,
4
4
  loadConfig,
5
5
  saveAgentCliPath
6
- } from "./chunk-4EIUH7CQ.js";
6
+ } from "./chunk-RQKKZC5T.js";
7
7
  import {
8
8
  PersistedSessionRecordSchema,
9
9
  extractAgentInvocation,
@@ -12,7 +12,7 @@ import {
12
12
  sessionRuntimeIpcVersionMatches,
13
13
  stripProxyProfileArgs,
14
14
  writeSessionRuntimeIpcVersions
15
- } from "./chunk-4KUJOGCV.js";
15
+ } from "./chunk-SGVG4V66.js";
16
16
  import {
17
17
  processExistsOrIsInaccessible
18
18
  } from "./chunk-5OARBB2B.js";
@@ -21,7 +21,7 @@ import {
21
21
  isPreviewControlRequest,
22
22
  readPreviewWorkerMessages,
23
23
  writePreviewWorkerMessage
24
- } from "./chunk-HPNB53V4.js";
24
+ } from "./chunk-GK3WHOWF.js";
25
25
  import {
26
26
  ContentBlockDeltaSchema,
27
27
  IGNORED_EVENT_TYPES,
@@ -30,7 +30,7 @@ import {
30
30
  createScopedApprovalRequestIdFactory,
31
31
  disposeSeqCounter,
32
32
  getSeqCounterFor
33
- } from "./chunk-CFPY2A6Q.js";
33
+ } from "./chunk-44IM5SVF.js";
34
34
  import {
35
35
  readWorkerConnection
36
36
  } from "./chunk-WG3KLJFJ.js";
@@ -40,7 +40,7 @@ import {
40
40
  import {
41
41
  buildHostedPtyArgs,
42
42
  parseTerminalWorkerCliArgs
43
- } from "./chunk-4IX5R5X3.js";
43
+ } from "./chunk-GTG6VONI.js";
44
44
  import {
45
45
  ReconnectSupervisor,
46
46
  TERMINAL_ADMISSION_FRAME_MAX_BYTES,
@@ -48,7 +48,7 @@ import {
48
48
  isTerminalAdmissionRequestCandidate,
49
49
  parseTerminalAdmissionRequest,
50
50
  serializeTerminalAdmissionMessage
51
- } from "./chunk-KM62ELKK.js";
51
+ } from "./chunk-Z6HCYOPJ.js";
52
52
  import {
53
53
  startServiceControl
54
54
  } from "./chunk-VYAEW7G6.js";
@@ -64,12 +64,15 @@ import {
64
64
  } from "./chunk-CFO5GU5U.js";
65
65
  import {
66
66
  CodexApprovalPolicyUnsupportedError,
67
+ CursorPermissionModeUnsupportedError,
67
68
  KimiPermissionModeUnsupportedError,
68
69
  buildKimiTerminalArgs,
69
70
  detectAgentCliStatus,
70
71
  resolveCodexPermissionPolicy,
72
+ resolveCursorAcpMode,
73
+ resolveCursorPermissionFlags,
71
74
  resolveKimiAcpMode
72
- } from "./chunk-FNZ5X2VZ.js";
75
+ } from "./chunk-5OJFDJ65.js";
73
76
  import {
74
77
  TERMINAL_IPC_PROTOCOL_VERSION,
75
78
  WORKER_IPC_PROTOCOL_VERSION,
@@ -77,8 +80,8 @@ import {
77
80
  createWorkerReader,
78
81
  serializeIpc,
79
82
  serializeWorkerMsg
80
- } from "./chunk-CZPY2BFR.js";
81
- import "./chunk-5RESCDN4.js";
83
+ } from "./chunk-GUNXL4C5.js";
84
+ import "./chunk-V3JJ352Q.js";
82
85
  import {
83
86
  ControlErrorCode,
84
87
  MessageEnvelopeSchema,
@@ -105,7 +108,7 @@ import {
105
108
  isProxyProtocolRejectDirection,
106
109
  serializeControl,
107
110
  summarizeToolActivity
108
- } from "./chunk-ZKMCE4JY.js";
111
+ } from "./chunk-E6NHFBCU.js";
109
112
  import {
110
113
  localIpcEndpointMayExist,
111
114
  removeLocalIpcEndpoint,
@@ -116,6 +119,7 @@ import {
116
119
  compareStableVersions,
117
120
  selectHighestStableVersion
118
121
  } from "./chunk-7LUBU2WA.js";
122
+ import "./chunk-LNSWARRW.js";
119
123
  import {
120
124
  PROXY_VERSION
121
125
  } from "./chunk-EGNWMOPC.js";
@@ -133,7 +137,7 @@ import {
133
137
  import {
134
138
  loadProxyRuntimeEnv,
135
139
  serviceLogger
136
- } from "./chunk-WTCJIDDT.js";
140
+ } from "./chunk-RW32NTSD.js";
137
141
  import {
138
142
  DATA_DIR,
139
143
  DEFAULT_PROXY_PROFILE,
@@ -152,7 +156,7 @@ import {
152
156
  ensureProfileWorkspace,
153
157
  sessionPaths,
154
158
  tildify
155
- } from "./chunk-SKKPJULC.js";
159
+ } from "./chunk-7BNZO6DB.js";
156
160
  import {
157
161
  flushLogger
158
162
  } from "./chunk-ICSO3ZIS.js";
@@ -395,7 +399,7 @@ function isManagedSessionProcess(pid, identity) {
395
399
  // src/serve/session-history-metadata.ts
396
400
  import { existsSync, readFileSync as readFileSync2 } from "fs";
397
401
  function isProviderId(value) {
398
- return value === "claude" || value === "codex" || value === "kimi";
402
+ return value === "claude" || value === "codex" || value === "kimi" || value === "cursor";
399
403
  }
400
404
  function isSessionMode(value) {
401
405
  return value === "pty" || value === "json";
@@ -562,7 +566,7 @@ function fsmForMode(mode) {
562
566
  return mode === "pty" ? ptyFSM : jsonFSM;
563
567
  }
564
568
  function isProviderId2(value) {
565
- return value === "claude" || value === "codex" || value === "kimi";
569
+ return value === "claude" || value === "codex" || value === "kimi" || value === "cursor";
566
570
  }
567
571
  var SessionManager = class {
568
572
  sessions = /* @__PURE__ */ new Map();
@@ -1619,12 +1623,12 @@ var RelayConnection = class extends EventEmitter {
1619
1623
  };
1620
1624
 
1621
1625
  // src/serve/handlers/control-messages.ts
1622
- import { readdir as readdir3, mkdir } from "fs/promises";
1623
- import { join as join8, isAbsolute as isAbsolute6, normalize as normalize2 } from "path";
1626
+ import { readdir as readdir4, mkdir } from "fs/promises";
1627
+ import { join as join9, isAbsolute as isAbsolute7, normalize as normalize2 } from "path";
1624
1628
 
1625
1629
  // src/serve/history/catalog.ts
1626
1630
  import { tmpdir } from "os";
1627
- import { isAbsolute as isAbsolute5, resolve as resolve3, sep as sep2 } from "path";
1631
+ import { isAbsolute as isAbsolute6, resolve as resolve3, sep as sep2 } from "path";
1628
1632
 
1629
1633
  // src/serve/history/claude.ts
1630
1634
  import { lstat as lstat2, readdir as readdir2 } from "fs/promises";
@@ -1914,9 +1918,300 @@ async function scanCodexHistory(root) {
1914
1918
  return sessions;
1915
1919
  }
1916
1920
 
1921
+ // src/serve/history/cursor.ts
1922
+ import { createRequire } from "module";
1923
+ import { lstat as lstat3, readdir as readdir3, readFile } from "fs/promises";
1924
+ import { isAbsolute as isAbsolute4, join as join6 } from "path";
1925
+
1926
+ // src/serve/history/paths.ts
1927
+ import { homedir as homedir2 } from "os";
1928
+ import { join as join5, resolve as resolve2 } from "path";
1929
+ var claudeProjectsDir = () => join5(homedir2(), ".claude", "projects");
1930
+ var codexSessionsDir = () => join5(homedir2(), ".codex", "sessions");
1931
+ function kimiSessionsDir() {
1932
+ const configured = process.env.KIMI_CODE_HOME?.trim();
1933
+ return join5(configured ? resolve2(configured) : join5(homedir2(), ".kimi-code"), "sessions");
1934
+ }
1935
+ function cursorConfigDir() {
1936
+ const configured = process.env.CURSOR_CONFIG_DIR?.trim();
1937
+ if (configured) return resolve2(configured);
1938
+ const xdg = process.env.XDG_CONFIG_HOME?.trim();
1939
+ return xdg ? join5(resolve2(xdg), "cursor") : join5(homedir2(), ".cursor");
1940
+ }
1941
+ function cursorAcpSessionsDir() {
1942
+ const explicit = process.env.CURSOR_ACP_SESSIONS_DIR?.trim();
1943
+ return explicit ? resolve2(explicit) : join5(cursorConfigDir(), "acp-sessions");
1944
+ }
1945
+
1946
+ // src/serve/history/cursor.ts
1947
+ var META_FILE = "meta.json";
1948
+ var STORE_FILE = "store.db";
1949
+ var ROOT_HASH_SIZE = 32;
1950
+ var PROTO_VARINT_MAX_BYTES = 5;
1951
+ var require2 = createRequire(import.meta.url);
1952
+ var CursorHistoryUnavailableError = class extends Error {
1953
+ constructor(cause) {
1954
+ super(
1955
+ `\u5F53\u524D Node.js ${process.version} \u4E0D\u652F\u6301\u8BFB\u53D6 Cursor \u5386\u53F2\uFF08\u9700\u8981\u5185\u7F6E\u7684 node:sqlite\uFF0C\u8BF7\u5347\u7EA7\u5230 Node.js 22.22.2 \u6216\u66F4\u9AD8\u7248\u672C\uFF09`,
1956
+ cause === void 0 ? void 0 : { cause }
1957
+ );
1958
+ this.name = "CursorHistoryUnavailableError";
1959
+ }
1960
+ };
1961
+ var cachedDatabaseSync;
1962
+ function loadDatabaseSync() {
1963
+ if (cachedDatabaseSync) return cachedDatabaseSync;
1964
+ let sqlite;
1965
+ try {
1966
+ sqlite = require2("node:sqlite");
1967
+ } catch (error) {
1968
+ throw new CursorHistoryUnavailableError(error);
1969
+ }
1970
+ if (typeof sqlite.DatabaseSync !== "function") throw new CursorHistoryUnavailableError();
1971
+ cachedDatabaseSync = sqlite.DatabaseSync;
1972
+ return cachedDatabaseSync;
1973
+ }
1974
+ function readProtoVarint(root, offset) {
1975
+ let value = 0;
1976
+ let shift = 0;
1977
+ let index = offset;
1978
+ while (index < root.length && index - offset < PROTO_VARINT_MAX_BYTES) {
1979
+ const byte = root[index++];
1980
+ if (byte === void 0) return null;
1981
+ value |= (byte & 127) << shift;
1982
+ if ((byte & 128) === 0) return { value, next: index };
1983
+ shift += 7;
1984
+ }
1985
+ return null;
1986
+ }
1987
+ function parseCursorRoot(root) {
1988
+ const blobIds = [];
1989
+ const inlineJson = [];
1990
+ let offset = 0;
1991
+ while (offset < root.length) {
1992
+ const tag = readProtoVarint(root, offset);
1993
+ if (!tag) break;
1994
+ const field = tag.value >>> 3;
1995
+ const wire = tag.value & 7;
1996
+ offset = tag.next;
1997
+ if (wire === 0) {
1998
+ const value = readProtoVarint(root, offset);
1999
+ if (!value) break;
2000
+ offset = value.next;
2001
+ continue;
2002
+ }
2003
+ if (wire === 1) {
2004
+ offset += 8;
2005
+ continue;
2006
+ }
2007
+ if (wire === 5) {
2008
+ offset += 4;
2009
+ continue;
2010
+ }
2011
+ if (wire !== 2) break;
2012
+ const length = readProtoVarint(root, offset);
2013
+ if (!length) break;
2014
+ offset = length.next;
2015
+ if (offset + length.value > root.length) break;
2016
+ const data = root.subarray(offset, offset + length.value);
2017
+ offset += length.value;
2018
+ if (field === 1 && length.value === ROOT_HASH_SIZE) {
2019
+ blobIds.push(Buffer.from(data).toString("hex"));
2020
+ continue;
2021
+ }
2022
+ if (field === 4 && data[0] === 123) {
2023
+ try {
2024
+ inlineJson.push(JSON.parse(Buffer.from(data).toString("utf8")));
2025
+ } catch {
2026
+ }
2027
+ }
2028
+ }
2029
+ return { blobIds, inlineJson };
2030
+ }
2031
+ function readCursorMetaFile(raw) {
2032
+ const meta = asRecord(JSON.parse(raw));
2033
+ if (!meta) return null;
2034
+ return {
2035
+ ...typeof meta.cwd === "string" ? { cwd: meta.cwd } : {},
2036
+ ...typeof meta.title === "string" ? { title: meta.title } : {}
2037
+ };
2038
+ }
2039
+ function decodeStoreMeta(value) {
2040
+ if (typeof value !== "string" || value.length === 0) return null;
2041
+ try {
2042
+ const decoded = /^[0-9a-fA-F]+$/.test(value) ? Buffer.from(value, "hex").toString("utf8") : value;
2043
+ return asRecord(JSON.parse(decoded));
2044
+ } catch {
2045
+ return null;
2046
+ }
2047
+ }
2048
+ function openCursorStore(storePath) {
2049
+ const DatabaseSync = loadDatabaseSync();
2050
+ try {
2051
+ return new DatabaseSync(storePath, { readOnly: true });
2052
+ } catch {
2053
+ try {
2054
+ return new DatabaseSync(storePath);
2055
+ } catch {
2056
+ return null;
2057
+ }
2058
+ }
2059
+ }
2060
+ function readStoreBlob(db, id) {
2061
+ const row = db.prepare("SELECT data FROM blobs WHERE id = ?").get(id);
2062
+ if (!row) return null;
2063
+ if (row.data instanceof Uint8Array) return row.data;
2064
+ if (Buffer.isBuffer(row.data)) return row.data;
2065
+ return null;
2066
+ }
2067
+ function readLatestRootBlobId(db) {
2068
+ const keyed = db.prepare("SELECT value FROM meta WHERE key = ?").get("0");
2069
+ const fromKeyed = decodeStoreMeta(keyed?.value)?.latestRootBlobId;
2070
+ if (typeof fromKeyed === "string") return fromKeyed;
2071
+ const rows = db.prepare("SELECT value FROM meta").all();
2072
+ for (const row of rows) {
2073
+ const rootId = decodeStoreMeta(row.value)?.latestRootBlobId;
2074
+ if (typeof rootId === "string") return rootId;
2075
+ }
2076
+ return null;
2077
+ }
2078
+ function conversationRecordIdentity(record) {
2079
+ const parsed = asRecord(record);
2080
+ return parsed && typeof parsed.id === "string" && parsed.id.length > 0 ? parsed.id : null;
2081
+ }
2082
+ function cursorUserTextHasConversation(rawText) {
2083
+ const text = rawText.replace(/<system_reminder>[\s\S]*?<\/system_reminder>/gi, "");
2084
+ if (/<user_query>\s*\S[\s\S]*?<\/user_query>/i.test(text)) return true;
2085
+ const trimmed = text.trim();
2086
+ if (!trimmed) return false;
2087
+ return !/^<(?:user_info|timestamp|environment_context|conversation_summary)(?:[\s>:-])/i.test(
2088
+ trimmed
2089
+ );
2090
+ }
2091
+ function cursorRecordHasConversation(record) {
2092
+ const parsed = asRecord(record);
2093
+ if (!parsed || typeof parsed.role !== "string") return false;
2094
+ if (parsed.role === "assistant" || parsed.role === "tool") return true;
2095
+ if (parsed.role !== "user") return false;
2096
+ if (typeof parsed.content === "string") return cursorUserTextHasConversation(parsed.content);
2097
+ if (!Array.isArray(parsed.content)) return false;
2098
+ return parsed.content.some((block) => {
2099
+ const part = asRecord(block);
2100
+ return part?.type === "text" && typeof part.text === "string" && cursorUserTextHasConversation(part.text);
2101
+ });
2102
+ }
2103
+ function appendConversationRecord(records, seenIds, record) {
2104
+ const identity = conversationRecordIdentity(record);
2105
+ if (identity) {
2106
+ if (seenIds.has(identity)) return;
2107
+ seenIds.add(identity);
2108
+ }
2109
+ records.push(record);
2110
+ }
2111
+ function readCursorConversationRecordsFromStore(storePath) {
2112
+ const db = openCursorStore(storePath);
2113
+ if (!db) return [];
2114
+ try {
2115
+ const rootId = readLatestRootBlobId(db);
2116
+ if (!rootId) return [];
2117
+ const root = readStoreBlob(db, rootId);
2118
+ if (!root) return [];
2119
+ const { blobIds, inlineJson } = parseCursorRoot(root);
2120
+ const records = [];
2121
+ const seenIds = /* @__PURE__ */ new Set();
2122
+ for (const blobId of blobIds) {
2123
+ const blob = readStoreBlob(db, blobId);
2124
+ if (!blob || blob[0] !== 123) continue;
2125
+ try {
2126
+ appendConversationRecord(records, seenIds, JSON.parse(Buffer.from(blob).toString("utf8")));
2127
+ } catch {
2128
+ }
2129
+ }
2130
+ for (const record of inlineJson) appendConversationRecord(records, seenIds, record);
2131
+ return records;
2132
+ } catch {
2133
+ return [];
2134
+ } finally {
2135
+ try {
2136
+ db.close();
2137
+ } catch {
2138
+ }
2139
+ }
2140
+ }
2141
+ async function readCursorConversationRecords(sessionId) {
2142
+ if (!SAFE_SESSION_ID_PATTERN.test(sessionId)) return [];
2143
+ const storePath = join6(cursorAcpSessionsDir(), sessionId, STORE_FILE);
2144
+ try {
2145
+ const info = await lstat3(storePath);
2146
+ if (!info.isFile() || info.isSymbolicLink()) return [];
2147
+ } catch {
2148
+ return [];
2149
+ }
2150
+ return readCursorConversationRecordsFromStore(storePath);
2151
+ }
2152
+ async function latestExistingFileTime(paths, fallback) {
2153
+ let latest = fallback;
2154
+ for (const path of paths) {
2155
+ try {
2156
+ const info = await lstat3(path);
2157
+ if (info.isFile() && !info.isSymbolicLink() && info.mtimeMs > latest) latest = info.mtimeMs;
2158
+ } catch {
2159
+ }
2160
+ }
2161
+ return latest;
2162
+ }
2163
+ async function scanCursorHistory(root) {
2164
+ const result = [];
2165
+ let entries;
2166
+ try {
2167
+ entries = await readdir3(root, { withFileTypes: true });
2168
+ } catch {
2169
+ return result;
2170
+ }
2171
+ for (const entry of entries) {
2172
+ if (!entry.isDirectory() || !SAFE_SESSION_ID_PATTERN.test(entry.name)) continue;
2173
+ const directory = join6(root, entry.name);
2174
+ try {
2175
+ const metaPath = join6(directory, META_FILE);
2176
+ const metaInfo = await lstat3(metaPath);
2177
+ if (!metaInfo.isFile() || metaInfo.isSymbolicLink()) continue;
2178
+ const meta = readCursorMetaFile(await readFile(metaPath, "utf8"));
2179
+ if (!meta || typeof meta.cwd !== "string" || !isAbsolute4(meta.cwd)) continue;
2180
+ const storePath = join6(directory, STORE_FILE);
2181
+ let hasStore = false;
2182
+ try {
2183
+ const storeInfo = await lstat3(storePath);
2184
+ hasStore = storeInfo.isFile() && !storeInfo.isSymbolicLink();
2185
+ } catch {
2186
+ hasStore = false;
2187
+ }
2188
+ if (!hasStore) continue;
2189
+ const updatedAt = await latestExistingFileTime(
2190
+ [storePath, `${storePath}-wal`, `${storePath}-shm`, metaPath],
2191
+ metaInfo.mtimeMs
2192
+ );
2193
+ const records = readCursorConversationRecordsFromStore(storePath);
2194
+ if (!records.some(cursorRecordHasConversation)) continue;
2195
+ const title = typeof meta.title === "string" && normalizeHistoryTitle(meta.title) !== null ? meta.title : void 0;
2196
+ result.push({
2197
+ provider: "cursor",
2198
+ id: entry.name,
2199
+ projectDir: meta.cwd,
2200
+ updatedAt,
2201
+ kind: "main",
2202
+ hasConversation: true,
2203
+ ...title !== void 0 ? { title } : {}
2204
+ });
2205
+ } catch (error) {
2206
+ if (error instanceof CursorHistoryUnavailableError) throw error;
2207
+ }
2208
+ }
2209
+ return result;
2210
+ }
2211
+
1917
2212
  // src/serve/history/kimi.ts
1918
- import { lstat as lstat3, readFile } from "fs/promises";
1919
- import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute4, join as join5, relative, sep } from "path";
2213
+ import { lstat as lstat4, readFile as readFile2 } from "fs/promises";
2214
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute5, join as join7, relative, sep } from "path";
1920
2215
  function readContent2(value) {
1921
2216
  if (typeof value === "string") {
1922
2217
  return isConversationText(value) ? { hasConversation: true, title: value } : { hasConversation: false };
@@ -1968,16 +2263,16 @@ function conversationContent2(record) {
1968
2263
  async function scanKimiHistory(root) {
1969
2264
  const result = [];
1970
2265
  try {
1971
- if (!(await lstat3(root)).isDirectory()) return result;
2266
+ if (!(await lstat4(root)).isDirectory()) return result;
1972
2267
  } catch {
1973
2268
  return result;
1974
2269
  }
1975
2270
  for (const path of await collectFilesNamed(root, "state.json")) {
1976
2271
  if (relative(root, path).split(sep).length !== 3) continue;
1977
2272
  try {
1978
- const info = await lstat3(path);
2273
+ const info = await lstat4(path);
1979
2274
  if (!info.isFile()) continue;
1980
- const state = asRecord(JSON.parse(await readFile(path, "utf8")));
2275
+ const state = asRecord(JSON.parse(await readFile2(path, "utf8")));
1981
2276
  if (!state || state.archived === true || typeof state.id !== "string" || !SAFE_SESSION_ID_PATTERN.test(state.id))
1982
2277
  continue;
1983
2278
  const directory = dirname2(path);
@@ -1992,7 +2287,7 @@ async function scanKimiHistory(root) {
1992
2287
  kind: "main",
1993
2288
  hasConversation: false
1994
2289
  };
1995
- if (typeof state.cwd === "string" && isAbsolute4(state.cwd)) session.projectDir = state.cwd;
2290
+ if (typeof state.cwd === "string" && isAbsolute5(state.cwd)) session.projectDir = state.cwd;
1996
2291
  for (const title of [state.title, state.lastPrompt]) {
1997
2292
  if (typeof title === "string" && normalizeHistoryTitle(title) !== null) {
1998
2293
  session.title = title;
@@ -2000,10 +2295,10 @@ async function scanKimiHistory(root) {
2000
2295
  }
2001
2296
  }
2002
2297
  try {
2003
- const agents = join5(directory, "agents");
2004
- const main = join5(agents, "main");
2005
- if ((await lstat3(agents)).isDirectory() && (await lstat3(main)).isDirectory()) {
2006
- for await (const record of readJsonlRecords(join5(main, "wire.jsonl"))) {
2298
+ const agents = join7(directory, "agents");
2299
+ const main = join7(agents, "main");
2300
+ if ((await lstat4(agents)).isDirectory() && (await lstat4(main)).isDirectory()) {
2301
+ for await (const record of readJsonlRecords(join7(main, "wire.jsonl"))) {
2007
2302
  const content = readContent2(conversationContent2(record));
2008
2303
  session.hasConversation ||= content.hasConversation;
2009
2304
  if (content.title && normalizeHistoryTitle(content.title) !== null)
@@ -2020,16 +2315,6 @@ async function scanKimiHistory(root) {
2020
2315
  return result;
2021
2316
  }
2022
2317
 
2023
- // src/serve/history/paths.ts
2024
- import { homedir as homedir2 } from "os";
2025
- import { join as join6, resolve as resolve2 } from "path";
2026
- var claudeProjectsDir = () => join6(homedir2(), ".claude", "projects");
2027
- var codexSessionsDir = () => join6(homedir2(), ".codex", "sessions");
2028
- function kimiSessionsDir() {
2029
- const configured = process.env.KIMI_CODE_HOME?.trim();
2030
- return join6(configured ? resolve2(configured) : join6(homedir2(), ".kimi-code"), "sessions");
2031
- }
2032
-
2033
2318
  // src/serve/history/catalog.ts
2034
2319
  var temporaryRoots = [.../* @__PURE__ */ new Set([tmpdir(), "/tmp", "/private/tmp", "/var/tmp"])].flatMap(
2035
2320
  (root) => {
@@ -2040,7 +2325,7 @@ var temporaryRoots = [.../* @__PURE__ */ new Set([tmpdir(), "/tmp", "/private/tm
2040
2325
  }
2041
2326
  );
2042
2327
  function projectPath(path) {
2043
- if (!path || !isAbsolute5(path) || path.includes("\0")) return;
2328
+ if (!path || !isAbsolute6(path) || path.includes("\0")) return;
2044
2329
  const normalized = resolve3(path);
2045
2330
  if (temporaryRoots.some((root) => normalized === root || normalized.startsWith(`${root}${sep2}`))) {
2046
2331
  return;
@@ -2073,7 +2358,12 @@ async function scanSessionHistory(options = {}) {
2073
2358
  const records = await Promise.all([
2074
2359
  scanClaudeHistory(claudeProjectsDir()),
2075
2360
  scanCodexHistory(codexSessionsDir()),
2076
- scanKimiHistory(kimiSessionsDir())
2361
+ scanKimiHistory(kimiSessionsDir()),
2362
+ scanCursorHistory(cursorAcpSessionsDir()).catch((error) => {
2363
+ if (!(error instanceof CursorHistoryUnavailableError)) throw error;
2364
+ serviceLogger.warn({ error: error.message }, "Cursor history is unavailable");
2365
+ return [];
2366
+ })
2077
2367
  ]);
2078
2368
  return applySessionHistoryMetadata(
2079
2369
  buildHistoryCatalog(records.flat()),
@@ -2084,7 +2374,7 @@ async function scanSessionHistory(options = {}) {
2084
2374
  // src/serve/command-discovery.ts
2085
2375
  import { readdirSync, readFileSync as readFileSync5 } from "fs";
2086
2376
  import { homedir as homedir3 } from "os";
2087
- import { join as join7 } from "path";
2377
+ import { join as join8 } from "path";
2088
2378
  var REPL_BUILTINS = [
2089
2379
  { name: "/compact", description: "Compact conversation history", source: "builtin" },
2090
2380
  { name: "/status", description: "Show session status", source: "builtin" },
@@ -2156,7 +2446,7 @@ function scanSkillsDir(dirPath, source) {
2156
2446
  }
2157
2447
  const commands = [];
2158
2448
  for (const name of entries) {
2159
- const skillPath = join7(dirPath, name, "SKILL.md");
2449
+ const skillPath = join8(dirPath, name, "SKILL.md");
2160
2450
  try {
2161
2451
  const content = readFileSync5(skillPath, "utf-8");
2162
2452
  const parsed = parseSkillFrontmatter(content);
@@ -2182,7 +2472,7 @@ function scanCommandsDir(dirPath, source) {
2182
2472
  for (const filename of entries) {
2183
2473
  const cmdName = filename.replace(/\.md$/, "");
2184
2474
  try {
2185
- const content = readFileSync5(join7(dirPath, filename), "utf-8");
2475
+ const content = readFileSync5(join8(dirPath, filename), "utf-8");
2186
2476
  const firstLine = content.split("\n")[0].trim();
2187
2477
  commands.push({
2188
2478
  name: `/${cmdName}`,
@@ -2200,7 +2490,7 @@ function scanCommandsDir(dirPath, source) {
2200
2490
  return commands;
2201
2491
  }
2202
2492
  function scanPluginDirs(homeDir) {
2203
- const pluginCacheDir = join7(homeDir, ".claude", "plugins", "cache");
2493
+ const pluginCacheDir = join8(homeDir, ".claude", "plugins", "cache");
2204
2494
  let pluginNames;
2205
2495
  try {
2206
2496
  pluginNames = readdirSync(pluginCacheDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
@@ -2209,9 +2499,9 @@ function scanPluginDirs(homeDir) {
2209
2499
  }
2210
2500
  const commands = [];
2211
2501
  for (const pluginName of pluginNames) {
2212
- const pluginDir = join7(pluginCacheDir, pluginName);
2213
- const skillCmds = scanSkillsDir(join7(pluginDir, "skills"), "plugin-skill");
2214
- const cmdCmds = scanCommandsDir(join7(pluginDir, "commands"), "plugin-command");
2502
+ const pluginDir = join8(pluginCacheDir, pluginName);
2503
+ const skillCmds = scanSkillsDir(join8(pluginDir, "skills"), "plugin-skill");
2504
+ const cmdCmds = scanCommandsDir(join8(pluginDir, "commands"), "plugin-command");
2215
2505
  commands.push(...skillCmds, ...cmdCmds);
2216
2506
  }
2217
2507
  return commands;
@@ -2219,10 +2509,10 @@ function scanPluginDirs(homeDir) {
2219
2509
  async function discoverCommands(workDir, options) {
2220
2510
  const homeDir = options?.homeDir ?? homedir3();
2221
2511
  const builtins = REPL_BUILTINS.filter((c) => !COMMAND_BLACKLIST.has(c.name));
2222
- const userSkills = scanSkillsDir(join7(homeDir, ".claude", "skills"), "user-skill");
2223
- const projectSkills = scanSkillsDir(join7(workDir, ".claude", "skills"), "project-skill");
2224
- const userCommands = scanCommandsDir(join7(homeDir, ".claude", "commands"), "user-command");
2225
- const projectCommands = scanCommandsDir(join7(workDir, ".claude", "commands"), "project-command");
2512
+ const userSkills = scanSkillsDir(join8(homeDir, ".claude", "skills"), "user-skill");
2513
+ const projectSkills = scanSkillsDir(join8(workDir, ".claude", "skills"), "project-skill");
2514
+ const userCommands = scanCommandsDir(join8(homeDir, ".claude", "commands"), "user-command");
2515
+ const projectCommands = scanCommandsDir(join8(workDir, ".claude", "commands"), "project-command");
2226
2516
  const pluginCommands = scanPluginDirs(homeDir);
2227
2517
  const commandMap = /* @__PURE__ */ new Map();
2228
2518
  for (const cmd of builtins) commandMap.set(cmd.name, cmd);
@@ -2373,7 +2663,7 @@ function touchSessionActivity(sessionManager, relay, sessionId, now = Date.now()
2373
2663
  // src/serve/handlers/control-messages.ts
2374
2664
  var COMMAND_REFRESH_MS = 6 * 60 * 60 * 1e3;
2375
2665
  function isPathSafe(path) {
2376
- if (!isAbsolute6(path)) return false;
2666
+ if (!isAbsolute7(path)) return false;
2377
2667
  const normalized = normalize2(path);
2378
2668
  if (normalized.includes("..")) return false;
2379
2669
  return true;
@@ -2387,7 +2677,7 @@ function sortEntries(a, b) {
2387
2677
  return a.name.localeCompare(b.name);
2388
2678
  }
2389
2679
  async function scanDir(dirPath, options) {
2390
- const entries = await readdir3(dirPath, { withFileTypes: true });
2680
+ const entries = await readdir4(dirPath, { withFileTypes: true });
2391
2681
  return entries.filter((entry) => options.includeHidden || isPickerVisible(entry.name)).map((e) => ({ name: e.name, isDir: e.isDirectory() })).sort(sortEntries);
2392
2682
  }
2393
2683
  async function getFileTree(rootPath) {
@@ -2401,7 +2691,7 @@ async function getFileTree(rootPath) {
2401
2691
  groups.push({ path: rootPath, entries: rootEntries });
2402
2692
  for (const sub of rootEntries) {
2403
2693
  if (!sub.isDir) continue;
2404
- const subPath = join8(rootPath, sub.name);
2694
+ const subPath = join9(rootPath, sub.name);
2405
2695
  try {
2406
2696
  const subEntries = await scanDir(subPath, { includeHidden: false });
2407
2697
  groups.push({ path: subPath, entries: subEntries });
@@ -2971,7 +3261,7 @@ function mapCodexAppServerEvent(sessionId, seq, event) {
2971
3261
  return [];
2972
3262
  }
2973
3263
 
2974
- // src/serve/kimi-acp-event-mapper.ts
3264
+ // src/serve/cursor-acp-event-mapper.ts
2975
3265
  var KNOWN_IGNORED_UPDATES = /* @__PURE__ */ new Set([
2976
3266
  "config_option_update",
2977
3267
  "current_mode_update",
@@ -2980,7 +3270,6 @@ var KNOWN_IGNORED_UPDATES = /* @__PURE__ */ new Set([
2980
3270
  "plan_update",
2981
3271
  "session_info_update",
2982
3272
  "usage_update",
2983
- // Live prompt input is already echoed by RelayInputHandlers. ACP may echo it back too.
2984
3273
  "user_message_chunk"
2985
3274
  ]);
2986
3275
  var COMPLETED_TOOL_ID_LIMIT = 512;
@@ -3016,7 +3305,7 @@ function toolName(tool) {
3016
3305
  case "switch_mode":
3017
3306
  return "SwitchMode";
3018
3307
  default:
3019
- return tool.title || "Kimi Tool";
3308
+ return tool.title || "Cursor Tool";
3020
3309
  }
3021
3310
  }
3022
3311
  function toolParameters(tool) {
@@ -3075,7 +3364,7 @@ function promptErrorMessage(params) {
3075
3364
  if (isRecord2(params.error) && typeof params.error.message === "string") {
3076
3365
  return params.error.message;
3077
3366
  }
3078
- return "Kimi ACP prompt failed";
3367
+ return "Cursor ACP prompt failed";
3079
3368
  }
3080
3369
  function availableCommands(update) {
3081
3370
  if (!Array.isArray(update.availableCommands)) return [];
@@ -3090,12 +3379,34 @@ function availableCommands(update) {
3090
3379
  name: rawName.startsWith("/") ? rawName : `/${rawName}`,
3091
3380
  description: typeof candidate.description === "string" ? candidate.description : "",
3092
3381
  ...argumentHint ? { argumentHint } : {},
3093
- source: "kimi"
3382
+ source: "cursor"
3094
3383
  }
3095
3384
  ];
3096
3385
  });
3097
3386
  }
3098
- var KimiAcpEventMapper = class {
3387
+ function cursorTodos(value) {
3388
+ if (!Array.isArray(value)) return [];
3389
+ return value.flatMap((candidate) => {
3390
+ if (!isRecord2(candidate) || typeof candidate.id !== "string" || typeof candidate.content !== "string") {
3391
+ return [];
3392
+ }
3393
+ const status = candidate.status === "pending" || candidate.status === "in_progress" || candidate.status === "completed" || candidate.status === "cancelled" ? candidate.status : "pending";
3394
+ return [{ id: candidate.id, content: candidate.content, status }];
3395
+ });
3396
+ }
3397
+ function uiControl(sessionId, payload) {
3398
+ return {
3399
+ kind: "control",
3400
+ raw: serializeControl({
3401
+ type: "cursor_session_ui",
3402
+ sessionId,
3403
+ payload
3404
+ }),
3405
+ notifyTurnResult: false,
3406
+ completeAssistant: false
3407
+ };
3408
+ }
3409
+ var CursorAcpEventMapper = class {
3099
3410
  toolsBySession = /* @__PURE__ */ new Map();
3100
3411
  completedToolIdsBySession = /* @__PURE__ */ new Map();
3101
3412
  clearSession(sessionId) {
@@ -3125,7 +3436,7 @@ var KimiAcpEventMapper = class {
3125
3436
  sessionId,
3126
3437
  success,
3127
3438
  isError: !success,
3128
- ...!success ? { result: `Kimi ACP stopped: ${stopReason}` } : {}
3439
+ ...!success ? { result: `Cursor ACP stopped: ${stopReason}` } : {}
3129
3440
  }),
3130
3441
  notifyTurnResult: true
3131
3442
  }
@@ -3148,6 +3459,103 @@ var KimiAcpEventMapper = class {
3148
3459
  }
3149
3460
  ];
3150
3461
  }
3462
+ if (method === "cursor/update_todos") {
3463
+ const todos = cursorTodos(params.todos);
3464
+ if (todos.length === 0 && params.merge !== false) return [];
3465
+ return [
3466
+ uiControl(sessionId, {
3467
+ kind: "todos",
3468
+ ...typeof params.toolCallId === "string" ? { toolCallId: params.toolCallId } : {},
3469
+ todos,
3470
+ merge: params.merge !== false
3471
+ })
3472
+ ];
3473
+ }
3474
+ if (method === "cursor/task") {
3475
+ const description = typeof params.description === "string" && params.description.trim() ? params.description : "Cursor Task";
3476
+ const toolId = typeof params.toolCallId === "string" ? params.toolCallId : `cursor-task-${seq}`;
3477
+ return [
3478
+ {
3479
+ kind: "envelope",
3480
+ envelope: buildMessage(
3481
+ "assistant_tool_use",
3482
+ sessionId,
3483
+ seq,
3484
+ {
3485
+ toolName: "Cursor Task",
3486
+ toolId,
3487
+ parameters: {
3488
+ description,
3489
+ ...typeof params.prompt === "string" ? { prompt: params.prompt } : {},
3490
+ ...params.subagentType !== void 0 ? { subagentType: params.subagentType } : {},
3491
+ ...typeof params.model === "string" ? { model: params.model } : {},
3492
+ ...typeof params.agentId === "string" ? { agentId: params.agentId } : {},
3493
+ ...typeof params.durationMs === "number" ? { durationMs: params.durationMs } : {}
3494
+ }
3495
+ },
3496
+ "proxy"
3497
+ )
3498
+ },
3499
+ uiControl(sessionId, {
3500
+ kind: "task",
3501
+ ...typeof params.toolCallId === "string" ? { toolCallId: params.toolCallId } : {},
3502
+ description,
3503
+ ...typeof params.prompt === "string" ? { prompt: params.prompt } : {},
3504
+ ...params.subagentType !== void 0 ? { subagentType: params.subagentType } : {},
3505
+ ...typeof params.model === "string" ? { model: params.model } : {},
3506
+ ...typeof params.agentId === "string" ? { agentId: params.agentId } : {},
3507
+ ...typeof params.durationMs === "number" ? { durationMs: params.durationMs } : {}
3508
+ })
3509
+ ];
3510
+ }
3511
+ if (method === "cursor/generate_image") {
3512
+ const description = typeof params.description === "string" && params.description.trim() ? params.description : "Generated image";
3513
+ const toolId = typeof params.toolCallId === "string" ? params.toolCallId : `cursor-image-${seq}`;
3514
+ const filePath = typeof params.filePath === "string" ? params.filePath : void 0;
3515
+ return [
3516
+ {
3517
+ kind: "envelope",
3518
+ envelope: buildMessage(
3519
+ "assistant_tool_use",
3520
+ sessionId,
3521
+ seq,
3522
+ {
3523
+ toolName: "GenerateImage",
3524
+ toolId,
3525
+ parameters: {
3526
+ description,
3527
+ ...filePath ? { filePath } : {},
3528
+ ...Array.isArray(params.referenceImagePaths) ? { referenceImagePaths: params.referenceImagePaths } : {}
3529
+ }
3530
+ },
3531
+ "proxy"
3532
+ )
3533
+ },
3534
+ ...filePath ? [
3535
+ {
3536
+ kind: "envelope",
3537
+ envelope: buildMessage(
3538
+ "tool_result",
3539
+ sessionId,
3540
+ seq,
3541
+ { toolId, result: filePath, isError: false },
3542
+ "proxy"
3543
+ )
3544
+ }
3545
+ ] : [],
3546
+ uiControl(sessionId, {
3547
+ kind: "image",
3548
+ ...typeof params.toolCallId === "string" ? { toolCallId: params.toolCallId } : {},
3549
+ description,
3550
+ ...filePath ? { filePath } : {},
3551
+ ...Array.isArray(params.referenceImagePaths) ? {
3552
+ referenceImagePaths: params.referenceImagePaths.filter(
3553
+ (path) => typeof path === "string"
3554
+ )
3555
+ } : {}
3556
+ })
3557
+ ];
3558
+ }
3151
3559
  if (method !== "session/update") return [];
3152
3560
  const update = isRecord2(params.update) ? params.update : null;
3153
3561
  if (!update) return [];
@@ -3248,6 +3656,283 @@ var KimiAcpEventMapper = class {
3248
3656
  }
3249
3657
  };
3250
3658
 
3659
+ // src/serve/kimi-acp-event-mapper.ts
3660
+ var KNOWN_IGNORED_UPDATES2 = /* @__PURE__ */ new Set([
3661
+ "config_option_update",
3662
+ "current_mode_update",
3663
+ "plan",
3664
+ "plan_removed",
3665
+ "plan_update",
3666
+ "session_info_update",
3667
+ "usage_update",
3668
+ // Live prompt input is already echoed by RelayInputHandlers. ACP may echo it back too.
3669
+ "user_message_chunk"
3670
+ ]);
3671
+ var COMPLETED_TOOL_ID_LIMIT2 = 512;
3672
+ function isRecord3(value) {
3673
+ return Boolean(value && typeof value === "object" && !Array.isArray(value));
3674
+ }
3675
+ function hasOwn2(record, key) {
3676
+ return Object.prototype.hasOwnProperty.call(record, key);
3677
+ }
3678
+ function contentText2(content) {
3679
+ if (!isRecord3(content) || content.type !== "text") return "";
3680
+ return typeof content.text === "string" ? content.text : "";
3681
+ }
3682
+ function toolName2(tool) {
3683
+ if (tool.name) return tool.name;
3684
+ switch (tool.kind) {
3685
+ case "read":
3686
+ return "Read";
3687
+ case "edit":
3688
+ return "Edit";
3689
+ case "delete":
3690
+ return "Delete";
3691
+ case "move":
3692
+ return "Move";
3693
+ case "search":
3694
+ return "Search";
3695
+ case "execute":
3696
+ return "Bash";
3697
+ case "think":
3698
+ return "Think";
3699
+ case "fetch":
3700
+ return "Fetch";
3701
+ case "switch_mode":
3702
+ return "SwitchMode";
3703
+ default:
3704
+ return tool.title || "Kimi Tool";
3705
+ }
3706
+ }
3707
+ function toolParameters2(tool) {
3708
+ const parameters = isRecord3(tool.rawInput) ? { ...tool.rawInput } : tool.rawInput === void 0 ? {} : { input: tool.rawInput };
3709
+ if (tool.title && !hasOwn2(parameters, "title")) parameters.title = tool.title;
3710
+ if (tool.kind && !hasOwn2(parameters, "kind")) parameters.kind = tool.kind;
3711
+ if (tool.locations?.length && !hasOwn2(parameters, "locations")) {
3712
+ parameters.locations = tool.locations;
3713
+ }
3714
+ return parameters;
3715
+ }
3716
+ function toolResult2(tool) {
3717
+ if (tool.rawOutput !== void 0) return tool.rawOutput;
3718
+ if (tool.content !== void 0) return tool.content;
3719
+ return tool.status ?? "completed";
3720
+ }
3721
+ function sameJsonValue2(left, right) {
3722
+ if (Object.is(left, right)) return true;
3723
+ try {
3724
+ return JSON.stringify(left) === JSON.stringify(right);
3725
+ } catch {
3726
+ return false;
3727
+ }
3728
+ }
3729
+ function mergeToolState2(previous, update) {
3730
+ const toolCallId = typeof update.toolCallId === "string" ? update.toolCallId : previous?.toolCallId;
3731
+ if (!toolCallId) return null;
3732
+ const next = previous ? { ...previous } : { toolCallId };
3733
+ const stringFields = ["name", "title", "kind", "status"];
3734
+ for (const field of stringFields) {
3735
+ if (!hasOwn2(update, field)) continue;
3736
+ const value = update[field];
3737
+ if (typeof value === "string" && value) next[field] = value;
3738
+ else delete next[field];
3739
+ }
3740
+ const arrayFields = ["content", "locations"];
3741
+ for (const field of arrayFields) {
3742
+ if (!hasOwn2(update, field)) continue;
3743
+ const value = update[field];
3744
+ if (Array.isArray(value)) next[field] = value;
3745
+ else delete next[field];
3746
+ }
3747
+ for (const field of ["rawInput", "rawOutput"]) {
3748
+ if (!hasOwn2(update, field)) continue;
3749
+ const value = update[field];
3750
+ if (value === null || value === void 0) delete next[field];
3751
+ else next[field] = value;
3752
+ }
3753
+ return next;
3754
+ }
3755
+ function eventParams2(event) {
3756
+ return isRecord3(event.params) ? event.params : {};
3757
+ }
3758
+ function promptErrorMessage2(params) {
3759
+ if (typeof params.message === "string" && params.message.trim()) return params.message;
3760
+ if (isRecord3(params.error) && typeof params.error.message === "string") {
3761
+ return params.error.message;
3762
+ }
3763
+ return "Kimi ACP prompt failed";
3764
+ }
3765
+ function availableCommands2(update) {
3766
+ if (!Array.isArray(update.availableCommands)) return [];
3767
+ return update.availableCommands.flatMap((candidate) => {
3768
+ if (!isRecord3(candidate) || typeof candidate.name !== "string") return [];
3769
+ const rawName = candidate.name.trim();
3770
+ if (!rawName) return [];
3771
+ const input = isRecord3(candidate.input) ? candidate.input : null;
3772
+ const argumentHint = input && typeof input.hint === "string" ? input.hint : void 0;
3773
+ return [
3774
+ {
3775
+ name: rawName.startsWith("/") ? rawName : `/${rawName}`,
3776
+ description: typeof candidate.description === "string" ? candidate.description : "",
3777
+ ...argumentHint ? { argumentHint } : {},
3778
+ source: "kimi"
3779
+ }
3780
+ ];
3781
+ });
3782
+ }
3783
+ var KimiAcpEventMapper = class {
3784
+ toolsBySession = /* @__PURE__ */ new Map();
3785
+ completedToolIdsBySession = /* @__PURE__ */ new Map();
3786
+ clearSession(sessionId) {
3787
+ this.toolsBySession.delete(sessionId);
3788
+ this.completedToolIdsBySession.delete(sessionId);
3789
+ }
3790
+ clear() {
3791
+ this.toolsBySession.clear();
3792
+ this.completedToolIdsBySession.clear();
3793
+ }
3794
+ finishTurn(sessionId) {
3795
+ this.toolsBySession.delete(sessionId);
3796
+ }
3797
+ map(sessionId, seq, event) {
3798
+ const method = typeof event.method === "string" ? event.method : "";
3799
+ const params = eventParams2(event);
3800
+ if (method === "session/prompt/result") {
3801
+ this.finishTurn(sessionId);
3802
+ const response = isRecord3(params.response) ? params.response : params;
3803
+ const stopReason = typeof response.stopReason === "string" ? response.stopReason : "unknown";
3804
+ const success = stopReason === "end_turn";
3805
+ return [
3806
+ {
3807
+ kind: "control",
3808
+ raw: serializeControl({
3809
+ type: "turn_result",
3810
+ sessionId,
3811
+ success,
3812
+ isError: !success,
3813
+ ...!success ? { result: `Kimi ACP stopped: ${stopReason}` } : {}
3814
+ }),
3815
+ notifyTurnResult: true
3816
+ }
3817
+ ];
3818
+ }
3819
+ if (method === "session/prompt/error") {
3820
+ this.finishTurn(sessionId);
3821
+ const message = promptErrorMessage2(params);
3822
+ return [
3823
+ {
3824
+ kind: "control",
3825
+ raw: serializeControl({
3826
+ type: "turn_result",
3827
+ sessionId,
3828
+ success: false,
3829
+ isError: true,
3830
+ result: message
3831
+ }),
3832
+ notifyTurnResult: true
3833
+ }
3834
+ ];
3835
+ }
3836
+ if (method !== "session/update") return [];
3837
+ const update = isRecord3(params.update) ? params.update : null;
3838
+ if (!update) return [];
3839
+ const updateType = typeof update.sessionUpdate === "string" ? update.sessionUpdate : "";
3840
+ if (updateType === "agent_message_chunk") {
3841
+ const text = contentText2(update.content);
3842
+ return text ? [{ kind: "assistant_text", text }] : [];
3843
+ }
3844
+ if (updateType === "agent_thought_chunk") {
3845
+ const text = contentText2(update.content);
3846
+ return text ? [
3847
+ {
3848
+ kind: "envelope",
3849
+ envelope: buildMessage("thinking", sessionId, seq, { text }, "proxy")
3850
+ }
3851
+ ] : [];
3852
+ }
3853
+ if (updateType === "tool_call" || updateType === "tool_call_update") {
3854
+ return this.mapToolUpdate(sessionId, seq, update, updateType === "tool_call");
3855
+ }
3856
+ if (updateType === "available_commands_update") {
3857
+ const commands = availableCommands2(update);
3858
+ return [
3859
+ {
3860
+ kind: "control",
3861
+ raw: serializeControl({
3862
+ type: "command_list_push",
3863
+ sessionId,
3864
+ commands
3865
+ }),
3866
+ notifyTurnResult: false,
3867
+ completeAssistant: false,
3868
+ providerCommands: commands
3869
+ }
3870
+ ];
3871
+ }
3872
+ if (KNOWN_IGNORED_UPDATES2.has(updateType)) return [];
3873
+ return [{ kind: "unknown_update", updateType: updateType || "<missing>" }];
3874
+ }
3875
+ mapToolUpdate(sessionId, seq, update, isInitial) {
3876
+ const sessionTools = this.toolsBySession.get(sessionId) ?? /* @__PURE__ */ new Map();
3877
+ this.toolsBySession.set(sessionId, sessionTools);
3878
+ const toolCallId = typeof update.toolCallId === "string" ? update.toolCallId : "";
3879
+ if (!toolCallId) return [];
3880
+ const completedToolIds = this.completedToolIdsBySession.get(sessionId) ?? /* @__PURE__ */ new Set();
3881
+ this.completedToolIdsBySession.set(sessionId, completedToolIds);
3882
+ if (completedToolIds.has(toolCallId)) return [];
3883
+ const previous = sessionTools.get(toolCallId);
3884
+ const tool = mergeToolState2(previous, update);
3885
+ if (!tool) return [];
3886
+ sessionTools.set(toolCallId, tool);
3887
+ const mapped = [];
3888
+ const hasPresentationUpdate = ["name", "title", "kind", "rawInput", "locations"].some(
3889
+ (field) => hasOwn2(update, field)
3890
+ );
3891
+ if (isInitial || !previous || hasPresentationUpdate) {
3892
+ mapped.push({
3893
+ kind: "envelope",
3894
+ envelope: buildMessage(
3895
+ "assistant_tool_use",
3896
+ sessionId,
3897
+ seq,
3898
+ {
3899
+ toolName: toolName2(tool),
3900
+ toolId: tool.toolCallId,
3901
+ parameters: toolParameters2(tool)
3902
+ },
3903
+ "proxy"
3904
+ )
3905
+ });
3906
+ }
3907
+ const terminal = tool.status === "completed" || tool.status === "failed";
3908
+ const previousTerminal = previous?.status === "completed" || previous?.status === "failed";
3909
+ const terminalResultChanged = previousTerminal && (hasOwn2(update, "rawOutput") || hasOwn2(update, "content")) && !sameJsonValue2(toolResult2(previous), toolResult2(tool));
3910
+ if (terminal && (!previousTerminal || previous?.status !== tool.status || terminalResultChanged)) {
3911
+ mapped.push({
3912
+ kind: "envelope",
3913
+ envelope: buildMessage(
3914
+ "tool_result",
3915
+ sessionId,
3916
+ seq,
3917
+ {
3918
+ toolId: tool.toolCallId,
3919
+ result: toolResult2(tool),
3920
+ isError: tool.status === "failed"
3921
+ },
3922
+ "proxy"
3923
+ )
3924
+ });
3925
+ sessionTools.delete(toolCallId);
3926
+ completedToolIds.add(toolCallId);
3927
+ if (completedToolIds.size > COMPLETED_TOOL_ID_LIMIT2) {
3928
+ const oldest = completedToolIds.values().next().value;
3929
+ if (oldest !== void 0) completedToolIds.delete(oldest);
3930
+ }
3931
+ }
3932
+ return mapped;
3933
+ }
3934
+ };
3935
+
3251
3936
  // src/serve/worker-registry.ts
3252
3937
  var RECONNECT_WORKER_HANDSHAKE_TIMEOUT_MS = 1e3;
3253
3938
  var WorkerStartupError = class extends Error {
@@ -3294,6 +3979,9 @@ var WorkerRegistry = class {
3294
3979
  pendingNativeSessions = /* @__PURE__ */ new Map();
3295
3980
  assistantSnapshots = /* @__PURE__ */ new Map();
3296
3981
  kimiAcpEventMapper = new KimiAcpEventMapper();
3982
+ cursorAcpEventMapper = new CursorAcpEventMapper();
3983
+ /** 用户点停止后到下一轮开始前,丢弃 Cursor 晚到的旧回答,避免接进下一轮。 */
3984
+ interruptedCursorSessions = /* @__PURE__ */ new Set();
3297
3985
  startupFailures = /* @__PURE__ */ new Map();
3298
3986
  assistantTurnCounter = 0;
3299
3987
  onEnvelopeDropped(raw) {
@@ -3617,6 +4305,8 @@ var WorkerRegistry = class {
3617
4305
  this.pendingNativeSessions.delete(sessionId);
3618
4306
  this.assistantSnapshots.delete(sessionId);
3619
4307
  this.kimiAcpEventMapper.clearSession(sessionId);
4308
+ this.cursorAcpEventMapper.clearSession(sessionId);
4309
+ this.interruptedCursorSessions.delete(sessionId);
3620
4310
  this.rejectReadyWaiters(
3621
4311
  new Error(`Worker session deleted before ready: ${sessionId}`),
3622
4312
  sessionId
@@ -3631,6 +4321,8 @@ var WorkerRegistry = class {
3631
4321
  this.pendingNativeSessions.delete(sessionId);
3632
4322
  this.assistantSnapshots.delete(sessionId);
3633
4323
  this.kimiAcpEventMapper.clearSession(sessionId);
4324
+ this.cursorAcpEventMapper.clearSession(sessionId);
4325
+ this.interruptedCursorSessions.delete(sessionId);
3634
4326
  this.startupFailures.delete(sessionId);
3635
4327
  this.children.delete(sessionId);
3636
4328
  this.providers.delete(sessionId);
@@ -3658,6 +4350,8 @@ var WorkerRegistry = class {
3658
4350
  this.pendingNativeSessions.clear();
3659
4351
  this.assistantSnapshots.clear();
3660
4352
  this.kimiAcpEventMapper.clear();
4353
+ this.cursorAcpEventMapper.clear();
4354
+ this.interruptedCursorSessions.clear();
3661
4355
  this.startupFailures.clear();
3662
4356
  this.rejectReadyWaiters(new Error("Worker registry destroyed"));
3663
4357
  }
@@ -3709,8 +4403,16 @@ var WorkerRegistry = class {
3709
4403
  "JSON session exited"
3710
4404
  );
3711
4405
  break;
3712
- case "worker_interrupted":
4406
+ case "worker_interrupted": {
3713
4407
  this.kimiAcpEventMapper.finishTurn(sessionId);
4408
+ this.cursorAcpEventMapper.finishTurn(sessionId);
4409
+ this.completeAssistantSnapshot(
4410
+ sessionId,
4411
+ this.deps.nextSeq?.(sessionId) ?? getSeqCounterFor(sessionId).next()
4412
+ );
4413
+ if ((this.providers.get(sessionId) ?? this.deps.sessionManager.getSession(sessionId)?.provider) === "cursor") {
4414
+ this.interruptedCursorSessions.add(sessionId);
4415
+ }
3714
4416
  this.deps.permissionBroker.cleanupSession(sessionId, "Turn interrupted");
3715
4417
  this.deps.relayConnection.sendRaw(
3716
4418
  serializeControl({
@@ -3730,7 +4432,9 @@ var WorkerRegistry = class {
3730
4432
  this.deps.jsonObserver.onTurnResult(sessionId);
3731
4433
  serviceLogger.info({ sessionId }, "JSON turn interrupted");
3732
4434
  break;
4435
+ }
3733
4436
  case "worker_turn_started":
4437
+ this.interruptedCursorSessions.delete(sessionId);
3734
4438
  this.deps.jsonObserver.onTurnStart(sessionId);
3735
4439
  serviceLogger.debug({ sessionId }, "Queued JSON turn started");
3736
4440
  break;
@@ -3881,6 +4585,8 @@ var WorkerRegistry = class {
3881
4585
  this.pendingNativeSessions.delete(sessionId);
3882
4586
  this.assistantSnapshots.delete(sessionId);
3883
4587
  this.kimiAcpEventMapper.clearSession(sessionId);
4588
+ this.cursorAcpEventMapper.clearSession(sessionId);
4589
+ this.interruptedCursorSessions.delete(sessionId);
3884
4590
  if (child) this.startupFailures.set(sessionId, error);
3885
4591
  else this.startupFailures.delete(sessionId);
3886
4592
  this.rejectReadyWaiters(error, sessionId);
@@ -3979,6 +4685,10 @@ var WorkerRegistry = class {
3979
4685
  this.forwardKimiAcpEvent(sessionId, seq, event);
3980
4686
  return;
3981
4687
  }
4688
+ if (event.type === "cursor_acp") {
4689
+ this.forwardCursorAcpEvent(sessionId, seq, event);
4690
+ return;
4691
+ }
3982
4692
  if (event.type === "codex_app_server") {
3983
4693
  this.forwardCodexAppServerEvent(sessionId, seq, event);
3984
4694
  return;
@@ -4081,6 +4791,33 @@ var WorkerRegistry = class {
4081
4791
  }
4082
4792
  }
4083
4793
  }
4794
+ forwardCursorAcpEvent(sessionId, seq, event) {
4795
+ const relay = this.deps.relayConnection;
4796
+ this.deps.touchSessionActivity?.(sessionId);
4797
+ for (const mapped of this.cursorAcpEventMapper.map(sessionId, seq, event)) {
4798
+ if (mapped.kind === "assistant_text") {
4799
+ if (this.interruptedCursorSessions.has(sessionId)) continue;
4800
+ this.appendAssistantSnapshot(sessionId, seq, mapped.text);
4801
+ } else if (mapped.kind === "envelope") {
4802
+ if (mapped.envelope.type === "assistant_tool_use" || mapped.envelope.type === "user_input" || mapped.envelope.type === "assistant_message") {
4803
+ this.completeAssistantSnapshot(sessionId, seq);
4804
+ }
4805
+ relay.sendEnvelope(mapped.envelope);
4806
+ } else if (mapped.kind === "control") {
4807
+ if (mapped.providerCommands) {
4808
+ this.deps.setProviderCommands?.(sessionId, mapped.providerCommands);
4809
+ }
4810
+ if (mapped.completeAssistant !== false) this.completeAssistantSnapshot(sessionId, seq);
4811
+ relay.sendRaw(mapped.raw);
4812
+ if (mapped.notifyTurnResult) this.deps.jsonObserver.onTurnResult(sessionId);
4813
+ } else {
4814
+ serviceLogger.warn(
4815
+ { sessionId, seq, updateType: mapped.updateType },
4816
+ "Unknown Cursor ACP session update; protocol may have changed"
4817
+ );
4818
+ }
4819
+ }
4820
+ }
4084
4821
  nextAssistantTurnId(sessionId) {
4085
4822
  this.assistantTurnCounter += 1;
4086
4823
  return `${sessionId}-assistant-${Date.now()}-${this.assistantTurnCounter}`;
@@ -4185,7 +4922,8 @@ var WorkerRegistry = class {
4185
4922
  toolName: msg.toolName,
4186
4923
  toolId: msg.requestId,
4187
4924
  parameters: msg.input,
4188
- ...msg.options ? { options: msg.options } : {}
4925
+ ...msg.options ? { options: msg.options } : {},
4926
+ ...msg.cursorPrompt ? { cursorPrompt: msg.cursorPrompt } : {}
4189
4927
  },
4190
4928
  "proxy"
4191
4929
  );
@@ -4210,7 +4948,8 @@ var WorkerRegistry = class {
4210
4948
  sessionId,
4211
4949
  toolName: msg.toolName,
4212
4950
  input: msg.input,
4213
- ...msg.options ? { options: msg.options } : {}
4951
+ ...msg.options ? { options: msg.options } : {},
4952
+ ...msg.cursorPrompt ? { cursorPrompt: msg.cursorPrompt } : {}
4214
4953
  },
4215
4954
  (decision) => {
4216
4955
  this.send(sessionId, {
@@ -4219,7 +4958,8 @@ var WorkerRegistry = class {
4219
4958
  behavior: decision.behavior,
4220
4959
  ...decision.message ? { message: decision.message } : {},
4221
4960
  ...decision.remember ? { remember: true } : {},
4222
- ...decision.optionId ? { optionId: decision.optionId } : {}
4961
+ ...decision.optionId ? { optionId: decision.optionId } : {},
4962
+ ...decision.cursorAnswer ? { cursorAnswer: decision.cursorAnswer } : {}
4223
4963
  });
4224
4964
  }
4225
4965
  );
@@ -4414,13 +5154,13 @@ var RelayInputHandlers = class {
4414
5154
  };
4415
5155
 
4416
5156
  // src/serve/session-history.ts
4417
- import { readdir as readdir4, lstat as lstat4, access, open, readFile as readFile2 } from "fs/promises";
5157
+ import { readdir as readdir5, lstat as lstat5, access, open, readFile as readFile3 } from "fs/promises";
4418
5158
  import { createReadStream as createReadStream2 } from "fs";
4419
- import { join as join9 } from "path";
5159
+ import { join as join10 } from "path";
4420
5160
  import { createInterface as createInterface2 } from "readline";
4421
5161
  async function readKimiSessionState(filePath) {
4422
5162
  try {
4423
- return asRecord2(JSON.parse(await readFile2(filePath, "utf8")));
5163
+ return asRecord2(JSON.parse(await readFile3(filePath, "utf8")));
4424
5164
  } catch {
4425
5165
  return null;
4426
5166
  }
@@ -4429,6 +5169,7 @@ var DEFAULT_HISTORY_PAGE_LIMIT = 50;
4429
5169
  var MAX_HISTORY_PAGE_LIMIT = 200;
4430
5170
  var HISTORY_READ_CHUNK_BYTES = 64 * 1024;
4431
5171
  var HISTORY_CURSOR_PREFIX = "b:";
5172
+ var CURSOR_INDEX_PREFIX = "i:";
4432
5173
  var ANSI_ESCAPE_PATTERN2 = new RegExp(`${String.fromCharCode(27)}\\[[0-?]*[ -/]*[@-~]`, "g");
4433
5174
  var COMPACT_HISTORY_MARKER = "\u4E0A\u4E0B\u6587\u5DF2\u538B\u7F29";
4434
5175
  function normalizeHistoryPageLimit(limit) {
@@ -4439,6 +5180,15 @@ function encodeHistoryCursor(offset, itemIndex = 0) {
4439
5180
  const base = `${HISTORY_CURSOR_PREFIX}${Math.max(0, Math.floor(offset))}`;
4440
5181
  return itemIndex > 0 ? `${base}:${itemIndex}` : base;
4441
5182
  }
5183
+ function encodeCursorIndexCursor(index) {
5184
+ return `${CURSOR_INDEX_PREFIX}${Math.max(0, Math.floor(index))}`;
5185
+ }
5186
+ function decodeCursorIndexCursor(cursor, length) {
5187
+ if (!cursor || !cursor.startsWith(CURSOR_INDEX_PREFIX)) return length;
5188
+ const parsed = Number(cursor.slice(CURSOR_INDEX_PREFIX.length));
5189
+ if (!Number.isInteger(parsed) || parsed < 0) return length;
5190
+ return Math.min(parsed, length);
5191
+ }
4442
5192
  function decodeHistoryCursor(cursor, fileSize) {
4443
5193
  if (!cursor) return fileSize;
4444
5194
  const raw = cursor.startsWith(HISTORY_CURSOR_PREFIX) ? cursor.slice(HISTORY_CURSOR_PREFIX.length) : cursor;
@@ -4450,12 +5200,12 @@ async function findClaudeSessionFile(claudeSessionId) {
4450
5200
  if (!SAFE_SESSION_ID_PATTERN.test(claudeSessionId)) return null;
4451
5201
  let projectDirs;
4452
5202
  try {
4453
- projectDirs = await readdir4(claudeProjectsDir());
5203
+ projectDirs = await readdir5(claudeProjectsDir());
4454
5204
  } catch {
4455
5205
  return null;
4456
5206
  }
4457
5207
  for (const encodedDir of projectDirs) {
4458
- const filePath = join9(claudeProjectsDir(), encodedDir, `${claudeSessionId}.jsonl`);
5208
+ const filePath = join10(claudeProjectsDir(), encodedDir, `${claudeSessionId}.jsonl`);
4459
5209
  try {
4460
5210
  await access(filePath);
4461
5211
  return filePath;
@@ -4481,6 +5231,7 @@ async function findCodexSessionFile(codexSessionId) {
4481
5231
  return null;
4482
5232
  }
4483
5233
  async function findSessionFile(sessionId, provider) {
5234
+ if (provider === "cursor") return null;
4484
5235
  if (provider === "claude") return findClaudeSessionFile(sessionId);
4485
5236
  if (provider === "codex") return findCodexSessionFile(sessionId);
4486
5237
  if (provider === "kimi") return findKimiSessionFile(sessionId);
@@ -4492,9 +5243,9 @@ async function findKimiSessionFile(kimiSessionId) {
4492
5243
  for (const stateFile of stateFiles) {
4493
5244
  const state = await readKimiSessionState(stateFile);
4494
5245
  if (state?.id !== kimiSessionId) continue;
4495
- const wireFile = join9(stateFile.slice(0, -"state.json".length), "agents", "main", "wire.jsonl");
5246
+ const wireFile = join10(stateFile.slice(0, -"state.json".length), "agents", "main", "wire.jsonl");
4496
5247
  try {
4497
- const wireStat = await lstat4(wireFile);
5248
+ const wireStat = await lstat5(wireFile);
4498
5249
  if (wireStat.isSymbolicLink() || !wireStat.isFile()) continue;
4499
5250
  return wireFile;
4500
5251
  } catch {
@@ -4863,8 +5614,8 @@ function decodeCodexExecInput(input) {
4863
5614
  }
4864
5615
  function normalizeHistoryToolParameters(rawToolName, input) {
4865
5616
  const parameters = parseToolInput(input);
4866
- const toolName2 = normalizeHistoryToolName(rawToolName);
4867
- if (toolName2 === "Bash" && typeof parameters.command !== "string") {
5617
+ const toolName3 = normalizeHistoryToolName(rawToolName);
5618
+ if (toolName3 === "Bash" && typeof parameters.command !== "string") {
4868
5619
  const command = typeof parameters.cmd === "string" ? parameters.cmd : void 0;
4869
5620
  if (command) {
4870
5621
  const rest = { ...parameters };
@@ -4879,7 +5630,7 @@ function normalizeHistoryToolParameters(rawToolName, input) {
4879
5630
  }
4880
5631
  }
4881
5632
  }
4882
- if (toolName2 === "Patch" && typeof input === "string" && !parameters.content) {
5633
+ if (toolName3 === "Patch" && typeof input === "string" && !parameters.content) {
4883
5634
  return { ...parameters, content: input };
4884
5635
  }
4885
5636
  return parameters;
@@ -4892,19 +5643,19 @@ function normalizeHistoryToolCall(rawToolName, input) {
4892
5643
  return { toolName: "ToolScript", parameters: {} };
4893
5644
  }
4894
5645
  }
4895
- const toolName2 = normalizeHistoryToolName(rawToolName);
4896
- return { toolName: toolName2, parameters: normalizeHistoryToolParameters(rawToolName, input) };
5646
+ const toolName3 = normalizeHistoryToolName(rawToolName);
5647
+ return { toolName: toolName3, parameters: normalizeHistoryToolParameters(rawToolName, input) };
4897
5648
  }
4898
5649
  function toolUseHistoryItem(toolId, rawToolName, input, timestamp) {
4899
5650
  if (!toolId || !rawToolName) return null;
4900
- const { toolName: toolName2, parameters } = normalizeHistoryToolCall(rawToolName, input);
5651
+ const { toolName: toolName3, parameters } = normalizeHistoryToolCall(rawToolName, input);
4901
5652
  return {
4902
5653
  kind: "message",
4903
5654
  message: {
4904
5655
  role: "activity",
4905
- text: summarizeToolActivity(toolName2, parameters),
5656
+ text: summarizeToolActivity(toolName3, parameters),
4906
5657
  toolId,
4907
- toolName: toolName2,
5658
+ toolName: toolName3,
4908
5659
  parameters,
4909
5660
  status: "running",
4910
5661
  ...timestamp !== void 0 ? { timestamp } : {}
@@ -4970,6 +5721,124 @@ ${payload.text}`
4970
5721
  }
4971
5722
  return items;
4972
5723
  }
5724
+ function stripCursorSystemReminders(text) {
5725
+ return text.replace(/<system_reminder>[\s\S]*?<\/system_reminder>/gi, "");
5726
+ }
5727
+ function unwrapCursorUserText(rawText) {
5728
+ const text = stripCursorSystemReminders(rawText);
5729
+ const query = text.match(/<user_query>\s*([\s\S]*?)\s*<\/user_query>/i);
5730
+ if (query?.[1] !== void 0) {
5731
+ const unwrapped = query[1].trim();
5732
+ return unwrapped.length > 0 ? unwrapped : null;
5733
+ }
5734
+ if (/^<(?:user_info|timestamp|environment_context|conversation_summary)(?:[\s>:-])/i.test(
5735
+ text.trim()
5736
+ )) {
5737
+ return null;
5738
+ }
5739
+ return text.trim() ? text.trim() : null;
5740
+ }
5741
+ function unwrapCursorUserContent(content) {
5742
+ if (typeof content === "string") return unwrapCursorUserText(content) ?? "";
5743
+ if (!Array.isArray(content)) return content;
5744
+ return content.flatMap((block) => {
5745
+ const record = asRecord2(block);
5746
+ if (record?.type === "text" && typeof record.text === "string") {
5747
+ const text = unwrapCursorUserText(record.text);
5748
+ return text ? [{ ...record, text }] : [];
5749
+ }
5750
+ return [block];
5751
+ });
5752
+ }
5753
+ function mapCursorAssistantContent(content) {
5754
+ if (!Array.isArray(content)) return content;
5755
+ return content.flatMap((block) => {
5756
+ const record = asRecord2(block);
5757
+ if (!record || typeof record.type !== "string") return [];
5758
+ if (record.type === "reasoning") return [];
5759
+ if (record.type === "tool-call") {
5760
+ return [
5761
+ {
5762
+ type: "tool_use",
5763
+ id: record.toolCallId,
5764
+ name: record.toolName,
5765
+ input: record.args ?? record.input
5766
+ }
5767
+ ];
5768
+ }
5769
+ return [block];
5770
+ });
5771
+ }
5772
+ function extractCursorToolResults(content) {
5773
+ if (!Array.isArray(content)) return [];
5774
+ const items = [];
5775
+ for (const block of content) {
5776
+ const record = asRecord2(block);
5777
+ if (record?.type !== "tool-result" || typeof record.toolCallId !== "string") continue;
5778
+ items.push({
5779
+ kind: "tool-result",
5780
+ toolId: record.toolCallId,
5781
+ isError: record.isError === true || record.is_error === true
5782
+ });
5783
+ }
5784
+ return items;
5785
+ }
5786
+ function extractCursorConversationItems(obj) {
5787
+ const record = asRecord2(obj);
5788
+ if (!record || typeof record.role !== "string") return [];
5789
+ if (record.role === "user") {
5790
+ return extractClaudeContentItems("user", unwrapCursorUserContent(record.content));
5791
+ }
5792
+ if (record.role === "assistant") {
5793
+ return extractClaudeContentItems("assistant", mapCursorAssistantContent(record.content));
5794
+ }
5795
+ if (record.role === "tool") return extractCursorToolResults(record.content);
5796
+ return [];
5797
+ }
5798
+ function collectCursorHistoryMessages(records) {
5799
+ const messages = [];
5800
+ const toolMessageIndexes = /* @__PURE__ */ new Map();
5801
+ for (const record of records) {
5802
+ for (const item of extractCursorConversationItems(record)) {
5803
+ if (item.kind === "tool-result") {
5804
+ const messageIndex = toolMessageIndexes.get(item.toolId);
5805
+ const message = messageIndex !== void 0 ? messages[messageIndex] : void 0;
5806
+ if (messageIndex !== void 0 && message?.role === "activity") {
5807
+ messages[messageIndex] = {
5808
+ ...message,
5809
+ status: item.isError ? "error" : "done"
5810
+ };
5811
+ }
5812
+ continue;
5813
+ }
5814
+ if (item.message.role === "activity") {
5815
+ toolMessageIndexes.set(item.message.toolId, messages.length);
5816
+ }
5817
+ messages.push(item.message);
5818
+ }
5819
+ }
5820
+ return messages;
5821
+ }
5822
+ function pageCursorHistoryMessages(messages, options = {}) {
5823
+ const limit = normalizeHistoryPageLimit(options.limit);
5824
+ const positioned = messages.map((message, index) => ({
5825
+ ...message,
5826
+ cursor: encodeCursorIndexCursor(index)
5827
+ }));
5828
+ const end = decodeCursorIndexCursor(options.before, positioned.length);
5829
+ const start = Math.max(0, end - limit);
5830
+ const page = positioned.slice(start, end);
5831
+ const hasMore = start > 0;
5832
+ return {
5833
+ messages: page,
5834
+ hasMore,
5835
+ ...hasMore ? { nextBefore: encodeCursorIndexCursor(start) } : {}
5836
+ };
5837
+ }
5838
+ async function readCursorSessionMessagesPage(sessionId, options = {}) {
5839
+ const messages = collectCursorHistoryMessages(await readCursorConversationRecords(sessionId));
5840
+ return pageCursorHistoryMessages(messages, options);
5841
+ }
4973
5842
  function extractCodexMessage(payload, source, timestamp, turnId) {
4974
5843
  const role = payload.role;
4975
5844
  if (role !== "user" && role !== "assistant") return [];
@@ -5082,9 +5951,9 @@ function extractConversationItemsFromJson(obj) {
5082
5951
  if (payload.type === "message") return extractCodexMessage(payload, "response_item", timestamp);
5083
5952
  if (payload.type === "function_call" || payload.type === "custom_tool_call") {
5084
5953
  const toolId = typeof payload.call_id === "string" ? payload.call_id : typeof payload.id === "string" ? payload.id : "";
5085
- const toolName2 = typeof payload.name === "string" ? payload.name : "";
5954
+ const toolName3 = typeof payload.name === "string" ? payload.name : "";
5086
5955
  const input = payload.arguments ?? payload.input;
5087
- const item = toolUseHistoryItem(toolId, toolName2, input, timestamp);
5956
+ const item = toolUseHistoryItem(toolId, toolName3, input, timestamp);
5088
5957
  return item ? [item] : [];
5089
5958
  }
5090
5959
  if (payload.type === "function_call_output" || payload.type === "custom_tool_call_output") {
@@ -5192,6 +6061,7 @@ async function readSessionMessagesPageFromFile(filePath, options = {}) {
5192
6061
  }
5193
6062
  }
5194
6063
  async function readSessionMessagesPage(sessionId, options = {}, provider) {
6064
+ if (provider === "cursor") return readCursorSessionMessagesPage(sessionId, options);
5195
6065
  const filePath = await findSessionFile(sessionId, provider);
5196
6066
  if (!filePath) return { messages: [], hasMore: false };
5197
6067
  return readSessionMessagesPageFromFile(filePath, options);
@@ -5302,7 +6172,8 @@ var RelayHistoryHandlers = class {
5302
6172
  requestId: approval.requestId,
5303
6173
  toolName: approval.toolName,
5304
6174
  input: approval.input,
5305
- ...approval.options ? { options: approval.options } : {}
6175
+ ...approval.options ? { options: approval.options } : {},
6176
+ ...approval.cursorPrompt ? { cursorPrompt: approval.cursorPrompt } : {}
5306
6177
  }));
5307
6178
  this.deps.relaySend(
5308
6179
  serializeControl({ type: "pending_approvals_push", sessionId: sid, approvals })
@@ -5411,7 +6282,7 @@ var RelayPermissionHandlers = class {
5411
6282
  );
5412
6283
  return;
5413
6284
  }
5414
- const optionError = validateDecisionOption(pending.options, optionId, "allow");
6285
+ const optionError = pending.cursorPrompt ? null : validateDecisionOption(pending.options, optionId, "allow");
5415
6286
  if (optionError) {
5416
6287
  this.resolveInvalidOption(pending, payload.toolId, optionError);
5417
6288
  return;
@@ -5419,7 +6290,8 @@ var RelayPermissionHandlers = class {
5419
6290
  if (!this.deps.permissionBroker.resolve(payload.toolId, {
5420
6291
  behavior: "allow",
5421
6292
  ...payload.whitelistTool ? { remember: true } : {},
5422
- ...optionId ? { optionId } : {}
6293
+ ...optionId ? { optionId } : {},
6294
+ ...payload.cursorAnswer ? { cursorAnswer: payload.cursorAnswer } : {}
5423
6295
  })) {
5424
6296
  this.pushPermissionDecisionResult(
5425
6297
  pending.sessionId,
@@ -5442,15 +6314,15 @@ var RelayPermissionHandlers = class {
5442
6314
  }
5443
6315
  );
5444
6316
  if (pending.source === "worker" && payload.whitelistTool) {
5445
- const toolName2 = pending.toolName;
5446
- if (toolName2) {
6317
+ const toolName3 = pending.toolName;
6318
+ if (toolName3) {
5447
6319
  const whitelisted = this.deps.workerRegistry.send(pending.sessionId, {
5448
6320
  type: "worker_whitelist_add",
5449
- toolName: toolName2
6321
+ toolName: toolName3
5450
6322
  });
5451
6323
  if (whitelisted) {
5452
6324
  serviceLogger.info(
5453
- { sessionId: pending.sessionId, toolName: toolName2 },
6325
+ { sessionId: pending.sessionId, toolName: toolName3 },
5454
6326
  "Tool added to session whitelist via relay"
5455
6327
  );
5456
6328
  }
@@ -5478,7 +6350,7 @@ var RelayPermissionHandlers = class {
5478
6350
  );
5479
6351
  return;
5480
6352
  }
5481
- const optionError = validateDecisionOption(pending.options, optionId, "deny");
6353
+ const optionError = pending.cursorPrompt ? null : validateDecisionOption(pending.options, optionId, "deny");
5482
6354
  if (optionError) {
5483
6355
  this.resolveInvalidOption(pending, payload.toolId, optionError);
5484
6356
  return;
@@ -5486,7 +6358,8 @@ var RelayPermissionHandlers = class {
5486
6358
  if (!this.deps.permissionBroker.resolve(payload.toolId, {
5487
6359
  behavior: "deny",
5488
6360
  message: reason,
5489
- ...optionId ? { optionId } : {}
6361
+ ...optionId ? { optionId } : {},
6362
+ ...payload.cursorAnswer ? { cursorAnswer: payload.cursorAnswer } : {}
5490
6363
  })) {
5491
6364
  this.pushPermissionDecisionResult(
5492
6365
  pending.sessionId,
@@ -5569,7 +6442,7 @@ var RelayPermissionHandlers = class {
5569
6442
  // src/serve/relay-resource-handlers.ts
5570
6443
  import { homedir as homedir4 } from "os";
5571
6444
  import { accessSync, constants, statSync } from "fs";
5572
- import { isAbsolute as isAbsolute7 } from "path";
6445
+ import { isAbsolute as isAbsolute8 } from "path";
5573
6446
 
5574
6447
  // src/common/terminal-shell.ts
5575
6448
  import { win32 } from "path";
@@ -5622,7 +6495,7 @@ function resolveTerminalShell(shell, env = process.env, options = {}) {
5622
6495
 
5623
6496
  // src/common/filesystem-roots.ts
5624
6497
  import { execFile } from "child_process";
5625
- import { readdir as readdir5, readFile as readFile3 } from "fs/promises";
6498
+ import { readdir as readdir6, readFile as readFile4 } from "fs/promises";
5626
6499
  import { platform } from "os";
5627
6500
  import { basename as basename3 } from "path";
5628
6501
  import { promisify } from "util";
@@ -5672,7 +6545,7 @@ async function listFileSystemRoots() {
5672
6545
  return uniqueRoots(paths.sort().map((path) => ({ name: path, path })));
5673
6546
  }
5674
6547
  if (platform() === "darwin") {
5675
- const volumes = await readdir5("/Volumes", { withFileTypes: true });
6548
+ const volumes = await readdir6("/Volumes", { withFileTypes: true });
5676
6549
  return [
5677
6550
  { name: "/", path: "/" },
5678
6551
  ...volumes.filter(
@@ -5681,7 +6554,7 @@ async function listFileSystemRoots() {
5681
6554
  ];
5682
6555
  }
5683
6556
  if (platform() === "linux") {
5684
- return linuxMountRoots(await readFile3("/proc/self/mountinfo", "utf8"));
6557
+ return linuxMountRoots(await readFile4("/proc/self/mountinfo", "utf8"));
5685
6558
  }
5686
6559
  return [{ name: "/", path: "/" }];
5687
6560
  }
@@ -5692,7 +6565,7 @@ function errorMessage(err) {
5692
6565
  }
5693
6566
  function validateExecutablePath(path) {
5694
6567
  const normalized = path.trim();
5695
- if (!isAbsolute7(normalized)) throw new Error("CLI \u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
6568
+ if (!isAbsolute8(normalized)) throw new Error("CLI \u8DEF\u5F84\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84");
5696
6569
  const stat2 = statSync(normalized);
5697
6570
  if (!stat2.isFile()) throw new Error("CLI \u8DEF\u5F84\u4E0D\u662F\u53EF\u6267\u884C\u6587\u4EF6");
5698
6571
  accessSync(normalized, constants.X_OK);
@@ -5721,7 +6594,7 @@ var RelayResourceHandlers = class {
5721
6594
  onAgentCliConfigUpdate(msg) {
5722
6595
  const { requestId, provider } = msg;
5723
6596
  const rawPath = msg.path;
5724
- if (provider !== "claude" && provider !== "codex" && provider !== "kimi") {
6597
+ if (provider !== "claude" && provider !== "codex" && provider !== "kimi" && provider !== "cursor") {
5725
6598
  this.deps.relaySend(
5726
6599
  serializeControl({
5727
6600
  type: "agent_cli_config_update_response",
@@ -5823,7 +6696,7 @@ var RelayResourceHandlers = class {
5823
6696
  sessionId: sid,
5824
6697
  requestId: msg.requestId,
5825
6698
  workDir: session.cwd,
5826
- includeCommands: session.provider !== "kimi"
6699
+ includeCommands: session.provider !== "kimi" && session.provider !== "cursor"
5827
6700
  });
5828
6701
  serviceLogger.info({ sessionId: sid, cwd: session.cwd }, "Session resources requested");
5829
6702
  }
@@ -5832,13 +6705,13 @@ var RelayResourceHandlers = class {
5832
6705
  // src/serve/relay-session-create-handler.ts
5833
6706
  import { rmSync, statSync as statSync2 } from "fs";
5834
6707
  import { homedir as homedir6 } from "os";
5835
- import { isAbsolute as isAbsolute9 } from "path";
6708
+ import { isAbsolute as isAbsolute10 } from "path";
5836
6709
  import { nanoid as nanoid3 } from "nanoid";
5837
6710
 
5838
6711
  // src/common/codex-active-writer.ts
5839
6712
  import { existsSync as existsSync5 } from "fs";
5840
6713
  import { homedir as homedir5 } from "os";
5841
- import { isAbsolute as isAbsolute8, join as join10 } from "path";
6714
+ import { isAbsolute as isAbsolute9, join as join11 } from "path";
5842
6715
  import { spawnSync as spawnSync2 } from "child_process";
5843
6716
  var CODEX_THREAD_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;
5844
6717
  var LSOF_TIMEOUT_MS = 1e3;
@@ -5846,8 +6719,8 @@ function findCodexActiveWriter(threadId, env = process.env) {
5846
6719
  if (process.platform === "win32") return null;
5847
6720
  if (!CODEX_THREAD_ID_RE.test(threadId)) return null;
5848
6721
  const configuredHome = env.CODEX_HOME?.trim();
5849
- const codexHome = configuredHome && isAbsolute8(configuredHome) ? configuredHome : join10(homedir5(), ".codex");
5850
- const lockPath = join10(codexHome, "thread-writer-locks", `${threadId}.lock`);
6722
+ const codexHome = configuredHome && isAbsolute9(configuredHome) ? configuredHome : join11(homedir5(), ".codex");
6723
+ const lockPath = join11(codexHome, "thread-writer-locks", `${threadId}.lock`);
5851
6724
  if (!existsSync5(lockPath)) return null;
5852
6725
  const commands = process.platform === "darwin" ? ["/usr/sbin/lsof", "lsof"] : ["lsof"];
5853
6726
  for (const command of commands) {
@@ -6016,7 +6889,7 @@ function validateSessionCwd(cwd) {
6016
6889
  return { message: "\u8BF7\u8F93\u5165\u5DE5\u4F5C\u76EE\u5F55", code: ControlErrorCode.INVALID_PATH };
6017
6890
  }
6018
6891
  const trimmed = cwd.trim();
6019
- if (!isAbsolute9(trimmed)) {
6892
+ if (!isAbsolute10(trimmed)) {
6020
6893
  return { message: "\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84", code: ControlErrorCode.INVALID_PATH };
6021
6894
  }
6022
6895
  try {
@@ -6081,9 +6954,9 @@ var RelaySessionCreateHandler = class {
6081
6954
  const mode = msg.mode;
6082
6955
  const permissionMode = msg.permissionMode;
6083
6956
  const resumeSessionId = msg.resumeSessionId;
6084
- if (provider === "kimi" && resumeSessionId) {
6957
+ if ((provider === "kimi" || provider === "cursor") && resumeSessionId) {
6085
6958
  const existing = this.deps.sessionManager.listSessions().find(
6086
- (session) => session.provider === "kimi" && session.historySessionId === resumeSessionId
6959
+ (session) => session.provider === provider && session.historySessionId === resumeSessionId
6087
6960
  );
6088
6961
  if (existing) {
6089
6962
  this.respondWithExistingSession(requestId, existing);
@@ -6173,6 +7046,30 @@ var RelaySessionCreateHandler = class {
6173
7046
  return;
6174
7047
  }
6175
7048
  }
7049
+ if (provider === "cursor") {
7050
+ try {
7051
+ if (mode === "pty") resolveCursorPermissionFlags(permissionMode);
7052
+ else resolveCursorAcpMode(permissionMode);
7053
+ } catch (err) {
7054
+ if (!(err instanceof CursorPermissionModeUnsupportedError)) {
7055
+ throw err;
7056
+ }
7057
+ this.deps.relaySend(
7058
+ serializeControl({
7059
+ type: "session_create_response",
7060
+ requestId,
7061
+ success: false,
7062
+ errorCode: ControlErrorCode.APPROVAL_POLICY_UNSUPPORTED,
7063
+ error: err.message
7064
+ })
7065
+ );
7066
+ serviceLogger.warn(
7067
+ { provider, permissionMode },
7068
+ "Cursor session create rejected: unsupported approval policy"
7069
+ );
7070
+ return;
7071
+ }
7072
+ }
6176
7073
  const cwdError = validateSessionCwd(cwd);
6177
7074
  if (cwdError) {
6178
7075
  this.deps.relaySend(
@@ -6442,6 +7339,7 @@ var RelaySessionCreateHandler = class {
6442
7339
  claudeBin: providerEnv.CLAUDE_BIN,
6443
7340
  codexBin: providerEnv.CODEX_BIN,
6444
7341
  kimiBin: providerEnv.KIMI_BIN,
7342
+ cursorBin: providerEnv.CURSOR_BIN,
6445
7343
  path: providerEnv.PATH
6446
7344
  },
6447
7345
  "Hosted PTY session create failed"
@@ -6471,7 +7369,7 @@ var RelaySessionCreateHandler = class {
6471
7369
  ptyOwner: "proxy-hosted"
6472
7370
  })
6473
7371
  );
6474
- if (provider !== "kimi") {
7372
+ if (provider !== "kimi" && provider !== "cursor") {
6475
7373
  this.deps.controlHandlers.pushCommandList(session.id, cwd);
6476
7374
  }
6477
7375
  this.deps.controlHandlers.pushFileTree(session.id, cwd);
@@ -7232,6 +8130,7 @@ function snapshot(pending) {
7232
8130
  toolName: pending.toolName,
7233
8131
  input: pending.input,
7234
8132
  ...pending.options ? { options: pending.options } : {},
8133
+ ...pending.cursorPrompt ? { cursorPrompt: pending.cursorPrompt } : {},
7235
8134
  createdAt: pending.createdAt,
7236
8135
  ...pending.deliveredAt !== void 0 ? { deliveredAt: pending.deliveredAt } : {}
7237
8136
  };
@@ -7394,15 +8293,15 @@ var HookEventRouter = class {
7394
8293
  }
7395
8294
  forwardPermissionRequest(event) {
7396
8295
  const requestId = event.requestId ?? this.nextFallbackRequestId(event.sessionId);
7397
- const toolName2 = toolNameFromPayload(event.payload);
8296
+ const toolName3 = toolNameFromPayload(event.payload);
7398
8297
  const input = toolInputFromPayload(event.payload);
7399
8298
  this.deps.changeSessionState(event.sessionId, SessionState.WAITING_APPROVAL);
7400
8299
  this.forwardAgentStatus(event, "waiting_permission", {
7401
- toolName: toolName2,
8300
+ toolName: toolName3,
7402
8301
  toolInput: input,
7403
8302
  permissionRequest: {
7404
8303
  requestId,
7405
- toolName: toolName2,
8304
+ toolName: toolName3,
7406
8305
  input
7407
8306
  }
7408
8307
  });
@@ -7412,7 +8311,7 @@ var HookEventRouter = class {
7412
8311
  event.sessionId,
7413
8312
  seq,
7414
8313
  {
7415
- toolName: toolName2,
8314
+ toolName: toolName3,
7416
8315
  toolId: requestId,
7417
8316
  parameters: input
7418
8317
  },
@@ -7421,10 +8320,10 @@ var HookEventRouter = class {
7421
8320
  this.deps.relayConnection.sendEnvelope(envelope);
7422
8321
  }
7423
8322
  forwardToolUse(event) {
7424
- const toolName2 = toolNameFromPayload(event.payload);
8323
+ const toolName3 = toolNameFromPayload(event.payload);
7425
8324
  const input = toolInputFromPayload(event.payload);
7426
8325
  this.forwardAgentStatus(event, "tool_use", {
7427
- toolName: toolName2,
8326
+ toolName: toolName3,
7428
8327
  toolInput: input
7429
8328
  });
7430
8329
  }
@@ -7793,7 +8692,7 @@ function handleTerminalConnection(socket, deps, admission) {
7793
8692
  provider
7794
8693
  });
7795
8694
  const { session } = claim;
7796
- const hook = msg.kind === "terminal" || provider === "kimi" ? void 0 : createHookContext(session.id, provider);
8695
+ const hook = msg.kind === "terminal" || provider === "kimi" || provider === "cursor" ? void 0 : createHookContext(session.id, provider);
7797
8696
  acceptedRegistration = { sessionId: session.id, pid: msg.pid };
7798
8697
  terminalClaims.set(session.id, socket);
7799
8698
  socket.write(
@@ -8081,17 +8980,17 @@ var UNVERSIONED_RECONNECT_KEYS = /* @__PURE__ */ new Set([
8081
8980
  "sessionId",
8082
8981
  "kind"
8083
8982
  ]);
8084
- function isRecord3(value) {
8983
+ function isRecord4(value) {
8085
8984
  return value !== null && typeof value === "object" && !Array.isArray(value);
8086
8985
  }
8087
8986
  function isBoundedNonEmptyString(value, maximum) {
8088
8987
  return typeof value === "string" && value.length > 0 && value.length <= maximum;
8089
8988
  }
8090
8989
  function parseUnversionedTerminalReconnect(value) {
8091
- if (!isRecord3(value)) return null;
8990
+ if (!isRecord4(value)) return null;
8092
8991
  if (Object.keys(value).some((key) => !UNVERSIONED_RECONNECT_KEYS.has(key))) return null;
8093
8992
  if (value.type !== "session_create_request" || value.mode !== "pty") return null;
8094
- if (value.provider !== "claude" && value.provider !== "codex" && value.provider !== "kimi") {
8993
+ if (value.provider !== "claude" && value.provider !== "codex" && value.provider !== "kimi" && value.provider !== "cursor") {
8095
8994
  return null;
8096
8995
  }
8097
8996
  if (!isBoundedNonEmptyString(value.cwd, PRE_ADMISSION_PATH_MAX_LENGTH)) return null;
@@ -8111,7 +9010,7 @@ function parseUnversionedTerminalReconnect(value) {
8111
9010
  };
8112
9011
  }
8113
9012
  function parseVersionedTerminalReconnect(value) {
8114
- if (!isRecord3(value)) return null;
9013
+ if (!isRecord4(value)) return null;
8115
9014
  if (value.type !== "session_create_request" || value.mode !== "pty") return null;
8116
9015
  if (typeof value.protocolVersion !== "number" || !Number.isSafeInteger(value.protocolVersion) || value.protocolVersion < 0) {
8117
9016
  return null;
@@ -8120,7 +9019,7 @@ function parseVersionedTerminalReconnect(value) {
8120
9019
  if (value.pid !== void 0 && (typeof value.pid !== "number" || !Number.isSafeInteger(value.pid) || value.pid <= 0)) {
8121
9020
  return null;
8122
9021
  }
8123
- if (value.provider !== void 0 && value.provider !== "claude" && value.provider !== "codex" && value.provider !== "kimi") {
9022
+ if (value.provider !== void 0 && value.provider !== "claude" && value.provider !== "codex" && value.provider !== "kimi" && value.provider !== "cursor") {
8124
9023
  return null;
8125
9024
  }
8126
9025
  if (value.kind !== void 0 && value.kind !== "agent" && value.kind !== "terminal") {
@@ -8675,14 +9574,14 @@ var HookServer = class {
8675
9574
  }
8676
9575
  async handlePermissionRequest(event, res) {
8677
9576
  const requestId = event.requestId ?? (typeof event.payload.tool_use_id === "string" ? event.payload.tool_use_id : void 0) ?? this.nextFallbackRequestId(event.sessionId);
8678
- const toolName2 = toolNameFromPayload(event.payload);
9577
+ const toolName3 = toolNameFromPayload(event.payload);
8679
9578
  const input = asRecord3(event.payload.input ?? event.payload.tool_input);
8680
9579
  this.options.onEvent?.({ ...event, requestId });
8681
9580
  const decision = await this.options.permissionBroker.request({
8682
9581
  requestId,
8683
9582
  sessionId: event.sessionId,
8684
9583
  provider: event.provider,
8685
- toolName: toolName2,
9584
+ toolName: toolName3,
8686
9585
  input
8687
9586
  });
8688
9587
  this.writeJson(res, 200, this.toProviderDecision(event.event, decision));
@@ -8823,9 +9722,9 @@ function createServeShutdown(deps) {
8823
9722
  // src/serve/remote-file-upload.ts
8824
9723
  import { createWriteStream, mkdirSync as mkdirSync3 } from "fs";
8825
9724
  import { tmpdir as tmpdir2 } from "os";
8826
- import { extname, join as join11 } from "path";
9725
+ import { extname, join as join12 } from "path";
8827
9726
  import { nanoid as nanoid4 } from "nanoid";
8828
- var DEFAULT_DATA_DIR = join11(tmpdir2(), "dev-anywhere");
9727
+ var DEFAULT_DATA_DIR = join12(tmpdir2(), "dev-anywhere");
8829
9728
  var SAFE_EXT_RE = /^[A-Za-z0-9]{1,6}$/;
8830
9729
  var IMAGE_EXTENSIONS = /* @__PURE__ */ new Map([
8831
9730
  ["image/png", "png"],
@@ -8841,9 +9740,9 @@ function uploadPathFor(msg, dataDir, suffix) {
8841
9740
  if (msg.kind === "clipboard_image") {
8842
9741
  const extension = IMAGE_EXTENSIONS.get(msg.mimeType);
8843
9742
  if (!extension) throw new Error("\u4E0D\u652F\u6301\u8FD9\u79CD\u56FE\u7247\u683C\u5F0F");
8844
- return join11(dataDir, `paste-${suffix}.${extension}`);
9743
+ return join12(dataDir, `paste-${suffix}.${extension}`);
8845
9744
  }
8846
- return join11(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
9745
+ return join12(dataDir, `up-${suffix}${safeExtension(msg.fileName)}`);
8847
9746
  }
8848
9747
  var RemoteFileUploadManager = class {
8849
9748
  constructor(deps) {
@@ -9807,7 +10706,8 @@ var PreviewWorkerClient = class {
9807
10706
  var AGENT_CLI_PATH_FIELDS = {
9808
10707
  claude: "claudeBin",
9809
10708
  codex: "codexBin",
9810
- kimi: "kimiBin"
10709
+ kimi: "kimiBin",
10710
+ cursor: "cursorBin"
9811
10711
  };
9812
10712
  function resolveInterruptedApprovals(permissionBroker, hookEventRouter, relay, sessionId) {
9813
10713
  const approvals = permissionBroker.listSession(sessionId);