praxo-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +159 -2
  3. package/dist/app.js +75 -0
  4. package/dist/bin.js +21 -0
  5. package/dist/cli/commands/ai.command.js +189 -0
  6. package/dist/cli/commands/cmd.command.js +265 -0
  7. package/dist/cli/commands/completion.command.js +334 -0
  8. package/dist/cli/commands/config.command.js +27 -0
  9. package/dist/cli/commands/decision.command.js +287 -0
  10. package/dist/cli/commands/doctor.command.js +45 -0
  11. package/dist/cli/commands/project.command.js +24 -0
  12. package/dist/cli/commands/search.command.js +59 -0
  13. package/dist/cli/commands/sync.command.js +122 -0
  14. package/dist/cli/commands/transfer.command.js +148 -0
  15. package/dist/cli/index.js +156 -0
  16. package/dist/cli/output.js +133 -0
  17. package/dist/cli/prompts.js +68 -0
  18. package/dist/features/ai/client.js +238 -0
  19. package/dist/features/ai/output.js +7 -0
  20. package/dist/features/ai/providers.js +52 -0
  21. package/dist/features/ai/schemas.js +43 -0
  22. package/dist/features/ai/service.js +183 -0
  23. package/dist/features/commands/executor.js +54 -0
  24. package/dist/features/commands/repository.js +61 -0
  25. package/dist/features/commands/safety.js +154 -0
  26. package/dist/features/commands/service.js +254 -0
  27. package/dist/features/commands/template.js +153 -0
  28. package/dist/features/decisions/repository.js +53 -0
  29. package/dist/features/decisions/service.js +209 -0
  30. package/dist/features/decisions/stats.js +84 -0
  31. package/dist/features/decisions/status.js +7 -0
  32. package/dist/features/projects/repository.js +51 -0
  33. package/dist/features/projects/service.js +74 -0
  34. package/dist/features/sync/git.js +207 -0
  35. package/dist/features/sync/merge.js +194 -0
  36. package/dist/features/sync/repository.js +151 -0
  37. package/dist/features/sync/sanitizer.js +21 -0
  38. package/dist/features/sync/service.js +199 -0
  39. package/dist/features/sync/snapshot.js +230 -0
  40. package/dist/infrastructure/credentials/store.js +105 -0
  41. package/dist/infrastructure/database/client.js +41 -0
  42. package/dist/infrastructure/database/migrate.js +102 -0
  43. package/dist/infrastructure/database/schema.js +138 -0
  44. package/dist/infrastructure/git/detector.js +48 -0
  45. package/dist/shared/clipboard.js +19 -0
  46. package/dist/shared/config.js +163 -0
  47. package/dist/shared/doctor.js +47 -0
  48. package/dist/shared/errors.js +19 -0
  49. package/dist/shared/global-search.js +51 -0
  50. package/dist/shared/input.js +37 -0
  51. package/dist/shared/links.js +48 -0
  52. package/dist/shared/paths.js +14 -0
  53. package/dist/shared/query.js +10 -0
  54. package/dist/shared/redaction.js +54 -0
  55. package/dist/shared/search.js +39 -0
  56. package/dist/shared/sync-metadata.js +7 -0
  57. package/dist/shared/tags.js +91 -0
  58. package/dist/shared/transfer/archive.js +197 -0
  59. package/dist/shared/transfer/markdown.js +53 -0
  60. package/dist/shared/transfer/service.js +278 -0
  61. package/dist/tui/Workspace.js +121 -0
  62. package/dist/tui/components/AiPanel.js +200 -0
  63. package/dist/tui/components/Catalog.js +47 -0
  64. package/dist/tui/components/Confirm.js +28 -0
  65. package/dist/tui/components/Form.js +113 -0
  66. package/dist/tui/components/HelpModal.js +44 -0
  67. package/dist/tui/components/Inspection.js +28 -0
  68. package/dist/tui/components/KeyHints.js +7 -0
  69. package/dist/tui/components/SearchInput.js +31 -0
  70. package/dist/tui/components/SyncPanel.js +93 -0
  71. package/dist/tui/index.js +18 -0
  72. package/dist/tui/screens/Commands.js +383 -0
  73. package/dist/tui/screens/DecisionForms.js +117 -0
  74. package/dist/tui/screens/Decisions.js +260 -0
  75. package/dist/tui/screens/Lookup.js +96 -0
  76. package/dist/tui/theme.js +47 -0
  77. package/drizzle/0000_initial.sql +105 -0
  78. package/drizzle/0001_v11_sync.sql +117 -0
  79. package/drizzle/meta/0000_snapshot.json +735 -0
  80. package/drizzle/meta/0001_snapshot.json +867 -0
  81. package/drizzle/meta/_journal.json +20 -0
  82. package/package.json +77 -4
