@cjhyy/code-shell 0.1.5 → 0.1.7

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 (158) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/anthropic-UBSB5AQH.js +1 -0
  3. package/dist/arena/index.js +1 -104
  4. package/dist/arena-OW55ZCHT.js +3 -0
  5. package/dist/bwrap-PVZMLHZR.js +2 -0
  6. package/dist/chunk-2NS3JMNK.js +1 -0
  7. package/dist/chunk-3QP5BQ3L.js +1 -0
  8. package/dist/chunk-B7K2OWKC.js +2 -0
  9. package/dist/chunk-EWWK56K6.js +2 -0
  10. package/dist/chunk-FU7AHZNN.js +1 -0
  11. package/dist/chunk-HIJ2XXGX.js +1 -0
  12. package/dist/chunk-KCXSARAA.js +1 -0
  13. package/dist/chunk-NFH3UQ3E.js +2 -0
  14. package/dist/chunk-NMBYBGC7.js +250 -0
  15. package/dist/chunk-NVAZJ5XS.js +2 -0
  16. package/dist/chunk-O5HFCH2U.js +1 -0
  17. package/dist/chunk-P6JSTIFM.js +1 -0
  18. package/dist/chunk-PGANL6F2.js +3 -0
  19. package/dist/chunk-Q4O2HGWS.js +251 -0
  20. package/dist/chunk-QTWU7UNA.js +5 -0
  21. package/dist/chunk-RP26WO4R.js +1 -0
  22. package/dist/chunk-SNFAPSLA.js +1 -0
  23. package/dist/chunk-T222K6IV.js +18 -0
  24. package/dist/chunk-TKJA6W36.js +3 -0
  25. package/dist/chunk-UDPUTFQT.js +2 -0
  26. package/dist/chunk-W47Z7MGS.js +33 -0
  27. package/dist/chunk-WI6FSWGU.js +1 -0
  28. package/dist/chunk-WOP6MJKW.js +1 -0
  29. package/dist/chunk-XDOWC7EG.js +4 -0
  30. package/dist/chunk-Y2NS6HPO.js +641 -0
  31. package/dist/cli/main.js +303 -22037
  32. package/dist/cli/updater.d.ts +8 -0
  33. package/dist/client-base-6ZZJJYDY.js +1 -0
  34. package/dist/compaction-ECVQVOCT.js +1 -0
  35. package/dist/devtools-SGDUOOM4.js +1 -0
  36. package/dist/engine/engine.d.ts +15 -0
  37. package/dist/export-md-U72T7NW7.js +22 -0
  38. package/dist/file-history-7FQFEQOL.js +1 -0
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.js +1 -347
  41. package/dist/llm/token-counter.d.ts +17 -0
  42. package/dist/manager-C3TDN6MS.js +1 -0
  43. package/dist/mcp-manager-OP4XYV53.js +1 -0
  44. package/dist/memory-BNI4WEWL.js +1 -0
  45. package/dist/model-cache-HEDXI7UJ.js +1 -0
  46. package/dist/model-fetcher-BJ64META.js +1 -0
  47. package/dist/off-7SDVMMXW.js +1 -0
  48. package/dist/openai-KEWQ54TM.js +1 -0
  49. package/dist/openrouter-models-AM6M52D6.js +1 -0
  50. package/dist/openrouter-sync-5JNBL3Z6.js +1 -0
  51. package/dist/product/index.js +1 -21
  52. package/dist/run/index.js +1 -48
  53. package/dist/seatbelt-WBYROQT6.js +37 -0
  54. package/dist/session/session-manager.d.ts +2 -0
  55. package/dist/session-manager-AGWS5SMJ.js +1 -0
  56. package/dist/settings/schema.d.ts +72 -6
  57. package/dist/tool-summary-5UE62VU4.js +2 -0
  58. package/dist/tool-system/builtin/bash.d.ts +7 -1
  59. package/dist/tool-system/context.d.ts +7 -0
  60. package/dist/tool-system/investigation-guard.d.ts +9 -0
  61. package/dist/tool-system/sandbox/bwrap.d.ts +13 -0
  62. package/dist/tool-system/sandbox/index.d.ts +71 -0
  63. package/dist/tool-system/sandbox/off.d.ts +2 -0
  64. package/dist/tool-system/sandbox/seatbelt.d.ts +18 -0
  65. package/dist/types.d.ts +4 -0
  66. package/dist/ui/components/SessionPicker.d.ts +2 -0
  67. package/dist/ui/components/SpinnerWithVerb.d.ts +2 -2
  68. package/dist/ui/components/StatusLine.d.ts +2 -2
  69. package/dist/updater-OCNU2K2Z.js +1 -0
  70. package/package.json +8 -10
  71. package/skills-builtin/codeshell-help.md +135 -0
  72. package/dist/anthropic-IBTI4WL2.cjs +0 -10
  73. package/dist/anthropic-PRZZKHEZ.js +0 -10
  74. package/dist/arena/index.cjs +0 -104
  75. package/dist/arena-KBQOPLFV.cjs +0 -261
  76. package/dist/arena-O2L4TN6A.js +0 -261
  77. package/dist/chunk-2EP3CLEN.js +0 -44
  78. package/dist/chunk-2YW4FPFG.cjs +0 -101
  79. package/dist/chunk-3OA5G4TM.js +0 -47
  80. package/dist/chunk-52LGZKT3.cjs +0 -47
  81. package/dist/chunk-55XGPMAP.cjs +0 -146
  82. package/dist/chunk-5ECBT4YA.js +0 -450
  83. package/dist/chunk-6QVAYW7C.cjs +0 -438
  84. package/dist/chunk-6S4BJ65N.js +0 -113
  85. package/dist/chunk-76HYEPDM.js +0 -307
  86. package/dist/chunk-76W334S4.js +0 -54
  87. package/dist/chunk-7EG3V4JY.cjs +0 -113
  88. package/dist/chunk-7JVTYEEC.js +0 -340
  89. package/dist/chunk-7K6SDRRF.js +0 -9047
  90. package/dist/chunk-7Y6S3OCX.js +0 -438
  91. package/dist/chunk-A5LCRPDP.cjs +0 -54
  92. package/dist/chunk-BSW22MPA.js +0 -146
  93. package/dist/chunk-BUU5PZK2.cjs +0 -9048
  94. package/dist/chunk-BWTOS5BH.cjs +0 -5128
  95. package/dist/chunk-BXCY2FSE.js +0 -203
  96. package/dist/chunk-C5YQBIRK.js +0 -5128
  97. package/dist/chunk-HEKQCI7B.cjs +0 -224
  98. package/dist/chunk-HS2MFNUC.cjs +0 -44
  99. package/dist/chunk-IK4EWJBP.cjs +0 -203
  100. package/dist/chunk-JMR33QVF.cjs +0 -169
  101. package/dist/chunk-KOVYSDHZ.cjs +0 -340
  102. package/dist/chunk-KS3RYAYL.cjs +0 -45
  103. package/dist/chunk-MD32R22I.js +0 -50
  104. package/dist/chunk-MY5XHADU.cjs +0 -216
  105. package/dist/chunk-NUNC3VFB.cjs +0 -307
  106. package/dist/chunk-QRM7IF2S.cjs +0 -4711
  107. package/dist/chunk-R47ROHGL.cjs +0 -298
  108. package/dist/chunk-RMYKO74M.js +0 -1252
  109. package/dist/chunk-SFXHZSRF.js +0 -101
  110. package/dist/chunk-SIHHIQLO.js +0 -224
  111. package/dist/chunk-SNT563K3.cjs +0 -107
  112. package/dist/chunk-T6VYG46N.js +0 -105
  113. package/dist/chunk-TUY2T5KP.cjs +0 -105
  114. package/dist/chunk-VIAGTYYW.js +0 -169
  115. package/dist/chunk-VYL4EFRC.cjs +0 -1252
  116. package/dist/chunk-W22P377T.js +0 -299
  117. package/dist/chunk-WASS5YWB.js +0 -215
  118. package/dist/chunk-XDIQWQJ4.js +0 -4711
  119. package/dist/chunk-YIQBXAYU.cjs +0 -264
  120. package/dist/chunk-YJ77GQK5.js +0 -107
  121. package/dist/chunk-YUI524OE.cjs +0 -450
  122. package/dist/chunk-ZBPSQCPU.js +0 -264
  123. package/dist/cli/main.cjs +0 -22133
  124. package/dist/client-base-HTF236ZD.cjs +0 -9
  125. package/dist/client-base-QKRKCOWB.js +0 -9
  126. package/dist/compaction-6VU2T643.js +0 -33
  127. package/dist/compaction-OKUNTCA7.cjs +0 -33
  128. package/dist/devtools-T2NIZBJK.cjs +0 -6
  129. package/dist/devtools-YXWHOVKR.js +0 -6
  130. package/dist/export-md-RXDW6F5W.cjs +0 -135
  131. package/dist/export-md-XXKZANW5.js +0 -135
  132. package/dist/file-history-KYPE3ECT.cjs +0 -7
  133. package/dist/file-history-LF4F7X26.js +0 -7
  134. package/dist/index.cjs +0 -347
  135. package/dist/manager-C2IUXKRC.js +0 -7
  136. package/dist/manager-YYKWYTRM.cjs +0 -7
  137. package/dist/mcp-manager-QMKWPBZ4.js +0 -8
  138. package/dist/mcp-manager-Z3OKI74O.cjs +0 -8
  139. package/dist/memory-5LWZ6FI2.cjs +0 -9
  140. package/dist/memory-VIJLBAMQ.js +0 -9
  141. package/dist/model-cache-5KIYL5SL.js +0 -13
  142. package/dist/model-cache-OED3IM4R.cjs +0 -13
  143. package/dist/model-fetcher-HKGICACL.js +0 -8
  144. package/dist/model-fetcher-UR6WJOQP.cjs +0 -8
  145. package/dist/openai-JR2WEKOF.js +0 -10
  146. package/dist/openai-YBTOET4O.cjs +0 -10
  147. package/dist/openrouter-models-OU4GRZQY.cjs +0 -15
  148. package/dist/openrouter-models-TGKDKY52.js +0 -15
  149. package/dist/openrouter-sync-BBHUM3R6.cjs +0 -11
  150. package/dist/openrouter-sync-UXUSJCIR.js +0 -11
  151. package/dist/product/index.cjs +0 -21
  152. package/dist/run/index.cjs +0 -48
  153. package/dist/session-manager-Q22BBMD3.js +0 -8
  154. package/dist/session-manager-XODQVL3C.cjs +0 -8
  155. package/dist/tool-summary-63DPIS7G.cjs +0 -31
  156. package/dist/tool-summary-NP5CDBKG.js +0 -31
  157. package/dist/updater-QW473OF4.cjs +0 -17
  158. package/dist/updater-VFUAHCVY.js +0 -17
