@wrongstack/tools 0.293.0 → 0.295.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_env.d.ts +1 -1
- package/dist/_env.d.ts.map +1 -1
- package/dist/_fetch-guard.d.ts.map +1 -1
- package/dist/_spawn-stream.d.ts +1 -1
- package/dist/_spawn-stream.d.ts.map +1 -1
- package/dist/_util.d.ts +1 -1
- package/dist/_util.d.ts.map +1 -1
- package/dist/audit.d.ts +1 -1
- package/dist/audit.d.ts.map +1 -1
- package/dist/audit.js +81 -16
- package/dist/audit.js.map +2 -2
- package/dist/auto-proceed-loop-guard.d.ts +31 -0
- package/dist/auto-proceed-loop-guard.d.ts.map +1 -1
- package/dist/auto-proceed-loop-guard.js +24 -1
- package/dist/auto-proceed-loop-guard.js.map +2 -2
- package/dist/bash.d.ts +1 -1
- package/dist/bash.d.ts.map +1 -1
- package/dist/bash.js +105 -75
- package/dist/bash.js.map +3 -3
- package/dist/batch-tool-use.d.ts +1 -1
- package/dist/batch-tool-use.d.ts.map +1 -1
- package/dist/batch-tool-use.js +1 -1
- package/dist/batch-tool-use.js.map +1 -1
- package/dist/browser/index.js +10 -1
- package/dist/browser/index.js.map +2 -2
- package/dist/browser/manager.d.ts +2 -0
- package/dist/browser/manager.d.ts.map +1 -1
- package/dist/browser/tools.d.ts +1 -1
- package/dist/browser/tools.d.ts.map +1 -1
- package/dist/builtin.d.ts +1 -1
- package/dist/builtin.d.ts.map +1 -1
- package/dist/builtin.js +1650 -640
- package/dist/builtin.js.map +4 -4
- package/dist/codebase-index/background-indexer.d.ts +2 -2
- package/dist/codebase-index/background-indexer.d.ts.map +1 -1
- package/dist/codebase-index/bm25.d.ts +3 -1
- package/dist/codebase-index/bm25.d.ts.map +1 -1
- package/dist/codebase-index/codebase-index-tool.d.ts +1 -1
- package/dist/codebase-index/codebase-index-tool.d.ts.map +1 -1
- package/dist/codebase-index/codebase-search-tool.d.ts +1 -1
- package/dist/codebase-index/codebase-search-tool.d.ts.map +1 -1
- package/dist/codebase-index/codebase-stats-tool.d.ts +1 -1
- package/dist/codebase-index/codebase-stats-tool.d.ts.map +1 -1
- package/dist/codebase-index/generic-parser.d.ts +34 -0
- package/dist/codebase-index/generic-parser.d.ts.map +1 -0
- package/dist/codebase-index/go-parser.d.ts +1 -1
- package/dist/codebase-index/go-parser.d.ts.map +1 -1
- package/dist/codebase-index/index.d.ts +4 -2
- package/dist/codebase-index/index.d.ts.map +1 -1
- package/dist/codebase-index/index.js +1068 -372
- package/dist/codebase-index/index.js.map +4 -4
- package/dist/codebase-index/indexer.d.ts +6 -1
- package/dist/codebase-index/indexer.d.ts.map +1 -1
- package/dist/codebase-index/json-parser.d.ts +1 -1
- package/dist/codebase-index/languages.d.ts +25 -0
- package/dist/codebase-index/languages.d.ts.map +1 -0
- package/dist/codebase-index/py-parser.d.ts +9 -1
- package/dist/codebase-index/py-parser.d.ts.map +1 -1
- package/dist/codebase-index/refs-extractor.d.ts.map +1 -1
- package/dist/codebase-index/rs-parser.d.ts +1 -1
- package/dist/codebase-index/rs-parser.d.ts.map +1 -1
- package/dist/codebase-index/schema.d.ts +9 -2
- package/dist/codebase-index/schema.d.ts.map +1 -1
- package/dist/codebase-index/spawn-gate.d.ts +15 -0
- package/dist/codebase-index/spawn-gate.d.ts.map +1 -0
- package/dist/codebase-index/ts-parser.d.ts +2 -2
- package/dist/codebase-index/ts-parser.d.ts.map +1 -1
- package/dist/codebase-index/worker.js +993 -348
- package/dist/codebase-index/worker.js.map +4 -4
- package/dist/codebase-index/writer.d.ts +83 -4
- package/dist/codebase-index/writer.d.ts.map +1 -1
- package/dist/codebase-index/yaml-parser.d.ts +1 -1
- package/dist/design.d.ts +5 -2
- package/dist/design.d.ts.map +1 -1
- package/dist/design.js +36 -3
- package/dist/design.js.map +2 -2
- package/dist/diff.d.ts +1 -1
- package/dist/diff.d.ts.map +1 -1
- package/dist/diff.js +2 -2
- package/dist/diff.js.map +1 -1
- package/dist/document.d.ts +1 -1
- package/dist/document.d.ts.map +1 -1
- package/dist/document.js +1 -1
- package/dist/document.js.map +1 -1
- package/dist/e2e.d.ts +1 -1
- package/dist/e2e.d.ts.map +1 -1
- package/dist/e2e.js +1 -1
- package/dist/e2e.js.map +1 -1
- package/dist/edit.d.ts +1 -1
- package/dist/edit.d.ts.map +1 -1
- package/dist/edit.js +3 -3
- package/dist/edit.js.map +2 -2
- package/dist/exec.d.ts +1 -1
- package/dist/exec.d.ts.map +1 -1
- package/dist/exec.js +99 -44
- package/dist/exec.js.map +3 -3
- package/dist/fetch.d.ts +1 -1
- package/dist/fetch.d.ts.map +1 -1
- package/dist/fetch.js +4 -5
- package/dist/fetch.js.map +2 -2
- package/dist/format.d.ts +1 -1
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +81 -16
- package/dist/format.js.map +2 -2
- package/dist/git.d.ts +1 -1
- package/dist/git.d.ts.map +1 -1
- package/dist/git.js +3 -2
- package/dist/git.js.map +2 -2
- package/dist/glob.d.ts +1 -1
- package/dist/glob.d.ts.map +1 -1
- package/dist/glob.js +81 -31
- package/dist/glob.js.map +4 -4
- package/dist/grep.d.ts +1 -1
- package/dist/grep.d.ts.map +1 -1
- package/dist/grep.js +90 -22
- package/dist/grep.js.map +4 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1895 -771
- package/dist/index.js.map +4 -4
- package/dist/install.d.ts +1 -1
- package/dist/install.d.ts.map +1 -1
- package/dist/install.js +85 -17
- package/dist/install.js.map +2 -2
- package/dist/json.d.ts +1 -1
- package/dist/json.d.ts.map +1 -1
- package/dist/json.js +2 -2
- package/dist/json.js.map +2 -2
- package/dist/kanban-evidence-bridge.d.ts +21 -0
- package/dist/kanban-evidence-bridge.d.ts.map +1 -0
- package/dist/kanban.d.ts +20 -3
- package/dist/kanban.d.ts.map +1 -1
- package/dist/kanban.js +256 -32
- package/dist/kanban.js.map +3 -3
- package/dist/languages/execute-tool.d.ts +1 -1
- package/dist/languages/execute-tool.d.ts.map +1 -1
- package/dist/languages/execute.d.ts +1 -1
- package/dist/languages/execute.d.ts.map +1 -1
- package/dist/languages/index.d.ts +1 -1
- package/dist/languages/index.d.ts.map +1 -1
- package/dist/languages/index.js +99 -17
- package/dist/languages/index.js.map +2 -2
- package/dist/languages/package-tool.d.ts +3 -4
- package/dist/languages/package-tool.d.ts.map +1 -1
- package/dist/languages/plan.d.ts.map +1 -1
- package/dist/languages/profiles/additional.d.ts.map +1 -1
- package/dist/languages/profiles/primary.d.ts.map +1 -1
- package/dist/languages/tool.d.ts +1 -1
- package/dist/languages/tool.d.ts.map +1 -1
- package/dist/lint.d.ts +1 -1
- package/dist/lint.d.ts.map +1 -1
- package/dist/lint.js +81 -16
- package/dist/lint.js.map +2 -2
- package/dist/logs.d.ts +1 -1
- package/dist/logs.d.ts.map +1 -1
- package/dist/logs.js +2 -2
- package/dist/logs.js.map +1 -1
- package/dist/memory.d.ts +1 -1
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +1 -1
- package/dist/memory.js.map +1 -1
- package/dist/mode.d.ts +1 -1
- package/dist/mode.d.ts.map +1 -1
- package/dist/mode.js.map +1 -1
- package/dist/outdated.d.ts +1 -1
- package/dist/outdated.d.ts.map +1 -1
- package/dist/outdated.js +101 -19
- package/dist/outdated.js.map +2 -2
- package/dist/pack.d.ts +1 -1
- package/dist/pack.js +1650 -640
- package/dist/pack.js.map +4 -4
- package/dist/patch.d.ts +1 -1
- package/dist/patch.d.ts.map +1 -1
- package/dist/patch.js +2 -2
- package/dist/patch.js.map +1 -1
- package/dist/plan.d.ts +1 -1
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +7 -7
- package/dist/plan.js.map +2 -2
- package/dist/process-guardian.d.ts +7 -0
- package/dist/process-guardian.d.ts.map +1 -1
- package/dist/process-registry-persistent.d.ts +5 -0
- package/dist/process-registry-persistent.d.ts.map +1 -1
- package/dist/process-registry.d.ts +9 -1
- package/dist/process-registry.d.ts.map +1 -1
- package/dist/process-registry.js +18 -3
- package/dist/process-registry.js.map +2 -2
- package/dist/ps-slash.js +93 -38
- package/dist/ps-slash.js.map +2 -2
- package/dist/read.d.ts +1 -1
- package/dist/read.d.ts.map +1 -1
- package/dist/read.js +3 -2
- package/dist/read.js.map +2 -2
- package/dist/replace.d.ts +1 -1
- package/dist/replace.d.ts.map +1 -1
- package/dist/replace.js +4 -4
- package/dist/replace.js.map +2 -2
- package/dist/scaffold.d.ts +1 -1
- package/dist/scaffold.d.ts.map +1 -1
- package/dist/scaffold.js +2 -2
- package/dist/scaffold.js.map +1 -1
- package/dist/search.d.ts +1 -1
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +4 -4
- package/dist/search.js.map +2 -2
- package/dist/session-kanban.d.ts +4 -1
- package/dist/session-kanban.d.ts.map +1 -1
- package/dist/session-kanban.js +23 -15
- package/dist/session-kanban.js.map +2 -2
- package/dist/set-working-dir.d.ts +1 -1
- package/dist/set-working-dir.d.ts.map +1 -1
- package/dist/skill.d.ts +1 -1
- package/dist/skill.d.ts.map +1 -1
- package/dist/skill.js +2 -5
- package/dist/skill.js.map +2 -2
- package/dist/spawn-background.d.ts.map +1 -1
- package/dist/task.d.ts +3 -2
- package/dist/task.d.ts.map +1 -1
- package/dist/task.js +6 -8
- package/dist/task.js.map +2 -2
- package/dist/test.d.ts +1 -1
- package/dist/test.d.ts.map +1 -1
- package/dist/test.js +81 -16
- package/dist/test.js.map +2 -2
- package/dist/todo.d.ts +2 -1
- package/dist/todo.d.ts.map +1 -1
- package/dist/todo.js +4 -4
- package/dist/todo.js.map +2 -2
- package/dist/tool-help.d.ts +1 -1
- package/dist/tool-help.d.ts.map +1 -1
- package/dist/tool-help.js.map +1 -1
- package/dist/tool-search.d.ts +1 -1
- package/dist/tool-search.d.ts.map +1 -1
- package/dist/tool-search.js.map +1 -1
- package/dist/tool-tier.d.ts +16 -0
- package/dist/tool-tier.d.ts.map +1 -0
- package/dist/tool-tier.js +22402 -0
- package/dist/tool-tier.js.map +7 -0
- package/dist/tool-use.d.ts +1 -1
- package/dist/tool-use.d.ts.map +1 -1
- package/dist/tool-use.js.map +1 -1
- package/dist/tree.d.ts +1 -1
- package/dist/tree.d.ts.map +1 -1
- package/dist/tree.js +3 -15
- package/dist/tree.js.map +2 -2
- package/dist/typecheck.d.ts +1 -1
- package/dist/typecheck.d.ts.map +1 -1
- package/dist/typecheck.js +81 -16
- package/dist/typecheck.js.map +2 -2
- package/dist/win32.d.ts +10 -0
- package/dist/win32.d.ts.map +1 -0
- package/dist/win32.js +67 -0
- package/dist/win32.js.map +7 -0
- package/dist/write.d.ts +1 -1
- package/dist/write.d.ts.map +1 -1
- package/dist/write.js +3 -2
- package/dist/write.js.map +2 -2
- package/package.json +11 -3
package/dist/logs.d.ts
CHANGED
package/dist/logs.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logs.d.ts","sourceRoot":"","sources":["../src/logs.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"logs.d.ts","sourceRoot":"","sources":["../src/logs.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAInD,UAAU,SAAS;IACjB,OAAO,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1B,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,MAAM,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IAC7B,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC5B,KAAK,CAAC,EAAE,IAAI,GAAG,IAAI,GAAG,KAAK,GAAG,KAAK,GAAG,SAAS,CAAC;IAChD,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1B;AAED,UAAU,QAAQ;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B;AAED,UAAU,UAAU;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,QAAQ,EAAE,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,OAAO,CAAC;IACnB,WAAW,EAAE,OAAO,CAAC;CACtB;AAED,eAAO,MAAM,QAAQ,EAAE,IAAI,CAAC,SAAS,EAAE,UAAU,CA6EhD,CAAC"}
|
package/dist/logs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// src/logs.ts
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { buildChildEnv } from "@wrongstack/core";
|
|
3
|
+
import { buildChildEnv } from "@wrongstack/core/utils";
|
|
4
4
|
|
|
5
5
|
// src/_regex.ts
|
|
6
6
|
var MAX_PATTERN_LEN = 256;
|
|
@@ -46,7 +46,7 @@ var MAX_SUBJECT_LEN = 64 * 1024;
|
|
|
46
46
|
|
|
47
47
|
// src/_util.ts
|
|
48
48
|
import * as path from "node:path";
|
|
49
|
-
import * as Core from "@wrongstack/core";
|
|
49
|
+
import * as Core from "@wrongstack/core/utils";
|
|
50
50
|
function resolvePath(input, ctx) {
|
|
51
51
|
return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);
|
|
52
52
|
}
|
package/dist/logs.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/logs.ts", "../src/_regex.ts", "../src/_util.ts"],
|
|
4
|
-
"sourcesContent": ["import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core';\nimport type { Tool } from '@wrongstack/core';\nimport { compileUserRegex } from './_regex.js';\nimport { safeResolve } from './_util.js';\n\ninterface LogsInput {\n service?: string | undefined;\n path?: string | undefined;\n lines?: number | undefined;\n stream?: boolean | undefined;\n filter?: string | undefined;\n since?: '1h' | '6h' | '24h' | 'all' | undefined;\n cwd?: string | undefined;\n}\n\ninterface LogEntry {\n timestamp: string;\n level: string;\n message: string;\n source?: string | undefined;\n}\n\ninterface LogsOutput {\n source: string;\n entries: LogEntry[];\n total: number;\n truncated: boolean;\n stream_mode: boolean;\n}\n\nexport const logsTool: Tool<LogsInput, LogsOutput> = {\n name: 'logs',\n category: 'Logs',\n description:\n 'Read or stream logs from files, Docker containers, or systemd services. Useful for debugging running applications.',\n usageHint:\n 'DEBUGGING TOOL \u2014 USE CAREFULLY IN AUTONOMOUS MODE:\\n\\n' +\n '- Prefer `path` for local files or `service` for containers/systemd.\\n' +\n '- `stream: true` = live tail (can be expensive).\\n' +\n '- Always use `filter` (regex) when possible to reduce noise and token usage.\\n' +\n '- Long-running streams should be avoided unless the user explicitly wants live logs.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 30_000,\n capabilities: ['shell.restricted'],\n icon: 'logs',\n inputSchema: {\n type: 'object',\n properties: {\n service: {\n type: 'string',\n description: 'Service name for Docker or systemd journal',\n },\n path: {\n type: 'string',\n description: 'Path to log file (alternative to service)',\n },\n lines: {\n type: 'integer',\n description: 'Number of log lines to fetch (default: 100, 0 for all)',\n minimum: 0,\n maximum: 10000,\n },\n stream: {\n type: 'boolean',\n description: 'Stream logs continuously (like tail -f) (default: false)',\n },\n filter: {\n type: 'string',\n description: 'Regex pattern to filter log lines',\n },\n since: {\n type: 'string',\n enum: ['1h', '6h', '24h', 'all'],\n description: 'Only show logs since duration',\n },\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n },\n },\n async execute(input, ctx, opts) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const lines = input.lines ?? 100;\n let filterRe: RegExp | null = null;\n if (input.filter) {\n const compiled = compileUserRegex(input.filter, 'i');\n if (!compiled.ok) {\n throw new Error(`logs: ${compiled.reason}`);\n }\n filterRe = compiled.regex;\n }\n\n if (input.service) {\n return await dockerLogs(input.service, lines, filterRe, cwd, opts.signal);\n }\n\n if (input.path) {\n return await fileLogs(safeResolve(input.path, ctx), lines, filterRe, input.stream ?? false);\n }\n\n return {\n source: 'none',\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n },\n};\n\nasync function dockerLogs(\n service: string,\n lines: number,\n filterRe: RegExp | null,\n cwd: string,\n signal: AbortSignal,\n since?: string | undefined,\n): Promise<LogsOutput> {\n const args = ['logs'];\n if (lines > 0) args.push('--tail', String(lines));\n /* v8 ignore start -- execute() does not forward `since` to dockerLogs yet; this block is currently unreachable. */\n if (since) {\n const sinceMap: Record<string, string> = { '1h': '1h', '6h': '6h', '24h': '24h' };\n args.push('--since', sinceMap[since] ?? '1h');\n }\n /* v8 ignore stop */\n // Validate service name to prevent container name injection.\n // Docker container names are limited to [a-zA-Z0-9][a-zA-Z0-9._-]+.\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]+$/.test(service)) {\n return {\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n }\n args.push('--timestamps', service);\n\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n const MAX = 200_000;\n let settled = false;\n\n const empty = (): LogsOutput => ({\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n });\n const finish = (result: LogsOutput) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(result);\n };\n\n const child = spawn('docker', args, { cwd, signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n // `docker logs --tail N` reads recent lines and exits \u2014 fast when the\n // daemon is up. But if the daemon is unreachable (common on CI runners\n // with no running Docker), the CLI can hang on the socket connection and\n // emit neither `close` nor `error`. Kill it and return empty so the tool\n // (and its tests) never hang.\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish(empty());\n }, DOCKER_LOGS_TIMEOUT_MS);\n\n child.stdout?.on('data', (c) => {\n if (stdout.length < MAX) stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n if (stderr.length < MAX) stderr += c.toString();\n });\n // When the child is SIGTERM-killed on timeout (or aborted via `signal`),\n // its pipes can emit `error` (e.g. EPIPE on Windows). Without a listener\n // that surfaces as an unhandled error and can fail the host/test \u2014 swallow\n // it at debug level; `child.on('error')` and the timeout already drive the result.\n child.stdout?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stdout', error: e.message }));\n });\n child.stderr?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stderr', error: e.message }));\n });\n child.on('close', () => {\n const output = stdout + stderr;\n const entries = parseLogLines(output, filterRe);\n finish({\n source: `docker:${service}`,\n entries,\n total: entries.length,\n truncated: output.length >= MAX,\n stream_mode: false,\n });\n });\n child.on('error', () => finish(empty()));\n });\n}\n\n/**\n * Hard ceiling for a `docker logs` read. The daemon may be unreachable on CI\n * (no Docker running), where the CLI hangs on the socket without ever exiting.\n */\nconst DOCKER_LOGS_TIMEOUT_MS = 3_000;\n\n// Hard cap on tail-window size \u2014 `lines: 0` historically meant \"all\" and\n// happily buffered an entire multi-GB log into memory. Cap at 100k lines;\n// callers that need more should narrow with `filter`.\nconst MAX_TAIL_LINES = 100_000;\n\nasync function fileLogs(\n path: string,\n lines: number,\n filterRe: RegExp | null,\n stream: boolean,\n): Promise<LogsOutput> {\n const { createInterface } = await import('node:readline');\n const { createReadStream } = await import('node:fs');\n const entries: LogEntry[] = [];\n\n // Effective tail window: clamp to MAX_TAIL_LINES; treat 0 / negative as\n // \"max window\" rather than \"unlimited\" so a malicious /proc/kcore path\n // cannot OOM the worker.\n const effLines = lines > 0 ? Math.min(lines, MAX_TAIL_LINES) : MAX_TAIL_LINES;\n // Rolling window backed by a fixed-size circular buffer \u2014 at most\n // `effLines` strings live in memory regardless of file size.\n const window: string[] = new Array(effLines);\n let writeIdx = 0;\n let totalLines = 0;\n\n const rl = createInterface({\n input: createReadStream(path),\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n\n for await (const line of rl) {\n if (filterRe && !filterRe.test(line)) continue;\n window[writeIdx] = line;\n writeIdx = (writeIdx + 1) % effLines;\n totalLines++;\n }\n\n // Read the window back in arrival order.\n const ordered: string[] = [];\n const start = totalLines >= effLines ? writeIdx : 0;\n const count = Math.min(totalLines, effLines);\n for (let i = 0; i < count; i++) {\n const v = window[(start + i) % effLines];\n if (v !== undefined) ordered.push(v);\n }\n\n for (const line of ordered) {\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return {\n source: path,\n entries,\n total: entries.length,\n truncated: totalLines > effLines,\n stream_mode: stream,\n };\n}\n\nfunction parseLogLines(output: string, filterRe: RegExp | null): LogEntry[] {\n const lines = output.split('\\n').filter(Boolean);\n const entries: LogEntry[] = [];\n\n for (const line of lines) {\n if (filterRe && !filterRe.test(line)) continue;\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return entries;\n}\n\nfunction parseLine(line: string): LogEntry | null {\n const tsRe = /^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?)\\s+(?:\\[?(\\w+)\\]?)\\s*(.*)/;\n const match = tsRe.exec(line);\n\n if (match) {\n return {\n timestamp: match[1] ?? '',\n level: match[2]?.toLowerCase() ?? 'info',\n message: match[3] ?? '',\n };\n }\n\n const levelRe = /(ERROR|WARN|INFO|DEBUG|TRACE)\\s+(.*)/i;\n const levelMatch = levelRe.exec(line);\n\n if (levelMatch) {\n return {\n timestamp: '',\n level: levelMatch[1]?.toLowerCase() ?? 'info',\n message: levelMatch[2] ?? line,\n };\n }\n\n return {\n timestamp: '',\n level: 'info',\n message: line,\n };\n}\n", "/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match \u2014 a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length \u2014 practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc \u2014 nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind \u2014 (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking \u2014 rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core';\nimport type { Context } from '@wrongstack/core';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` \u2014 the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm \u2192 yarn \u2192 npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root\u2192out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink \u2014 macOS `/var`\u2192`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n\u2026[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]\u2026\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// \u2500\u2500\u2500 Command-output normalization (token-saving) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) \u2014 never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only \u2014 it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `\u2026 \u27E8repeated ${run}\u00D7\u27E9`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends \u2014 the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n\u2026[truncated ${total - kept} bytes]\u2026\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI \u2192 collapse\n * carriage-return progress \u2192 trim trailing whitespace \u2192 collapse identical\n * consecutive lines \u2192 squeeze blank-line runs \u2192 head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines \u2192 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n"],
|
|
4
|
+
"sourcesContent": ["import { spawn } from 'node:child_process';\nimport { buildChildEnv } from '@wrongstack/core/utils';\nimport type { Tool } from '@wrongstack/core/types';\nimport { compileUserRegex } from './_regex.js';\nimport { safeResolve } from './_util.js';\n\ninterface LogsInput {\n service?: string | undefined;\n path?: string | undefined;\n lines?: number | undefined;\n stream?: boolean | undefined;\n filter?: string | undefined;\n since?: '1h' | '6h' | '24h' | 'all' | undefined;\n cwd?: string | undefined;\n}\n\ninterface LogEntry {\n timestamp: string;\n level: string;\n message: string;\n source?: string | undefined;\n}\n\ninterface LogsOutput {\n source: string;\n entries: LogEntry[];\n total: number;\n truncated: boolean;\n stream_mode: boolean;\n}\n\nexport const logsTool: Tool<LogsInput, LogsOutput> = {\n name: 'logs',\n category: 'Logs',\n description:\n 'Read or stream logs from files, Docker containers, or systemd services. Useful for debugging running applications.',\n usageHint:\n 'DEBUGGING TOOL \u2014 USE CAREFULLY IN AUTONOMOUS MODE:\\n\\n' +\n '- Prefer `path` for local files or `service` for containers/systemd.\\n' +\n '- `stream: true` = live tail (can be expensive).\\n' +\n '- Always use `filter` (regex) when possible to reduce noise and token usage.\\n' +\n '- Long-running streams should be avoided unless the user explicitly wants live logs.',\n permission: 'confirm',\n mutating: false,\n timeoutMs: 30_000,\n capabilities: ['shell.restricted'],\n icon: 'logs',\n inputSchema: {\n type: 'object',\n properties: {\n service: {\n type: 'string',\n description: 'Service name for Docker or systemd journal',\n },\n path: {\n type: 'string',\n description: 'Path to log file (alternative to service)',\n },\n lines: {\n type: 'integer',\n description: 'Number of log lines to fetch (default: 100, 0 for all)',\n minimum: 0,\n maximum: 10000,\n },\n stream: {\n type: 'boolean',\n description: 'Stream logs continuously (like tail -f) (default: false)',\n },\n filter: {\n type: 'string',\n description: 'Regex pattern to filter log lines',\n },\n since: {\n type: 'string',\n enum: ['1h', '6h', '24h', 'all'],\n description: 'Only show logs since duration',\n },\n cwd: { type: 'string', description: 'Working directory (default: cwd)' },\n },\n },\n async execute(input, ctx, opts) {\n const cwd = input.cwd ? safeResolve(input.cwd, ctx) : ctx.cwd;\n const lines = input.lines ?? 100;\n let filterRe: RegExp | null = null;\n if (input.filter) {\n const compiled = compileUserRegex(input.filter, 'i');\n if (!compiled.ok) {\n throw new Error(`logs: ${compiled.reason}`);\n }\n filterRe = compiled.regex;\n }\n\n if (input.service) {\n return await dockerLogs(input.service, lines, filterRe, cwd, opts.signal);\n }\n\n if (input.path) {\n return await fileLogs(safeResolve(input.path, ctx), lines, filterRe, input.stream ?? false);\n }\n\n return {\n source: 'none',\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n },\n};\n\nasync function dockerLogs(\n service: string,\n lines: number,\n filterRe: RegExp | null,\n cwd: string,\n signal: AbortSignal,\n since?: string | undefined,\n): Promise<LogsOutput> {\n const args = ['logs'];\n if (lines > 0) args.push('--tail', String(lines));\n /* v8 ignore start -- execute() does not forward `since` to dockerLogs yet; this block is currently unreachable. */\n if (since) {\n const sinceMap: Record<string, string> = { '1h': '1h', '6h': '6h', '24h': '24h' };\n args.push('--since', sinceMap[since] ?? '1h');\n }\n /* v8 ignore stop */\n // Validate service name to prevent container name injection.\n // Docker container names are limited to [a-zA-Z0-9][a-zA-Z0-9._-]+.\n if (!/^[a-zA-Z0-9][a-zA-Z0-9._:-]+$/.test(service)) {\n return {\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n };\n }\n args.push('--timestamps', service);\n\n return new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n const MAX = 200_000;\n let settled = false;\n\n const empty = (): LogsOutput => ({\n source: `docker:${service}`,\n entries: [],\n total: 0,\n truncated: false,\n stream_mode: false,\n });\n const finish = (result: LogsOutput) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(result);\n };\n\n const child = spawn('docker', args, { cwd, signal, env: buildChildEnv(), stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });\n\n // `docker logs --tail N` reads recent lines and exits \u2014 fast when the\n // daemon is up. But if the daemon is unreachable (common on CI runners\n // with no running Docker), the CLI can hang on the socket connection and\n // emit neither `close` nor `error`. Kill it and return empty so the tool\n // (and its tests) never hang.\n const timer = setTimeout(() => {\n child.kill('SIGTERM');\n finish(empty());\n }, DOCKER_LOGS_TIMEOUT_MS);\n\n child.stdout?.on('data', (c) => {\n if (stdout.length < MAX) stdout += c.toString();\n });\n child.stderr?.on('data', (c) => {\n if (stderr.length < MAX) stderr += c.toString();\n });\n // When the child is SIGTERM-killed on timeout (or aborted via `signal`),\n // its pipes can emit `error` (e.g. EPIPE on Windows). Without a listener\n // that surfaces as an unhandled error and can fail the host/test \u2014 swallow\n // it at debug level; `child.on('error')` and the timeout already drive the result.\n child.stdout?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stdout', error: e.message }));\n });\n child.stderr?.on('error', (e) => {\n console.log(JSON.stringify({ level: 'debug', event: 'pipe_error', stream: 'stderr', error: e.message }));\n });\n child.on('close', () => {\n const output = stdout + stderr;\n const entries = parseLogLines(output, filterRe);\n finish({\n source: `docker:${service}`,\n entries,\n total: entries.length,\n truncated: output.length >= MAX,\n stream_mode: false,\n });\n });\n child.on('error', () => finish(empty()));\n });\n}\n\n/**\n * Hard ceiling for a `docker logs` read. The daemon may be unreachable on CI\n * (no Docker running), where the CLI hangs on the socket without ever exiting.\n */\nconst DOCKER_LOGS_TIMEOUT_MS = 3_000;\n\n// Hard cap on tail-window size \u2014 `lines: 0` historically meant \"all\" and\n// happily buffered an entire multi-GB log into memory. Cap at 100k lines;\n// callers that need more should narrow with `filter`.\nconst MAX_TAIL_LINES = 100_000;\n\nasync function fileLogs(\n path: string,\n lines: number,\n filterRe: RegExp | null,\n stream: boolean,\n): Promise<LogsOutput> {\n const { createInterface } = await import('node:readline');\n const { createReadStream } = await import('node:fs');\n const entries: LogEntry[] = [];\n\n // Effective tail window: clamp to MAX_TAIL_LINES; treat 0 / negative as\n // \"max window\" rather than \"unlimited\" so a malicious /proc/kcore path\n // cannot OOM the worker.\n const effLines = lines > 0 ? Math.min(lines, MAX_TAIL_LINES) : MAX_TAIL_LINES;\n // Rolling window backed by a fixed-size circular buffer \u2014 at most\n // `effLines` strings live in memory regardless of file size.\n const window: string[] = new Array(effLines);\n let writeIdx = 0;\n let totalLines = 0;\n\n const rl = createInterface({\n input: createReadStream(path),\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n\n for await (const line of rl) {\n if (filterRe && !filterRe.test(line)) continue;\n window[writeIdx] = line;\n writeIdx = (writeIdx + 1) % effLines;\n totalLines++;\n }\n\n // Read the window back in arrival order.\n const ordered: string[] = [];\n const start = totalLines >= effLines ? writeIdx : 0;\n const count = Math.min(totalLines, effLines);\n for (let i = 0; i < count; i++) {\n const v = window[(start + i) % effLines];\n if (v !== undefined) ordered.push(v);\n }\n\n for (const line of ordered) {\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return {\n source: path,\n entries,\n total: entries.length,\n truncated: totalLines > effLines,\n stream_mode: stream,\n };\n}\n\nfunction parseLogLines(output: string, filterRe: RegExp | null): LogEntry[] {\n const lines = output.split('\\n').filter(Boolean);\n const entries: LogEntry[] = [];\n\n for (const line of lines) {\n if (filterRe && !filterRe.test(line)) continue;\n const parsed = parseLine(line);\n if (parsed) entries.push(parsed);\n }\n\n return entries;\n}\n\nfunction parseLine(line: string): LogEntry | null {\n const tsRe = /^(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z?)\\s+(?:\\[?(\\w+)\\]?)\\s*(.*)/;\n const match = tsRe.exec(line);\n\n if (match) {\n return {\n timestamp: match[1] ?? '',\n level: match[2]?.toLowerCase() ?? 'info',\n message: match[3] ?? '',\n };\n }\n\n const levelRe = /(ERROR|WARN|INFO|DEBUG|TRACE)\\s+(.*)/i;\n const levelMatch = levelRe.exec(line);\n\n if (levelMatch) {\n return {\n timestamp: '',\n level: levelMatch[1]?.toLowerCase() ?? 'info',\n message: levelMatch[2] ?? line,\n };\n }\n\n return {\n timestamp: '',\n level: 'info',\n message: line,\n };\n}\n", "/**\n * Compile a user-supplied regex with conservative bounds against ReDoS.\n *\n * Node's regex engine (V8) is backtracking-based and cannot interrupt a\n * synchronous match \u2014 a pattern like `(a+)+$` against a sufficiently long\n * line will pin a worker for seconds. The executor's outer `timeoutMs` only\n * fires between async boundaries, so a long regex eval inside a sync loop\n * is uninterruptible.\n *\n * We can't fully prevent ReDoS without an alternative engine (re2-wasm), but\n * we can sharply limit the blast radius:\n *\n * 1. Cap pattern length \u2014 practically all legitimate user patterns are\n * under 256 characters. A 4 KB pattern is almost certainly malicious\n * or a copy-paste accident.\n * 2. Reject patterns containing the most obvious super-linear structures.\n * This is a coarse filter (false-positives are likely; we accept that\n * for hostile-input contexts).\n *\n * Callers should additionally bound the *subject* length (e.g. by capping\n * line size before matching).\n */\n\nconst MAX_PATTERN_LEN = 256;\n\n// Heuristics for catastrophic-backtracking constructs. Not exhaustive; bias\n// toward false-positives in tools that accept LLM-generated input.\nconst DANGEROUS_PATTERNS: ReadonlyArray<RegExp> = [\n // (a+)+, (.*)+, etc \u2014 nested quantifier on a group with internal quantifier\n /(\\([^)]*[+*][^)]*\\))[+*]/,\n /(\\(\\?:[^)]*[+*][^)]*\\))[+*]/,\n // Adjacent quantifiers: a++ a*+\n /[+*]{2,}/,\n // Quantifier on alternation with length 2+\n /\\([^|)]+\\|[^)]+\\)[+*][+*]/,\n // Greedy quantifier inside lookahead/lookbehind \u2014 (?!.*a+)\n /[([][^)\\]]*[+*][^)\\]]*[)\\]][^)]*\\?\\??/,\n];\n\nexport interface CompileResult {\n ok: true;\n regex: RegExp;\n}\n\nexport interface CompileFail {\n ok: false;\n reason: string;\n}\n\nexport function compileUserRegex(pattern: string, flags: string): CompileResult | CompileFail {\n if (typeof pattern !== 'string') {\n return { ok: false, reason: 'pattern must be a string' };\n }\n if (pattern.length === 0) {\n return { ok: false, reason: 'pattern is empty' };\n }\n if (pattern.length > MAX_PATTERN_LEN) {\n return { ok: false, reason: `pattern exceeds ${MAX_PATTERN_LEN} characters` };\n }\n for (const rx of DANGEROUS_PATTERNS) {\n if (rx.test(pattern)) {\n return {\n ok: false,\n reason:\n 'pattern looks vulnerable to catastrophic backtracking \u2014 rewrite without nested quantifiers',\n };\n }\n }\n try {\n return { ok: true, regex: new RegExp(pattern, flags) };\n } catch (err) {\n return {\n ok: false,\n reason: err instanceof Error ? err.message : 'invalid regex',\n };\n }\n}\n\n/**\n * Truncate a subject line to a safe length for synchronous regex eval.\n * The cap is conservative; tools that need exact-line matching against very\n * long lines should use ripgrep externally rather than the native walker.\n */\nexport const MAX_SUBJECT_LEN = 64 * 1024;\n\nexport function capSubject(line: string): string {\n return line.length > MAX_SUBJECT_LEN ? line.slice(0, MAX_SUBJECT_LEN) : line;\n}\n", "import { createHash } from 'node:crypto';\nimport * as fsp from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as Core from '@wrongstack/core/utils';\nimport type { Context } from '@wrongstack/core/agent';\n\n/**\n * sha-256 hex of a UTF-8 string. Used by the file tools to record a content\n * hash alongside the mtime in `ctx.recordRead` \u2014 the hash is the authoritative\n * staleness arbiter for `edit` (mtime has a 2 s tolerance window on Windows).\n */\nexport function sha256hex(content: string): string {\n return createHash('sha256').update(content, 'utf8').digest('hex');\n}\n/** Detected package manager for a project directory. */\nexport type PackageManager = 'pnpm' | 'yarn' | 'npm';\n\n/**\n * Detect the project's package manager by inspecting lockfiles in `cwd`.\n * Order: pnpm \u2192 yarn \u2192 npm (default). Missing or unreadable directories fall\n * back to `npm` rather than throwing, so a `safeResolve`-checked cwd that\n * happens to be empty never aborts the tool.\n */\nexport async function detectPackageManager(cwd: string): Promise<PackageManager> {\n const { stat } = await import('node:fs/promises');\n try {\n await stat(`${cwd}/pnpm-lock.yaml`);\n return 'pnpm';\n } catch {\n /* not pnpm */\n }\n try {\n await stat(`${cwd}/yarn.lock`);\n return 'yarn';\n } catch {\n /* not yarn */\n }\n return 'npm';\n}\n\nexport function resolvePath(input: string, ctx: Context): string {\n return path.isAbsolute(input) ? path.normalize(input) : path.resolve(ctx.workingDir ?? ctx.cwd, input);\n}\n\n/**\n * Roots every file tool may always reach, even in restricted mode: the\n * project root and the user-global `~/.wrongstack` directory (config, memory,\n * sessions, skills). `~/.wrongstack` honors the `WRONGSTACK_HOME` override.\n */\nfunction allowedRoots(ctx: Context): string[] {\n return [path.resolve(ctx.projectRoot), path.resolve(Core.wstackGlobalRoot())];\n}\n\n/** True if `target` is `root` itself or nested inside any of `roots`. */\nfunction isInsideAny(target: string, roots: string[]): boolean {\n return roots.some((root) => {\n const rel = path.relative(root, target);\n return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));\n });\n}\n\nexport function ensureInsideRoot(absPath: string, ctx: Context): string {\n const target = path.resolve(absPath);\n // Unrestricted filesystem access: skip the project-root containment check.\n if (ctx.allowOutsideProjectRoot) return target;\n if (isInsideAny(target, allowedRoots(ctx))) return target;\n throw new Error(`Path \"${absPath}\" is outside project root \"${path.resolve(ctx.projectRoot)}\"`);\n}\n\nexport function safeResolve(input: string, ctx: Context): string {\n return ensureInsideRoot(resolvePath(input, ctx), ctx);\n}\n\n/**\n * Defense against in-root\u2192out-of-root symlink escape (CWE-59). `safeResolve`\n * only does a syntactic `../` check, so a symlink that lives *inside* the\n * project root but points outside still passes it. This resolves the path\n * through `fs.realpath` and re-verifies containment against the realpath of\n * the project root (comparing like-for-like, since the root itself may be a\n * symlink \u2014 macOS `/var`\u2192`/private/var`, Windows 8.3 short names). For a path\n * that does not exist yet (e.g. a `write` to a new file) the nearest existing\n * ancestor directory is checked instead. Throws if the real target escapes.\n *\n * Mirrors the per-file guard already used in `replace.ts`/`grep.ts`; applied\n * to single-file `read`/`edit`/`write` it throws (rather than skips) because\n * the caller named exactly one file.\n */\nexport async function assertRealInsideRoot(absPath: string, ctx: Context): Promise<void> {\n // Unrestricted filesystem access: no symlink-escape check to perform.\n if (ctx.allowOutsideProjectRoot) return;\n // Compare like-for-like against the realpath of each always-allowed root\n // (project root + ~/.wrongstack), since a root may itself be a symlink.\n const realRoots = await Promise.all(\n allowedRoots(ctx).map((r) => fsp.realpath(r).catch(() => path.resolve(r))),\n );\n let probe = absPath;\n for (;;) {\n let real: string;\n try {\n real = await fsp.realpath(probe);\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT') {\n const parent = path.dirname(probe);\n if (parent === probe) return; // reached fs root without escaping\n probe = parent;\n continue;\n }\n throw err;\n }\n if (isInsideAny(real, realRoots)) return;\n throw new Error(\n `Path \"${absPath}\" resolves through a symlink outside project root \"${realRoots[0]}\"`,\n );\n }\n}\n\n/** `safeResolve` + symlink realpath containment check. Async. */\nexport async function safeResolveReal(input: string, ctx: Context): Promise<string> {\n const abs = safeResolve(input, ctx);\n await assertRealInsideRoot(abs, ctx);\n return abs;\n}\n\nexport function truncateMiddle(s: string, max: number): string {\n if (Buffer.byteLength(s, 'utf8') <= max) return s;\n const half = Math.floor(max / 2);\n return (\n s.slice(0, half) +\n `\\n\u2026[truncated ${Buffer.byteLength(s, 'utf8') - max} bytes from middle]\u2026\\n` +\n s.slice(-half)\n );\n}\n\nexport function isBinaryBuffer(buf: Buffer): boolean {\n const len = Math.min(buf.length, 8192);\n for (let i = 0; i < len; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n}\n\n// \u2500\u2500\u2500 Command-output normalization (token-saving) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Raw process output is full of tokens the model gains nothing from: ANSI\n// escapes, carriage-return progress spam, runs of identical warning lines, and\n// huge tails of build noise. These helpers strip that noise before the output\n// reaches the LLM. They are scoped to COMMAND tools (bash/git/exec and the\n// _spawn-stream consumers) \u2014 never applied to structured/code outputs.\n\n/** Unified byte cap for all command tool output fed to the model. */\nexport const COMMAND_OUTPUT_MAX_BYTES = 32_768;\n\n/** Runs of >= this many identical consecutive lines are collapsed. */\nconst REPEAT_RUN_THRESHOLD = 3;\n\n/**\n * Collapse carriage-return overwrites the way a terminal would: `\\r\\n` becomes\n * `\\n`, and a bare `\\r` (progress redraw) keeps only the text after the LAST\n * `\\r` on its physical line. Without this, a single progress bar that redraws\n * 200 times explodes into 200 lines.\n */\nexport function collapseCarriageReturns(text: string): string {\n const lf = text.replace(/\\r\\n/g, '\\n');\n if (!lf.includes('\\r')) return lf;\n return lf\n .split('\\n')\n .map((line) => (line.includes('\\r') ? line.slice(line.lastIndexOf('\\r') + 1) : line))\n .join('\\n');\n}\n\n/**\n * Collapse a run of `minRun`+ identical consecutive lines into the line once\n * plus a marker. Consecutive-only \u2014 it never reorders or dedups non-adjacent\n * lines, so diffs/source stay intact.\n */\nexport function collapseConsecutiveDuplicates(text: string, minRun = REPEAT_RUN_THRESHOLD): string {\n const lines = text.split('\\n');\n const out: string[] = [];\n let i = 0;\n while (i < lines.length) {\n let j = i + 1;\n while (j < lines.length && lines[j] === lines[i]) j++;\n const run = j - i;\n if (run >= minRun) {\n out.push(lines[i]!, `\u2026 \u27E8repeated ${run}\u00D7\u27E9`);\n } else {\n for (let k = i; k < j; k++) out.push(lines[k]!);\n }\n i = j;\n }\n return out.join('\\n');\n}\n\n/** Largest prefix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeHeadBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(0, mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(0, lo);\n}\n\n/** Largest suffix of `s` whose UTF-8 byte length is <= `maxBytes`. */\nfunction takeTailBytes(s: string, maxBytes: number): string {\n if (maxBytes <= 0) return '';\n /* v8 ignore next -- only caller (truncateHeadTail) passes a budget smaller than s; defensive. */\n if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;\n let lo = 0;\n let hi = s.length;\n while (lo < hi) {\n const mid = Math.ceil((lo + hi) / 2);\n if (Buffer.byteLength(s.slice(s.length - mid), 'utf8') <= maxBytes) lo = mid;\n else hi = mid - 1;\n }\n return s.slice(s.length - lo);\n}\n\n/**\n * Truncate to `maxBytes` keeping BOTH ends \u2014 the head (what ran / early context)\n * and the tail (errors and summaries usually land last), biased ~45/55 toward\n * the tail. The result never exceeds `maxBytes`.\n */\nexport function truncateHeadTail(s: string, maxBytes: number): string {\n const total = Buffer.byteLength(s, 'utf8');\n if (total <= maxBytes) return s;\n // Reserve a fixed allowance for the marker so the final string can't exceed\n // the cap even though the dropped-byte count's digit width varies.\n const MARKER_RESERVE = 64;\n const avail = Math.max(0, maxBytes - MARKER_RESERVE);\n const headBudget = Math.floor(avail * 0.45);\n const head = takeHeadBytes(s, headBudget);\n const tail = takeTailBytes(s, avail - Buffer.byteLength(head, 'utf8'));\n const kept = Buffer.byteLength(head, 'utf8') + Buffer.byteLength(tail, 'utf8');\n return `${head}\\n\u2026[truncated ${total - kept} bytes]\u2026\\n${tail}`;\n}\n\n/**\n * Full token-saving pipeline for command tool output: strip ANSI \u2192 collapse\n * carriage-return progress \u2192 trim trailing whitespace \u2192 collapse identical\n * consecutive lines \u2192 squeeze blank-line runs \u2192 head+tail truncate to the cap.\n */\nexport function normalizeCommandOutput(\n raw: string,\n opts: { maxBytes?: number | undefined } = {},\n): string {\n if (!raw) return raw;\n let text = Core.stripAnsi(raw);\n text = collapseCarriageReturns(text);\n text = text.replace(/[ \\t]+$/gm, ''); // trailing whitespace per line\n text = collapseConsecutiveDuplicates(text);\n text = text.replace(/\\n{3,}/g, '\\n\\n'); // >=2 blank lines \u2192 1\n return truncateHeadTail(text, opts.maxBytes ?? COMMAND_OUTPUT_MAX_BYTES);\n}\n"],
|
|
5
5
|
"mappings": ";AAAA,SAAS,aAAa;AACtB,SAAS,qBAAqB;;;ACsB9B,IAAM,kBAAkB;AAIxB,IAAM,qBAA4C;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C1E,QAAM,QAAQ,OAAO,MAAM,IAAI,EAAE,OAAO,OAAO;AAC/C,QAAM,UAAsB,CAAC;AAE7B,aAAW,QAAQ,OAAO;AACxB,QAAI,YAAY,CAAC,SAAS,KAAK,IAAI,EAAG;AACtC,UAAM,SAAS,UAAU,IAAI;AAC7B,QAAI,OAAQ,SAAQ,KAAK,MAAM;AAAA,EACjC;AAEA,SAAO;AACT;AAEA,SAAS,UAAU,MAA+B;AAChD,QAAM,OAAO;AACb,QAAM,QAAQ,KAAK,KAAK,IAAI;AAE5B,MAAI,OAAO;AACT,WAAO;AAAA,MACL,WAAW,MAAM,CAAC,KAAK;AAAA,MACvB,OAAO,MAAM,CAAC,GAAG,YAAY,KAAK;AAAA,MAClC,SAAS,MAAM,CAAC,KAAK;AAAA,IACvB;AAAA,EACF;AAEA,QAAM,UAAU;AAChB,QAAM,aAAa,QAAQ,KAAK,IAAI;AAEpC,MAAI,YAAY;AACd,WAAO;AAAA,MACL,WAAW;AAAA,MACX,OAAO,WAAW,CAAC,GAAG,YAAY,KAAK;AAAA,MACvC,SAAS,WAAW,CAAC,KAAK;AAAA,IAC5B;AAAA,EACF;AAEA,SAAO;AAAA,IACL,WAAW;AAAA,IACX,OAAO;AAAA,IACP,SAAS;AAAA,EACX;AACF;",
|
|
6
6
|
"names": ["resolve", "path"]
|
|
7
7
|
}
|
package/dist/memory.d.ts
CHANGED
package/dist/memory.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAG7E,UAAU,aAAa;IACrB,I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C,EAAE,MAAM,GAAG,SAAS,CAAC;KAC/B,CAAC,CAAC;CACJ;AAED,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAAC,iBAAiB,EAAE,kBAAkB,CAAC,CAwDjG;AAED,UAAU,kBAAkB;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IAChC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC5B;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,CA0DnG"}
|
package/dist/memory.js
CHANGED
package/dist/memory.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/memory.ts"],
|
|
4
|
-
"sourcesContent": ["import type { MemoryScope, MemoryStore, Tool } from '@wrongstack/core';\nimport { ToolValidationError, type MemoryEntry } from '@wrongstack/core';\n\ninterface RememberInput {\n text: string;\n scope?: MemoryScope | undefined;\n /** Memory type for categorization. */\n type?: 'fact' | 'decision' | 'convention' | 'preference' | 'reference' | 'anti_pattern' | undefined;\n /** Hashtag-style tags for grouping and search. */\n tags?: string[] | undefined;\n /** Priority level \u2014 critical entries always injected into context. */\n priority?: 'critical' | 'high' | 'medium' | 'low' | undefined;\n}\n\ninterface RememberOutput {\n ok: true;\n scope: MemoryScope;\n}\n\ninterface ForgetInput {\n query: string;\n scope?: MemoryScope | undefined;\n}\n\ninterface ForgetOutput {\n removed: number;\n scope: MemoryScope;\n}\n\nexport function rememberTool(memory: MemoryStore): Tool<RememberInput, RememberOutput> {\n return {\n name: 'remember',\n category: 'Session',\n description:\n 'Persist facts, conventions, decisions, and preferences into long-term memory. Memories survive restarts and are scored for relevance in future sessions.',\n usageHint:\n 'Persist facts, conventions, decisions, and preferences into long-term memory.\\n\\n' +\n 'WHEN TO USE:\\n' +\n '- Project conventions discovered during a task (build tool, lint rules, code style)\\n' +\n '- Architecture decisions made (chose X over Y, decided to use pattern Z)\\n' +\n '- User preferences expressed (prefers short names, always uses pnpm)\\n' +\n '- Anti-patterns identified (never do X, avoid pattern Y)\\n' +\n '- File/location references useful across sessions\\n\\n' +\n 'WHEN NOT TO USE:\\n' +\n '- Temporary task state or progress \u2192 use `todo`\\n' +\n '- One-off debugging notes\\n' +\n '- Information already obvious from the codebase\\n\\n' +\n 'Always include `type` and `priority`. Use 1-3 `tags` for grouping.\\n' +\n 'Better to remember a fact now than rediscover it next session.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 2_000,\n capabilities: ['memory.write'],\n icon: 'settings',\n inputSchema: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: 'The fact or note to remember. Keep it concise and factual.',\n },\n scope: {\n type: 'string',\n enum: ['project-agents', 'project-memory', 'user-memory'],\n description: 'Where to store it: project-memory (shared), user-memory (personal), or project-agents.',\n },\n type: {\n type: 'string',\n enum: ['fact', 'decision', 'convention', 'preference', 'reference', 'anti_pattern'],\n description: 'Category for filtering and relevance scoring.',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Hashtag-style tags for grouping and search.',\n },\n priority: {\n type: 'string',\n enum: ['critical', 'high', 'medium', 'low'],\n description: 'Priority level. Critical = always injected into context.',\n },\n },\n required: ['text'],\n },\n async execute(input) {\n if (!input?.text) {\n throw new ToolValidationError({\n message: 'remember: text is required',\n field: 'text',\n });\n }\n const scope = input.scope ?? 'project-memory';\n await memory.remember(input.text, scope, {\n type: input.type,\n tags: input.tags,\n priority: input.priority,\n });\n return { ok: true, scope };\n },\n };\n}\n\nexport function forgetTool(memory: MemoryStore): Tool<ForgetInput, ForgetOutput> {\n return {\n name: 'forget',\n category: 'Session',\n description: 'Remove memory entries that contain the given substring (case-insensitive). Use with caution.',\n usageHint:\n 'This permanently deletes matching memories in the chosen scope.\\n' +\n '- Provide a reasonably specific `query` to avoid deleting unrelated memories.\\n' +\n '- Always double-check before calling with broad queries.\\n' +\n '- Use `remember` + `forget` together to maintain clean long-term memory.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 2_000,\n capabilities: ['memory.delete'],\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string' },\n scope: { type: 'string', enum: ['project-agents', 'project-memory', 'user-memory'] },\n },\n required: ['query'],\n },\n async execute(input) {\n if (!input?.query) {\n throw new ToolValidationError({\n message: 'forget: query is required',\n field: 'query',\n });\n }\n const scope = input.scope ?? 'project-memory';\n const removed = await memory.forget(input.query, scope);\n return { removed, scope };\n },\n };\n}\n\n// \u2500\u2500 Enhanced memory query tools \u2014 use backend capabilities \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface SearchMemoryInput {\n query: string;\n scope?: MemoryScope | undefined;\n limit?: number | undefined;\n}\n\ninterface SearchMemoryOutput {\n results: Array<{\n text: string;\n ts: string;\n scope: MemoryScope;\n type?: string | undefined;\n tags?: string[] | undefined;\n priority?: string | undefined;\n }>;\n}\n\nexport function searchMemoryTool(memory: MemoryStore): Tool<SearchMemoryInput, SearchMemoryOutput> {\n return {\n name: 'search_memory',\n category: 'Session',\n description:\n 'Search memory entries by content. With the default backend this does substring matching; semantic/graph backends use embedding similarity or graph traversal.',\n usageHint:\n 'Search long-term memory for relevant facts, conventions, or decisions.\\n' +\n '- Returns results ordered by relevance (newest-first for default, similarity for semantic).\\n' +\n '- Use before starting a task to recall project conventions and past decisions.\\n' +\n '- `limit` caps results (default 5, max 20).',\n permission: 'auto',\n mutating: false,\n timeoutMs: 2_000,\n capabilities: ['memory.read'],\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search query \u2014 words or phrase to find in memory.',\n },\n scope: {\n type: 'string',\n enum: ['project-agents', 'project-memory', 'user-memory'],\n description: 'Which scope to search. Defaults to project-memory.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default 5, max 20).',\n },\n },\n required: ['query'],\n },\n async execute(input) {\n if (!input?.query) {\n throw new ToolValidationError({\n message: 'search_memory: query is required',\n field: 'query',\n });\n }\n const scope = input.scope ?? 'project-memory';\n const limit = Math.min(input.limit ?? 5, 20);\n const entries = await memory.search(input.query, scope, limit);\n return {\n results: entries.map((e: MemoryEntry) => ({\n text: e.text,\n ts: e.ts,\n scope: e.scope,\n type: e.type,\n tags: e.tags,\n priority: e.priority,\n })),\n };\n },\n };\n}\n\ninterface RelatedMemoryInput {\n text: string;\n scope?: MemoryScope | undefined;\n limit?: number | undefined;\n}\n\nexport function relatedMemoryTool(memory: MemoryStore): Tool<RelatedMemoryInput, SearchMemoryOutput> {\n return {\n name: 'find_related_memories',\n category: 'Session',\n description:\n 'Find memories related to the given text via graph traversal. Only available with graph backends; falls back to content search with file backends.',\n usageHint:\n 'Discover memories connected to a topic through co-occurrence or similarity edges.\\n' +\n '- Useful for exploring what else the project knows about a given concept.\\n' +\n '- Falls back to content search when no graph backend is configured.\\n' +\n '- `limit` caps results (default 5, max 20).',\n permission: 'auto',\n mutating: false,\n timeoutMs: 2_000,\n capabilities: ['memory.read'],\n inputSchema: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: 'Text to find related memories for.',\n },\n scope: {\n type: 'string',\n enum: ['project-agents', 'project-memory', 'user-memory'],\n description: 'Which scope to search. Defaults to project-memory.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default 5, max 20).',\n },\n },\n required: ['text'],\n },\n async execute(input) {\n if (!input?.text) {\n throw new ToolValidationError({\n message: 'find_related_memories: text is required',\n field: 'text',\n });\n }\n const scope = input.scope ?? 'project-memory';\n const limit = Math.min(input.limit ?? 5, 20);\n const entries = memory.findRelated\n ? await memory.findRelated(input.text, scope, limit)\n : await memory.search(input.text, scope, limit);\n return {\n results: entries.map((e: MemoryEntry) => ({\n text: e.text,\n ts: e.ts,\n scope: e.scope,\n type: e.type,\n tags: e.tags,\n priority: e.priority,\n })),\n };\n },\n };\n}\n"],
|
|
4
|
+
"sourcesContent": ["import type { MemoryScope, MemoryStore, Tool } from '@wrongstack/core/types';\nimport { ToolValidationError, type MemoryEntry } from '@wrongstack/core/types';\n\ninterface RememberInput {\n text: string;\n scope?: MemoryScope | undefined;\n /** Memory type for categorization. */\n type?: 'fact' | 'decision' | 'convention' | 'preference' | 'reference' | 'anti_pattern' | undefined;\n /** Hashtag-style tags for grouping and search. */\n tags?: string[] | undefined;\n /** Priority level \u2014 critical entries always injected into context. */\n priority?: 'critical' | 'high' | 'medium' | 'low' | undefined;\n}\n\ninterface RememberOutput {\n ok: true;\n scope: MemoryScope;\n}\n\ninterface ForgetInput {\n query: string;\n scope?: MemoryScope | undefined;\n}\n\ninterface ForgetOutput {\n removed: number;\n scope: MemoryScope;\n}\n\nexport function rememberTool(memory: MemoryStore): Tool<RememberInput, RememberOutput> {\n return {\n name: 'remember',\n category: 'Session',\n description:\n 'Persist facts, conventions, decisions, and preferences into long-term memory. Memories survive restarts and are scored for relevance in future sessions.',\n usageHint:\n 'Persist facts, conventions, decisions, and preferences into long-term memory.\\n\\n' +\n 'WHEN TO USE:\\n' +\n '- Project conventions discovered during a task (build tool, lint rules, code style)\\n' +\n '- Architecture decisions made (chose X over Y, decided to use pattern Z)\\n' +\n '- User preferences expressed (prefers short names, always uses pnpm)\\n' +\n '- Anti-patterns identified (never do X, avoid pattern Y)\\n' +\n '- File/location references useful across sessions\\n\\n' +\n 'WHEN NOT TO USE:\\n' +\n '- Temporary task state or progress \u2192 use `todo`\\n' +\n '- One-off debugging notes\\n' +\n '- Information already obvious from the codebase\\n\\n' +\n 'Always include `type` and `priority`. Use 1-3 `tags` for grouping.\\n' +\n 'Better to remember a fact now than rediscover it next session.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 2_000,\n capabilities: ['memory.write'],\n icon: 'settings',\n inputSchema: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: 'The fact or note to remember. Keep it concise and factual.',\n },\n scope: {\n type: 'string',\n enum: ['project-agents', 'project-memory', 'user-memory'],\n description: 'Where to store it: project-memory (shared), user-memory (personal), or project-agents.',\n },\n type: {\n type: 'string',\n enum: ['fact', 'decision', 'convention', 'preference', 'reference', 'anti_pattern'],\n description: 'Category for filtering and relevance scoring.',\n },\n tags: {\n type: 'array',\n items: { type: 'string' },\n description: 'Hashtag-style tags for grouping and search.',\n },\n priority: {\n type: 'string',\n enum: ['critical', 'high', 'medium', 'low'],\n description: 'Priority level. Critical = always injected into context.',\n },\n },\n required: ['text'],\n },\n async execute(input) {\n if (!input?.text) {\n throw new ToolValidationError({\n message: 'remember: text is required',\n field: 'text',\n });\n }\n const scope = input.scope ?? 'project-memory';\n await memory.remember(input.text, scope, {\n type: input.type,\n tags: input.tags,\n priority: input.priority,\n });\n return { ok: true, scope };\n },\n };\n}\n\nexport function forgetTool(memory: MemoryStore): Tool<ForgetInput, ForgetOutput> {\n return {\n name: 'forget',\n category: 'Session',\n description: 'Remove memory entries that contain the given substring (case-insensitive). Use with caution.',\n usageHint:\n 'This permanently deletes matching memories in the chosen scope.\\n' +\n '- Provide a reasonably specific `query` to avoid deleting unrelated memories.\\n' +\n '- Always double-check before calling with broad queries.\\n' +\n '- Use `remember` + `forget` together to maintain clean long-term memory.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 2_000,\n capabilities: ['memory.delete'],\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string' },\n scope: { type: 'string', enum: ['project-agents', 'project-memory', 'user-memory'] },\n },\n required: ['query'],\n },\n async execute(input) {\n if (!input?.query) {\n throw new ToolValidationError({\n message: 'forget: query is required',\n field: 'query',\n });\n }\n const scope = input.scope ?? 'project-memory';\n const removed = await memory.forget(input.query, scope);\n return { removed, scope };\n },\n };\n}\n\n// \u2500\u2500 Enhanced memory query tools \u2014 use backend capabilities \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface SearchMemoryInput {\n query: string;\n scope?: MemoryScope | undefined;\n limit?: number | undefined;\n}\n\ninterface SearchMemoryOutput {\n results: Array<{\n text: string;\n ts: string;\n scope: MemoryScope;\n type?: string | undefined;\n tags?: string[] | undefined;\n priority?: string | undefined;\n }>;\n}\n\nexport function searchMemoryTool(memory: MemoryStore): Tool<SearchMemoryInput, SearchMemoryOutput> {\n return {\n name: 'search_memory',\n category: 'Session',\n description:\n 'Search memory entries by content. With the default backend this does substring matching; semantic/graph backends use embedding similarity or graph traversal.',\n usageHint:\n 'Search long-term memory for relevant facts, conventions, or decisions.\\n' +\n '- Returns results ordered by relevance (newest-first for default, similarity for semantic).\\n' +\n '- Use before starting a task to recall project conventions and past decisions.\\n' +\n '- `limit` caps results (default 5, max 20).',\n permission: 'auto',\n mutating: false,\n timeoutMs: 2_000,\n capabilities: ['memory.read'],\n inputSchema: {\n type: 'object',\n properties: {\n query: {\n type: 'string',\n description: 'Search query \u2014 words or phrase to find in memory.',\n },\n scope: {\n type: 'string',\n enum: ['project-agents', 'project-memory', 'user-memory'],\n description: 'Which scope to search. Defaults to project-memory.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default 5, max 20).',\n },\n },\n required: ['query'],\n },\n async execute(input) {\n if (!input?.query) {\n throw new ToolValidationError({\n message: 'search_memory: query is required',\n field: 'query',\n });\n }\n const scope = input.scope ?? 'project-memory';\n const limit = Math.min(input.limit ?? 5, 20);\n const entries = await memory.search(input.query, scope, limit);\n return {\n results: entries.map((e: MemoryEntry) => ({\n text: e.text,\n ts: e.ts,\n scope: e.scope,\n type: e.type,\n tags: e.tags,\n priority: e.priority,\n })),\n };\n },\n };\n}\n\ninterface RelatedMemoryInput {\n text: string;\n scope?: MemoryScope | undefined;\n limit?: number | undefined;\n}\n\nexport function relatedMemoryTool(memory: MemoryStore): Tool<RelatedMemoryInput, SearchMemoryOutput> {\n return {\n name: 'find_related_memories',\n category: 'Session',\n description:\n 'Find memories related to the given text via graph traversal. Only available with graph backends; falls back to content search with file backends.',\n usageHint:\n 'Discover memories connected to a topic through co-occurrence or similarity edges.\\n' +\n '- Useful for exploring what else the project knows about a given concept.\\n' +\n '- Falls back to content search when no graph backend is configured.\\n' +\n '- `limit` caps results (default 5, max 20).',\n permission: 'auto',\n mutating: false,\n timeoutMs: 2_000,\n capabilities: ['memory.read'],\n inputSchema: {\n type: 'object',\n properties: {\n text: {\n type: 'string',\n description: 'Text to find related memories for.',\n },\n scope: {\n type: 'string',\n enum: ['project-agents', 'project-memory', 'user-memory'],\n description: 'Which scope to search. Defaults to project-memory.',\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return (default 5, max 20).',\n },\n },\n required: ['text'],\n },\n async execute(input) {\n if (!input?.text) {\n throw new ToolValidationError({\n message: 'find_related_memories: text is required',\n field: 'text',\n });\n }\n const scope = input.scope ?? 'project-memory';\n const limit = Math.min(input.limit ?? 5, 20);\n const entries = memory.findRelated\n ? await memory.findRelated(input.text, scope, limit)\n : await memory.search(input.text, scope, limit);\n return {\n results: entries.map((e: MemoryEntry) => ({\n text: e.text,\n ts: e.ts,\n scope: e.scope,\n type: e.type,\n tags: e.tags,\n priority: e.priority,\n })),\n };\n },\n };\n}\n"],
|
|
5
5
|
"mappings": ";AACA,SAAS,2BAA6C;AA4B/C,SAAS,aAAa,QAA0D;AACrF,SAAO;AAAA,IACL,MAAM;AAAA,IACN,UAAU;AAAA,IACV,aACE;AAAA,IACF,WACE;AAAA,IAaF,YAAY;AAAA,IACZ,UAAU;AAAA,IACV,WAAW;AAAA,IACX,cAAc,CAAC,cAAc;AAAA,IAC7B,MAAM;AAAA,IACN,aAAa;AAAA,MACX,MAAM;AAAA,MACN,YAAY;AAAA,QACV,MAAM;AAAA,UACJ,MAAM;AAAA,UACN,aAAa;AAAA,QACf;AAAA,QACA,OAAO;AAAA,UACL,MAAM;AAAA,UACN,MAAM,CAAC,kBAAkB,kBAAkB,aAAa;AAAA,UACxD,aAAa;AAAA,QACf;AAAA,QACA,MAAM;AAAA,UACJ,MAAM;AAAA,UACN,MAAM,CAAC,QAAQ,Y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1 @@
|
|
|
1
|
-
{"version":3,"file":"mode.d.ts","sourceRoot":"","sources":["../src/mode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"mode.d.ts","sourceRoot":"","sources":["../src/mode.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAE9D,UAAU,SAAS;IACjB,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,CAAC;IACzC,IAAI,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3B;AAED,KAAK,UAAU,GAAG,MAAM,GAAG,MAAM,GAAG,UAAU,GAAG,QAAQ,CAAC;AAE1D,UAAU,UAAU;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,KAAK,CAAC,EAAE;QACN,EAAE,EAAE,MAAM,GAAG,SAAS,CAAC;QACvB,IAAI,EAAE,MAAM,CAAC;QACb,WAAW,EAAE,MAAM,CAAC;QACpB,MAAM,EAAE,UAAU,CAAC;QACnB,IAAI,EAAE,MAAM,EAAE,CAAC;KAChB,EAAE,CAAC;IACJ,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;CACjB;AASD,wBAAgB,cAAc,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,UAAU,CAAC,CAiGhF"}
|
package/dist/mode.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/mode.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModeStore, Tool } from '@wrongstack/core';\n\ninterface ModeInput {\n action: 'get' | 'list' | 'set' | 'clear';\n mode?: string | undefined;\n}\n\ntype ModeFamily = 'lite' | 'deep' | 'balanced' | 'custom';\n\ninterface ModeOutput {\n action: string;\n currentMode?: string | undefined;\n modes?: {\n id: string | undefined;\n name: string;\n description: string;\n family: ModeFamily;\n tags: string[];\n }[];\n success: boolean;\n message: string;\n}\n\nfunction modeFamily(mode: { id?: string | undefined; tags?: string[] | undefined }): ModeFamily {\n if (mode.tags?.includes('lite')) return 'lite';\n if (mode.tags?.includes('deep')) return 'deep';\n if (mode.tags?.includes('balanced') || mode.id === 'default') return 'balanced';\n return 'custom';\n}\n\nexport function createModeTool(modeStore: ModeStore): Tool<ModeInput, ModeOutput> {\n return {\n name: 'mode',\n category: 'Session',\n description:\n 'Manage agent operating modes. Modes change the agent\\'s behavior, personality, and system prompt for different workflows (e.g. coding, security review, planning).',\n usageHint:\n 'POWERFUL BEHAVIOR CONTROL TOOL:\\n\\n' +\n '- Use `list` to see available modes.\\n' +\n '- Use `set <modeId>` to switch the agent into a specific role/mode.\\n' +\n '- Use `get` to check current mode.\\n' +\n '- Use `clear` to return to default behavior.\\n' +\n 'Switching modes is very effective for specialized tasks. The mode change affects how the agent reasons and which guidelines it follows.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 5_000,\n capabilities: ['session.mode'],\n icon: 'settings',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['get', 'list', 'set', 'clear'],\n description: 'The mode operation to perform.',\n },\n mode: {\n type: 'string',\n description: 'The mode identifier to activate (only required when action=set).',\n },\n },\n required: ['action'],\n },\n async execute(input) {\n switch (input.action) {\n case 'get': {\n const mode = await modeStore.getActiveMode();\n return {\n action: 'get',\n currentMode: mode?.id,\n success: true,\n message: mode\n ? `Current mode: ${mode.name} \u2014 ${mode.description}`\n : 'No mode set (using default)',\n };\n }\n case 'list': {\n const modes = await modeStore.listModes();\n const lines = modes\n .map((m) => ` ${m.id.padEnd(20)} [${modeFamily(m)}] ${m.name} \u2014 ${m.description}`)\n .join('\\n');\n return {\n action: 'list',\n modes: modes.map((m) => ({\n id: m.id,\n name: m.name,\n description: m.description,\n family: modeFamily(m),\n tags: m.tags ?? [],\n })),\n success: true,\n message: lines,\n };\n }\n case 'set': {\n if (!input.mode) {\n return { action: 'set', success: false, message: 'mode is required for action=set' };\n }\n const mode = await modeStore.getMode(input.mode);\n if (!mode) {\n return { action: 'set', success: false, message: `Mode \"${input.mode}\" not found` };\n }\n await modeStore.setActiveMode(input.mode);\n return {\n action: 'set',\n currentMode: mode.id,\n success: true,\n message: `Switched to mode: ${mode.name}\\n\\n${mode.description}`,\n };\n }\n case 'clear': {\n await modeStore.setActiveMode(null);\n return {\n action: 'clear',\n success: true,\n message: 'Mode cleared \u2014 using default mode',\n };\n }\n default:\n return {\n action: input.action,\n success: false,\n message: `Unknown action \"${input.action}\"`,\n };\n }\n },\n };\n}\n"],
|
|
4
|
+
"sourcesContent": ["import type { ModeStore, Tool } from '@wrongstack/core/types';\n\ninterface ModeInput {\n action: 'get' | 'list' | 'set' | 'clear';\n mode?: string | undefined;\n}\n\ntype ModeFamily = 'lite' | 'deep' | 'balanced' | 'custom';\n\ninterface ModeOutput {\n action: string;\n currentMode?: string | undefined;\n modes?: {\n id: string | undefined;\n name: string;\n description: string;\n family: ModeFamily;\n tags: string[];\n }[];\n success: boolean;\n message: string;\n}\n\nfunction modeFamily(mode: { id?: string | undefined; tags?: string[] | undefined }): ModeFamily {\n if (mode.tags?.includes('lite')) return 'lite';\n if (mode.tags?.includes('deep')) return 'deep';\n if (mode.tags?.includes('balanced') || mode.id === 'default') return 'balanced';\n return 'custom';\n}\n\nexport function createModeTool(modeStore: ModeStore): Tool<ModeInput, ModeOutput> {\n return {\n name: 'mode',\n category: 'Session',\n description:\n 'Manage agent operating modes. Modes change the agent\\'s behavior, personality, and system prompt for different workflows (e.g. coding, security review, planning).',\n usageHint:\n 'POWERFUL BEHAVIOR CONTROL TOOL:\\n\\n' +\n '- Use `list` to see available modes.\\n' +\n '- Use `set <modeId>` to switch the agent into a specific role/mode.\\n' +\n '- Use `get` to check current mode.\\n' +\n '- Use `clear` to return to default behavior.\\n' +\n 'Switching modes is very effective for specialized tasks. The mode change affects how the agent reasons and which guidelines it follows.',\n permission: 'confirm',\n mutating: true,\n timeoutMs: 5_000,\n capabilities: ['session.mode'],\n icon: 'settings',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['get', 'list', 'set', 'clear'],\n description: 'The mode operation to perform.',\n },\n mode: {\n type: 'string',\n description: 'The mode identifier to activate (only required when action=set).',\n },\n },\n required: ['action'],\n },\n async execute(input) {\n switch (input.action) {\n case 'get': {\n const mode = await modeStore.getActiveMode();\n return {\n action: 'get',\n currentMode: mode?.id,\n success: true,\n message: mode\n ? `Current mode: ${mode.name} \u2014 ${mode.description}`\n : 'No mode set (using default)',\n };\n }\n case 'list': {\n const modes = await modeStore.listModes();\n const lines = modes\n .map((m) => ` ${m.id.padEnd(20)} [${modeFamily(m)}] ${m.name} \u2014 ${m.description}`)\n .join('\\n');\n return {\n action: 'list',\n modes: modes.map((m) => ({\n id: m.id,\n name: m.name,\n description: m.description,\n family: modeFamily(m),\n tags: m.tags ?? [],\n })),\n success: true,\n message: lines,\n };\n }\n case 'set': {\n if (!input.mode) {\n return { action: 'set', success: false, message: 'mode is required for action=set' };\n }\n const mode = await modeStore.getMode(input.mode);\n if (!mode) {\n return { action: 'set', success: false, message: `Mode \"${input.mode}\" not found` };\n }\n await modeStore.setActiveMode(input.mode);\n return {\n action: 'set',\n currentMode: mode.id,\n success: true,\n message: `Switched to mode: ${mode.name}\\n\\n${mode.description}`,\n };\n }\n case 'clear': {\n await modeStore.setActiveMode(null);\n return {\n action: 'clear',\n success: true,\n message: 'Mode cleared \u2014 using default mode',\n };\n }\n default:\n return {\n action: input.action,\n success: false,\n message: `Unknown action \"${input.action}\"`,\n };\n }\n },\n };\n}\n"],
|
|
5
5
|
"mappings": ";AAuBA,SAAS,WAAW,MAA4E;AAC9F,MAAI,KAAK,MAAM,SAAS,MAAM,EAAG,QAAO;AACxC,MAAI,KAAK,MAAM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E;AAAA,cACf,QAAQ,WAAW,CAAC;AAAA,cACpB,MAAM,EAAE,QAAQ,CAAC;AAAA,YACnB,EAAE;AAAA,YACF,SAAS;AAAA,YACT,SAAS;AAAA,UACX;AAAA,QACF;AAAA,QACA,KAAK,OAAO;AACV,cAAI,CAAC,MAAM,MAAM;AACf,mBAAO,EAAE,QAAQ,OAAO,SAAS,OAAO,SAAS,kCAAkC;AAAA,UACrF;AACA,gBAAM,OAAO,MAAM,UAAU,QAAQ,MAAM,IAAI;AAC/C,cAAI,CAAC,MAAM;AACT,mBAAO,EAAE,QAAQ,OAAO,SAAS,OAAO,SAAS,SAAS,MAAM,IAAI,cAAc;AAAA,UACpF;AACA,gBAAM,UAAU,cAAc,MAAM,IAAI;AACxC,iBAAO;AAAA,YACL,QAAQ;AAAA,YACR,aAAa,KAAK;AAAA,YAClB,SAAS;AAAA,YACT,SAAS,qBAAqB,KAAK,IAAI;AAAA;AAAA,EAAO,KAAK,WAAW;AAAA,UAChE;AAAA,QACF;AAAA,QACA,KAAK,SAAS;AACZ,gBAAM,UAAU,cAAc,IAAI;AAClC,iBAAO;AAAA,YACL,QAAQ;AAAA,YACR,SAAS;AAAA,YACT,SAAS;AAAA,UACX;AAAA,QACF;AAAA,QACA;AACE,iBAAO;AAAA,YACL,QAAQ,MAAM;AAAA,YACd,SAAS;AAAA,YACT,SAAS,mBAAmB,MAAM,MAAM;AAAA,UAC1C;AAAA,MACJ;AAAA,IACF;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/outdated.d.ts
CHANGED
package/dist/outdated.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"outdated.d.ts","sourceRoot":"","sources":["../src/outdated.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"outdated.d.ts","sourceRoot":"","sources":["../src/outdated.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAKnD,UAAU,aAAa;IACrB,GAAG,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS,CAAC;IACtC,kBAAkB,CAAC,EAAE,OAAO,GAAG,SAAS,CAAC;IACzC,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;CACvC;AAED,UAAU,eAAe;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,UAAU,cAAc;IACtB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,eAAe,EAAE,CAAC;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;CACpB;AAED,eAAO,MAAM,YAAY,EAAE,IAAI,CAAC,aAAa,EAAE,cAAc,CAwH5D,CAAC"}
|
package/dist/outdated.js
CHANGED
|
@@ -16,7 +16,7 @@ var __export = (target, all) => {
|
|
|
16
16
|
// src/_util.ts
|
|
17
17
|
import * as fsp from "node:fs/promises";
|
|
18
18
|
import * as path from "node:path";
|
|
19
|
-
import * as Core from "@wrongstack/core";
|
|
19
|
+
import * as Core from "@wrongstack/core/utils";
|
|
20
20
|
async function detectPackageManager(cwd) {
|
|
21
21
|
const { stat: stat5 } = await import("node:fs/promises");
|
|
22
22
|
try {
|
|
@@ -292,7 +292,20 @@ function pythonProfile() {
|
|
|
292
292
|
]),
|
|
293
293
|
ignoredDirectories: IGNORES,
|
|
294
294
|
packageManagers: Object.freeze(["pip", "poetry", "pipenv", "uv"]),
|
|
295
|
-
executables: Object.freeze([
|
|
295
|
+
executables: Object.freeze([
|
|
296
|
+
"python",
|
|
297
|
+
"python3",
|
|
298
|
+
"pip",
|
|
299
|
+
"pip3",
|
|
300
|
+
"poetry",
|
|
301
|
+
"pipenv",
|
|
302
|
+
"uv",
|
|
303
|
+
"ruff",
|
|
304
|
+
"black",
|
|
305
|
+
"pytest",
|
|
306
|
+
"mypy",
|
|
307
|
+
"pyright"
|
|
308
|
+
]),
|
|
296
309
|
operations: Object.freeze({
|
|
297
310
|
syntax: async (ctx) => {
|
|
298
311
|
const py = ctx.options.target ? "python3" : "python3";
|
|
@@ -352,6 +365,14 @@ function pythonProfile() {
|
|
|
352
365
|
network: true
|
|
353
366
|
});
|
|
354
367
|
},
|
|
368
|
+
"package-remove": async (ctx) => {
|
|
369
|
+
const names = packageNames(ctx);
|
|
370
|
+
return names.length === 0 ? unavailable(ctx, "package-remove", "At least one package name is required.") : processPlan(ctx, "package-remove", "pip", ["uninstall", "--yes", ...names], {
|
|
371
|
+
parser: "package-text",
|
|
372
|
+
reason: "Remove validated Python packages.",
|
|
373
|
+
mutating: true
|
|
374
|
+
});
|
|
375
|
+
},
|
|
355
376
|
"package-audit": async (ctx) => processPlan(ctx, "package-audit", "pip", ["audit"], {
|
|
356
377
|
parser: "pip-audit",
|
|
357
378
|
reason: "Audit Python dependencies for vulnerabilities.",
|
|
@@ -963,6 +984,19 @@ function typescriptProfile() {
|
|
|
963
984
|
network: true
|
|
964
985
|
});
|
|
965
986
|
},
|
|
987
|
+
"package-remove": async (ctx) => {
|
|
988
|
+
const names = packageNames(ctx);
|
|
989
|
+
if (names.length === 0)
|
|
990
|
+
return unavailable(ctx, "package-remove", "At least one package name is required.");
|
|
991
|
+
const manager = ctx.workspace.packageManager ?? "npm";
|
|
992
|
+
const args = manager === "npm" ? ["uninstall", "--ignore-scripts", ...names] : ["remove", "--ignore-scripts", ...names];
|
|
993
|
+
return processPlan(ctx, "package-remove", manager, args, {
|
|
994
|
+
parser: "package-text",
|
|
995
|
+
reason: `Remove validated packages with ${manager} and lifecycle scripts disabled.`,
|
|
996
|
+
mutating: true,
|
|
997
|
+
network: true
|
|
998
|
+
});
|
|
999
|
+
},
|
|
966
1000
|
"package-audit": async (ctx) => {
|
|
967
1001
|
const manager = ctx.workspace.packageManager ?? "npm";
|
|
968
1002
|
return processPlan(ctx, "package-audit", manager, ["audit", "--json"], {
|
|
@@ -1415,13 +1449,28 @@ var init_primary = __esm({
|
|
|
1415
1449
|
}),
|
|
1416
1450
|
"package-add": async (ctx) => {
|
|
1417
1451
|
const names = packageNames(ctx);
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1452
|
+
const [spec] = names;
|
|
1453
|
+
const versionAt = spec?.lastIndexOf("@") ?? -1;
|
|
1454
|
+
const packageName = versionAt > 0 ? spec?.slice(0, versionAt) : spec;
|
|
1455
|
+
const packageVersion = versionAt > 0 ? spec?.slice(versionAt + 1) : void 0;
|
|
1456
|
+
return names.length === 0 ? unavailable(ctx, "package-add", "At least one NuGet package is required.") : names.length > 1 ? unavailable(ctx, "package-add", "NuGet package changes run one package at a time.") : processPlan(
|
|
1457
|
+
ctx,
|
|
1458
|
+
"package-add",
|
|
1459
|
+
"dotnet",
|
|
1460
|
+
[
|
|
1461
|
+
"add",
|
|
1462
|
+
"package",
|
|
1463
|
+
packageName ?? "",
|
|
1464
|
+
...packageVersion ? ["--version", packageVersion] : []
|
|
1465
|
+
],
|
|
1466
|
+
{
|
|
1467
|
+
parser: "dotnet-package",
|
|
1468
|
+
reason: "Add validated NuGet packages.",
|
|
1469
|
+
mutating: true,
|
|
1470
|
+
network: true,
|
|
1471
|
+
executesProjectCode: true
|
|
1472
|
+
}
|
|
1473
|
+
);
|
|
1425
1474
|
},
|
|
1426
1475
|
"package-remove": async (ctx) => {
|
|
1427
1476
|
const names = packageNames(ctx);
|
|
@@ -2329,7 +2378,7 @@ var init_diagnostics = __esm({
|
|
|
2329
2378
|
import { createWriteStream, mkdirSync } from "node:fs";
|
|
2330
2379
|
import * as fsp2 from "node:fs/promises";
|
|
2331
2380
|
import * as path5 from "node:path";
|
|
2332
|
-
import { wstackGlobalRoot as wstackGlobalRoot2 } from "@wrongstack/core";
|
|
2381
|
+
import { wstackGlobalRoot as wstackGlobalRoot2 } from "@wrongstack/core/utils";
|
|
2333
2382
|
function toolOutputDir() {
|
|
2334
2383
|
return path5.join(wstackGlobalRoot2(), "tool-output");
|
|
2335
2384
|
}
|
|
@@ -2637,7 +2686,7 @@ var init_circuit_breaker = __esm({
|
|
|
2637
2686
|
});
|
|
2638
2687
|
|
|
2639
2688
|
// src/_redact-command.ts
|
|
2640
|
-
import { expectDefined } from "@wrongstack/core";
|
|
2689
|
+
import { expectDefined } from "@wrongstack/core/utils";
|
|
2641
2690
|
function redactCommand(cmd) {
|
|
2642
2691
|
let result = cmd;
|
|
2643
2692
|
for (const pattern of SENSITIVE_FLAG_PATTERNS) {
|
|
@@ -2751,7 +2800,12 @@ var init_process_registry = __esm({
|
|
|
2751
2800
|
this.breaker.setEnabled(false);
|
|
2752
2801
|
}
|
|
2753
2802
|
register(info) {
|
|
2754
|
-
this.processes.set(info.pid, {
|
|
2803
|
+
this.processes.set(info.pid, {
|
|
2804
|
+
...info,
|
|
2805
|
+
killed: false,
|
|
2806
|
+
protected: info.protected ?? false,
|
|
2807
|
+
background: info.background ?? false
|
|
2808
|
+
});
|
|
2755
2809
|
}
|
|
2756
2810
|
_isSafeSignalPid(pid) {
|
|
2757
2811
|
return Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid;
|
|
@@ -2804,12 +2858,21 @@ var init_process_registry = __esm({
|
|
|
2804
2858
|
}
|
|
2805
2859
|
return n;
|
|
2806
2860
|
}
|
|
2861
|
+
/** Count of active jobs explicitly launched in background mode. */
|
|
2862
|
+
get activeBackgroundCount() {
|
|
2863
|
+
let n = 0;
|
|
2864
|
+
for (const p of this.processes.values()) {
|
|
2865
|
+
if (p.background && !p.killed) n++;
|
|
2866
|
+
}
|
|
2867
|
+
return n;
|
|
2868
|
+
}
|
|
2807
2869
|
/**
|
|
2808
2870
|
* Combined stats for observability — used by /ps and the TUI status bar.
|
|
2809
2871
|
*/
|
|
2810
2872
|
stats() {
|
|
2811
2873
|
return {
|
|
2812
2874
|
activeCount: this.activeCount,
|
|
2875
|
+
backgroundCount: this.activeBackgroundCount,
|
|
2813
2876
|
totalCount: this.processes.size,
|
|
2814
2877
|
breaker: this.breaker.snapshot()
|
|
2815
2878
|
};
|
|
@@ -2910,7 +2973,7 @@ var init_process_registry = __esm({
|
|
|
2910
2973
|
this.autoKillTimer = setTimeout(() => {
|
|
2911
2974
|
this.autoKillTimer = null;
|
|
2912
2975
|
this.autoKillArmedAt = null;
|
|
2913
|
-
this.killAll({ force: false });
|
|
2976
|
+
this.killAll({ force: false, preserveBackground: true });
|
|
2914
2977
|
this.breaker.forceReset();
|
|
2915
2978
|
this._emitBreakerCountdown();
|
|
2916
2979
|
}, this.autoKillResetMs);
|
|
@@ -2950,6 +3013,7 @@ var init_process_registry = __esm({
|
|
|
2950
3013
|
if (!p) return false;
|
|
2951
3014
|
if (p.killed) return true;
|
|
2952
3015
|
if (p.protected) return false;
|
|
3016
|
+
if (opts.preserveBackground && p.background) return false;
|
|
2953
3017
|
const { force = false, graceMs = DEFAULT_GRACE_MS } = opts;
|
|
2954
3018
|
const isWin2 = os.platform() === "win32";
|
|
2955
3019
|
if (isWin2) {
|
|
@@ -3052,11 +3116,11 @@ var init_process_registry = __esm({
|
|
|
3052
3116
|
// src/_spawn-stream.ts
|
|
3053
3117
|
import { spawn as spawn2 } from "node:child_process";
|
|
3054
3118
|
import {
|
|
3055
|
-
buildChildEnv,
|
|
3056
3119
|
emitProcessCompleted,
|
|
3057
3120
|
emitProcessOutput,
|
|
3058
3121
|
emitProcessStarted
|
|
3059
|
-
} from "@wrongstack/core";
|
|
3122
|
+
} from "@wrongstack/core/observability";
|
|
3123
|
+
import { buildChildEnv } from "@wrongstack/core/utils";
|
|
3060
3124
|
async function* spawnStream(opts) {
|
|
3061
3125
|
const max = opts.maxBytes ?? 2e5;
|
|
3062
3126
|
const flushAt = opts.flushBytes ?? 4 * 1024;
|
|
@@ -3450,7 +3514,7 @@ function validateOperationOptions(operation, packages) {
|
|
|
3450
3514
|
if (value.startsWith(".") || value.startsWith("/") || /^[A-Za-z]:/.test(value) || value.includes("://")) {
|
|
3451
3515
|
throw new Error(`Package paths and URLs are not supported: "${value}"`);
|
|
3452
3516
|
}
|
|
3453
|
-
if (!PACKAGE_NAME_RE.test(value) && !COMPOSER_PACKAGE_RE.test(value) && !GO_MODULE_RE.test(value)) {
|
|
3517
|
+
if (!PACKAGE_NAME_RE.test(value) && !COMPOSER_PACKAGE_RE.test(value) && !GO_MODULE_RE.test(value) && !PYTHON_PACKAGE_RE.test(value)) {
|
|
3454
3518
|
throw new Error(`Invalid package identifier "${value}"`);
|
|
3455
3519
|
}
|
|
3456
3520
|
}
|
|
@@ -3472,7 +3536,7 @@ function isInside2(candidate, root) {
|
|
|
3472
3536
|
const relative5 = path6.relative(path6.resolve(root), path6.resolve(candidate));
|
|
3473
3537
|
return relative5 === "" || !relative5.startsWith("..") && !path6.isAbsolute(relative5);
|
|
3474
3538
|
}
|
|
3475
|
-
var MAX_ARGUMENTS, MAX_ARGUMENT_LENGTH, PACKAGE_NAME_RE, COMPOSER_PACKAGE_RE, GO_MODULE_RE;
|
|
3539
|
+
var MAX_ARGUMENTS, MAX_ARGUMENT_LENGTH, PACKAGE_NAME_RE, COMPOSER_PACKAGE_RE, GO_MODULE_RE, PYTHON_PACKAGE_RE;
|
|
3476
3540
|
var init_plan = __esm({
|
|
3477
3541
|
"src/languages/plan.ts"() {
|
|
3478
3542
|
"use strict";
|
|
@@ -3483,6 +3547,7 @@ var init_plan = __esm({
|
|
|
3483
3547
|
PACKAGE_NAME_RE = /^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+(?:@[a-z0-9*+._~^<>=|-]+)?$/i;
|
|
3484
3548
|
COMPOSER_PACKAGE_RE = /^[a-z0-9_.-]+\/[a-z0-9_.-]+(?::[a-z0-9*+._~^<>=|-]+)?$/i;
|
|
3485
3549
|
GO_MODULE_RE = /^(?:[a-z0-9.-]+\.)+[a-z0-9.-]+\/[a-z0-9._~+/@-]+$/i;
|
|
3550
|
+
PYTHON_PACKAGE_RE = /^[a-z0-9._-]+(?:\[[a-z0-9._,-]+\])?==[a-z0-9*+._!~-]+$/i;
|
|
3486
3551
|
}
|
|
3487
3552
|
});
|
|
3488
3553
|
|
|
@@ -4384,7 +4449,6 @@ var init_package_tool = __esm({
|
|
|
4384
4449
|
const operationOptions2 = {
|
|
4385
4450
|
...input.names ? { packages: input.names } : {},
|
|
4386
4451
|
...input.scope ? { packageScope: input.scope } : {},
|
|
4387
|
-
...input.dryRun !== void 0 ? { allowScripts: input.dryRun } : { allowScripts: false },
|
|
4388
4452
|
...input.allowScripts !== void 0 ? { allowScripts: input.allowScripts } : {}
|
|
4389
4453
|
};
|
|
4390
4454
|
const planResult = await planLanguageOperation({
|
|
@@ -4413,6 +4477,24 @@ var init_package_tool = __esm({
|
|
|
4413
4477
|
};
|
|
4414
4478
|
return;
|
|
4415
4479
|
}
|
|
4480
|
+
if (input.dryRun) {
|
|
4481
|
+
yield {
|
|
4482
|
+
type: "final",
|
|
4483
|
+
output: {
|
|
4484
|
+
status: "passed",
|
|
4485
|
+
language: planResult.workspace.language,
|
|
4486
|
+
workspace: planResult.workspace.root,
|
|
4487
|
+
operation: planResult.plan.operation,
|
|
4488
|
+
mutations: [],
|
|
4489
|
+
vulnerabilities: [],
|
|
4490
|
+
outdated: [],
|
|
4491
|
+
manifestsChanged: [],
|
|
4492
|
+
lockfilesChanged: [],
|
|
4493
|
+
output: `Dry run: ${planResult.plan.command ?? "internal"} ${planResult.plan.args.join(" ")}`.trim()
|
|
4494
|
+
}
|
|
4495
|
+
};
|
|
4496
|
+
return;
|
|
4497
|
+
}
|
|
4416
4498
|
const runner = executePackagePlan({
|
|
4417
4499
|
projectRoot: ctx.projectRoot,
|
|
4418
4500
|
workspace: planResult.workspace,
|
|
@@ -4781,7 +4863,7 @@ var init_legacy_bridge = __esm({
|
|
|
4781
4863
|
init_util();
|
|
4782
4864
|
init_win32_resolve();
|
|
4783
4865
|
import { spawn as spawn3 } from "node:child_process";
|
|
4784
|
-
import { buildChildEnv as buildChildEnv2 } from "@wrongstack/core";
|
|
4866
|
+
import { buildChildEnv as buildChildEnv2 } from "@wrongstack/core/utils";
|
|
4785
4867
|
var outdatedTool = {
|
|
4786
4868
|
name: "outdated",
|
|
4787
4869
|
category: "Package Management",
|