dsh-project-flow-explainer 0.0.0-stage → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +201 -2
- package/client.js +273 -0
- package/cordis.patch.yml +26 -0
- package/index.js +546 -0
- package/lib/command.js +160 -0
- package/lib/core-runner.js +170 -0
- package/lib/paths.js +235 -0
- package/lib/tools.js +1022 -0
- package/lib/validate.js +158 -0
- package/package.json +71 -4
package/lib/command.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slash command `/project-flow-explainer` — the human entry point.
|
|
3
|
+
*
|
|
4
|
+
* Why a command and not only a tool: a tool is chosen by the model, so a person
|
|
5
|
+
* who already knows what they want has to explain it and hope the model agrees.
|
|
6
|
+
* A command is chosen by the person, runs the same core, and returns its output
|
|
7
|
+
* straight to the UI without entering model history
|
|
8
|
+
* (`@deepseek-ai/dsh-commands`: command output is rendered by the adapter and
|
|
9
|
+
* does not affect the model's context or cache).
|
|
10
|
+
*
|
|
11
|
+
* Contract kept identical to the tool path: same repository policy, same core
|
|
12
|
+
* invocation, same artifact location, no network, no repository code execution.
|
|
13
|
+
*/
|
|
14
|
+
import path from 'node:path'
|
|
15
|
+
import { runCore } from './core-runner.js'
|
|
16
|
+
import {
|
|
17
|
+
InputError, resolveArtifactRoot, resolveRepository,
|
|
18
|
+
} from './paths.js'
|
|
19
|
+
|
|
20
|
+
export const COMMAND_NAME = 'project-flow-explainer'
|
|
21
|
+
|
|
22
|
+
const USAGE = 'Cách dùng: /project-flow-explainer <mô tả luồng>'
|
|
23
|
+
+ '\nVí dụ: /project-flow-explainer từ lúc bấm xuất báo cáo đến khi nhận được file'
|
|
24
|
+
+ '\nThiếu gì: cần repository hiện tại nằm trong allowedRoots của plugin.'
|
|
25
|
+
|
|
26
|
+
/** Split `<request>` from optional `--repo <path>` so a person can target another repo. */
|
|
27
|
+
function parseInput(rawInput) {
|
|
28
|
+
let text = String(rawInput ?? '').trim()
|
|
29
|
+
let repo
|
|
30
|
+
const match = text.match(/(?:^|\s)--repo(?:=|\s+)(\S+)/)
|
|
31
|
+
if (match !== null) {
|
|
32
|
+
repo = match[1]
|
|
33
|
+
text = (text.slice(0, match.index) + text.slice(match.index + match[0].length)).trim()
|
|
34
|
+
}
|
|
35
|
+
return { request: text, repository: repo }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Resolve the repository for a command invocation.
|
|
40
|
+
*
|
|
41
|
+
* A slash command runs outside a tool execution, so there is no `exec.cwd`. The
|
|
42
|
+
* session's working directory is the closest honest answer; `process.cwd()` is
|
|
43
|
+
* only a fallback and is never treated as a repository without passing the same
|
|
44
|
+
* allowed-roots policy the tools use.
|
|
45
|
+
* @param {object} ctx - plugin context (for the working-directory service).
|
|
46
|
+
* @param {object|undefined} agent - invoking agent.
|
|
47
|
+
* @param {string|undefined} explicit - `--repo` value when the user supplied one.
|
|
48
|
+
* @param {AbortSignal|undefined} signal - cancellation from the UI request.
|
|
49
|
+
* @param {object} settings - live plugin settings, read at call time.
|
|
50
|
+
*/
|
|
51
|
+
async function repositoryFor(ctx, agent, explicit, signal, settings) {
|
|
52
|
+
const allowedRoots = settings.allowedRoots
|
|
53
|
+
if (typeof explicit === 'string' && explicit !== '') {
|
|
54
|
+
return resolveRepository(explicit, { allowedRoots })
|
|
55
|
+
}
|
|
56
|
+
let candidate
|
|
57
|
+
try {
|
|
58
|
+
if (agent !== undefined && typeof ctx.workingDirectory?.ensure === 'function') {
|
|
59
|
+
candidate = await ctx.workingDirectory.ensure(agent, signal)
|
|
60
|
+
}
|
|
61
|
+
} catch {
|
|
62
|
+
candidate = undefined
|
|
63
|
+
}
|
|
64
|
+
if (typeof candidate !== 'string' || candidate === '') candidate = process.cwd()
|
|
65
|
+
return resolveRepository(candidate, { allowedRoots })
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Build the command definition for one mount.
|
|
70
|
+
* @param {object} options - plugin settings plus the resolved core.
|
|
71
|
+
* @returns {object} a definition accepted by `ctx.commands.register()`.
|
|
72
|
+
*/
|
|
73
|
+
export function flowCommand({ ctx, settings, core }) {
|
|
74
|
+
return {
|
|
75
|
+
name: COMMAND_NAME,
|
|
76
|
+
description: 'Dựng sơ đồ luồng từ repository hiện tại: flow.html mở offline + flow.json + overview.md',
|
|
77
|
+
input: {
|
|
78
|
+
hint: '<mô tả luồng> [--repo <đường dẫn tuyệt đối>]',
|
|
79
|
+
attachments: false,
|
|
80
|
+
},
|
|
81
|
+
// The request text is what the person typed; keeping it in the session log
|
|
82
|
+
// is the point — it is the record of what they asked for.
|
|
83
|
+
recordInput: true,
|
|
84
|
+
handler: async (invocation) => {
|
|
85
|
+
const { agent, rawInput, signal } = invocation
|
|
86
|
+
const { request, repository } = parseInput(rawInput)
|
|
87
|
+
if (request === '') return { kind: 'error', text: 'Thiếu mô tả luồng.\n' + USAGE }
|
|
88
|
+
let root
|
|
89
|
+
let outputDirectory
|
|
90
|
+
try {
|
|
91
|
+
root = (await repositoryFor(ctx, agent, repository, signal, settings)).root
|
|
92
|
+
outputDirectory = resolveArtifactRoot(root)
|
|
93
|
+
} catch (error) {
|
|
94
|
+
const code = error?.code ?? 'command_failed'
|
|
95
|
+
const hint = error?.hint ? '\n' + error.hint : ''
|
|
96
|
+
return { kind: 'error', text: `${code}: ${error?.message ?? String(error)}${hint}` }
|
|
97
|
+
}
|
|
98
|
+
if (signal?.aborted) return { kind: 'error', text: 'ABORTED: lệnh đã bị huỷ.' }
|
|
99
|
+
let run
|
|
100
|
+
try {
|
|
101
|
+
run = await runCore({
|
|
102
|
+
pythonPath: settings.pythonPath,
|
|
103
|
+
coreRoot: core.root,
|
|
104
|
+
script: core.script,
|
|
105
|
+
repository: root,
|
|
106
|
+
request,
|
|
107
|
+
outputDirectory,
|
|
108
|
+
signal,
|
|
109
|
+
timeoutMs: settings.timeoutMs,
|
|
110
|
+
maxOutputBytes: settings.maxOutputBytes,
|
|
111
|
+
})
|
|
112
|
+
} catch (error) {
|
|
113
|
+
return { kind: 'error', text: `core_spawn_failed: ${error?.message ?? String(error)}` }
|
|
114
|
+
}
|
|
115
|
+
if (run.aborted) return { kind: 'error', text: 'ABORTED: core đã bị dừng theo lệnh huỷ.' }
|
|
116
|
+
if (run.timedOut) {
|
|
117
|
+
return {
|
|
118
|
+
kind: 'error',
|
|
119
|
+
text: `core_timeout: core vượt quá ${settings.timeoutMs} ms.\n`
|
|
120
|
+
+ 'Thu hẹp mô tả luồng, hoặc tăng config.timeoutMs.',
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const line = run.stdout.trim().split('\n').filter(Boolean).pop() ?? ''
|
|
124
|
+
let payload
|
|
125
|
+
try {
|
|
126
|
+
payload = JSON.parse(line)
|
|
127
|
+
} catch {
|
|
128
|
+
const tail = run.stderr.trim().split('\n').slice(-2).join(' ').slice(0, 300)
|
|
129
|
+
return { kind: 'error', text: `core_failed: core không trả JSON hợp lệ. ${tail}` }
|
|
130
|
+
}
|
|
131
|
+
if (payload.status === 'error') {
|
|
132
|
+
return {
|
|
133
|
+
kind: 'error',
|
|
134
|
+
text: `${payload.code}: ${payload.message}${payload.hint ? '\n' + payload.hint : ''}`,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const relative = (value) => {
|
|
138
|
+
if (typeof value !== 'string' || value === '') return ''
|
|
139
|
+
return path.relative(root, value).split(path.sep).join('/')
|
|
140
|
+
}
|
|
141
|
+
const counts = payload.counts ?? {}
|
|
142
|
+
const lines = [
|
|
143
|
+
`Sơ đồ: ${payload.flow_id}`,
|
|
144
|
+
`${counts.verified ?? 0} bước đã kiểm chứng · ${counts.partial ?? 0} một phần · `
|
|
145
|
+
+ `${counts.inferred ?? 0} suy luận`,
|
|
146
|
+
`Mở file: ${relative(payload.paths?.flow_html)}`,
|
|
147
|
+
`Dữ liệu: ${relative(payload.paths?.flow_json)} · Giải thích: ${relative(payload.paths?.overview)}`,
|
|
148
|
+
]
|
|
149
|
+
const related = Array.isArray(payload.related) ? payload.related.length : 0
|
|
150
|
+
if (related > 0) lines.push(`Ngoài luồng: ${related} file chỉ khớp từ khoá`)
|
|
151
|
+
const firstLimit = Array.isArray(payload.limits) ? payload.limits[0] : undefined
|
|
152
|
+
if (firstLimit !== undefined) lines.push(`Giới hạn: ${firstLimit}`)
|
|
153
|
+
if (Array.isArray(payload.warnings) && payload.warnings.length > 0) {
|
|
154
|
+
lines.push(`Cảnh báo: ${payload.warnings[0]}`)
|
|
155
|
+
}
|
|
156
|
+
lines.push('Phân tích tĩnh: chưa chạy code của repository, không dùng network.')
|
|
157
|
+
return { kind: 'success', text: lines.join('\n') }
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Invoke the Python core as a child process.
|
|
3
|
+
*
|
|
4
|
+
* Contract: arguments are always passed as an array (never a shell string),
|
|
5
|
+
* stdout carries one JSON object, stderr carries human diagnostics. The child
|
|
6
|
+
* is killed on abort or timeout; it inherits a minimal environment.
|
|
7
|
+
*
|
|
8
|
+
* Two entry points share one implementation:
|
|
9
|
+
* runCli - arbitrary subcommand args (index/search/context-pack/impact/...)
|
|
10
|
+
* runCore - the original flow call, kept for backward compatibility
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process'
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_MAX_OUTPUT = 1024 * 1024
|
|
15
|
+
|
|
16
|
+
class Capture {
|
|
17
|
+
constructor(limit) {
|
|
18
|
+
this.limit = limit
|
|
19
|
+
this.chunks = []
|
|
20
|
+
this.size = 0
|
|
21
|
+
this.truncated = false
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
push(chunk) {
|
|
25
|
+
if (this.size >= this.limit) {
|
|
26
|
+
this.truncated = true
|
|
27
|
+
return
|
|
28
|
+
}
|
|
29
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk))
|
|
30
|
+
const room = this.limit - this.size
|
|
31
|
+
const slice = buffer.length > room ? buffer.subarray(0, room) : buffer
|
|
32
|
+
if (slice.length < buffer.length) this.truncated = true
|
|
33
|
+
this.chunks.push(slice)
|
|
34
|
+
this.size += slice.length
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
text() {
|
|
38
|
+
return Buffer.concat(this.chunks).toString('utf8')
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Run one CLI subcommand.
|
|
44
|
+
* @param {object} options
|
|
45
|
+
* @param {string} options.pythonPath - interpreter.
|
|
46
|
+
* @param {string} options.coreRoot - directory holding the core (cwd).
|
|
47
|
+
* @param {string} options.script - absolute path of tools/pfe_cli.py.
|
|
48
|
+
* @param {string[]} options.args - argv tail (subcommand + flags).
|
|
49
|
+
* @param {AbortSignal} [options.signal] - caller cancellation.
|
|
50
|
+
* @param {number} [options.timeoutMs] - cooperative budget.
|
|
51
|
+
* @param {number} [options.maxOutputBytes] - capture cap per stream.
|
|
52
|
+
*/
|
|
53
|
+
export function runCli(options) {
|
|
54
|
+
const {
|
|
55
|
+
pythonPath, coreRoot, script, args, signal, timeoutMs, maxOutputBytes,
|
|
56
|
+
} = options
|
|
57
|
+
const argv = [script, ...args]
|
|
58
|
+
const limit = Number.isFinite(maxOutputBytes) && maxOutputBytes > 0
|
|
59
|
+
? Math.floor(maxOutputBytes)
|
|
60
|
+
: DEFAULT_MAX_OUTPUT
|
|
61
|
+
const stdout = new Capture(limit)
|
|
62
|
+
const stderr = new Capture(limit)
|
|
63
|
+
|
|
64
|
+
return new Promise((resolve) => {
|
|
65
|
+
let aborted = false
|
|
66
|
+
let timedOut = false
|
|
67
|
+
let settled = false
|
|
68
|
+
|
|
69
|
+
const child = spawn(pythonPath, argv, {
|
|
70
|
+
cwd: coreRoot,
|
|
71
|
+
shell: false,
|
|
72
|
+
windowsHide: true,
|
|
73
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
74
|
+
env: {
|
|
75
|
+
PATH: process.env.PATH ?? '/usr/local/bin:/usr/bin:/bin',
|
|
76
|
+
HOME: process.env.HOME ?? '',
|
|
77
|
+
LANG: process.env.LANG ?? 'C.UTF-8',
|
|
78
|
+
PYTHONIOENCODING: 'utf-8',
|
|
79
|
+
PYTHONDONTWRITEBYTECODE: '1',
|
|
80
|
+
},
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
const finish = (code) => {
|
|
84
|
+
if (settled) return
|
|
85
|
+
settled = true
|
|
86
|
+
clearTimeout(timer)
|
|
87
|
+
if (signal) signal.removeEventListener('abort', onAbort)
|
|
88
|
+
resolve({
|
|
89
|
+
code,
|
|
90
|
+
stdout: stdout.text(),
|
|
91
|
+
stderr: stderr.text(),
|
|
92
|
+
timedOut,
|
|
93
|
+
aborted,
|
|
94
|
+
truncated: stdout.truncated || stderr.truncated,
|
|
95
|
+
argv,
|
|
96
|
+
})
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const kill = () => {
|
|
100
|
+
try {
|
|
101
|
+
child.kill('SIGTERM')
|
|
102
|
+
} catch {
|
|
103
|
+
/* already gone */
|
|
104
|
+
}
|
|
105
|
+
const hard = setTimeout(() => {
|
|
106
|
+
try {
|
|
107
|
+
child.kill('SIGKILL')
|
|
108
|
+
} catch {
|
|
109
|
+
/* already gone */
|
|
110
|
+
}
|
|
111
|
+
}, 2000)
|
|
112
|
+
hard.unref?.()
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const onAbort = () => {
|
|
116
|
+
aborted = true
|
|
117
|
+
kill()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const timer = Number.isFinite(timeoutMs) && timeoutMs > 0
|
|
121
|
+
? setTimeout(() => {
|
|
122
|
+
timedOut = true
|
|
123
|
+
kill()
|
|
124
|
+
}, Math.floor(timeoutMs))
|
|
125
|
+
: null
|
|
126
|
+
timer?.unref?.()
|
|
127
|
+
|
|
128
|
+
if (signal) {
|
|
129
|
+
if (signal.aborted) {
|
|
130
|
+
aborted = true
|
|
131
|
+
kill()
|
|
132
|
+
} else {
|
|
133
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
child.stdout.on('data', (chunk) => stdout.push(chunk))
|
|
138
|
+
child.stderr.on('data', (chunk) => stderr.push(chunk))
|
|
139
|
+
child.on('error', (error) => {
|
|
140
|
+
stderr.push(`spawn_error: ${error?.message ?? error}\n`)
|
|
141
|
+
finish(null)
|
|
142
|
+
})
|
|
143
|
+
child.on('close', (code, signalName) => {
|
|
144
|
+
if (signalName && code === null && !aborted && !timedOut) {
|
|
145
|
+
stderr.push(`terminated_by_signal: ${signalName}\n`)
|
|
146
|
+
}
|
|
147
|
+
finish(code)
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Run `build_flow.py --json` for one request (legacy shape, still used by the
|
|
154
|
+
* flow tool so its behaviour and tests stay stable).
|
|
155
|
+
*/
|
|
156
|
+
export function runCore(options) {
|
|
157
|
+
const {
|
|
158
|
+
pythonPath, coreRoot, script, repository, request,
|
|
159
|
+
outputDirectory, slug, signal, timeoutMs, maxOutputBytes,
|
|
160
|
+
} = options
|
|
161
|
+
|
|
162
|
+
const argv = [script, '--repo', repository, '--request', request, '--json']
|
|
163
|
+
if (outputDirectory) argv.push('--out-dir', outputDirectory)
|
|
164
|
+
if (slug) argv.push('--slug', slug)
|
|
165
|
+
|
|
166
|
+
return runCli({
|
|
167
|
+
pythonPath, coreRoot, script, args: argv.slice(1),
|
|
168
|
+
signal, timeoutMs, maxOutputBytes,
|
|
169
|
+
})
|
|
170
|
+
}
|
package/lib/paths.js
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Path, config and core-location policy for the adapter.
|
|
3
|
+
*
|
|
4
|
+
* Every rule here exists so the tool cannot read or write outside what the
|
|
5
|
+
* profile explicitly allows, and so a package installed from a tarball can
|
|
6
|
+
* still find its core.
|
|
7
|
+
*/
|
|
8
|
+
import { accessSync, constants, existsSync, lstatSync, realpathSync, statSync } from 'node:fs'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
|
|
11
|
+
export const ARTIFACT_SUBPATH = path.join('artifacts', 'flows')
|
|
12
|
+
|
|
13
|
+
export class InputError extends Error {
|
|
14
|
+
/**
|
|
15
|
+
* @param {string} code - stable machine code, surfaced to the caller.
|
|
16
|
+
* @param {string} message - what went wrong, in the user's language.
|
|
17
|
+
* @param {string} [hint] - how to fix it.
|
|
18
|
+
*/
|
|
19
|
+
constructor(code, message, hint) {
|
|
20
|
+
super(message)
|
|
21
|
+
this.name = 'InputError'
|
|
22
|
+
this.code = code
|
|
23
|
+
this.hint = hint || ''
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Return true when `target` is `root` itself or lives under it. */
|
|
28
|
+
export function isInside(root, target) {
|
|
29
|
+
const relative = path.relative(path.resolve(root), path.resolve(target))
|
|
30
|
+
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function canonicalExisting(input, label) {
|
|
34
|
+
try {
|
|
35
|
+
return realpathSync(input)
|
|
36
|
+
} catch (error) {
|
|
37
|
+
throw new InputError('path_unreadable', `Không đọc được ${label}: ${input}`,
|
|
38
|
+
String(error?.message || error))
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Canonicalize the configured roots; missing entries are dropped, but an
|
|
44
|
+
* entirely unusable configuration is a hard error (deny-by-default).
|
|
45
|
+
* @param {unknown} allowedRoots
|
|
46
|
+
* @returns {string[]}
|
|
47
|
+
*/
|
|
48
|
+
export function resolveAllowedRoots(allowedRoots) {
|
|
49
|
+
if (allowedRoots === undefined || allowedRoots === null) {
|
|
50
|
+
throw new InputError(
|
|
51
|
+
'allowed_roots_unconfigured',
|
|
52
|
+
'Chưa cấu hình allowedRoots nên tool từ chối phân tích mọi đường dẫn.',
|
|
53
|
+
'Thêm vào profile patch: config.allowedRoots: ["/duong/dan/workspace", ...]. '
|
|
54
|
+
+ 'Tool chỉ đọc repository nằm trong các root này.',
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
if (!Array.isArray(allowedRoots)) {
|
|
58
|
+
throw new InputError('allowed_roots_invalid', 'allowedRoots phải là mảng chuỗi đường dẫn.')
|
|
59
|
+
}
|
|
60
|
+
if (allowedRoots.length === 0) {
|
|
61
|
+
throw new InputError(
|
|
62
|
+
'allowed_roots_unconfigured',
|
|
63
|
+
'allowedRoots rỗng nên tool từ chối phân tích mọi đường dẫn (deny-by-default).',
|
|
64
|
+
'Khai báo ít nhất một thư mục gốc trong config.allowedRoots của profile patch.',
|
|
65
|
+
)
|
|
66
|
+
}
|
|
67
|
+
const resolved = []
|
|
68
|
+
for (const entry of allowedRoots) {
|
|
69
|
+
if (typeof entry !== 'string' || entry.trim() === '') {
|
|
70
|
+
throw new InputError('allowed_roots_invalid', 'allowedRoots chứa phần tử không phải chuỗi đường dẫn.')
|
|
71
|
+
}
|
|
72
|
+
if (!path.isAbsolute(entry)) {
|
|
73
|
+
throw new InputError('allowed_roots_invalid',
|
|
74
|
+
`allowedRoots phải là đường dẫn tuyệt đối: ${entry}`)
|
|
75
|
+
}
|
|
76
|
+
if (!existsSync(entry)) continue
|
|
77
|
+
try {
|
|
78
|
+
const stat = statSync(entry)
|
|
79
|
+
if (!stat.isDirectory()) continue
|
|
80
|
+
resolved.push(realpathSync(entry))
|
|
81
|
+
} catch {
|
|
82
|
+
/* unreadable entry: ignored, deny-by-default still holds */
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (resolved.length === 0) {
|
|
86
|
+
throw new InputError(
|
|
87
|
+
'allowed_roots_unconfigured',
|
|
88
|
+
'Không root nào trong allowedRoots tồn tại và đọc được.',
|
|
89
|
+
`Đã cấu hình: ${JSON.stringify(allowedRoots)}`,
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
return [...new Set(resolved)]
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Canonicalize a repository path and prove it is readable and allowed.
|
|
97
|
+
* @param {unknown} input - caller-supplied path.
|
|
98
|
+
* @param {{allowedRoots?: unknown}} options - profile configuration.
|
|
99
|
+
* @returns {{root: string, allowedRoots: string[]}}
|
|
100
|
+
*/
|
|
101
|
+
export function resolveRepository(input, options = {}) {
|
|
102
|
+
const allowedRoots = resolveAllowedRoots(options.allowedRoots)
|
|
103
|
+
if (typeof input !== 'string' || input.trim() === '') {
|
|
104
|
+
throw new InputError('repository_path_missing', 'Thiếu repository_path.',
|
|
105
|
+
'Truyền đường dẫn tuyệt đối tới thư mục repository, ví dụ /home/ban/du-an.')
|
|
106
|
+
}
|
|
107
|
+
if (!path.isAbsolute(input)) {
|
|
108
|
+
throw new InputError('repository_path_relative',
|
|
109
|
+
`repository_path phải là đường dẫn tuyệt đối: ${input}`,
|
|
110
|
+
'Dùng đường dẫn bắt đầu bằng / (không dùng ~ hoặc đường dẫn tương đối).')
|
|
111
|
+
}
|
|
112
|
+
if (!existsSync(input)) {
|
|
113
|
+
throw new InputError('repository_not_found', `Không thấy thư mục repository: ${input}`,
|
|
114
|
+
'Kiểm tra lại đường dẫn; tool không tự clone hay tải repository.')
|
|
115
|
+
}
|
|
116
|
+
const root = canonicalExisting(input, 'repository')
|
|
117
|
+
let stat
|
|
118
|
+
try {
|
|
119
|
+
stat = statSync(root)
|
|
120
|
+
} catch (error) {
|
|
121
|
+
throw new InputError('repository_unreadable', `Không đọc được thư mục: ${root}`,
|
|
122
|
+
String(error?.message || error))
|
|
123
|
+
}
|
|
124
|
+
if (!stat.isDirectory()) {
|
|
125
|
+
throw new InputError('repository_not_directory', `Đường dẫn không phải thư mục: ${root}`)
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
accessSync(root, constants.R_OK | constants.X_OK)
|
|
129
|
+
} catch {
|
|
130
|
+
throw new InputError('repository_unreadable', `Không có quyền đọc thư mục: ${root}`)
|
|
131
|
+
}
|
|
132
|
+
const match = allowedRoots.find((allowed) => isInside(allowed, root))
|
|
133
|
+
if (!match) {
|
|
134
|
+
throw new InputError('repository_outside_allowed_roots',
|
|
135
|
+
`repository_path nằm ngoài allowedRoots: ${root}`,
|
|
136
|
+
`allowedRoots hiện tại: ${allowedRoots.join(', ')}`)
|
|
137
|
+
}
|
|
138
|
+
return { root, allowedRoots }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The only accepted artifact root is `<repo>/artifacts/flows`; nothing else —
|
|
143
|
+
* not the repo root, not src, not docs, not tmp, not a sibling directory.
|
|
144
|
+
* @param {string} root - canonical repository root.
|
|
145
|
+
* @param {unknown} outputDirectory - caller-supplied directory (absolute or repo-relative).
|
|
146
|
+
* @returns {string}
|
|
147
|
+
*/
|
|
148
|
+
export function resolveArtifactRoot(root, outputDirectory) {
|
|
149
|
+
const expected = path.join(root, ARTIFACT_SUBPATH)
|
|
150
|
+
// A symlinked artifacts/ or flows/ would escape the repo after the prefix
|
|
151
|
+
// check, so refuse it before looking at the caller's argument at all.
|
|
152
|
+
let probe = root
|
|
153
|
+
for (const part of ARTIFACT_SUBPATH.split(path.sep)) {
|
|
154
|
+
probe = path.join(probe, part)
|
|
155
|
+
let link = false
|
|
156
|
+
try {
|
|
157
|
+
link = lstatSync(probe).isSymbolicLink()
|
|
158
|
+
} catch {
|
|
159
|
+
link = false
|
|
160
|
+
}
|
|
161
|
+
if (link) {
|
|
162
|
+
const target = realpathSync(probe)
|
|
163
|
+
if (!isInside(root, target)) {
|
|
164
|
+
throw new InputError('artifact_symlink_escape',
|
|
165
|
+
`Thư mục artifact là symlink ra ngoài repository: ${probe} → ${target}`)
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
if (outputDirectory === undefined || outputDirectory === null || outputDirectory === '') {
|
|
170
|
+
return expected
|
|
171
|
+
}
|
|
172
|
+
if (typeof outputDirectory !== 'string' || outputDirectory.includes('\0')) {
|
|
173
|
+
throw new InputError('invalid_artifact_root', 'output_directory không hợp lệ.',
|
|
174
|
+
`Chỉ chấp nhận ${ARTIFACT_SUBPATH}.`)
|
|
175
|
+
}
|
|
176
|
+
const candidate = path.isAbsolute(outputDirectory)
|
|
177
|
+
? outputDirectory
|
|
178
|
+
: path.join(root, outputDirectory)
|
|
179
|
+
const normalised = path.resolve(candidate)
|
|
180
|
+
const expectedReal = existsSync(expected) ? realpathSync(expected) : expected
|
|
181
|
+
const candidateReal = existsSync(normalised) ? realpathSync(normalised) : normalised
|
|
182
|
+
if (candidateReal !== expectedReal) {
|
|
183
|
+
throw new InputError('invalid_artifact_root',
|
|
184
|
+
`output_directory không hợp lệ: ${outputDirectory}`,
|
|
185
|
+
`Artifact chỉ được ghi vào ${ARTIFACT_SUBPATH} trong repository đã duyệt; `
|
|
186
|
+
+ 'không chấp nhận repo root, src, docs, tmp hay thư mục ngoài repo.')
|
|
187
|
+
}
|
|
188
|
+
return expected
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Find the core: explicit config → env → bundled vendor copy → dev checkout.
|
|
193
|
+
* A packaged install (tarball) only has the vendor copy, so the parent
|
|
194
|
+
* directory is a convenience for development, never an assumption.
|
|
195
|
+
* @param {{coreRoot?: string, packageRoot: string, env?: NodeJS.ProcessEnv}} options
|
|
196
|
+
* @returns {{root: string, script: string, cli: string|null, source: string}}
|
|
197
|
+
* `script` is scripts/build_flow.py (flow tool); `cli` is tools/pfe_cli.py
|
|
198
|
+
* (knowledge tools) and is null when this copy of the core predates it.
|
|
199
|
+
*/
|
|
200
|
+
export function resolveCoreRoot({ coreRoot, packageRoot, env = process.env }) {
|
|
201
|
+
const candidates = []
|
|
202
|
+
if (typeof coreRoot === 'string' && coreRoot.trim() !== '') {
|
|
203
|
+
const configured = path.resolve(coreRoot)
|
|
204
|
+
const script = path.join(configured, 'scripts', 'build_flow.py')
|
|
205
|
+
const template = path.join(configured, 'assets', 'workflow_template.html')
|
|
206
|
+
const cli = path.join(configured, 'tools', 'pfe_cli.py')
|
|
207
|
+
if (!existsSync(script) || !existsSync(template)) {
|
|
208
|
+
// An explicit coreRoot that is wrong is a configuration bug: fail loudly
|
|
209
|
+
// instead of silently falling back to another copy.
|
|
210
|
+
throw new InputError('core_not_found',
|
|
211
|
+
`config.coreRoot không chứa core hợp lệ: ${configured}`,
|
|
212
|
+
'Cần có scripts/build_flow.py và assets/workflow_template.html trong thư mục này.')
|
|
213
|
+
}
|
|
214
|
+
return { root: configured, script, cli: existsSync(cli) ? cli : null, source: 'config' }
|
|
215
|
+
}
|
|
216
|
+
if (typeof env.PFE_CORE_ROOT === 'string' && env.PFE_CORE_ROOT.trim() !== '') {
|
|
217
|
+
candidates.push({ root: path.resolve(env.PFE_CORE_ROOT), source: 'env' })
|
|
218
|
+
}
|
|
219
|
+
candidates.push({ root: path.join(packageRoot, 'vendor', 'core'), source: 'vendor' })
|
|
220
|
+
candidates.push({ root: path.resolve(packageRoot, '..'), source: 'checkout' })
|
|
221
|
+
for (const candidate of candidates) {
|
|
222
|
+
const script = path.join(candidate.root, 'scripts', 'build_flow.py')
|
|
223
|
+
const template = path.join(candidate.root, 'assets', 'workflow_template.html')
|
|
224
|
+
if (existsSync(script) && existsSync(template)) {
|
|
225
|
+
const cli = path.join(candidate.root, 'tools', 'pfe_cli.py')
|
|
226
|
+
return { ...candidate, script, cli: existsSync(cli) ? cli : null }
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
throw new InputError(
|
|
230
|
+
'core_not_found',
|
|
231
|
+
'Không tìm thấy core (scripts/build_flow.py + assets/workflow_template.html).',
|
|
232
|
+
`Đã thử: ${candidates.map((item) => `${item.root} (${item.source})`).join(', ')}. `
|
|
233
|
+
+ 'Cài bundle đã pack (có vendor/core) hoặc đặt config.coreRoot trỏ tới checkout của repo.',
|
|
234
|
+
)
|
|
235
|
+
}
|