@polka-codes/cli-shared 0.10.31 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +211 -331
- package/dist/provider.d.ts +2 -2
- package/package.json +13 -14
- package/dist/config.parameters.test.d.ts +0 -1
- package/dist/config.rules.test.d.ts +0 -1
- package/dist/config.test.d.ts +0 -1
- package/dist/provider.test.d.ts +0 -1
- package/dist/sqlite-memory-store.test.d.ts +0 -1
- package/dist/utils/__tests__/parameterSimplifier.test.d.ts +0 -1
- package/dist/utils/eventHandler.test.d.ts +0 -1
- package/dist/utils/listFiles.test.d.ts +0 -1
- package/dist/utils/searchFiles.test.d.ts +0 -1
package/dist/index.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
var __require = /* @__PURE__ */ createRequire(import.meta.url);
|
|
3
|
+
|
|
1
4
|
// src/config.ts
|
|
2
|
-
import { existsSync, readFileSync } from "fs";
|
|
3
|
-
import { readFile } from "fs/promises";
|
|
4
|
-
import { homedir } from "os";
|
|
5
|
-
import { join } from "path";
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { homedir } from "node:os";
|
|
8
|
+
import { join } from "node:path";
|
|
6
9
|
import { configSchema } from "@polka-codes/core";
|
|
7
10
|
import { merge } from "lodash-es";
|
|
8
11
|
import { parse } from "yaml";
|
|
@@ -17,13 +20,13 @@ function loadConfigAtPath(path) {
|
|
|
17
20
|
if (error instanceof ZodError) {
|
|
18
21
|
console.warn(`Config validation failed for ${path}: ${error.message}`);
|
|
19
22
|
}
|
|
20
|
-
return
|
|
23
|
+
return;
|
|
21
24
|
}
|
|
22
25
|
}
|
|
23
26
|
var localConfigFileName = ".polkacodes.yml";
|
|
24
27
|
var mergeArray = (a, b) => {
|
|
25
28
|
if (!a && !b) {
|
|
26
|
-
return
|
|
29
|
+
return;
|
|
27
30
|
}
|
|
28
31
|
if (!a) {
|
|
29
32
|
return b;
|
|
@@ -39,8 +42,8 @@ function mergeConfigs(configs) {
|
|
|
39
42
|
}
|
|
40
43
|
const mergedConfig = configs.reduce((acc, config) => {
|
|
41
44
|
const merged = merge({}, acc, config);
|
|
42
|
-
const accRules = acc.rules ? Array.isArray(acc.rules) ? acc.rules : [acc.rules] :
|
|
43
|
-
const configRules = config.rules ? Array.isArray(config.rules) ? config.rules : [config.rules] :
|
|
45
|
+
const accRules = acc.rules ? Array.isArray(acc.rules) ? acc.rules : [acc.rules] : undefined;
|
|
46
|
+
const configRules = config.rules ? Array.isArray(config.rules) ? config.rules : [config.rules] : undefined;
|
|
44
47
|
merged.rules = mergeArray(accRules, configRules);
|
|
45
48
|
merged.excludeFiles = mergeArray(acc.excludeFiles, config.excludeFiles);
|
|
46
49
|
return merged;
|
|
@@ -49,62 +52,62 @@ function mergeConfigs(configs) {
|
|
|
49
52
|
}
|
|
50
53
|
async function resolveRules(rules) {
|
|
51
54
|
if (!rules) {
|
|
52
|
-
return
|
|
55
|
+
return;
|
|
53
56
|
}
|
|
54
57
|
if (typeof rules === "string") {
|
|
55
58
|
return rules;
|
|
56
59
|
}
|
|
57
|
-
const resolvedRules = await Promise.all(
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
return await response.text();
|
|
70
|
-
}
|
|
71
|
-
console.warn(`Failed to fetch rule from ${rule.url}: ${response.statusText}`);
|
|
72
|
-
} catch (error) {
|
|
73
|
-
if (error instanceof Error && error.name === "AbortError") {
|
|
74
|
-
console.warn(`Timeout fetching rule from ${rule.url} (30s)`);
|
|
75
|
-
} else {
|
|
76
|
-
console.warn(`Error fetching rule from ${rule.url}: ${error}`);
|
|
77
|
-
}
|
|
60
|
+
const resolvedRules = await Promise.all(rules.map(async (rule) => {
|
|
61
|
+
if (typeof rule === "string") {
|
|
62
|
+
return rule;
|
|
63
|
+
}
|
|
64
|
+
if ("url" in rule) {
|
|
65
|
+
try {
|
|
66
|
+
const controller = new AbortController;
|
|
67
|
+
const timeoutId = setTimeout(() => controller.abort(), 30000);
|
|
68
|
+
const response = await fetch(rule.url, { signal: controller.signal });
|
|
69
|
+
clearTimeout(timeoutId);
|
|
70
|
+
if (response.ok) {
|
|
71
|
+
return await response.text();
|
|
78
72
|
}
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
73
|
+
console.warn(`Failed to fetch rule from ${rule.url}: ${response.statusText}`);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
76
|
+
console.warn(`Timeout fetching rule from ${rule.url} (30s)`);
|
|
77
|
+
} else {
|
|
78
|
+
console.warn(`Error fetching rule from ${rule.url}: ${error}`);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
} else if ("repo" in rule) {
|
|
82
|
+
const ref = rule.commit ?? rule.tag ?? rule.branch ?? "main";
|
|
83
|
+
const url = `https://raw.githubusercontent.com/${rule.repo}/${ref}/${rule.path}`;
|
|
84
|
+
try {
|
|
85
|
+
const controller = new AbortController;
|
|
86
|
+
const timeoutId = setTimeout(() => controller.abort(), 30000);
|
|
87
|
+
const response = await fetch(url, { signal: controller.signal });
|
|
88
|
+
clearTimeout(timeoutId);
|
|
89
|
+
if (response.ok) {
|
|
90
|
+
return await response.text();
|
|
97
91
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
92
|
+
console.warn(`Failed to fetch rule from ${url}: ${response.statusText}`);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
95
|
+
console.warn(`Timeout fetching rule from ${url} (30s)`);
|
|
96
|
+
} else {
|
|
97
|
+
console.warn(`Error fetching rule from ${url}: ${error}`);
|
|
101
98
|
}
|
|
102
|
-
console.warn(`Rule file not found: ${rule.path}`);
|
|
103
99
|
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
100
|
+
} else if ("path" in rule) {
|
|
101
|
+
if (existsSync(rule.path)) {
|
|
102
|
+
return await readFile(rule.path, "utf-8");
|
|
103
|
+
}
|
|
104
|
+
console.warn(`Rule file not found: ${rule.path}`);
|
|
105
|
+
}
|
|
106
|
+
return;
|
|
107
|
+
}));
|
|
108
|
+
return resolvedRules.filter((rule) => rule !== undefined).join(`
|
|
109
|
+
|
|
110
|
+
`);
|
|
108
111
|
}
|
|
109
112
|
async function loadConfig(paths, cwd = process.cwd(), home = homedir()) {
|
|
110
113
|
const configs = [];
|
|
@@ -147,9 +150,9 @@ ${error}`);
|
|
|
147
150
|
}
|
|
148
151
|
}
|
|
149
152
|
}
|
|
150
|
-
const mergedConfig = configs.length > 0 ? mergeConfigs(configs) :
|
|
153
|
+
const mergedConfig = configs.length > 0 ? mergeConfigs(configs) : undefined;
|
|
151
154
|
if (!mergedConfig) {
|
|
152
|
-
return
|
|
155
|
+
return;
|
|
153
156
|
}
|
|
154
157
|
const resolvedRules = await resolveRules(mergedConfig.rules);
|
|
155
158
|
return {
|
|
@@ -173,67 +176,42 @@ var readLocalConfig = (path) => {
|
|
|
173
176
|
if (error instanceof ZodError) {
|
|
174
177
|
console.warn(`Local config validation failed for ${path ?? localConfigFileName}: ${error.message}`);
|
|
175
178
|
} else {
|
|
176
|
-
console.debug(
|
|
177
|
-
`Could not load local config from ${path ?? localConfigFileName}: ${error instanceof Error ? error.message : String(error)}`
|
|
178
|
-
);
|
|
179
|
+
console.debug(`Could not load local config from ${path ?? localConfigFileName}: ${error instanceof Error ? error.message : String(error)}`);
|
|
179
180
|
}
|
|
180
|
-
return
|
|
181
|
+
return;
|
|
181
182
|
}
|
|
182
183
|
};
|
|
183
|
-
|
|
184
184
|
// src/memory-manager.ts
|
|
185
|
-
|
|
185
|
+
class MemoryManager {
|
|
186
186
|
store;
|
|
187
187
|
constructor(store) {
|
|
188
188
|
this.store = store;
|
|
189
189
|
}
|
|
190
|
-
/**
|
|
191
|
-
* Read memory by topic name
|
|
192
|
-
*/
|
|
193
190
|
async readMemory(topic) {
|
|
194
191
|
return this.store.readMemory(topic);
|
|
195
192
|
}
|
|
196
|
-
/**
|
|
197
|
-
* Update memory with operation
|
|
198
|
-
*/
|
|
199
193
|
async updateMemory(operation, topic, content, metadata) {
|
|
200
194
|
return this.store.updateMemory(operation, topic, content, metadata);
|
|
201
195
|
}
|
|
202
|
-
/**
|
|
203
|
-
* Query memory with filters
|
|
204
|
-
*/
|
|
205
196
|
async queryMemory(query = {}, options) {
|
|
206
197
|
const finalQuery = {
|
|
207
198
|
...query
|
|
208
199
|
};
|
|
209
200
|
const operation = options?.operation;
|
|
210
201
|
if ((operation === "select" || !operation) && !finalQuery.limit) {
|
|
211
|
-
finalQuery.limit =
|
|
202
|
+
finalQuery.limit = 1000;
|
|
212
203
|
}
|
|
213
204
|
return this.store.queryMemory(finalQuery, options);
|
|
214
205
|
}
|
|
215
|
-
/**
|
|
216
|
-
* Batch update memory
|
|
217
|
-
*/
|
|
218
206
|
async batchUpdateMemory(operations) {
|
|
219
207
|
return this.store.batchUpdateMemory(operations);
|
|
220
208
|
}
|
|
221
|
-
/**
|
|
222
|
-
* Get database statistics
|
|
223
|
-
*/
|
|
224
209
|
async getStats() {
|
|
225
210
|
return this.store.getStats();
|
|
226
211
|
}
|
|
227
|
-
/**
|
|
228
|
-
* Close the memory store
|
|
229
|
-
*/
|
|
230
212
|
async close() {
|
|
231
213
|
await this.store.close();
|
|
232
214
|
}
|
|
233
|
-
/**
|
|
234
|
-
* Execute a transaction
|
|
235
|
-
* Exposes the underlying store's transaction method if available
|
|
236
|
-
*/
|
|
237
215
|
async transaction(callback) {
|
|
238
216
|
const storeWithTransaction = this.store;
|
|
239
217
|
if (typeof storeWithTransaction.transaction === "function") {
|
|
@@ -241,11 +219,10 @@ var MemoryManager = class {
|
|
|
241
219
|
}
|
|
242
220
|
return callback();
|
|
243
221
|
}
|
|
244
|
-
}
|
|
245
|
-
|
|
222
|
+
}
|
|
246
223
|
// src/project-scope.ts
|
|
247
|
-
import { existsSync as existsSync2 } from "fs";
|
|
248
|
-
import { dirname, normalize, resolve, sep } from "path";
|
|
224
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
225
|
+
import { dirname, normalize, resolve, sep } from "node:path";
|
|
249
226
|
function detectProjectScope(cwd) {
|
|
250
227
|
const projectPath = findProjectRoot(cwd);
|
|
251
228
|
if (!projectPath) {
|
|
@@ -261,21 +238,13 @@ function findProjectRoot(dir) {
|
|
|
261
238
|
const primaryMarkers = [".git", "package.json"];
|
|
262
239
|
const secondaryMarkers = [
|
|
263
240
|
"Cargo.toml",
|
|
264
|
-
// Rust
|
|
265
241
|
"go.mod",
|
|
266
|
-
// Go
|
|
267
242
|
"pyproject.toml",
|
|
268
|
-
// Python
|
|
269
243
|
"requirements.txt",
|
|
270
|
-
// Python
|
|
271
244
|
"setup.py",
|
|
272
|
-
// Python
|
|
273
245
|
"Gemfile",
|
|
274
|
-
// Ruby
|
|
275
246
|
"pom.xml",
|
|
276
|
-
// Java Maven
|
|
277
247
|
"build.gradle"
|
|
278
|
-
// Java Gradle
|
|
279
248
|
];
|
|
280
249
|
for (const marker of primaryMarkers) {
|
|
281
250
|
if (existsSync2(resolve(dir, marker))) {
|
|
@@ -296,11 +265,10 @@ function findProjectRoot(dir) {
|
|
|
296
265
|
function normalizePath(path) {
|
|
297
266
|
return normalize(path).split(sep).join("/");
|
|
298
267
|
}
|
|
299
|
-
|
|
300
268
|
// src/provider.ts
|
|
301
|
-
import { spawn as spawn2 } from "child_process";
|
|
302
|
-
import { mkdir, readFile as readFile2, rename, unlink, writeFile } from "fs/promises";
|
|
303
|
-
import { dirname as dirname2, normalize as normalize2, resolve as resolve3 } from "path";
|
|
269
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
270
|
+
import { mkdir, readFile as readFile2, rename, unlink, writeFile } from "node:fs/promises";
|
|
271
|
+
import { dirname as dirname2, normalize as normalize2, resolve as resolve3 } from "node:path";
|
|
304
272
|
import { vertex } from "@ai-sdk/google-vertex";
|
|
305
273
|
import { input, select } from "@inquirer/prompts";
|
|
306
274
|
import { generateText, stepCountIs } from "ai";
|
|
@@ -308,7 +276,7 @@ import ignore2 from "ignore";
|
|
|
308
276
|
import { lookup } from "mime-types";
|
|
309
277
|
|
|
310
278
|
// src/utils/checkRipgrep.ts
|
|
311
|
-
import { spawnSync } from "child_process";
|
|
279
|
+
import { spawnSync } from "node:child_process";
|
|
312
280
|
var rgAvailability = {
|
|
313
281
|
isAvailable: null
|
|
314
282
|
};
|
|
@@ -326,8 +294,8 @@ function checkRipgrep() {
|
|
|
326
294
|
}
|
|
327
295
|
|
|
328
296
|
// src/utils/listFiles.ts
|
|
329
|
-
import { promises as fs } from "fs";
|
|
330
|
-
import { join as join2, relative, resolve as resolve2 } from "path";
|
|
297
|
+
import { promises as fs } from "node:fs";
|
|
298
|
+
import { join as join2, relative, resolve as resolve2 } from "node:path";
|
|
331
299
|
import ignore from "ignore";
|
|
332
300
|
var DEFAULT_IGNORES = [
|
|
333
301
|
"__pycache__",
|
|
@@ -365,11 +333,10 @@ async function listFiles(dirPath, recursive, maxCount, cwd, excludeFiles, includ
|
|
|
365
333
|
const rootGitignore = await fs.readFile(join2(cwd, ".gitignore"), "utf8");
|
|
366
334
|
const lines = rootGitignore.split(/\r?\n/).filter(Boolean);
|
|
367
335
|
rootPatterns = [...rootPatterns, ...lines];
|
|
368
|
-
} catch {
|
|
369
|
-
}
|
|
336
|
+
} catch {}
|
|
370
337
|
}
|
|
371
338
|
const results = [];
|
|
372
|
-
const processedDirs =
|
|
339
|
+
const processedDirs = new Set;
|
|
373
340
|
const queue = [
|
|
374
341
|
{
|
|
375
342
|
path: resolve2(dirPath),
|
|
@@ -402,9 +369,7 @@ async function listFiles(dirPath, recursive, maxCount, cwd, excludeFiles, includ
|
|
|
402
369
|
results.push(relPath);
|
|
403
370
|
if (results.length >= maxCount) {
|
|
404
371
|
const remainingEntries = entries.slice(entries.indexOf(entry) + 1);
|
|
405
|
-
const hasRemainingFiles = remainingEntries.some(
|
|
406
|
-
(e) => !e.isDirectory() && !folderIg.ignores(relative(cwd, join2(currentPath, e.name)).replace(/\\/g, "/"))
|
|
407
|
-
);
|
|
372
|
+
const hasRemainingFiles = remainingEntries.some((e) => !e.isDirectory() && !folderIg.ignores(relative(cwd, join2(currentPath, e.name)).replace(/\\/g, "/")));
|
|
408
373
|
if (hasRemainingFiles) {
|
|
409
374
|
const marker = `${currentRelPath}/(files omitted)`;
|
|
410
375
|
results.push(marker);
|
|
@@ -427,11 +392,10 @@ async function listFiles(dirPath, recursive, maxCount, cwd, excludeFiles, includ
|
|
|
427
392
|
}
|
|
428
393
|
|
|
429
394
|
// src/utils/searchFiles.ts
|
|
430
|
-
import { spawn } from "child_process";
|
|
395
|
+
import { spawn } from "node:child_process";
|
|
431
396
|
|
|
432
397
|
// src/utils/search.constants.ts
|
|
433
398
|
var SEARCH_CONSTANTS = {
|
|
434
|
-
/** Default number of context lines to show around search matches */
|
|
435
399
|
DEFAULT_CONTEXT_LINES: 5
|
|
436
400
|
};
|
|
437
401
|
|
|
@@ -439,15 +403,10 @@ var SEARCH_CONSTANTS = {
|
|
|
439
403
|
async function searchFiles(path, regex, filePattern, cwd, excludeFiles) {
|
|
440
404
|
const args = [
|
|
441
405
|
"--line-number",
|
|
442
|
-
// Show line numbers
|
|
443
406
|
`--context=${SEARCH_CONSTANTS.DEFAULT_CONTEXT_LINES}`,
|
|
444
|
-
// Show lines before and after matches
|
|
445
407
|
"--color=never",
|
|
446
|
-
// No color codes in output
|
|
447
408
|
"--with-filename",
|
|
448
|
-
// Show filenames
|
|
449
409
|
"--smart-case"
|
|
450
|
-
// Smart case sensitivity
|
|
451
410
|
];
|
|
452
411
|
if (filePattern && filePattern !== "*") {
|
|
453
412
|
const patterns = filePattern.split(",").map((p) => p.trim()).filter(Boolean);
|
|
@@ -463,7 +422,7 @@ async function searchFiles(path, regex, filePattern, cwd, excludeFiles) {
|
|
|
463
422
|
}
|
|
464
423
|
}
|
|
465
424
|
args.push(regex, path);
|
|
466
|
-
return new Promise((
|
|
425
|
+
return new Promise((resolve3, reject) => {
|
|
467
426
|
const results = [];
|
|
468
427
|
let stderr = "";
|
|
469
428
|
const rg = spawn("rg", args, {
|
|
@@ -471,7 +430,8 @@ async function searchFiles(path, regex, filePattern, cwd, excludeFiles) {
|
|
|
471
430
|
stdio: ["ignore", "pipe", "pipe"]
|
|
472
431
|
});
|
|
473
432
|
rg.stdout.on("data", (data) => {
|
|
474
|
-
const lines = data.toString().split(
|
|
433
|
+
const lines = data.toString().split(`
|
|
434
|
+
`).filter(Boolean);
|
|
475
435
|
results.push(...lines);
|
|
476
436
|
});
|
|
477
437
|
rg.stderr.on("data", (data) => {
|
|
@@ -487,13 +447,13 @@ async function searchFiles(path, regex, filePattern, cwd, excludeFiles) {
|
|
|
487
447
|
reject(new Error(`Ripgrep process exited with code ${code}${details}`));
|
|
488
448
|
return;
|
|
489
449
|
}
|
|
490
|
-
|
|
450
|
+
resolve3(results);
|
|
491
451
|
});
|
|
492
452
|
});
|
|
493
453
|
}
|
|
494
454
|
|
|
495
455
|
// src/provider.ts
|
|
496
|
-
|
|
456
|
+
class InMemoryStore {
|
|
497
457
|
#data;
|
|
498
458
|
async read() {
|
|
499
459
|
return this.#data;
|
|
@@ -501,20 +461,19 @@ var InMemoryStore = class {
|
|
|
501
461
|
async write(data) {
|
|
502
462
|
this.#data = data;
|
|
503
463
|
}
|
|
504
|
-
}
|
|
464
|
+
}
|
|
505
465
|
function notifyCommandObserver(callback, value) {
|
|
506
466
|
try {
|
|
507
467
|
callback?.(value);
|
|
508
|
-
} catch {
|
|
509
|
-
}
|
|
468
|
+
} catch {}
|
|
510
469
|
}
|
|
511
470
|
function isIMemoryStore(store) {
|
|
512
471
|
return "readMemory" in store && "updateMemory" in store;
|
|
513
472
|
}
|
|
514
473
|
var getProvider = (options = {}) => {
|
|
515
474
|
const ig = ignore2().add(options.excludeFiles ?? []);
|
|
516
|
-
const memoryStore = options.memoryStore ?? new InMemoryStore
|
|
517
|
-
const todoItemStore = options.todoItemStore ?? new InMemoryStore
|
|
475
|
+
const memoryStore = options.memoryStore ?? new InMemoryStore;
|
|
476
|
+
const todoItemStore = options.todoItemStore ?? new InMemoryStore;
|
|
518
477
|
const defaultMemoryTopic = ":default:";
|
|
519
478
|
const searchModel = options.getModel?.("search");
|
|
520
479
|
const readMemoryKV = async (topic) => {
|
|
@@ -529,14 +488,14 @@ var getProvider = (options = {}) => {
|
|
|
529
488
|
const data = await memoryStore.read() ?? {};
|
|
530
489
|
switch (operation) {
|
|
531
490
|
case "append":
|
|
532
|
-
if (content ===
|
|
491
|
+
if (content === undefined) {
|
|
533
492
|
throw new Error("Content is required for append operation.");
|
|
534
493
|
}
|
|
535
494
|
data[topic] = `${data[topic] || ""}
|
|
536
495
|
${content}`;
|
|
537
496
|
break;
|
|
538
497
|
case "replace":
|
|
539
|
-
if (content ===
|
|
498
|
+
if (content === undefined) {
|
|
540
499
|
throw new Error("Content is required for replace operation.");
|
|
541
500
|
}
|
|
542
501
|
data[topic] = content;
|
|
@@ -581,8 +540,8 @@ ${content}`;
|
|
|
581
540
|
const aParts = a.id.split(".");
|
|
582
541
|
const bParts = b.id.split(".");
|
|
583
542
|
const len = Math.min(aParts.length, bParts.length);
|
|
584
|
-
for (let i = 0;
|
|
585
|
-
const comparison = aParts[i].localeCompare(bParts[i],
|
|
543
|
+
for (let i = 0;i < len; i++) {
|
|
544
|
+
const comparison = aParts[i].localeCompare(bParts[i], undefined, { numeric: true });
|
|
586
545
|
if (comparison !== 0) {
|
|
587
546
|
return comparison;
|
|
588
547
|
}
|
|
@@ -613,9 +572,7 @@ ${content}`;
|
|
|
613
572
|
if (!parent) {
|
|
614
573
|
throw new Error(`Parent to-do item with id ${parentId} not found`);
|
|
615
574
|
}
|
|
616
|
-
const childItems = todoItems.filter(
|
|
617
|
-
(i) => i.id.startsWith(`${parentId}.`) && i.id.split(".").length === parentId.split(".").length + 1
|
|
618
|
-
);
|
|
575
|
+
const childItems = todoItems.filter((i) => i.id.startsWith(`${parentId}.`) && i.id.split(".").length === parentId.split(".").length + 1);
|
|
619
576
|
const maxId = childItems.reduce((max, item) => {
|
|
620
577
|
const parts = item.id.split(".");
|
|
621
578
|
const lastPart = parseInt(parts[parts.length - 1], 10);
|
|
@@ -677,7 +634,7 @@ ${content}`;
|
|
|
677
634
|
try {
|
|
678
635
|
return await readFile2(path, "utf8");
|
|
679
636
|
} catch (_e) {
|
|
680
|
-
return
|
|
637
|
+
return;
|
|
681
638
|
}
|
|
682
639
|
},
|
|
683
640
|
writeFile: async (path, content) => {
|
|
@@ -728,7 +685,7 @@ ${content}`;
|
|
|
728
685
|
};
|
|
729
686
|
},
|
|
730
687
|
executeCommand: (command, _needApprove) => {
|
|
731
|
-
return new Promise((
|
|
688
|
+
return new Promise((resolve4, reject) => {
|
|
732
689
|
notifyCommandObserver(options.command?.onStarted, command);
|
|
733
690
|
const child = spawn2(command, [], {
|
|
734
691
|
shell: true,
|
|
@@ -749,11 +706,11 @@ ${content}`;
|
|
|
749
706
|
child.on("close", async (code) => {
|
|
750
707
|
notifyCommandObserver(options.command?.onExit, code ?? 0);
|
|
751
708
|
const totalLength = stdoutText.length + stderrText.length;
|
|
752
|
-
if (totalLength > (options.summaryThreshold ??
|
|
709
|
+
if (totalLength > (options.summaryThreshold ?? 5000) && options.summarizeOutput) {
|
|
753
710
|
try {
|
|
754
711
|
const summary = await options.summarizeOutput(stdoutText, stderrText);
|
|
755
712
|
if (summary) {
|
|
756
|
-
|
|
713
|
+
resolve4({
|
|
757
714
|
summary,
|
|
758
715
|
stdout: stdoutText,
|
|
759
716
|
stderr: stderrText,
|
|
@@ -765,7 +722,7 @@ ${content}`;
|
|
|
765
722
|
console.error("Summarization failed:", _e);
|
|
766
723
|
}
|
|
767
724
|
}
|
|
768
|
-
|
|
725
|
+
resolve4({
|
|
769
726
|
stdout: stdoutText,
|
|
770
727
|
stderr: stderrText,
|
|
771
728
|
exitCode: code ?? 0
|
|
@@ -831,53 +788,38 @@ ${content}`;
|
|
|
831
788
|
return await searchFiles(path, regex, filePattern, process.cwd(), options.excludeFiles);
|
|
832
789
|
};
|
|
833
790
|
} else {
|
|
834
|
-
console.error(
|
|
835
|
-
"Error: ripgrep (rg) is not installed. Search file tool is disabled. Please install it from https://github.com/BurntSushi/ripgrep#installation"
|
|
836
|
-
);
|
|
791
|
+
console.error("Error: ripgrep (rg) is not installed. Search file tool is disabled. Please install it from https://github.com/BurntSushi/ripgrep#installation");
|
|
837
792
|
}
|
|
838
793
|
return provider;
|
|
839
794
|
};
|
|
840
|
-
|
|
841
795
|
// src/sqlite-memory-store.ts
|
|
842
|
-
import { AsyncLocalStorage } from "async_hooks";
|
|
843
|
-
import { randomUUID } from "crypto";
|
|
844
|
-
import { existsSync as existsSync3 } from "fs";
|
|
845
|
-
import { mkdir as mkdir2, readdir, readFile as readFile3, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "fs/promises";
|
|
846
|
-
import { basename, dirname as dirname3, resolve as resolve4 } from "path";
|
|
847
|
-
import { fileURLToPath } from "url";
|
|
796
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
797
|
+
import { randomUUID } from "node:crypto";
|
|
798
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
799
|
+
import { mkdir as mkdir2, readdir, readFile as readFile3, rename as rename2, unlink as unlink2, writeFile as writeFile2 } from "node:fs/promises";
|
|
800
|
+
import { basename, dirname as dirname3, resolve as resolve4 } from "node:path";
|
|
801
|
+
import { fileURLToPath } from "node:url";
|
|
848
802
|
import { DEFAULT_MEMORY_CONFIG, resolveHomePath } from "@polka-codes/core";
|
|
849
803
|
import initSqlJs from "sql.js";
|
|
850
|
-
|
|
804
|
+
|
|
805
|
+
class FileLock {
|
|
851
806
|
lockfilePath;
|
|
852
|
-
static LOCK_TIMEOUT =
|
|
853
|
-
|
|
854
|
-
static CLEANUP_AGE = 6e5;
|
|
855
|
-
// 10 minutes - cleanup old lock files
|
|
807
|
+
static LOCK_TIMEOUT = 30000;
|
|
808
|
+
static CLEANUP_AGE = 600000;
|
|
856
809
|
static lastCleanupTime = 0;
|
|
857
|
-
static CLEANUP_THROTTLE =
|
|
858
|
-
// Throttle cleanup to once per minute
|
|
810
|
+
static CLEANUP_THROTTLE = 60000;
|
|
859
811
|
constructor(dbPath) {
|
|
860
812
|
this.lockfilePath = `${dbPath}.lock`;
|
|
861
813
|
}
|
|
862
|
-
/**
|
|
863
|
-
* Reset the cleanup throttle. For testing purposes only.
|
|
864
|
-
*/
|
|
865
814
|
static resetCleanupThrottle() {
|
|
866
|
-
|
|
867
|
-
}
|
|
868
|
-
|
|
869
|
-
* Clean up old lock files (.released.*, .stale.*, .invalid.*, .corrupt.*)
|
|
870
|
-
* Only removes files older than CLEANUP_AGE (10 minutes by default)
|
|
871
|
-
* This method is safe to call multiple times concurrently
|
|
872
|
-
* Cleanup is throttled to run at most once per minute to avoid performance impact
|
|
873
|
-
* @param force - Skip throttling and force cleanup (for testing)
|
|
874
|
-
*/
|
|
875
|
-
static async cleanupOldLockFiles(dbPath, maxAge = _FileLock.CLEANUP_AGE, force = false) {
|
|
815
|
+
FileLock.lastCleanupTime = 0;
|
|
816
|
+
}
|
|
817
|
+
static async cleanupOldLockFiles(dbPath, maxAge = FileLock.CLEANUP_AGE, force = false) {
|
|
876
818
|
const now = Date.now();
|
|
877
|
-
if (!force && now -
|
|
819
|
+
if (!force && now - FileLock.lastCleanupTime < FileLock.CLEANUP_THROTTLE) {
|
|
878
820
|
return;
|
|
879
821
|
}
|
|
880
|
-
|
|
822
|
+
FileLock.lastCleanupTime = now;
|
|
881
823
|
try {
|
|
882
824
|
const lockDir = dirname3(dbPath);
|
|
883
825
|
const dbBaseName = basename(dbPath);
|
|
@@ -909,12 +851,8 @@ var FileLock = class _FileLock {
|
|
|
909
851
|
console.debug(`[FileLock] Cleanup encountered an error: ${error instanceof Error ? error.message : String(error)}`);
|
|
910
852
|
}
|
|
911
853
|
}
|
|
912
|
-
/**
|
|
913
|
-
* Try to acquire lock with retries
|
|
914
|
-
* @throws Error if lock cannot be acquired after retries
|
|
915
|
-
*/
|
|
916
854
|
async acquire(retries = 10, delay = 100) {
|
|
917
|
-
for (let i = 0;
|
|
855
|
+
for (let i = 0;i < retries; i++) {
|
|
918
856
|
try {
|
|
919
857
|
const lockData = JSON.stringify({
|
|
920
858
|
pid: process.pid,
|
|
@@ -922,7 +860,6 @@ var FileLock = class _FileLock {
|
|
|
922
860
|
});
|
|
923
861
|
await writeFile2(this.lockfilePath, lockData, {
|
|
924
862
|
flag: "wx",
|
|
925
|
-
// Exclusive create - fails if file exists
|
|
926
863
|
mode: 384
|
|
927
864
|
});
|
|
928
865
|
return;
|
|
@@ -938,7 +875,7 @@ var FileLock = class _FileLock {
|
|
|
938
875
|
continue;
|
|
939
876
|
}
|
|
940
877
|
const lockAge = Date.now() - lockData.acquiredAt;
|
|
941
|
-
if (lockAge >
|
|
878
|
+
if (lockAge > FileLock.LOCK_TIMEOUT) {
|
|
942
879
|
console.warn(`[FileLock] Breaking stale lock (age: ${lockAge}ms)`);
|
|
943
880
|
await rename2(this.lockfilePath, `${this.lockfilePath}.stale.${Date.now()}`);
|
|
944
881
|
continue;
|
|
@@ -961,15 +898,11 @@ var FileLock = class _FileLock {
|
|
|
961
898
|
}
|
|
962
899
|
}
|
|
963
900
|
}
|
|
964
|
-
/**
|
|
965
|
-
* Release the lock by removing the lockfile
|
|
966
|
-
*/
|
|
967
901
|
async release() {
|
|
968
902
|
try {
|
|
969
903
|
await rename2(this.lockfilePath, `${this.lockfilePath}.released.${Date.now()}`);
|
|
970
904
|
const dbPath = this.lockfilePath.slice(0, -5);
|
|
971
|
-
|
|
972
|
-
});
|
|
905
|
+
FileLock.cleanupOldLockFiles(dbPath).catch(() => {});
|
|
973
906
|
} catch (error) {
|
|
974
907
|
const errorCode = error.code;
|
|
975
908
|
if (errorCode !== "ENOENT") {
|
|
@@ -977,8 +910,9 @@ var FileLock = class _FileLock {
|
|
|
977
910
|
}
|
|
978
911
|
}
|
|
979
912
|
}
|
|
980
|
-
}
|
|
981
|
-
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
class ReentrantMutex {
|
|
982
916
|
queue = [];
|
|
983
917
|
locked = false;
|
|
984
918
|
lockCount = 0;
|
|
@@ -1010,7 +944,7 @@ var ReentrantMutex = class {
|
|
|
1010
944
|
}
|
|
1011
945
|
}
|
|
1012
946
|
}
|
|
1013
|
-
}
|
|
947
|
+
}
|
|
1014
948
|
var SqlJs = null;
|
|
1015
949
|
var SqlJsInitPromise = null;
|
|
1016
950
|
var moduleDir = dirname3(fileURLToPath(import.meta.url));
|
|
@@ -1035,43 +969,30 @@ async function getSqlJs() {
|
|
|
1035
969
|
SqlJs = await SqlJsInitPromise;
|
|
1036
970
|
return SqlJs;
|
|
1037
971
|
} catch (error) {
|
|
1038
|
-
throw new Error(
|
|
1039
|
-
`Failed to initialize sql.js: ${error instanceof Error ? error.message : String(error)}
|
|
972
|
+
throw new Error(`Failed to initialize sql.js: ${error instanceof Error ? error.message : String(error)}
|
|
1040
973
|
|
|
1041
|
-
Attempted to locate WASM at:
|
|
1042
|
-
- ${bundledWasmPath}
|
|
974
|
+
` + `Attempted to locate WASM at:
|
|
975
|
+
` + ` - ${bundledWasmPath}
|
|
1043
976
|
|
|
1044
|
-
If you're developing, run: bun run build in packages/cli-shared`
|
|
1045
|
-
);
|
|
977
|
+
` + `If you're developing, run: bun run build in packages/cli-shared`);
|
|
1046
978
|
}
|
|
1047
979
|
}
|
|
1048
|
-
var transactionOwnerStorage = new AsyncLocalStorage
|
|
1049
|
-
|
|
980
|
+
var transactionOwnerStorage = new AsyncLocalStorage;
|
|
981
|
+
|
|
982
|
+
class SQLiteMemoryStore {
|
|
1050
983
|
db = null;
|
|
1051
984
|
dbPromise = null;
|
|
1052
985
|
config;
|
|
1053
986
|
currentScope;
|
|
1054
987
|
inTransaction = false;
|
|
1055
|
-
|
|
1056
|
-
transactionMutex = new ReentrantMutex();
|
|
1057
|
-
// Serialize transactions
|
|
988
|
+
transactionMutex = new ReentrantMutex;
|
|
1058
989
|
fileLock;
|
|
1059
|
-
// Cross-process file lock (initialized in getFileLock())
|
|
1060
|
-
/**
|
|
1061
|
-
* Reset the lock file cleanup throttle. For testing purposes only.
|
|
1062
|
-
*/
|
|
1063
990
|
static resetCleanupThrottle() {
|
|
1064
991
|
FileLock.resetCleanupThrottle();
|
|
1065
992
|
}
|
|
1066
|
-
/**
|
|
1067
|
-
* Get the configured database path, or default if not set
|
|
1068
|
-
*/
|
|
1069
993
|
getDbPath() {
|
|
1070
994
|
return this.config.path || DEFAULT_MEMORY_CONFIG.path;
|
|
1071
995
|
}
|
|
1072
|
-
/**
|
|
1073
|
-
* Get lockfile instance for database path
|
|
1074
|
-
*/
|
|
1075
996
|
getFileLock() {
|
|
1076
997
|
if (!this.fileLock) {
|
|
1077
998
|
const dbPath = this.resolvePath(this.getDbPath());
|
|
@@ -1079,7 +1000,6 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1079
1000
|
}
|
|
1080
1001
|
return this.fileLock;
|
|
1081
1002
|
}
|
|
1082
|
-
// Whitelists for validation
|
|
1083
1003
|
static SORT_COLUMNS = {
|
|
1084
1004
|
created: "created_at",
|
|
1085
1005
|
updated: "updated_at",
|
|
@@ -1092,9 +1012,6 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1092
1012
|
this.config = config;
|
|
1093
1013
|
this.currentScope = scope;
|
|
1094
1014
|
}
|
|
1095
|
-
/**
|
|
1096
|
-
* Initialize database connection and schema
|
|
1097
|
-
*/
|
|
1098
1015
|
async initializeDatabase() {
|
|
1099
1016
|
if (this.dbPromise) {
|
|
1100
1017
|
return this.dbPromise;
|
|
@@ -1109,8 +1026,7 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1109
1026
|
if (!existsSync3(dir)) {
|
|
1110
1027
|
await mkdir2(dir, { recursive: true, mode: 448 });
|
|
1111
1028
|
}
|
|
1112
|
-
FileLock.cleanupOldLockFiles(dbPath).catch(() => {
|
|
1113
|
-
});
|
|
1029
|
+
FileLock.cleanupOldLockFiles(dbPath).catch(() => {});
|
|
1114
1030
|
let dbData;
|
|
1115
1031
|
if (existsSync3(dbPath)) {
|
|
1116
1032
|
const lock = this.getFileLock();
|
|
@@ -1122,13 +1038,13 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1122
1038
|
const header = String.fromCharCode(...dbData.subarray(0, 15));
|
|
1123
1039
|
if (header !== "SQLite format 3") {
|
|
1124
1040
|
console.warn("[SQLiteMemoryStore] Invalid SQLite database header, will recreate");
|
|
1125
|
-
dbData =
|
|
1041
|
+
dbData = undefined;
|
|
1126
1042
|
}
|
|
1127
1043
|
}
|
|
1128
1044
|
} catch (error) {
|
|
1129
1045
|
const errorCode = error?.code;
|
|
1130
1046
|
if (errorCode === "ENOENT") {
|
|
1131
|
-
dbData =
|
|
1047
|
+
dbData = undefined;
|
|
1132
1048
|
} else {
|
|
1133
1049
|
throw new Error(`Failed to read database file at ${dbPath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1134
1050
|
}
|
|
@@ -1165,9 +1081,6 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1165
1081
|
})();
|
|
1166
1082
|
return this.dbPromise;
|
|
1167
1083
|
}
|
|
1168
|
-
/**
|
|
1169
|
-
* Persist database to disk using atomic write with file locking
|
|
1170
|
-
*/
|
|
1171
1084
|
async saveDatabase() {
|
|
1172
1085
|
if (!this.db) {
|
|
1173
1086
|
return;
|
|
@@ -1184,18 +1097,12 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1184
1097
|
await lock.release();
|
|
1185
1098
|
}
|
|
1186
1099
|
}
|
|
1187
|
-
/**
|
|
1188
|
-
* Configure database pragmas
|
|
1189
|
-
*/
|
|
1190
1100
|
configurePragmas(db) {
|
|
1191
1101
|
db.run("PRAGMA synchronous = NORMAL");
|
|
1192
1102
|
db.run("PRAGMA busy_timeout = 5000");
|
|
1193
1103
|
db.run("PRAGMA foreign_keys = ON");
|
|
1194
1104
|
db.run("PRAGMA temp_store = MEMORY");
|
|
1195
1105
|
}
|
|
1196
|
-
/**
|
|
1197
|
-
* Check database integrity
|
|
1198
|
-
*/
|
|
1199
1106
|
checkIntegrity(db) {
|
|
1200
1107
|
try {
|
|
1201
1108
|
const results = db.exec("SELECT 1");
|
|
@@ -1207,9 +1114,6 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1207
1114
|
throw new Error("Database is corrupted");
|
|
1208
1115
|
}
|
|
1209
1116
|
}
|
|
1210
|
-
/**
|
|
1211
|
-
* Initialize database schema
|
|
1212
|
-
*/
|
|
1213
1117
|
initializeSchema(db) {
|
|
1214
1118
|
db.run(`
|
|
1215
1119
|
CREATE TABLE IF NOT EXISTS memory_entries (
|
|
@@ -1231,39 +1135,22 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1231
1135
|
db.run("CREATE INDEX IF NOT EXISTS idx_memory_entries_scope_type ON memory_entries(scope, entry_type)");
|
|
1232
1136
|
db.run("CREATE INDEX IF NOT EXISTS idx_memory_entries_updated ON memory_entries(updated_at)");
|
|
1233
1137
|
}
|
|
1234
|
-
/**
|
|
1235
|
-
* Get database instance
|
|
1236
|
-
*/
|
|
1237
1138
|
async getDatabase() {
|
|
1238
1139
|
if (!this.db) {
|
|
1239
1140
|
this.db = await this.initializeDatabase();
|
|
1240
1141
|
}
|
|
1241
1142
|
return this.db;
|
|
1242
1143
|
}
|
|
1243
|
-
/**
|
|
1244
|
-
* Resolve home directory in path using shared utility
|
|
1245
|
-
*/
|
|
1246
1144
|
resolvePath(path) {
|
|
1247
1145
|
const resolved = resolveHomePath(path);
|
|
1248
1146
|
return resolve4(resolved);
|
|
1249
1147
|
}
|
|
1250
|
-
/**
|
|
1251
|
-
* Generate UUID v4
|
|
1252
|
-
*/
|
|
1253
1148
|
generateUUID() {
|
|
1254
1149
|
return randomUUID();
|
|
1255
1150
|
}
|
|
1256
|
-
/**
|
|
1257
|
-
* Get current timestamp in milliseconds
|
|
1258
|
-
*/
|
|
1259
1151
|
now() {
|
|
1260
1152
|
return Date.now();
|
|
1261
1153
|
}
|
|
1262
|
-
/**
|
|
1263
|
-
* Execute transaction
|
|
1264
|
-
* Uses Mutex to serialize concurrent transaction calls for safety
|
|
1265
|
-
* Supports reentrancy (nested transactions from the same call chain)
|
|
1266
|
-
*/
|
|
1267
1154
|
async transaction(callback) {
|
|
1268
1155
|
let owner = transactionOwnerStorage.getStore();
|
|
1269
1156
|
if (!owner) {
|
|
@@ -1308,11 +1195,6 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1308
1195
|
}
|
|
1309
1196
|
});
|
|
1310
1197
|
}
|
|
1311
|
-
/**
|
|
1312
|
-
* Read memory by topic
|
|
1313
|
-
* Note: Does NOT update last_accessed timestamp to avoid expensive disk writes on every read.
|
|
1314
|
-
* The timestamp is updated when memory is modified through updateMemory operations.
|
|
1315
|
-
*/
|
|
1316
1198
|
async readMemory(topic) {
|
|
1317
1199
|
const db = await this.getDatabase();
|
|
1318
1200
|
const scope = this.currentScope;
|
|
@@ -1325,11 +1207,8 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1325
1207
|
return content;
|
|
1326
1208
|
}
|
|
1327
1209
|
stmt.free();
|
|
1328
|
-
return
|
|
1210
|
+
return;
|
|
1329
1211
|
}
|
|
1330
|
-
/**
|
|
1331
|
-
* Internal update memory without transaction (used by batchUpdateMemory)
|
|
1332
|
-
*/
|
|
1333
1212
|
async updateMemoryInternal(db, operation, topic, content, metadata) {
|
|
1334
1213
|
const scope = this.currentScope;
|
|
1335
1214
|
const now = this.now();
|
|
@@ -1356,7 +1235,7 @@ var SQLiteMemoryStore = class _SQLiteMemoryStore {
|
|
|
1356
1235
|
};
|
|
1357
1236
|
stmt.free();
|
|
1358
1237
|
} else {
|
|
1359
|
-
existing =
|
|
1238
|
+
existing = undefined;
|
|
1360
1239
|
stmt.free();
|
|
1361
1240
|
}
|
|
1362
1241
|
let finalContent;
|
|
@@ -1378,9 +1257,9 @@ ${content}`;
|
|
|
1378
1257
|
finalContent = content;
|
|
1379
1258
|
}
|
|
1380
1259
|
entry_type = metadata?.entry_type || existing.entry_type;
|
|
1381
|
-
status = (metadata?.status || existing.status) ??
|
|
1382
|
-
priority = (metadata?.priority || existing.priority) ??
|
|
1383
|
-
tags = (metadata?.tags || existing.tags) ??
|
|
1260
|
+
status = (metadata?.status || existing.status) ?? undefined;
|
|
1261
|
+
priority = (metadata?.priority || existing.priority) ?? undefined;
|
|
1262
|
+
tags = (metadata?.tags || existing.tags) ?? undefined;
|
|
1384
1263
|
} else {
|
|
1385
1264
|
if (!content) {
|
|
1386
1265
|
throw new Error("Content is required for new memory entries.");
|
|
@@ -1418,18 +1297,12 @@ ${content}`;
|
|
|
1418
1297
|
]);
|
|
1419
1298
|
upsertStmt.free();
|
|
1420
1299
|
}
|
|
1421
|
-
/**
|
|
1422
|
-
* Update memory
|
|
1423
|
-
*/
|
|
1424
1300
|
async updateMemory(operation, topic, content, metadata) {
|
|
1425
1301
|
return this.transaction(async () => {
|
|
1426
1302
|
const db = await this.getDatabase();
|
|
1427
1303
|
await this.updateMemoryInternal(db, operation, topic, content, metadata);
|
|
1428
1304
|
});
|
|
1429
1305
|
}
|
|
1430
|
-
/**
|
|
1431
|
-
* Query memory with filters
|
|
1432
|
-
*/
|
|
1433
1306
|
async queryMemory(query = {}, options = {}) {
|
|
1434
1307
|
if (options.operation === "delete") {
|
|
1435
1308
|
return this.transaction(async () => {
|
|
@@ -1466,9 +1339,6 @@ ${content}`;
|
|
|
1466
1339
|
stmt.free();
|
|
1467
1340
|
return entries;
|
|
1468
1341
|
}
|
|
1469
|
-
/**
|
|
1470
|
-
* Build SQL query safely with parameterized statements
|
|
1471
|
-
*/
|
|
1472
1342
|
buildQuery(query) {
|
|
1473
1343
|
const conditions = [];
|
|
1474
1344
|
const params = [];
|
|
@@ -1500,7 +1370,7 @@ ${content}`;
|
|
|
1500
1370
|
params.push(query.status);
|
|
1501
1371
|
}
|
|
1502
1372
|
if (query.priority) {
|
|
1503
|
-
if (!
|
|
1373
|
+
if (!SQLiteMemoryStore.ALLOWED_PRIORITIES.includes(query.priority)) {
|
|
1504
1374
|
throw new Error(`Invalid priority: ${query.priority}`);
|
|
1505
1375
|
}
|
|
1506
1376
|
conditions.push(`priority = ?`);
|
|
@@ -1544,12 +1414,12 @@ ${content}`;
|
|
|
1544
1414
|
sql += ` AND ${conditions.join(" AND ")}`;
|
|
1545
1415
|
}
|
|
1546
1416
|
if (query.sortBy) {
|
|
1547
|
-
const column =
|
|
1417
|
+
const column = SQLiteMemoryStore.SORT_COLUMNS[query.sortBy];
|
|
1548
1418
|
if (!column) {
|
|
1549
1419
|
throw new Error(`Invalid sortBy: ${query.sortBy}`);
|
|
1550
1420
|
}
|
|
1551
1421
|
const order = query.sortOrder || "desc";
|
|
1552
|
-
if (!
|
|
1422
|
+
if (!SQLiteMemoryStore.ALLOWED_SORT_ORDERS.includes(order)) {
|
|
1553
1423
|
throw new Error(`Invalid sortOrder: ${order}`);
|
|
1554
1424
|
}
|
|
1555
1425
|
sql += ` ORDER BY ${column} ${order.toUpperCase()}`;
|
|
@@ -1572,9 +1442,6 @@ ${content}`;
|
|
|
1572
1442
|
}
|
|
1573
1443
|
return { sql, params };
|
|
1574
1444
|
}
|
|
1575
|
-
/**
|
|
1576
|
-
* Batch update memory
|
|
1577
|
-
*/
|
|
1578
1445
|
async batchUpdateMemory(operations) {
|
|
1579
1446
|
return this.transaction(async () => {
|
|
1580
1447
|
const db = await this.getDatabase();
|
|
@@ -1583,10 +1450,6 @@ ${content}`;
|
|
|
1583
1450
|
}
|
|
1584
1451
|
});
|
|
1585
1452
|
}
|
|
1586
|
-
/**
|
|
1587
|
-
* Close database connection
|
|
1588
|
-
* @param skipSave - If true, skip saving before close (useful when save already failed)
|
|
1589
|
-
*/
|
|
1590
1453
|
async close(skipSave = false) {
|
|
1591
1454
|
const db = this.db;
|
|
1592
1455
|
if (db) {
|
|
@@ -1603,9 +1466,6 @@ ${content}`;
|
|
|
1603
1466
|
}
|
|
1604
1467
|
this.dbPromise = null;
|
|
1605
1468
|
}
|
|
1606
|
-
/**
|
|
1607
|
-
* Get database statistics
|
|
1608
|
-
*/
|
|
1609
1469
|
async getStats() {
|
|
1610
1470
|
const db = await this.getDatabase();
|
|
1611
1471
|
const results = db.exec("SELECT COUNT(*) as count FROM memory_entries");
|
|
@@ -1620,20 +1480,18 @@ ${content}`;
|
|
|
1620
1480
|
const dbPath = this.resolvePath(this.getDbPath());
|
|
1621
1481
|
let databaseSize = 0;
|
|
1622
1482
|
try {
|
|
1623
|
-
const stats = await import("fs/promises").then((fs2) => fs2.stat(dbPath));
|
|
1483
|
+
const stats = await import("node:fs/promises").then((fs2) => fs2.stat(dbPath));
|
|
1624
1484
|
databaseSize = stats.size;
|
|
1625
|
-
} catch {
|
|
1626
|
-
}
|
|
1485
|
+
} catch {}
|
|
1627
1486
|
return {
|
|
1628
1487
|
totalEntries,
|
|
1629
1488
|
entriesByType,
|
|
1630
1489
|
databaseSize
|
|
1631
1490
|
};
|
|
1632
1491
|
}
|
|
1633
|
-
}
|
|
1634
|
-
|
|
1492
|
+
}
|
|
1635
1493
|
// src/utils/eventHandler.ts
|
|
1636
|
-
import { Console } from "console";
|
|
1494
|
+
import { Console } from "node:console";
|
|
1637
1495
|
import { TaskEventKind } from "@polka-codes/core";
|
|
1638
1496
|
import chalk from "chalk";
|
|
1639
1497
|
|
|
@@ -1642,7 +1500,7 @@ function createSimplifier(keepFields) {
|
|
|
1642
1500
|
return (params) => {
|
|
1643
1501
|
const result = {};
|
|
1644
1502
|
for (const field of keepFields) {
|
|
1645
|
-
if (params[field] !==
|
|
1503
|
+
if (params[field] !== undefined) {
|
|
1646
1504
|
result[field] = params[field];
|
|
1647
1505
|
}
|
|
1648
1506
|
}
|
|
@@ -1653,17 +1511,14 @@ function createCustomSimplifier(transform) {
|
|
|
1653
1511
|
return transform;
|
|
1654
1512
|
}
|
|
1655
1513
|
var SIMPLIFIERS = {
|
|
1656
|
-
// Simple field-based simplifiers
|
|
1657
1514
|
replaceInFile: createSimplifier(["path"]),
|
|
1658
1515
|
writeToFile: createSimplifier(["path"]),
|
|
1659
1516
|
readFile: createSimplifier(["path", "includeIgnored"]),
|
|
1660
1517
|
executeCommand: createSimplifier(["command", "requiresApproval"]),
|
|
1661
1518
|
updateMemory: createSimplifier(["operation", "topic"]),
|
|
1662
|
-
// searchFiles passes through all params
|
|
1663
1519
|
searchFiles: createCustomSimplifier((params) => ({ ...params })),
|
|
1664
|
-
// listFiles has custom logic for maxCount default value
|
|
1665
1520
|
listFiles: createCustomSimplifier((params) => {
|
|
1666
|
-
const DEFAULT_MAX_COUNT =
|
|
1521
|
+
const DEFAULT_MAX_COUNT = 2000;
|
|
1667
1522
|
const maxCount = params.maxCount;
|
|
1668
1523
|
return {
|
|
1669
1524
|
path: params.path,
|
|
@@ -1673,7 +1528,7 @@ var SIMPLIFIERS = {
|
|
|
1673
1528
|
})
|
|
1674
1529
|
};
|
|
1675
1530
|
function simplifyToolParameters(toolName, params) {
|
|
1676
|
-
if (params ===
|
|
1531
|
+
if (params === undefined || params === null) {
|
|
1677
1532
|
return {};
|
|
1678
1533
|
}
|
|
1679
1534
|
const simplifier = SIMPLIFIERS[toolName];
|
|
@@ -1684,8 +1539,8 @@ function simplifyToolParameters(toolName, params) {
|
|
|
1684
1539
|
}
|
|
1685
1540
|
|
|
1686
1541
|
// src/utils/eventHandler.ts
|
|
1687
|
-
var taskToolCallStats =
|
|
1688
|
-
var globalToolCallStats =
|
|
1542
|
+
var taskToolCallStats = new Map;
|
|
1543
|
+
var globalToolCallStats = new Map;
|
|
1689
1544
|
function logToolCallStats(stream, statsMap, title) {
|
|
1690
1545
|
const customConsole = new Console(stream, stream);
|
|
1691
1546
|
customConsole.log(`
|
|
@@ -1708,7 +1563,7 @@ function logToolCallStats(stream, statsMap, title) {
|
|
|
1708
1563
|
}
|
|
1709
1564
|
}
|
|
1710
1565
|
var mergeToolCallStats = (a, b) => {
|
|
1711
|
-
const merged =
|
|
1566
|
+
const merged = new Map;
|
|
1712
1567
|
for (const [tool, stat] of a) {
|
|
1713
1568
|
merged.set(tool, { ...stat });
|
|
1714
1569
|
}
|
|
@@ -1733,8 +1588,7 @@ function logGlobalToolCallStats(stream, verbose = 0) {
|
|
|
1733
1588
|
}
|
|
1734
1589
|
var printEvent = (verbose, usageMeter, stream = process.stdout) => {
|
|
1735
1590
|
if (verbose < 0) {
|
|
1736
|
-
return (_event) => {
|
|
1737
|
-
};
|
|
1591
|
+
return (_event) => {};
|
|
1738
1592
|
}
|
|
1739
1593
|
const customConsole = new Console(stream, stream);
|
|
1740
1594
|
let hadReasoning = false;
|
|
@@ -1748,13 +1602,19 @@ var printEvent = (verbose, usageMeter, stream = process.stdout) => {
|
|
|
1748
1602
|
customConsole.log(`
|
|
1749
1603
|
====== System Prompt ======
|
|
1750
1604
|
${event.systemPrompt}`);
|
|
1751
|
-
customConsole.log(
|
|
1605
|
+
customConsole.log(`
|
|
1606
|
+
|
|
1607
|
+
================
|
|
1608
|
+
`);
|
|
1752
1609
|
}
|
|
1753
1610
|
break;
|
|
1754
1611
|
case TaskEventKind.StartRequest:
|
|
1755
1612
|
hasText = false;
|
|
1756
1613
|
if (verbose > 0) {
|
|
1757
|
-
customConsole.log(
|
|
1614
|
+
customConsole.log(`
|
|
1615
|
+
|
|
1616
|
+
======== New Request ========
|
|
1617
|
+
`);
|
|
1758
1618
|
}
|
|
1759
1619
|
if (verbose > 1) {
|
|
1760
1620
|
for (const message of event.userMessage) {
|
|
@@ -1792,15 +1652,23 @@ ${event.systemPrompt}`);
|
|
|
1792
1652
|
}
|
|
1793
1653
|
}
|
|
1794
1654
|
}
|
|
1795
|
-
customConsole.log(
|
|
1655
|
+
customConsole.log(`
|
|
1656
|
+
|
|
1657
|
+
======== Request Message Ended ========
|
|
1658
|
+
`);
|
|
1796
1659
|
}
|
|
1797
1660
|
break;
|
|
1798
1661
|
case TaskEventKind.EndRequest:
|
|
1799
1662
|
if (verbose > 0) {
|
|
1800
|
-
customConsole.log(
|
|
1663
|
+
customConsole.log(`
|
|
1664
|
+
|
|
1665
|
+
======== Request Ended ========
|
|
1666
|
+
`);
|
|
1801
1667
|
}
|
|
1802
1668
|
if (verbose === 0 && hasText) {
|
|
1803
|
-
write(
|
|
1669
|
+
write(`
|
|
1670
|
+
|
|
1671
|
+
`);
|
|
1804
1672
|
}
|
|
1805
1673
|
if (verbose > 1) {
|
|
1806
1674
|
customConsole.log(usageMeter.getUsageText());
|
|
@@ -1808,7 +1676,9 @@ ${event.systemPrompt}`);
|
|
|
1808
1676
|
break;
|
|
1809
1677
|
case TaskEventKind.Text: {
|
|
1810
1678
|
if (hadReasoning) {
|
|
1811
|
-
write(
|
|
1679
|
+
write(`
|
|
1680
|
+
|
|
1681
|
+
`);
|
|
1812
1682
|
hadReasoning = false;
|
|
1813
1683
|
}
|
|
1814
1684
|
if (event.newText.trim().length > 0) {
|
|
@@ -1827,7 +1697,9 @@ ${event.systemPrompt}`);
|
|
|
1827
1697
|
case TaskEventKind.ToolUse: {
|
|
1828
1698
|
if (verbose > 0) {
|
|
1829
1699
|
const params = verbose > 1 ? event.params : simplifyToolParameters(event.tool, event.params);
|
|
1830
|
-
customConsole.log(chalk.yellow(
|
|
1700
|
+
customConsole.log(chalk.yellow(`
|
|
1701
|
+
|
|
1702
|
+
Tool use:`, event.tool), params);
|
|
1831
1703
|
}
|
|
1832
1704
|
const stats = taskToolCallStats.get(event.tool) ?? { calls: 0, success: 0, errors: 0 };
|
|
1833
1705
|
stats.calls++;
|
|
@@ -1841,7 +1713,9 @@ ${event.systemPrompt}`);
|
|
|
1841
1713
|
break;
|
|
1842
1714
|
}
|
|
1843
1715
|
case TaskEventKind.ToolError: {
|
|
1844
|
-
customConsole.error(chalk.red(
|
|
1716
|
+
customConsole.error(chalk.red(`
|
|
1717
|
+
|
|
1718
|
+
Tool error:`, event.tool));
|
|
1845
1719
|
customConsole.error(event.error);
|
|
1846
1720
|
const stats = taskToolCallStats.get(event.tool) ?? { calls: 0, success: 0, errors: 0 };
|
|
1847
1721
|
stats.errors++;
|
|
@@ -1849,10 +1723,16 @@ ${event.systemPrompt}`);
|
|
|
1849
1723
|
break;
|
|
1850
1724
|
}
|
|
1851
1725
|
case TaskEventKind.UsageExceeded:
|
|
1852
|
-
customConsole.log(
|
|
1726
|
+
customConsole.log(`
|
|
1727
|
+
|
|
1728
|
+
======= Usage Exceeded ========
|
|
1729
|
+
`);
|
|
1853
1730
|
break;
|
|
1854
1731
|
case TaskEventKind.EndTask:
|
|
1855
|
-
customConsole.log(
|
|
1732
|
+
customConsole.log(`
|
|
1733
|
+
|
|
1734
|
+
======== Task Ended ========
|
|
1735
|
+
`);
|
|
1856
1736
|
customConsole.log("Reason:", event.exitReason.type);
|
|
1857
1737
|
switch (event.exitReason.type) {
|
|
1858
1738
|
case "Error": {
|
|
@@ -1879,9 +1759,8 @@ ${event.systemPrompt}`);
|
|
|
1879
1759
|
}
|
|
1880
1760
|
};
|
|
1881
1761
|
};
|
|
1882
|
-
|
|
1883
1762
|
// src/utils/readMultiline.ts
|
|
1884
|
-
import readline from "readline";
|
|
1763
|
+
import readline from "node:readline";
|
|
1885
1764
|
function readMultiline(prompt = "Enter text (Ctrl+D to finish):") {
|
|
1886
1765
|
return new Promise((resolve5) => {
|
|
1887
1766
|
console.log(prompt);
|
|
@@ -1895,31 +1774,32 @@ function readMultiline(prompt = "Enter text (Ctrl+D to finish):") {
|
|
|
1895
1774
|
lines.push(line);
|
|
1896
1775
|
});
|
|
1897
1776
|
rl.on("close", () => {
|
|
1898
|
-
resolve5(lines.join(
|
|
1777
|
+
resolve5(lines.join(`
|
|
1778
|
+
`));
|
|
1899
1779
|
});
|
|
1900
1780
|
});
|
|
1901
1781
|
}
|
|
1902
1782
|
export {
|
|
1903
|
-
|
|
1904
|
-
MemoryManager,
|
|
1905
|
-
SQLiteMemoryStore,
|
|
1906
|
-
checkRipgrep,
|
|
1907
|
-
configSchema,
|
|
1908
|
-
detectProjectScope,
|
|
1909
|
-
getGlobalConfigPath,
|
|
1910
|
-
getProvider,
|
|
1911
|
-
listFiles,
|
|
1912
|
-
loadConfig,
|
|
1913
|
-
loadConfigAtPath,
|
|
1914
|
-
localConfigFileName,
|
|
1915
|
-
logGlobalToolCallStats,
|
|
1916
|
-
logToolCallStats,
|
|
1917
|
-
mergeConfigs,
|
|
1918
|
-
printEvent,
|
|
1919
|
-
readConfig,
|
|
1920
|
-
readLocalConfig,
|
|
1921
|
-
readMultiline,
|
|
1922
|
-
resolveRules,
|
|
1783
|
+
simplifyToolParameters,
|
|
1923
1784
|
searchFiles,
|
|
1924
|
-
|
|
1785
|
+
resolveRules,
|
|
1786
|
+
readMultiline,
|
|
1787
|
+
readLocalConfig,
|
|
1788
|
+
readConfig,
|
|
1789
|
+
printEvent,
|
|
1790
|
+
mergeConfigs,
|
|
1791
|
+
logToolCallStats,
|
|
1792
|
+
logGlobalToolCallStats,
|
|
1793
|
+
localConfigFileName,
|
|
1794
|
+
loadConfigAtPath,
|
|
1795
|
+
loadConfig,
|
|
1796
|
+
listFiles,
|
|
1797
|
+
getProvider,
|
|
1798
|
+
getGlobalConfigPath,
|
|
1799
|
+
detectProjectScope,
|
|
1800
|
+
configSchema,
|
|
1801
|
+
checkRipgrep,
|
|
1802
|
+
SQLiteMemoryStore,
|
|
1803
|
+
MemoryManager,
|
|
1804
|
+
InMemoryStore
|
|
1925
1805
|
};
|
package/dist/provider.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { LanguageModelV4 } from '@ai-sdk/provider';
|
|
2
2
|
import type { IMemoryStore, TodoItem, ToolProvider } from '@polka-codes/core';
|
|
3
3
|
export interface ProviderDataStore<T> {
|
|
4
4
|
read(): Promise<T | undefined>;
|
|
@@ -26,7 +26,7 @@ export type ProviderOptions = {
|
|
|
26
26
|
summaryThreshold?: number;
|
|
27
27
|
memoryStore?: ProviderDataStore<Record<string, string>> | IMemoryStore;
|
|
28
28
|
todoItemStore?: ProviderDataStore<TodoItem[]>;
|
|
29
|
-
getModel?: (command: string) =>
|
|
29
|
+
getModel?: (command: string) => LanguageModelV4 | undefined;
|
|
30
30
|
yes?: boolean;
|
|
31
31
|
};
|
|
32
32
|
export declare const getProvider: (options?: ProviderOptions) => ToolProvider;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@polka-codes/cli-shared",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"license": "AGPL-3.0",
|
|
5
5
|
"author": "github@polka.codes",
|
|
6
6
|
"repository": {
|
|
@@ -11,8 +11,8 @@
|
|
|
11
11
|
"type": "module",
|
|
12
12
|
"exports": {
|
|
13
13
|
".": {
|
|
14
|
-
"
|
|
15
|
-
"
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.js"
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
18
|
"files": [
|
|
@@ -22,23 +22,22 @@
|
|
|
22
22
|
"access": "public"
|
|
23
23
|
},
|
|
24
24
|
"scripts": {
|
|
25
|
-
"build": "tsc --build &&
|
|
26
|
-
"build:copy-wasm": "mkdir -p dist && cp
|
|
25
|
+
"build": "rm -rf dist && tsc --build --force && bun run ../../scripts/fix-declaration-imports.ts dist && bun build src/index.ts --outdir dist --target node --format esm --packages external --tsconfig-override=../../tsconfig.bundle.json --external=@polka-codes/core && bun run build:copy-wasm",
|
|
26
|
+
"build:copy-wasm": "mkdir -p dist && cp node_modules/sql.js/dist/sql-wasm.wasm dist/"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@ai-sdk/google-vertex": "^
|
|
30
|
-
"@ai-sdk/provider": "^
|
|
31
|
-
"@
|
|
32
|
-
"@
|
|
33
|
-
"
|
|
34
|
-
"ai": "^6.0.170",
|
|
29
|
+
"@ai-sdk/google-vertex": "^5.0.20",
|
|
30
|
+
"@ai-sdk/provider": "^4.0.3",
|
|
31
|
+
"@inquirer/prompts": "^8.5.2",
|
|
32
|
+
"@polka-codes/core": "^0.11.0",
|
|
33
|
+
"ai": "^7.0.28",
|
|
35
34
|
"chalk": "^5.6.2",
|
|
36
|
-
"ignore": "^7.0.
|
|
35
|
+
"ignore": "^7.0.6",
|
|
37
36
|
"lodash-es": "^4.18.1",
|
|
38
37
|
"mime-types": "^3.0.2",
|
|
39
38
|
"sql.js": "^1.14.1",
|
|
40
|
-
"yaml": "^2.
|
|
41
|
-
"zod": "^4.4.
|
|
39
|
+
"yaml": "^2.9.0",
|
|
40
|
+
"zod": "^4.4.3"
|
|
42
41
|
},
|
|
43
42
|
"devDependencies": {
|
|
44
43
|
"@types/lodash-es": "^4.17.12",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/config.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
package/dist/provider.test.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|