@@ -1,224 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
-
3
- var _chunkIK4EWJBPcjs = require('./chunk-IK4EWJBP.cjs');
4
-
5
-
6
- var _chunkKS3RYAYLcjs = require('./chunk-KS3RYAYL.cjs');
7
-
8
- // src/tool-system/mcp-manager.ts
9
- _chunkKS3RYAYLcjs.init_cjs_shims.call(void 0, );
10
- var _indexjs = require('@modelcontextprotocol/sdk/client/index.js');
11
- var _stdiojs = require('@modelcontextprotocol/sdk/client/stdio.js');
12
- var _streamableHttpjs = require('@modelcontextprotocol/sdk/client/streamableHttp.js');
13
- var MCPManager = (_class = class _MCPManager {
14
- constructor(toolRegistry) {;_class.prototype.__init.call(this);
15
- this.toolRegistry = toolRegistry;
16
- _MCPManager.instance = this;
17
- }
18
- static __initStatic() {this.instance = null}
19
- __init() {this.connections = /* @__PURE__ */ new Map()}
20
- static getInstance() {
21
- if (!_MCPManager.instance) {
22
- throw new Error("MCPManager not initialized. Connect to servers first.");
23
- }
24
- return _MCPManager.instance;
25
- }
26
- /**
27
- * Connect to all configured MCP servers and register their tools.
28
- */
29
- async connectAll(servers) {
30
- const entries = Object.entries(servers);
31
- if (entries.length === 0) return;
32
- const results = await Promise.allSettled(
33
- entries.map(([name, config]) => this.connect(name, config))
34
- );
35
- for (let i = 0; i < results.length; i++) {
36
- const result = results[i];
37
- if (result.status === "rejected") {
38
- _chunkIK4EWJBPcjs.logger.warn("mcp.connect_failed", {
39
- server: entries[i][0],
40
- error: result.reason.message
41
- });
42
- }
43
- }
44
- }
45
- /**
46
- * Connect to a single MCP server.
47
- */
48
- async connect(name, config) {
49
- if (this.connections.has(name)) {
50
- _chunkIK4EWJBPcjs.logger.info("mcp.already_connected", { server: name });
51
- return;
52
- }
53
- _chunkIK4EWJBPcjs.logger.info("mcp.connecting", { server: name, transport: _nullishCoalesce(config.transport, () => ( "stdio")) });
54
- const client = new (0, _indexjs.Client)(
55
- { name: "code-shell", version: "0.1.0" },
56
- { capabilities: {} }
57
- );
58
- let transport;
59
- const transportType = _nullishCoalesce(config.transport, () => ( "stdio"));
60
- if (transportType === "stdio") {
61
- if (!config.command) {
62
- throw new Error(`MCP server "${name}": command is required for stdio transport`);
63
- }
64
- transport = new (0, _stdiojs.StdioClientTransport)({
65
- command: config.command,
66
- args: config.args,
67
- env: config.env ? { ...process.env, ...config.env } : void 0
68
- });
69
- } else if (transportType === "streamable-http" || transportType === "sse") {
70
- if (!config.url) {
71
- throw new Error(`MCP server "${name}": url is required for ${transportType} transport`);
72
- }
73
- transport = new (0, _streamableHttpjs.StreamableHTTPClientTransport)(new URL(config.url), {
74
- requestInit: config.headers ? { headers: config.headers } : void 0
75
- });
76
- } else {
77
- throw new Error(`MCP server "${name}": unsupported transport "${transportType}"`);
78
- }
79
- const CONNECT_TIMEOUT_MS = 15e3;
80
- let timeoutHandle;
81
- try {
82
- await new Promise((resolve, reject) => {
83
- timeoutHandle = setTimeout(() => {
84
- reject(new Error(`MCP server "${name}" connect timed out after ${CONNECT_TIMEOUT_MS}ms`));
85
- }, CONNECT_TIMEOUT_MS);
86
- client.connect(transport).then(
87
- () => resolve(),
88
- (err) => reject(err)
89
- );
90
- });
91
- } catch (err) {
92
- try {
93
- await _optionalChain([transport, 'access', _ => _.close, 'optionalCall', _2 => _2()]);
94
- } catch (e) {
95
- }
96
- throw err;
97
- } finally {
98
- if (timeoutHandle) clearTimeout(timeoutHandle);
99
- }
100
- this.connections.set(name, { client, serverName: name, transport });
101
- await this.discoverTools(name, client);
102
- _chunkIK4EWJBPcjs.logger.info("mcp.connected", { server: name });
103
- }
104
- /**
105
- * Discover tools from an MCP server and register them.
106
- */
107
- async discoverTools(serverName, client) {
108
- const result = await client.listTools();
109
- for (const tool of result.tools) {
110
- const registered = {
111
- name: `mcp_${serverName}_${tool.name}`,
112
- description: `[${serverName}] ${_nullishCoalesce(tool.description, () => ( tool.name))}`,
113
- inputSchema: _nullishCoalesce(tool.inputSchema, () => ( { type: "object", properties: {} })),
114
- source: "mcp",
115
- serverName,
116
- permissionDefault: "ask",
117
- isConcurrencySafe: true,
118
- isReadOnly: false
119
- };
120
- this.toolRegistry.registerTool(registered, async (args) => {
121
- const callResult = await client.callTool({ name: tool.name, arguments: args });
122
- const parts = [];
123
- if (Array.isArray(callResult.content)) {
124
- for (const item of callResult.content) {
125
- if (typeof item === "object" && item !== null && "text" in item) {
126
- parts.push(String(item.text));
127
- } else if (typeof item === "string") {
128
- parts.push(item);
129
- }
130
- }
131
- }
132
- return parts.join("\n") || "(no output)";
133
- });
134
- _chunkIK4EWJBPcjs.logger.info("mcp.tool_registered", { server: serverName, tool: registered.name });
135
- }
136
- }
137
- /**
138
- * Disconnect all MCP servers.
139
- */
140
- async disconnectAll() {
141
- for (const [name, conn] of this.connections) {
142
- try {
143
- await conn.client.close();
144
- _chunkIK4EWJBPcjs.logger.info("mcp.disconnected", { server: name });
145
- } catch (err) {
146
- _chunkIK4EWJBPcjs.logger.warn("mcp.disconnect_error", { server: name, error: err.message });
147
- }
148
- }
149
- this.connections.clear();
150
- }
151
- /**
152
- * List connected servers.
153
- */
154
- listServers() {
155
- return [...this.connections.keys()];
156
- }
157
- /**
158
- * Call a tool on a specific MCP server.
159
- */
160
- async callTool(serverName, toolName, args) {
161
- const conn = this.connections.get(serverName);
162
- if (!conn) {
163
- throw new Error(`MCP server "${serverName}" is not connected.`);
164
- }
165
- const result = await conn.client.callTool({ name: toolName, arguments: args });
166
- const parts = [];
167
- if (Array.isArray(result.content)) {
168
- for (const item of result.content) {
169
- if (typeof item === "object" && item !== null && "text" in item) {
170
- parts.push(String(item.text));
171
- } else if (typeof item === "string") {
172
- parts.push(item);
173
- }
174
- }
175
- }
176
- return parts.join("\n") || "(no output)";
177
- }
178
- /**
179
- * List resources from MCP servers.
180
- */
181
- async listResources(serverName) {
182
- const results = [];
183
- const servers = serverName ? [serverName] : [...this.connections.keys()];
184
- for (const name of servers) {
185
- const conn = this.connections.get(name);
186
- if (!conn) continue;
187
- try {
188
- const res = await conn.client.listResources();
189
- for (const r of res.resources) {
190
- results.push({
191
- uri: r.uri,
192
- name: _nullishCoalesce(r.name, () => ( r.uri)),
193
- description: r.description
194
- });
195
- }
196
- } catch (e2) {
197
- }
198
- }
199
- return results;
200
- }
201
- /**
202
- * Read a resource from an MCP server.
203
- */
204
- async readResource(serverName, uri) {
205
- const conn = this.connections.get(serverName);
206
- if (!conn) {
207
- throw new Error(`MCP server "${serverName}" is not connected.`);
208
- }
209
- const result = await conn.client.readResource({ uri });
210
- const parts = [];
211
- if (Array.isArray(result.contents)) {
212
- for (const item of result.contents) {
213
- if (typeof item === "object" && item !== null && "text" in item) {
214
- parts.push(String(item.text));
215
- }
216
- }
217
- }
218
- return parts.join("\n") || "(no content)";
219
- }
220
- }, _class.__initStatic(), _class);
221
-
222
-
223
-
224
- exports.MCPManager = MCPManager;
@@ -1,44 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
-
3
-
4
- var _chunkBUU5PZK2cjs = require('./chunk-BUU5PZK2.cjs');
5
-
6
-
7
- var _chunkKS3RYAYLcjs = require('./chunk-KS3RYAYL.cjs');
8
-
9
- // src/run/index.ts
10
- _chunkKS3RYAYLcjs.init_cjs_shims.call(void 0, );
11
-
12
- // src/run/factory.ts
13
- _chunkKS3RYAYLcjs.init_cjs_shims.call(void 0, );
14
- var _path = require('path');
15
- var _os = require('os');
16
- function createRunManager(options) {
17
- const runsDir = _nullishCoalesce(options.runsDir, () => ( _path.join.call(void 0, _os.homedir.call(void 0, ), ".code-shell", "runs")));
18
- const store = new (0, _chunkBUU5PZK2cjs.FileRunStore)(runsDir);
19
- return new (0, _chunkBUU5PZK2cjs.RunManager)({
20
- store,
21
- executor: {
22
- llm: options.llm,
23
- maxTurns: _nullishCoalesce(options.maxTurns, () => ( 30)),
24
- maxContextTokens: _nullishCoalesce(options.maxContextTokens, () => ( 2e5)),
25
- permissionMode: _nullishCoalesce(options.permissionMode, () => ( "acceptEdits")),
26
- sessionStorageDir: options.sessionStorageDir,
27
- mcpServers: options.mcpServers,
28
- enabledBuiltinTools: options.enabledBuiltinTools,
29
- disabledBuiltinTools: options.disabledBuiltinTools,
30
- customSystemPrompt: options.customSystemPrompt,
31
- appendSystemPrompt: options.appendSystemPrompt,
32
- hooks: options.hooks
33
- },
34
- concurrency: _nullishCoalesce(options.concurrency, () => ( 1)),
35
- runsDir,
36
- evaluator: options.evaluator,
37
- defaultTags: options.defaultTags,
38
- defaultMetadata: options.defaultMetadata
39
- });
40
- }
41
-
42
-
43
-
44
- exports.createRunManager = createRunManager;
@@ -1,203 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
-
3
- var _chunkKS3RYAYLcjs = require('./chunk-KS3RYAYL.cjs');
4
-
5
- // src/logging/logger.ts
6
- _chunkKS3RYAYLcjs.init_cjs_shims.call(void 0, );
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
- var _fs = require('fs');
15
- var _path = require('path');
16
- var _os = require('os');
17
- var LEVEL_ORDER = {
18
- debug: 0,
19
- info: 1,
20
- warn: 2,
21
- error: 3
22
- };
23
- var LOGS_DIR = _path.join.call(void 0, _os.homedir.call(void 0, ), ".code-shell", "logs");
24
- var MAX_LOG_FILES = 7;
25
- var MAX_IN_MEMORY_ERRORS = 100;
26
- function isLocalDev() {
27
- if (process.env.CODE_SHELL_DEV === "1") return true;
28
- if (process.argv.includes("--debug") || process.argv.includes("-d")) return true;
29
- if (process.argv.some((a) => a.startsWith("--debug="))) return true;
30
- if (process.env.NODE_ENV === "test" || process.env.BUN_TEST === "1") return false;
31
- if (process.argv.some((a) => a.includes("/tests/") || a.endsWith(".test.ts"))) return false;
32
- const entry = _nullishCoalesce(process.argv[1], () => ( ""));
33
- if (entry.includes(`${"/"}src${"/"}`)) return true;
34
- return false;
35
- }
36
- function resolveDefaultLevel() {
37
- const raw = _optionalChain([process, 'access', _ => _.env, 'access', _2 => _2.CODE_SHELL_LOG_LEVEL, 'optionalAccess', _3 => _3.toLowerCase, 'call', _4 => _4(), 'access', _5 => _5.trim, 'call', _6 => _6()]);
38
- if (raw && Object.hasOwn(LEVEL_ORDER, raw)) return raw;
39
- return isLocalDev() ? "debug" : "info";
40
- }
41
- function resolveCategoryFilter() {
42
- const cliArg = process.argv.find((a) => a.startsWith("--debug="));
43
- let raw;
44
- if (cliArg) raw = cliArg.slice("--debug=".length);
45
- else {
46
- const env = process.env.CODE_SHELL_DEBUG;
47
- if (env && env !== "1" && env !== "true") raw = env;
48
- }
49
- if (!raw) return null;
50
- const set = new Set(
51
- raw.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean)
52
- );
53
- return set.size > 0 ? set : null;
54
- }
55
- var _currentSid = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
56
- function setCurrentSid(sid) {
57
- _currentSid = sid;
58
- }
59
- function getCurrentSid() {
60
- return _currentSid;
61
- }
62
- var inMemoryErrors = [];
63
- var errorLogSink = null;
64
- var Logger = (_class = class _Logger {
65
- constructor(context = {}) {;_class.prototype.__init.call(this);
66
- this.context = context;
67
- this.enabled = process.env.CODE_SHELL_LOG !== "0";
68
- this.minLevel = resolveDefaultLevel();
69
- this.categoryFilter = resolveCategoryFilter();
70
- this.stderrEcho = process.env.CODE_SHELL_DEBUG === "1" || process.argv.includes("--debug-to-stderr") || process.argv.includes("-d2e");
71
- }
72
-
73
-
74
-
75
-
76
- __init() {this.dirReady = false}
77
- child(extra) {
78
- return new _Logger({ ...this.context, ...extra });
79
- }
80
- /**
81
- * Set the session id stamped on every subsequent log entry written by
82
- * any logger in the process. Called by Engine once a run's
83
- * authoritative session id is known.
84
- */
85
- setSid(sid) {
86
- setCurrentSid(sid);
87
- }
88
- getSid() {
89
- return getCurrentSid();
90
- }
91
- debug(msg, data) {
92
- this.write("debug", msg, data);
93
- }
94
- info(msg, data) {
95
- this.write("info", msg, data);
96
- }
97
- warn(msg, data) {
98
- this.write("warn", msg, data);
99
- }
100
- error(msgOrErr, data) {
101
- let msg;
102
- let entryData;
103
- let errObj;
104
- if (typeof msgOrErr === "string") {
105
- msg = msgOrErr;
106
- if (data instanceof Error) {
107
- errObj = data;
108
- entryData = { error: data.message, stack: data.stack };
109
- } else {
110
- entryData = data;
111
- }
112
- } else if (msgOrErr instanceof Error) {
113
- msg = msgOrErr.message;
114
- errObj = msgOrErr;
115
- entryData = { stack: msgOrErr.stack };
116
- } else {
117
- msg = String(msgOrErr);
118
- }
119
- this.recordError(msg, entryData);
120
- this.write("error", msg, entryData);
121
- if (errObj) _optionalChain([errorLogSink, 'optionalAccess', _7 => _7.logError, 'call', _8 => _8(errObj)]);
122
- }
123
- recordError(msg, data) {
124
- if (inMemoryErrors.length >= MAX_IN_MEMORY_ERRORS) inMemoryErrors.shift();
125
- inMemoryErrors.push({ msg, t: (/* @__PURE__ */ new Date()).toISOString(), data });
126
- }
127
- write(level, msg, data) {
128
- if (!this.enabled) return;
129
- if (LEVEL_ORDER[level] < LEVEL_ORDER[this.minLevel]) return;
130
- const cat = _nullishCoalesce(_optionalChain([data, 'optionalAccess', _9 => _9.cat]), () => ( this.context.cat));
131
- if (level === "debug" && this.categoryFilter) {
132
- if (!cat || !this.categoryFilter.has(cat.toLowerCase())) return;
133
- }
134
- const t = (/* @__PURE__ */ new Date()).toISOString();
135
- const entry = { t, l: level, msg, ...this.context };
136
- if (cat && !entry.cat) entry.cat = cat;
137
- if (entry.sid === void 0) entry.sid = _currentSid;
138
- if (data) entry.d = data;
139
- const line = JSON.stringify(entry) + "\n";
140
- if (this.stderrEcho) {
141
- process.stderr.write(line);
142
- return;
143
- }
144
- try {
145
- if (!this.dirReady) {
146
- if (!_fs.existsSync.call(void 0, LOGS_DIR)) _fs.mkdirSync.call(void 0, LOGS_DIR, { recursive: true });
147
- this.dirReady = true;
148
- }
149
- const dateStr = t.slice(0, 10);
150
- _fs.appendFileSync.call(void 0, _path.join.call(void 0, LOGS_DIR, `${dateStr}.log`), line, "utf-8");
151
- } catch (e) {
152
- }
153
- }
154
- getMinLevel() {
155
- return this.minLevel;
156
- }
157
- isCategoryActive(cat) {
158
- return !this.categoryFilter || this.categoryFilter.has(cat.toLowerCase());
159
- }
160
- /**
161
- * Open a span: writes a `<name>.begin` debug entry now and returns a handle
162
- * whose `end()` writes `<name>.end` with `duration_ms` populated. Use for
163
- * any "I want begin → end + how long" pattern (tool exec, LLM request,
164
- * permission ask, etc.) so the begin/end pair is grouped under one cat
165
- * and the duration is computed once instead of by hand from timestamps.
166
- */
167
- span(name, data) {
168
- const startedAt = Date.now();
169
- this.write("debug", `${name}.begin`, data);
170
- return {
171
- end: (extra) => {
172
- const duration_ms = Date.now() - startedAt;
173
- this.write("info", `${name}.end`, { ...data, ...extra, duration_ms });
174
- },
175
- fail: (err, extra) => {
176
- const duration_ms = Date.now() - startedAt;
177
- const message = err instanceof Error ? err.message : String(err);
178
- this.write("error", `${name}.fail`, { ...data, ...extra, duration_ms, error: message });
179
- }
180
- };
181
- }
182
- }, _class);
183
- var logger = new Logger();
184
- function rotateLogs() {
185
- try {
186
- if (!_fs.existsSync.call(void 0, LOGS_DIR)) return;
187
- const files = _fs.readdirSync.call(void 0, LOGS_DIR).filter((f) => f.endsWith(".log")).sort();
188
- if (files.length <= MAX_LOG_FILES) return;
189
- for (const f of files.slice(0, files.length - MAX_LOG_FILES)) {
190
- try {
191
- _fs.unlinkSync.call(void 0, _path.join.call(void 0, LOGS_DIR, f));
192
- } catch (e2) {
193
- }
194
- }
195
- } catch (e3) {
196
- }
197
- }
198
-
199
-
200
-
201
-
202
-
203
- exports.getCurrentSid = getCurrentSid; exports.logger = logger; exports.rotateLogs = rotateLogs;
@@ -1,169 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class;
2
-
3
- var _chunkKS3RYAYLcjs = require('./chunk-KS3RYAYL.cjs');
4
-
5
- // src/session/memory.ts
6
- _chunkKS3RYAYLcjs.init_cjs_shims.call(void 0, );
7
- var _fs = require('fs');
8
- var _path = require('path');
9
- var _os = require('os');
10
- function resolveMemoryBaseDir(override) {
11
- if (override) return override;
12
- const fromEnv = process.env.CODE_SHELL_HOME;
13
- if (fromEnv && fromEnv.length > 0) return fromEnv;
14
- return _path.join.call(void 0, _os.homedir.call(void 0, ), ".code-shell");
15
- }
16
- var MemoryManager = (_class = class {
17
-
18
-
19
-
20
- // Per-instance cache of {fileName -> {name, description}} so the
21
- // index can be rewritten without re-reading every memory file
22
- // every time a single entry is saved/deleted (the previous code
23
- // path called loadAll() on every save, giving O(N²) total I/O).
24
- // null = "not initialized yet, fall back to disk on next access."
25
- __init() {this.indexCache = null}
26
- constructor(options) {;_class.prototype.__init.call(this);
27
- const opts = typeof options === "string" ? { projectDir: options } : _nullishCoalesce(options, () => ( {}));
28
- this.baseDir = resolveMemoryBaseDir(opts.baseDir);
29
- if (opts.projectDir) {
30
- const projectHash = opts.projectDir.replace(/[/\\:]/g, "-").replace(/^-/, "");
31
- this.memoryDir = _path.join.call(void 0, this.baseDir, "projects", projectHash, "memory");
32
- } else {
33
- this.memoryDir = _path.join.call(void 0, this.baseDir, "memory");
34
- }
35
- this.indexPath = _path.join.call(void 0, this.memoryDir, "MEMORY.md");
36
- _fs.mkdirSync.call(void 0, this.memoryDir, { recursive: true });
37
- }
38
- getMemoryDir() {
39
- return this.memoryDir;
40
- }
41
- /**
42
- * Save a memory entry. Creates the file and updates the index.
43
- */
44
- save(entry) {
45
- const fileName = this.slugify(entry.name) + ".md";
46
- const filePath = _path.join.call(void 0, this.memoryDir, fileName);
47
- const content = `---
48
- name: ${entry.name}
49
- description: ${entry.description}
50
- type: ${entry.type}
51
- ---
52
-
53
- ${entry.content}
54
- `;
55
- _fs.writeFileSync.call(void 0, filePath, content, "utf-8");
56
- const cache = this.ensureIndexCache();
57
- cache.set(fileName, { name: entry.name, description: entry.description });
58
- this.writeIndex(cache);
59
- return fileName;
60
- }
61
- /**
62
- * Load all memory entries.
63
- */
64
- loadAll() {
65
- if (!_fs.existsSync.call(void 0, this.memoryDir)) return [];
66
- const files = _fs.readdirSync.call(void 0, this.memoryDir).filter(
67
- (f) => f.endsWith(".md") && f !== "MEMORY.md"
68
- );
69
- const entries = [];
70
- for (const file of files) {
71
- const entry = this.loadFile(file);
72
- if (entry) entries.push(entry);
73
- }
74
- return entries;
75
- }
76
- /**
77
- * Load a single memory file.
78
- */
79
- loadFile(fileName) {
80
- const filePath = _path.join.call(void 0, this.memoryDir, fileName);
81
- if (!_fs.existsSync.call(void 0, filePath)) return null;
82
- try {
83
- const raw = _fs.readFileSync.call(void 0, filePath, "utf-8");
84
- const frontmatterMatch = raw.match(/^---\n([\s\S]*?)\n---\n\n?([\s\S]*)$/);
85
- if (!frontmatterMatch) return null;
86
- const frontmatter = frontmatterMatch[1];
87
- const content = frontmatterMatch[2].trim();
88
- const name = _nullishCoalesce(_optionalChain([frontmatter, 'access', _ => _.match, 'call', _2 => _2(/name:\s*(.+)/), 'optionalAccess', _3 => _3[1], 'optionalAccess', _4 => _4.trim, 'call', _5 => _5()]), () => ( fileName));
89
- const description = _nullishCoalesce(_optionalChain([frontmatter, 'access', _6 => _6.match, 'call', _7 => _7(/description:\s*(.+)/), 'optionalAccess', _8 => _8[1], 'optionalAccess', _9 => _9.trim, 'call', _10 => _10()]), () => ( ""));
90
- const type = _nullishCoalesce(_optionalChain([frontmatter, 'access', _11 => _11.match, 'call', _12 => _12(/type:\s*(.+)/), 'optionalAccess', _13 => _13[1], 'optionalAccess', _14 => _14.trim, 'call', _15 => _15()]), () => ( "project"));
91
- return { name, description, type, content, fileName };
92
- } catch (e2) {
93
- return null;
94
- }
95
- }
96
- /**
97
- * Delete a memory by name or filename.
98
- */
99
- delete(nameOrFile) {
100
- const entries = this.loadAll();
101
- const entry = entries.find(
102
- (e) => e.name === nameOrFile || e.fileName === nameOrFile
103
- );
104
- if (!entry) return false;
105
- try {
106
- _fs.unlinkSync.call(void 0, _path.join.call(void 0, this.memoryDir, entry.fileName));
107
- const cache = this.ensureIndexCache();
108
- cache.delete(entry.fileName);
109
- this.writeIndex(cache);
110
- return true;
111
- } catch (e3) {
112
- return false;
113
- }
114
- }
115
- /**
116
- * Get the MEMORY.md index content for injection into prompts.
117
- */
118
- getIndex() {
119
- if (!_fs.existsSync.call(void 0, this.indexPath)) return "";
120
- return _fs.readFileSync.call(void 0, this.indexPath, "utf-8");
121
- }
122
- /**
123
- * Build a prompt-friendly summary of all memories.
124
- */
125
- buildMemoryContext() {
126
- const entries = this.loadAll();
127
- if (entries.length === 0) return "";
128
- const lines = entries.map(
129
- (e) => `- [${e.type}] ${e.name}: ${e.description}`
130
- );
131
- return `# Persistent Memory
132
-
133
- The following memories from previous sessions may be relevant:
134
-
135
- ` + lines.join("\n") + `
136
-
137
- To read a specific memory, check ${this.memoryDir}/`;
138
- }
139
- /**
140
- * Lazy-build the in-memory index from disk on first use, then
141
- * keep it in sync incrementally via save/delete. Avoids the
142
- * O(N²) re-read of every memory file on every save.
143
- */
144
- ensureIndexCache() {
145
- if (this.indexCache !== null) return this.indexCache;
146
- const cache = /* @__PURE__ */ new Map();
147
- for (const entry of this.loadAll()) {
148
- cache.set(entry.fileName, { name: entry.name, description: entry.description });
149
- }
150
- this.indexCache = cache;
151
- return cache;
152
- }
153
- writeIndex(cache) {
154
- const lines = [];
155
- for (const [fileName, meta] of cache) {
156
- lines.push(`- [${meta.name}](${fileName}) \u2014 ${meta.description}`);
157
- }
158
- const content = lines.length > 0 ? lines.join("\n") + "\n" : "(no memories stored)\n";
159
- _fs.writeFileSync.call(void 0, this.indexPath, content, "utf-8");
160
- }
161
- slugify(text) {
162
- return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 60);
163
- }
164
- }, _class);
165
-
166
-
167
-
168
-
169
- exports.resolveMemoryBaseDir = resolveMemoryBaseDir; exports.MemoryManager = MemoryManager;