@@ -0,0 +1,238 @@
1
+ import { z } from 'zod';
2
+ import { AppError } from '../../shared/errors.js';
3
+ import { cleanAiText, hasUnsafeAiText } from './output.js';
4
+ class FormatRejected extends AppError {
5
+ }
6
+ const invalid = () => new AppError(5, 'The AI provider returned incomplete or invalid output. Try another model or check its configured capabilities.');
7
+ const envelope = z.object({
8
+ choices: z.array(z.object({
9
+ message: z
10
+ .object({ content: z.string().nullable(), refusal: z.string().nullable().optional() })
11
+ .optional(),
12
+ delta: z
13
+ .object({
14
+ content: z.string().nullable().optional(),
15
+ refusal: z.string().nullable().optional(),
16
+ })
17
+ .optional(),
18
+ finish_reason: z.string().nullable().optional(),
19
+ })),
20
+ });
21
+ function errorStatus(code) {
22
+ if (code === 401)
23
+ return new AppError(1, 'AI authentication failed. Check the configured API key.');
24
+ if (code === 402)
25
+ return new AppError(1, 'The AI account has insufficient balance or quota.');
26
+ if (code === 403)
27
+ return new AppError(1, 'The AI account cannot access this provider or model.');
28
+ if (code === 429)
29
+ return new AppError(1, 'The AI provider rate-limited this request. Wait and retry, or check your quota.');
30
+ return new AppError(1, 'AI request failed with HTTP ' + code + '. Check the endpoint and model.');
31
+ }
32
+ export function aiClient(settings, key, fetcher = fetch) {
33
+ async function send(request, body, consume) {
34
+ const timeout = AbortSignal.timeout(settings.timeoutMs);
35
+ const signal = request.signal ? AbortSignal.any([timeout, request.signal]) : timeout;
36
+ try {
37
+ const response = await fetcher(settings.baseUrl.replace(/\/+$/u, '') + '/chat/completions', {
38
+ method: 'POST',
39
+ redirect: 'error',
40
+ signal,
41
+ headers: {
42
+ 'Content-Type': 'application/json',
43
+ ...(key ? { Authorization: 'Bearer ' + key } : {}),
44
+ },
45
+ body: JSON.stringify({
46
+ model: settings.model,
47
+ ...body,
48
+ messages: [
49
+ { role: 'system', content: request.instruction },
50
+ { role: 'user', content: JSON.stringify(request.input) },
51
+ ],
52
+ }),
53
+ });
54
+ if (!response.ok) {
55
+ void response.body?.cancel().catch(() => { });
56
+ if ((response.status === 400 || response.status === 422) && body.response_format)
57
+ throw new FormatRejected(5, 'AI response format request failed with HTTP ' + response.status + '.');
58
+ throw errorStatus(response.status);
59
+ }
60
+ return await consume(response);
61
+ }
62
+ catch (error) {
63
+ if (request.signal?.aborted)
64
+ throw new AppError(130, 'AI request cancelled.');
65
+ if (timeout.aborted)
66
+ throw new AppError(1, 'AI request timed out. Check the endpoint or increase its timeout.');
67
+ if (error instanceof AppError)
68
+ throw error;
69
+ throw new AppError(1, 'Could not reach the AI provider or read its response. Check the endpoint and retry.');
70
+ }
71
+ }
72
+ async function responseText(response) {
73
+ let parsed;
74
+ try {
75
+ parsed = await response.json();
76
+ }
77
+ catch {
78
+ throw invalid();
79
+ }
80
+ const result = envelope.safeParse(parsed);
81
+ const answer = result.success ? result.data.choices[0] : undefined;
82
+ if (!answer?.message?.content?.trim() ||
83
+ answer.message.refusal ||
84
+ (answer.finish_reason && answer.finish_reason !== 'stop'))
85
+ throw invalid();
86
+ return answer.message.content;
87
+ }
88
+ /** 每种结构化格式最多尝试一次,非预期输出最多重试一次。 */
89
+ async function generateJSONWithFormat(request, schema) {
90
+ const formats = [];
91
+ if (settings.capabilities.jsonSchema)
92
+ formats.push('json_schema');
93
+ if (settings.capabilities.jsonObject)
94
+ formats.push('json_object');
95
+ formats.push('text');
96
+ const jsonSchema = z.toJSONSchema(schema);
97
+ const prompt = {
98
+ ...request,
99
+ instruction: request.instruction +
100
+ '\nReturn a single JSON object matching this schema: ' +
101
+ JSON.stringify(jsonSchema),
102
+ };
103
+ const failedFormats = [];
104
+ const maxAttempts = Math.max(2, formats.length);
105
+ let invalidResponses = 0;
106
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
107
+ const type = formats[attempt] ?? 'text';
108
+ const response_format = type === 'json_schema'
109
+ ? {
110
+ type,
111
+ json_schema: { name: 'praxo_response', strict: true, schema: jsonSchema },
112
+ }
113
+ : type === 'json_object'
114
+ ? { type }
115
+ : undefined;
116
+ try {
117
+ let text = (await send(prompt, { stream: false, response_format }, responseText)).trim();
118
+ text =
119
+ /^\x60\x60\x60(?:json)?[ \t]*\r?\n([\s\S]+)\r?\n\x60\x60\x60$/iu.exec(text)?.[1] ?? text;
120
+ const value = JSON.parse(text, (_key, value) => {
121
+ if (typeof value === 'string' && hasUnsafeAiText(value))
122
+ throw invalid();
123
+ return value;
124
+ });
125
+ const result = schema.safeParse(value);
126
+ if (result.success)
127
+ return { value: result.data, format: type, failedFormats };
128
+ throw invalid();
129
+ }
130
+ catch (error) {
131
+ if (!(error instanceof SyntaxError) && (!(error instanceof AppError) || error.code !== 5))
132
+ throw error;
133
+ if (type !== 'text')
134
+ failedFormats.push(type);
135
+ if (!(error instanceof FormatRejected))
136
+ invalidResponses++;
137
+ if (invalidResponses >= 2)
138
+ throw invalid();
139
+ }
140
+ }
141
+ throw invalid();
142
+ }
143
+ async function generateJSON(request, schema) {
144
+ return (await generateJSONWithFormat(request, schema)).value;
145
+ }
146
+ /** 逐行解析 SSE,保留跨网络块的 UTF-8 字符与事件边界。 */
147
+ async function decode(response, onChunk) {
148
+ if (!response.body)
149
+ throw invalid();
150
+ const reader = response.body.getReader();
151
+ const decoder = new TextDecoder('utf-8', { fatal: true });
152
+ let pending = '', full = '', finished = false;
153
+ let event = [];
154
+ function dispatch() {
155
+ if (!event.length)
156
+ return;
157
+ const data = event.join('\n');
158
+ event = [];
159
+ if (data === '[DONE]') {
160
+ finished = true;
161
+ return;
162
+ }
163
+ let payload;
164
+ try {
165
+ payload = JSON.parse(data);
166
+ }
167
+ catch {
168
+ throw invalid();
169
+ }
170
+ const parsed = envelope.safeParse(payload);
171
+ if (!parsed.success)
172
+ throw invalid();
173
+ const choice = parsed.data.choices[0];
174
+ if (!choice)
175
+ return;
176
+ if (choice.delta?.refusal || (choice.finish_reason && choice.finish_reason !== 'stop'))
177
+ throw invalid();
178
+ const chunk = cleanAiText(choice.delta?.content ?? '');
179
+ if (chunk) {
180
+ full += chunk;
181
+ if (full.length > 250_000)
182
+ throw invalid();
183
+ onChunk(chunk);
184
+ }
185
+ if (choice.finish_reason === 'stop')
186
+ finished = true;
187
+ }
188
+ try {
189
+ while (!finished) {
190
+ const { done, value } = await reader.read();
191
+ pending += decoder.decode(value, { stream: !done });
192
+ if (pending.length > 250_000)
193
+ throw invalid();
194
+ for (let next = /\r\n|\r|\n/u.exec(pending); next; next = /\r\n|\r|\n/u.exec(pending)) {
195
+ if (!done && next[0] === '\r' && next.index === pending.length - 1)
196
+ break;
197
+ const line = pending.slice(0, next.index);
198
+ pending = pending.slice(next.index + next[0].length);
199
+ if (line === '')
200
+ dispatch();
201
+ else if (line.startsWith('data:'))
202
+ event.push(line.slice(5).replace(/^ /u, ''));
203
+ if (finished)
204
+ break;
205
+ }
206
+ if (done) {
207
+ if (pending.startsWith('data:'))
208
+ event.push(pending.slice(5).replace(/^ /u, ''));
209
+ dispatch();
210
+ break;
211
+ }
212
+ }
213
+ if (!finished || !full.trim())
214
+ throw invalid();
215
+ return full;
216
+ }
217
+ finally {
218
+ await reader.cancel().catch(() => { });
219
+ reader.releaseLock();
220
+ }
221
+ }
222
+ async function streamText(request, onChunk) {
223
+ if (!onChunk || !settings.capabilities.streaming) {
224
+ const result = cleanAiText(await send(request, { stream: false }, responseText));
225
+ if (!result.trim())
226
+ throw invalid();
227
+ onChunk?.(result);
228
+ return result;
229
+ }
230
+ return send(request, { stream: true }, (response) => decode(response, onChunk));
231
+ }
232
+ return {
233
+ generateJSON,
234
+ generateJSONWithFormat,
235
+ streamText,
236
+ streaming: settings.capabilities.streaming,
237
+ };
238
+ }
@@ -0,0 +1,7 @@
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ const unsafeControls = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/u;
3
+ /** 保留制表符和换行,拒绝会改变终端显示的控制字符。 */
4
+ export const hasUnsafeAiText = (value) => unsafeControls.test(value.replace(/\r\n/gu, '\n'));
5
+ export const cleanAiText = (value) => stripVTControlCharacters(value)
6
+ .replace(/\r\n/gu, '\n')
7
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/gu, '');
@@ -0,0 +1,52 @@
1
+ import { aiConfigSchema, providerName } from '../../shared/config.js';
2
+ import { AppError } from '../../shared/errors.js';
3
+ export const AI_PROVIDERS = ['deepseek', 'gemini'];
4
+ /** 底层通用服务商注册表:新增服务商时只需在此注册预设,无需修改上层调用。 */
5
+ const presets = {
6
+ deepseek: {
7
+ baseUrl: 'https://api.deepseek.com/v1',
8
+ defaultModel: 'deepseek-chat',
9
+ envKey: 'PRAXO_DEEPSEEK_API_KEY',
10
+ capabilities: { jsonSchema: false, jsonObject: true, streaming: true },
11
+ },
12
+ gemini: {
13
+ baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai',
14
+ defaultModel: 'gemini-2.5-flash',
15
+ envKey: 'PRAXO_GEMINI_API_KEY',
16
+ capabilities: { jsonSchema: true, jsonObject: true, streaming: true },
17
+ },
18
+ };
19
+ /** 获取指定服务商的内置预设配置。 */
20
+ export function providerPreset(provider) {
21
+ return presets[provider];
22
+ }
23
+ /** 返回服务商专属的 Praxo API Key 环境变量名。 */
24
+ export function aiKeyVariable(provider) {
25
+ return presets[provider].envKey;
26
+ }
27
+ /** 将用户极简配置展开为通用 OpenAI 兼容客户端运行参数。 */
28
+ export function runtimeClientConfig(config) {
29
+ const preset = presets[config.provider];
30
+ return {
31
+ baseUrl: preset.baseUrl,
32
+ model: config.model,
33
+ timeoutMs: config.timeoutMs,
34
+ capabilities: preset.capabilities,
35
+ };
36
+ }
37
+ /** 校验并生成持久化 AI 配置,未指定模型时自动使用服务商默认模型。 */
38
+ export function providerConfig(input, current) {
39
+ const parsed = providerName.safeParse(input.provider ?? current?.provider ?? 'deepseek');
40
+ if (!parsed.success)
41
+ throw new AppError(2, 'Choose deepseek or gemini.');
42
+ const provider = parsed.data;
43
+ const fallbackModel = current?.provider === provider ? current.model : presets[provider].defaultModel;
44
+ const config = aiConfigSchema.safeParse({
45
+ provider,
46
+ model: input.model?.trim() || fallbackModel,
47
+ timeoutMs: input.timeoutMs ?? current?.timeoutMs,
48
+ });
49
+ if (!config.success)
50
+ throw new AppError(2, 'Enter a valid model name. Timeout must be 100–300000 ms.');
51
+ return config.data;
52
+ }
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import { assessRisk } from '../commands/safety.js';
3
+ import { parseTemplate } from '../commands/template.js';
4
+ import { AppError } from '../../shared/errors.js';
5
+ import { inspectText } from '../../shared/redaction.js';
6
+ import { hasUnsafeAiText } from './output.js';
7
+ const required = z.string().trim().min(1);
8
+ export const draftSchema = z.strictObject({
9
+ name: required.max(200),
10
+ template: required.max(4000),
11
+ note: z.string().max(4000),
12
+ type: required.max(80),
13
+ tags: z.array(required.max(80)).max(20),
14
+ dangerLevel: z.enum(['low', 'medium', 'high']),
15
+ platform: z.enum(['macos', 'linux', 'windows', 'cross-platform']),
16
+ });
17
+ export const challengeSchema = z.strictObject({
18
+ risks: required.max(4000),
19
+ evidence: required.max(4000),
20
+ assumptions: required.max(4000),
21
+ indicators: required.max(4000),
22
+ });
23
+ export const reviewSchema = z.strictObject({
24
+ lesson: required.max(4000),
25
+ rating: z.enum(['accurate', 'partial', 'failed']),
26
+ });
27
+ /** 模型风险分类只会提高警示等级,最终模板始终走本机规则。 */
28
+ export function assessDraft(raw) {
29
+ const result = draftSchema.safeParse(raw);
30
+ if (!result.success)
31
+ throw new AppError(5, 'Invalid command draft. Review its name, command, tags, and platform.');
32
+ const draft = result.data;
33
+ if (Object.values(draft).flat().some(hasUnsafeAiText))
34
+ throw new AppError(5, 'Remove terminal control characters from the command draft.');
35
+ const template = parseTemplate(draft.template);
36
+ const placeholders = new Map(template.variables.map(({ name, fallback }) => [name, fallback ?? 'value']));
37
+ const risk = assessRisk(template, placeholders, false);
38
+ const danger = draft.dangerLevel !== 'low' || risk.kind !== 'ordinary';
39
+ return { draft, danger, risk: risk.reason };
40
+ }
41
+ export function hasSecret(draft) {
42
+ return [draft.name, draft.template, draft.note, draft.type, ...draft.tags].some((field) => inspectText(field).blocked);
43
+ }
@@ -0,0 +1,183 @@
1
+ import { z } from 'zod';
2
+ import { AppError } from '../../shared/errors.js';
3
+ import { inspectText } from '../../shared/redaction.js';
4
+ import { aiClient } from './client.js';
5
+ import { aiKeyVariable, providerConfig, runtimeClientConfig } from './providers.js';
6
+ import { assessDraft, challengeSchema, draftSchema, hasSecret, reviewSchema } from './schemas.js';
7
+ export function aiService({ config, credentials, fetcher, commands, decisions, stats, copy, }) {
8
+ const settings = () => config.read().ai;
9
+ const keyIdentity = (provider, base) => config.identity('ai:' + provider + ':' + base.replace(/\/+$/u, ''));
10
+ async function configure(input, key) {
11
+ const next = providerConfig(input, settings());
12
+ const runtime = runtimeClientConfig(next);
13
+ if (key)
14
+ await credentials.set(keyIdentity(next.provider, runtime.baseUrl), key, aiKeyVariable(next.provider));
15
+ config.set('ai', next);
16
+ return next;
17
+ }
18
+ async function resolveClient(options) {
19
+ const current = settings();
20
+ if (!current && !options.provider)
21
+ throw new AppError(2, 'AI is unconfigured. Run pxo ai config.');
22
+ const selected = providerConfig(options, current);
23
+ const runtime = runtimeClientConfig(selected);
24
+ const variable = aiKeyVariable(selected.provider);
25
+ const key = await credentials.get(keyIdentity(selected.provider, runtime.baseUrl), variable);
26
+ if (!key) {
27
+ throw new AppError(2, 'Configure the API key with pxo ai config --key-stdin or set ' + variable + '.');
28
+ }
29
+ return { selected, api: aiClient(runtime, key, fetcher) };
30
+ }
31
+ async function client(options) {
32
+ return (await resolveClient(options)).api;
33
+ }
34
+ /** 每项任务单独选取字段,疑似密钥只用占位符传给模型。 */
35
+ async function prepare(instruction, input, { signal, approve }) {
36
+ const findings = [];
37
+ function protect(field, value) {
38
+ if (typeof value === 'string') {
39
+ const result = inspectText(value);
40
+ if (result.blocked || result.suspicious)
41
+ findings.push(field);
42
+ return result.value.slice(0, 12_000);
43
+ }
44
+ if (Array.isArray(value))
45
+ return value.map((item, i) => protect(field + '.' + i, item));
46
+ if (value && typeof value === 'object')
47
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => {
48
+ const cleaned = inspectText(key);
49
+ if (cleaned.blocked || cleaned.suspicious)
50
+ findings.push(field || 'input');
51
+ return [
52
+ cleaned.value,
53
+ protect(field ? field + '.' + cleaned.value : cleaned.value, item),
54
+ ];
55
+ }));
56
+ return value;
57
+ }
58
+ const safe = protect('', input);
59
+ if (findings.length && !(await approve?.([...new Set(findings)]))) {
60
+ throw new AppError(4, 'Sensitive values were redacted. Confirm the redacted request in a terminal, or replace the values with variables.');
61
+ }
62
+ if (signal?.aborted)
63
+ throw new AppError(130, 'AI request cancelled.');
64
+ return { instruction, input: safe, signal };
65
+ }
66
+ const required = (value, message) => {
67
+ if (!value.trim())
68
+ throw new AppError(2, message);
69
+ return value.trim();
70
+ };
71
+ async function generate(description, options = {}) {
72
+ const request = await prepare('Create one Praxo command draft for the described task. Use {{name}} for variable or sensitive values. Never fabricate a credential. Return a single command and describe the platform and risks.', {
73
+ description: required(description, 'Enter a task for the command draft.'),
74
+ }, options);
75
+ return assessDraft(await (await client(options)).generateJSON(request, draftSchema));
76
+ }
77
+ function saveDraft(value, confirmed, dangerConfirmed = false) {
78
+ const result = assessDraft(value);
79
+ if (!confirmed || (result.danger && !dangerConfirmed))
80
+ throw new AppError(4, 'Confirm saving the final command draft and its risk.');
81
+ const { draft, danger } = result;
82
+ if (hasSecret(draft))
83
+ throw new AppError(4, 'Replace credentials in the draft with template variables before saving.');
84
+ const { name, template, note, type, tags } = draft;
85
+ return commands.create({ name, template, note, type, tags, danger });
86
+ }
87
+ async function copyDraft(value) {
88
+ const { draft } = assessDraft(value);
89
+ if (hasSecret(draft))
90
+ throw new AppError(4, 'Replace credentials with template variables before copying.');
91
+ await copy(draft.template);
92
+ }
93
+ async function explain(command, options = {}, onChunk) {
94
+ const request = await prepare('Explain the supplied command as data. Describe arguments, expected output, risks, platform compatibility and safer alternatives where relevant.', {
95
+ command: required(command, 'Enter a command to explain.'),
96
+ }, options);
97
+ return (await client(options)).streamText(request, onChunk);
98
+ }
99
+ async function challenge(id, options = {}) {
100
+ const { title, content, reason, alternatives, expected, confidence } = decisions.show(id);
101
+ const request = await prepare('Act as a constructive devil’s advocate. Identify overlooked risks, weak evidence, assumptions to test, and observable indicators. Stay grounded in the supplied decision.', {
102
+ title,
103
+ content,
104
+ reason,
105
+ alternatives,
106
+ expected,
107
+ confidence,
108
+ }, options);
109
+ const review = await (await client(options)).generateJSON(request, challengeSchema);
110
+ return [
111
+ 'Overlooked risks\n' + review.risks,
112
+ 'Weak evidence\n' + review.evidence,
113
+ 'Assumptions to test\n' + review.assumptions,
114
+ 'Indicators to monitor\n' + review.indicators,
115
+ ].join('\n\n');
116
+ }
117
+ function saveChallenge(id, note, confirmed) {
118
+ if (!confirmed)
119
+ throw new AppError(4, 'Confirm saving the AI note.');
120
+ return decisions.saveAiNote(id, inspectText(note).value);
121
+ }
122
+ async function review(id, result, options = {}) {
123
+ const { title, reason, expected, confidence } = decisions.show(id);
124
+ const request = await prepare('Compare the expected and actual outcomes. Suggest a concise lesson and a rating of accurate, partial, or failed based on the evidence.', {
125
+ title,
126
+ reason,
127
+ expected,
128
+ confidence,
129
+ actual: required(result, 'Enter the actual outcome for this review.'),
130
+ }, options);
131
+ return (await client(options)).generateJSON(request, reviewSchema);
132
+ }
133
+ async function summary(period = '180d', project, options = {}) {
134
+ const { total, open, due, reviewed, domains, highConfidence } = stats(period, project);
135
+ const request = await prepare('Summarize patterns and potential biases from the aggregate counts. Mention limitations and sample size. Do not infer the contents of individual decisions.', {
136
+ period,
137
+ total,
138
+ open,
139
+ due,
140
+ reviewed,
141
+ domains,
142
+ highConfidence,
143
+ }, options);
144
+ return (await client(options)).streamText(request);
145
+ }
146
+ async function test(options = {}) {
147
+ const { selected, api } = await resolveClient(options);
148
+ const { format, failedFormats } = await api.generateJSONWithFormat({
149
+ instruction: 'Return one JSON object with a short message.',
150
+ input: { message: 'Praxo connection test' },
151
+ signal: options.signal,
152
+ }, z.strictObject({ message: z.string().min(1) }));
153
+ if (api.streaming) {
154
+ await api.streamText({
155
+ instruction: 'Reply with one short line.',
156
+ input: 'Praxo stream test',
157
+ signal: options.signal,
158
+ }, () => { });
159
+ }
160
+ return {
161
+ ok: true,
162
+ provider: selected.provider,
163
+ model: selected.model,
164
+ format,
165
+ failedFormats,
166
+ streaming: api.streaming,
167
+ };
168
+ }
169
+ return {
170
+ settings,
171
+ configure,
172
+ generate,
173
+ assessDraft,
174
+ saveDraft,
175
+ copyDraft,
176
+ explain,
177
+ challenge,
178
+ saveChallenge,
179
+ review,
180
+ summary,
181
+ test,
182
+ };
183
+ }
@@ -0,0 +1,54 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { AppError } from '../../shared/errors.js';
3
+ /** CLI 继承终端。需要保留键盘控制的 TUI 可以独立捕获输出。 */
4
+ export function execute(executable, args, cwd, captured) {
5
+ if (captured?.signal.aborted)
6
+ return Promise.reject(new AppError(130, 'Command interrupted.'));
7
+ return new Promise((resolve, reject) => {
8
+ let interrupted = false;
9
+ let force;
10
+ const child = spawn(executable, args, {
11
+ cwd,
12
+ shell: false,
13
+ stdio: captured ? ['ignore', 'pipe', 'pipe'] : 'inherit',
14
+ windowsHide: true,
15
+ });
16
+ if (captured) {
17
+ child.stdout?.setEncoding('utf8').on('data', captured.onOutput);
18
+ child.stderr?.setEncoding('utf8').on('data', captured.onOutput);
19
+ }
20
+ const interrupt = () => {
21
+ if (interrupted)
22
+ return;
23
+ interrupted = true;
24
+ child.kill('SIGINT');
25
+ if (captured)
26
+ force = setTimeout(() => child.kill('SIGKILL'), 1500);
27
+ };
28
+ const cleanup = () => {
29
+ process.off('SIGINT', interrupt);
30
+ captured?.signal.removeEventListener('abort', interrupt);
31
+ if (force)
32
+ clearTimeout(force);
33
+ };
34
+ process.on('SIGINT', interrupt);
35
+ captured?.signal.addEventListener('abort', interrupt, { once: true });
36
+ child.once('error', (error) => {
37
+ cleanup();
38
+ reject(new AppError(6, 'Could not start the program. Check the executable and your PATH.', {
39
+ cause: error,
40
+ }));
41
+ });
42
+ child.once('close', (exitCode, signal) => {
43
+ cleanup();
44
+ resolve({
45
+ exitCode,
46
+ outcome: interrupted || signal === 'SIGINT'
47
+ ? 'interrupted'
48
+ : exitCode === 0
49
+ ? 'success'
50
+ : 'failed',
51
+ });
52
+ });
53
+ });
54
+ }
@@ -0,0 +1,61 @@
1
+ import { and, eq, isNull, sql } from 'drizzle-orm';
2
+ import { commandUsages, commands, entityLinks, entityTags, projects, } from '../../infrastructure/database/schema.js';
3
+ import { inScope } from '../../shared/query.js';
4
+ export function commandRepository(db) {
5
+ function summaries() {
6
+ const usage = db
7
+ .select({
8
+ owner: commandUsages.commandId,
9
+ count: sql `count(*)`.as('tally'),
10
+ copyCount: sql `sum(${commandUsages.kind} = 'copy')`.as('copy_tally'),
11
+ runCount: sql `sum(${commandUsages.kind} = 'run')`.as('run_tally'),
12
+ lastUsedAt: sql `max(${commandUsages.usedAt})`.as('last_used_at'),
13
+ })
14
+ .from(commandUsages)
15
+ .groupBy(commandUsages.commandId)
16
+ .as('usage');
17
+ return db
18
+ .select({
19
+ command: commands,
20
+ projectName: projects.name,
21
+ count: usage.count,
22
+ copyCount: usage.copyCount,
23
+ runCount: usage.runCount,
24
+ lastUsedAt: usage.lastUsedAt,
25
+ })
26
+ .from(commands)
27
+ .leftJoin(projects, eq(commands.projectId, projects.id))
28
+ .leftJoin(usage, eq(commands.id, usage.owner));
29
+ }
30
+ function list(projectId, filter) {
31
+ return summaries()
32
+ .where(and(isNull(commands.deletedAt), inScope(commands.projectId, projectId, filter.scope), filter.type === undefined ? undefined : eq(commands.type, filter.type), filter.tier === undefined ? undefined : eq(commands.tier, filter.tier), filter.sos === undefined ? undefined : eq(commands.sos, filter.sos)))
33
+ .all();
34
+ }
35
+ return {
36
+ detail: (id) => summaries()
37
+ .where(and(eq(commands.id, id), isNull(commands.deletedAt)))
38
+ .get(),
39
+ byId: (id) => db
40
+ .select()
41
+ .from(commands)
42
+ .where(and(eq(commands.id, id), isNull(commands.deletedAt)))
43
+ .get(),
44
+ list,
45
+ insert: (row) => db.insert(commands).values(row).run(),
46
+ update: (id, patch) => db.update(commands).set(patch).where(eq(commands.id, id)).run(),
47
+ remove: (id, at) => {
48
+ db.update(commands).set({ deletedAt: at, updatedAt: at }).where(eq(commands.id, id)).run();
49
+ db.update(entityTags)
50
+ .set({ deletedAt: at, updatedAt: at })
51
+ .where(and(eq(entityTags.commandId, id), isNull(entityTags.deletedAt)))
52
+ .run();
53
+ db.update(entityLinks)
54
+ .set({ deletedAt: at, updatedAt: at })
55
+ .where(and(eq(entityLinks.commandId, id), isNull(entityLinks.deletedAt)))
56
+ .run();
57
+ db.delete(commandUsages).where(eq(commandUsages.commandId, id)).run();
58
+ },
59
+ use: (usage) => db.insert(commandUsages).values(usage).run(),
60
+ };
61
+ }