agent-steward 0.0.5 → 0.0.6
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/CHANGELOG.md +176 -1
- package/README.md +9 -7
- package/ROADMAP-STRATEGY.md +5 -5
- package/ROADMAP.md +107 -17
- package/dist/cli.js +5 -0
- package/dist/core/analytics.d.ts +6 -0
- package/dist/core/analytics.d.ts.map +1 -1
- package/dist/core/analytics.js +20 -3
- package/dist/core/audit.d.ts +6 -0
- package/dist/core/audit.d.ts.map +1 -1
- package/dist/core/audit.js +24 -0
- package/dist/core/budget.d.ts +118 -0
- package/dist/core/budget.d.ts.map +1 -0
- package/dist/core/budget.js +206 -0
- package/dist/core/cron-to-schtasks.d.ts.map +1 -1
- package/dist/core/cron-to-schtasks.js +38 -0
- package/dist/core/dry-run.d.ts +26 -1
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +199 -8
- package/dist/core/feedback.d.ts +192 -0
- package/dist/core/feedback.d.ts.map +1 -0
- package/dist/core/feedback.js +426 -0
- package/dist/core/gate-integrity.d.ts +36 -0
- package/dist/core/gate-integrity.d.ts.map +1 -1
- package/dist/core/gate-integrity.js +144 -1
- package/dist/core/local-ai.d.ts.map +1 -1
- package/dist/core/local-ai.js +7 -3
- package/dist/core/matrix.d.ts +8 -0
- package/dist/core/matrix.d.ts.map +1 -1
- package/dist/core/matrix.js +57 -2
- package/dist/core/mission.d.ts +20 -0
- package/dist/core/mission.d.ts.map +1 -1
- package/dist/core/mission.js +45 -5
- package/dist/core/opencode-models.d.ts +2 -2
- package/dist/core/opencode-models.d.ts.map +1 -1
- package/dist/core/opencode-models.js +28 -21
- package/dist/core/opencode-usage.d.ts +35 -0
- package/dist/core/opencode-usage.d.ts.map +1 -0
- package/dist/core/opencode-usage.js +132 -0
- package/dist/core/pipeline-io.d.ts +1 -1
- package/dist/core/pipeline-io.d.ts.map +1 -1
- package/dist/core/pipeline-io.js +26 -12
- package/dist/core/pipeline-map.d.ts +6 -0
- package/dist/core/pipeline-map.d.ts.map +1 -1
- package/dist/core/pipeline-map.js +12 -0
- package/dist/core/ps-wrapper.d.ts +10 -2
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +176 -5
- package/dist/core/record-history.d.ts.map +1 -1
- package/dist/core/record-history.js +76 -4
- package/dist/core/run-mode.d.ts +12 -0
- package/dist/core/run-mode.d.ts.map +1 -0
- package/dist/core/run-mode.js +17 -0
- package/dist/core/scheduler/logs.d.ts +4 -0
- package/dist/core/scheduler/logs.d.ts.map +1 -1
- package/dist/core/scheduler/logs.js +25 -1
- package/dist/core/secrets.d.ts.map +1 -1
- package/dist/core/secrets.js +18 -8
- package/dist/core/self-analysis.d.ts +32 -2
- package/dist/core/self-analysis.d.ts.map +1 -1
- package/dist/core/self-analysis.js +38 -27
- package/dist/core/shutdown.d.ts +33 -2
- package/dist/core/shutdown.d.ts.map +1 -1
- package/dist/core/shutdown.js +58 -2
- package/dist/core/structured-log.d.ts +30 -0
- package/dist/core/structured-log.d.ts.map +1 -1
- package/dist/core/structured-log.js +37 -0
- package/dist/core/usage-surface.d.ts +25 -0
- package/dist/core/usage-surface.d.ts.map +1 -0
- package/dist/core/usage-surface.js +41 -0
- package/dist/core/wrappers/bash.d.ts +2 -0
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +58 -6
- package/dist/db/history-repo.d.ts +32 -0
- package/dist/db/history-repo.d.ts.map +1 -1
- package/dist/db/history-repo.js +85 -7
- package/dist/db/metrics-repo.d.ts +20 -2
- package/dist/db/metrics-repo.d.ts.map +1 -1
- package/dist/db/metrics-repo.js +33 -11
- package/dist/db/migrate.d.ts.map +1 -1
- package/dist/db/migrate.js +37 -17
- package/dist/db/recovery.d.ts +3 -1
- package/dist/db/recovery.d.ts.map +1 -1
- package/dist/db/recovery.js +9 -4
- package/dist/db/runs-repo.d.ts.map +1 -1
- package/dist/db/runs-repo.js +71 -56
- package/dist/db/schema.d.ts +2 -2
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +70 -1
- package/dist/db/templates-repo.d.ts +2 -2
- package/dist/db/templates-repo.d.ts.map +1 -1
- package/dist/db/templates-repo.js +5 -3
- package/dist/history.d.ts +6 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +4 -2
- package/dist/hook-output.d.ts +2 -0
- package/dist/hook-output.d.ts.map +1 -0
- package/dist/hook-output.js +31 -0
- package/dist/index.d.ts +247 -53
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +999 -211
- package/dist/notifications.d.ts +31 -2
- package/dist/notifications.d.ts.map +1 -1
- package/dist/notifications.js +132 -13
- package/dist/profiles.d.ts.map +1 -1
- package/dist/profiles.js +66 -15
- package/dist/rpc.d.ts +108 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +28 -0
- package/dist/server.d.ts +17 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +77 -12
- package/dist/settings.d.ts +42 -0
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +82 -0
- package/dist/task-transfer.d.ts +5 -0
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +48 -3
- package/dist/templates.d.ts +2 -2
- package/dist/templates.d.ts.map +1 -1
- package/dist/templates.js +3 -3
- package/dist/types.d.ts +22 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/workspaces.d.ts.map +1 -1
- package/dist/workspaces.js +34 -11
- package/docs/ARCHITECTURE.md +49 -12
- package/docs/COMPATIBILITY.md +2 -2
- package/docs/EXECUTION-LOOP.md +6 -3
- package/docs/FEATURES.md +65 -4
- package/docs/FEATURES.zh.md +45 -2
- package/docs/QA-A2-GUI-TUI.md +205 -0
- package/docs/README.ru.md +3 -3
- package/docs/README.zh.md +2 -2
- package/gui-experimental.cjs +9 -9
- package/locales/en.json +42 -3
- package/locales/ru.json +42 -3
- package/locales/zh.json +42 -3
- package/package.json +15 -2
- package/scripts/check-eslint-baseline.mjs +139 -0
- package/scripts/gen-test-plan-counters.mjs +117 -0
- package/scripts/github-ci-fetch.ps1 +37 -0
- package/scripts/pl-commit.ps1 +112 -0
- package/scripts/qa-a2-commit.ps1 +104 -0
- package/scripts/test-home.mjs +26 -2
- package/skills/scheduled-job-best-practices/SKILL.md +95 -1
- package/skills/scheduled-job-best-practices/references/recipes.md +139 -0
- package/src/cli.ts +5 -0
- package/src/core/analytics.ts +27 -4
- package/src/core/audit.ts +25 -0
- package/src/core/budget.ts +340 -0
- package/src/core/cron-to-schtasks.ts +42 -0
- package/src/core/dry-run.ts +233 -10
- package/src/core/feedback.ts +582 -0
- package/src/core/gate-integrity.ts +171 -1
- package/src/core/local-ai.ts +7 -3
- package/src/core/matrix.ts +63 -2
- package/src/core/mission.ts +51 -5
- package/src/core/opencode-models.ts +30 -21
- package/src/core/opencode-usage.ts +182 -0
- package/src/core/pipeline-io.ts +28 -11
- package/src/core/pipeline-map.ts +19 -0
- package/src/core/ps-wrapper.ts +173 -4
- package/src/core/record-history.ts +94 -4
- package/src/core/run-mode.ts +19 -0
- package/src/core/scheduler/logs.ts +32 -1
- package/src/core/secrets.ts +18 -11
- package/src/core/self-analysis.ts +75 -29
- package/src/core/shutdown.ts +90 -4
- package/src/core/structured-log.ts +67 -0
- package/src/core/usage-surface.ts +70 -0
- package/src/core/wrappers/bash.ts +60 -5
- package/src/db/history-repo.ts +153 -19
- package/src/db/metrics-repo.ts +38 -11
- package/src/db/migrate.ts +57 -32
- package/src/db/recovery.ts +10 -4
- package/src/db/runs-repo.ts +113 -61
- package/src/db/schema.ts +70 -1
- package/src/db/templates-repo.ts +5 -3
- package/src/gui.tsx +261 -5
- package/src/history.ts +10 -3
- package/src/hook-output.ts +39 -0
- package/src/index.ts +1407 -345
- package/src/notifications.ts +189 -39
- package/src/profiles.ts +72 -16
- package/src/rpc.ts +30 -0
- package/src/server.ts +107 -23
- package/src/settings.ts +120 -0
- package/src/task-transfer.ts +59 -6
- package/src/templates.ts +3 -3
- package/src/types.ts +23 -2
- package/src/workspaces.ts +37 -14
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Деталь 3.8 — обратная связь «чужой пользователь → автор» (F-1).
|
|
3
|
+
*
|
|
4
|
+
* Публичный npm-пакет не может содержать токены: в коде только URL write-only
|
|
5
|
+
* приёмника (Cloudflare Worker из infra/feedback-worker). Секреты живут в
|
|
6
|
+
* секретах Worker. При недоступности приёмника отчёт уходит в локальный
|
|
7
|
+
* outbox и НЕ блокирует запуск/завершение задачи (fail-open).
|
|
8
|
+
*/
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import os from "node:os";
|
|
11
|
+
import { getDb } from "../db/index.js";
|
|
12
|
+
import type { FeedbackSettings } from "../settings.js";
|
|
13
|
+
import { getPluginVersion } from "../version.js";
|
|
14
|
+
|
|
15
|
+
/** Версия контракта payload. Приёмник обязателен принимать только её. */
|
|
16
|
+
export const FEEDBACK_SCHEMA_VERSION = 1;
|
|
17
|
+
/** Таймаут одного HTTP-запроса (F-1.2). */
|
|
18
|
+
export const FEEDBACK_TIMEOUT_MS = 10_000;
|
|
19
|
+
/** Количество повторов после первой попытки (F-1.2). */
|
|
20
|
+
export const FEEDBACK_MAX_RETRIES = 2;
|
|
21
|
+
/** Базовая задержка backoff в мс (удваивается на каждом повторе). */
|
|
22
|
+
export const FEEDBACK_BACKOFF_MS = 500;
|
|
23
|
+
/** Окно антиспама по хешу описания (F-1.7). */
|
|
24
|
+
export const FEEDBACK_ANTISPAM_WINDOW_MS = 5 * 60_000;
|
|
25
|
+
/** Лимит отчётов в час по умолчанию (F-1.7). */
|
|
26
|
+
export const FEEDBACK_MAX_PER_HOUR = 6;
|
|
27
|
+
/** Максимальное число попыток отправки из outbox. */
|
|
28
|
+
export const FEEDBACK_OUTBOX_MAX_ATTEMPTS = 5;
|
|
29
|
+
/** Пределы длин полей (совпадают с валидацией Worker). */
|
|
30
|
+
export const FEEDBACK_LIMITS = {
|
|
31
|
+
description: 4000,
|
|
32
|
+
logs: 8000,
|
|
33
|
+
contactEmail: 254,
|
|
34
|
+
taskName: 200,
|
|
35
|
+
} as const;
|
|
36
|
+
|
|
37
|
+
export type FeedbackDestination = "author" | "local" | "both";
|
|
38
|
+
|
|
39
|
+
/** Контракт, который получает приёмник (F-1.1). */
|
|
40
|
+
export interface FeedbackPayload {
|
|
41
|
+
schemaVersion: 1;
|
|
42
|
+
reportId: string;
|
|
43
|
+
createdAt: string;
|
|
44
|
+
pluginVersion: string;
|
|
45
|
+
os: { platform: string; release: string; arch: string };
|
|
46
|
+
node: string;
|
|
47
|
+
locale: string;
|
|
48
|
+
profile: string;
|
|
49
|
+
taskName?: string;
|
|
50
|
+
description: string;
|
|
51
|
+
contactEmail?: string;
|
|
52
|
+
redactedLogs?: string;
|
|
53
|
+
metrics?: Record<string, number>;
|
|
54
|
+
/** Honeypot: боты заполняют, человек — никогда. Приёмник молча дропает. */
|
|
55
|
+
website?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Входные данные для сборки payload. */
|
|
59
|
+
export interface FeedbackBuildInput {
|
|
60
|
+
description: string;
|
|
61
|
+
taskName?: string;
|
|
62
|
+
contactEmail?: string;
|
|
63
|
+
redactedLogs?: string;
|
|
64
|
+
metrics?: Record<string, number>;
|
|
65
|
+
locale?: string;
|
|
66
|
+
profile?: string;
|
|
67
|
+
reportId?: string;
|
|
68
|
+
now?: Date;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Окружение, подставляемое в payload (легко подменить в тестах). */
|
|
72
|
+
export interface FeedbackBuildEnv {
|
|
73
|
+
platform?: string;
|
|
74
|
+
release?: string;
|
|
75
|
+
arch?: string;
|
|
76
|
+
node?: string;
|
|
77
|
+
pluginVersion?: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Результат отправки. */
|
|
81
|
+
export interface FeedbackSendResult {
|
|
82
|
+
ok: boolean;
|
|
83
|
+
reportId: string;
|
|
84
|
+
attempts: number;
|
|
85
|
+
issueUrl?: string;
|
|
86
|
+
error?: string;
|
|
87
|
+
status?: number;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Результат высокоуровневой обработки report_bug. */
|
|
91
|
+
export interface FeedbackReportResult {
|
|
92
|
+
success: boolean;
|
|
93
|
+
reportId: string;
|
|
94
|
+
destination: FeedbackDestination;
|
|
95
|
+
mode: "sent" | "dryRun" | "outbox" | "duplicate" | "local";
|
|
96
|
+
preview?: string;
|
|
97
|
+
error?: string;
|
|
98
|
+
author?: FeedbackSendResult;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
interface OutboxRow {
|
|
102
|
+
id: string;
|
|
103
|
+
report_id: string;
|
|
104
|
+
payload_json: string;
|
|
105
|
+
attempts: number;
|
|
106
|
+
last_error: string | null;
|
|
107
|
+
created_at: string;
|
|
108
|
+
last_attempt_at: string | null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
interface AntispamRow {
|
|
112
|
+
at: string;
|
|
113
|
+
hash: string;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
type FetchLike = (url: string, init?: Record<string, unknown>) => Promise<{
|
|
117
|
+
ok: boolean;
|
|
118
|
+
status: number;
|
|
119
|
+
text: () => Promise<string>;
|
|
120
|
+
}>;
|
|
121
|
+
|
|
122
|
+
export function makeReportId(): string {
|
|
123
|
+
return crypto.randomUUID();
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Стабильный хеш описания для антиспама (без самого текста в БД). */
|
|
127
|
+
export function descriptionHash(description: string): string {
|
|
128
|
+
return crypto.createHash("sha256").update(description.trim().toLowerCase()).digest("hex");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Редакция секретов и приватных данных (F-1.4).
|
|
133
|
+
*
|
|
134
|
+
* Порядок важен: сначала Known-паттерны токенов, затем явные значения из
|
|
135
|
+
* manage_secrets (после — home и email). Возвращает plaintext, пригодный
|
|
136
|
+
* для включения в payload; при dryRun ничего не уходит по сети.
|
|
137
|
+
*/
|
|
138
|
+
export function redactText(
|
|
139
|
+
text: string,
|
|
140
|
+
options: { secrets?: string[]; home?: string; redactEmails?: boolean } = {},
|
|
141
|
+
): string {
|
|
142
|
+
let out = String(text ?? "");
|
|
143
|
+
const known: [RegExp, string][] = [
|
|
144
|
+
[/\bgh[pousr]_[A-Za-z0-9]{20,}/g, "[REDACTED:github]"],
|
|
145
|
+
[/\bgithub_pat_[A-Za-z0-9_]{20,}/g, "[REDACTED:github]"],
|
|
146
|
+
[/\bsk-[A-Za-z0-9_-]{16,}/g, "[REDACTED:openai]"],
|
|
147
|
+
[/\bxox[baprs]-[A-Za-z0-9-]{10,}/g, "[REDACTED:slack]"],
|
|
148
|
+
[/\b\d{8,}:[A-Za-z0-9_-]{30,}/g, "[REDACTED:bot]"],
|
|
149
|
+
[/\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi, "Bearer [REDACTED]"],
|
|
150
|
+
[/\bAKIA[0-9A-Z]{16}\b/g, "[REDACTED:aws]"],
|
|
151
|
+
];
|
|
152
|
+
for (const [re, replacement] of known) out = out.replace(re, replacement);
|
|
153
|
+
|
|
154
|
+
const secrets = (options.secrets ?? []).filter((v) => v.length >= 4);
|
|
155
|
+
secrets.sort((a, b) => b.length - a.length);
|
|
156
|
+
for (const secret of secrets) {
|
|
157
|
+
out = out.split(secret).join("[REDACTED:secret]");
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const home = options.home ?? os.homedir();
|
|
161
|
+
if (home && home.length > 2) {
|
|
162
|
+
out = out.split(home).join("~");
|
|
163
|
+
// Windows-пути часто приходят с прямыми слешами.
|
|
164
|
+
out = out.split(home.replace(/\\/g, "/")).join("~");
|
|
165
|
+
}
|
|
166
|
+
if (options.redactEmails !== false) {
|
|
167
|
+
out = out.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "[EMAIL]");
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function clamp(value: string | undefined, max: number): string | undefined {
|
|
173
|
+
if (!value) return undefined;
|
|
174
|
+
const trimmed = value.trim();
|
|
175
|
+
if (!trimmed) return undefined;
|
|
176
|
+
return trimmed.length > max ? `${trimmed.slice(0, max - 1)}…` : trimmed;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Собирает payload по контракту F-1.1. Никакой сети — только данные. */
|
|
180
|
+
export function buildFeedbackPayload(
|
|
181
|
+
input: FeedbackBuildInput,
|
|
182
|
+
env: FeedbackBuildEnv = {},
|
|
183
|
+
): FeedbackPayload {
|
|
184
|
+
const now = input.now ?? new Date();
|
|
185
|
+
const payload: FeedbackPayload = {
|
|
186
|
+
schemaVersion: FEEDBACK_SCHEMA_VERSION,
|
|
187
|
+
reportId: input.reportId ?? makeReportId(),
|
|
188
|
+
createdAt: now.toISOString(),
|
|
189
|
+
pluginVersion: clamp(env.pluginVersion ?? getPluginVersion(), 64) ?? "unknown",
|
|
190
|
+
os: {
|
|
191
|
+
platform: clamp(env.platform ?? os.platform(), 64) ?? "unknown",
|
|
192
|
+
release: clamp(env.release ?? os.release(), 128) ?? "unknown",
|
|
193
|
+
arch: clamp(env.arch ?? os.arch(), 32) ?? "unknown",
|
|
194
|
+
},
|
|
195
|
+
node: clamp(env.node ?? process.version, 64) ?? "unknown",
|
|
196
|
+
locale: clamp(input.locale, 16) ?? "ru",
|
|
197
|
+
profile: clamp(input.profile, 64) ?? "default",
|
|
198
|
+
description: clamp(input.description, FEEDBACK_LIMITS.description) ?? "",
|
|
199
|
+
};
|
|
200
|
+
const taskName = clamp(input.taskName, FEEDBACK_LIMITS.taskName);
|
|
201
|
+
if (taskName) payload.taskName = taskName;
|
|
202
|
+
const contactEmail = clamp(input.contactEmail, FEEDBACK_LIMITS.contactEmail);
|
|
203
|
+
if (contactEmail) payload.contactEmail = contactEmail;
|
|
204
|
+
const redactedLogs = clamp(input.redactedLogs, FEEDBACK_LIMITS.logs);
|
|
205
|
+
if (redactedLogs) payload.redactedLogs = redactedLogs;
|
|
206
|
+
if (input.metrics && Object.keys(input.metrics).length > 0) payload.metrics = input.metrics;
|
|
207
|
+
return payload;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Валидация URL приёмника (F-1.3): только http(s), без встроенных учётных
|
|
212
|
+
* данных (username/password) и без фрагмента. http разрешён только для
|
|
213
|
+
* localhost (разработка).
|
|
214
|
+
*/
|
|
215
|
+
export function validateFeedbackEndpoint(raw: string): { ok: boolean; reason?: string } {
|
|
216
|
+
const value = (raw ?? "").trim();
|
|
217
|
+
if (!value) return { ok: false, reason: "endpoint is empty" };
|
|
218
|
+
let url: URL;
|
|
219
|
+
try {
|
|
220
|
+
url = new URL(value);
|
|
221
|
+
} catch {
|
|
222
|
+
return { ok: false, reason: "endpoint is not a valid URL" };
|
|
223
|
+
}
|
|
224
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
225
|
+
return { ok: false, reason: "only http(s) endpoint is allowed" };
|
|
226
|
+
}
|
|
227
|
+
if (url.protocol === "http:" && !["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)) {
|
|
228
|
+
return { ok: false, reason: "http is allowed only for localhost" };
|
|
229
|
+
}
|
|
230
|
+
if (url.username || url.password) {
|
|
231
|
+
return { ok: false, reason: "endpoint must not contain credentials" };
|
|
232
|
+
}
|
|
233
|
+
if (url.hash) return { ok: false, reason: "endpoint must not contain a fragment" };
|
|
234
|
+
if (value.length > 2048) return { ok: false, reason: "endpoint is too long" };
|
|
235
|
+
return { ok: true };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Красивый preview payload для dryRun и окна подтверждения (F-3.1). */
|
|
239
|
+
export function buildReportPreview(payload: FeedbackPayload): string {
|
|
240
|
+
const lines = [
|
|
241
|
+
"=== FEEDBACK PAYLOAD (dryRun — ничего не отправлено) ===",
|
|
242
|
+
`schemaVersion: ${payload.schemaVersion}`,
|
|
243
|
+
`reportId: ${payload.reportId}`,
|
|
244
|
+
`createdAt: ${payload.createdAt}`,
|
|
245
|
+
`pluginVersion: ${payload.pluginVersion}`,
|
|
246
|
+
`os: ${payload.os.platform} ${payload.os.release} ${payload.os.arch}`,
|
|
247
|
+
`node: ${payload.node}`,
|
|
248
|
+
`locale: ${payload.locale}`,
|
|
249
|
+
`profile: ${payload.profile}`,
|
|
250
|
+
];
|
|
251
|
+
if (payload.taskName) lines.push(`taskName: ${payload.taskName}`);
|
|
252
|
+
lines.push(`description: ${payload.description}`);
|
|
253
|
+
if (payload.contactEmail) lines.push(`contactEmail: ${payload.contactEmail}`);
|
|
254
|
+
if (payload.redactedLogs) lines.push(`redactedLogs (${payload.redactedLogs.length} chars): ${payload.redactedLogs}`);
|
|
255
|
+
if (payload.metrics) lines.push(`metrics: ${JSON.stringify(payload.metrics)}`);
|
|
256
|
+
return lines.join("\n");
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function sleep(ms: number): Promise<void> {
|
|
260
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Одна попытка POST с таймаутом (F-1.2). */
|
|
264
|
+
export async function sendFeedbackOnce(
|
|
265
|
+
payload: FeedbackPayload,
|
|
266
|
+
endpoint: string,
|
|
267
|
+
fetchImpl: FetchLike = globalThis.fetch,
|
|
268
|
+
): Promise<FeedbackSendResult> {
|
|
269
|
+
const controller = new AbortController();
|
|
270
|
+
const timer = setTimeout(() => controller.abort(), FEEDBACK_TIMEOUT_MS);
|
|
271
|
+
try {
|
|
272
|
+
const response = await fetchImpl(endpoint, {
|
|
273
|
+
method: "POST",
|
|
274
|
+
headers: {
|
|
275
|
+
"content-type": "application/json",
|
|
276
|
+
"user-agent": `agent-steward/${payload.pluginVersion}`,
|
|
277
|
+
"x-report-id": payload.reportId,
|
|
278
|
+
},
|
|
279
|
+
body: JSON.stringify(payload),
|
|
280
|
+
signal: controller.signal,
|
|
281
|
+
});
|
|
282
|
+
const body = await response.text();
|
|
283
|
+
let parsed: { issueUrl?: string; error?: string } = {};
|
|
284
|
+
try {
|
|
285
|
+
parsed = JSON.parse(body) as { issueUrl?: string; error?: string };
|
|
286
|
+
} catch {
|
|
287
|
+
// Не JSON — считаем ошибкой, textual body не логируем целиком (PII).
|
|
288
|
+
}
|
|
289
|
+
return {
|
|
290
|
+
ok: response.ok,
|
|
291
|
+
reportId: payload.reportId,
|
|
292
|
+
attempts: 1,
|
|
293
|
+
status: response.status,
|
|
294
|
+
issueUrl: typeof parsed.issueUrl === "string" ? parsed.issueUrl : undefined,
|
|
295
|
+
error: response.ok ? undefined : (parsed.error ?? `HTTP ${response.status}`),
|
|
296
|
+
};
|
|
297
|
+
} catch (err) {
|
|
298
|
+
return {
|
|
299
|
+
ok: false,
|
|
300
|
+
reportId: payload.reportId,
|
|
301
|
+
attempts: 1,
|
|
302
|
+
error: err instanceof Error ? err.message : String(err),
|
|
303
|
+
};
|
|
304
|
+
} finally {
|
|
305
|
+
clearTimeout(timer);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** POST с 2 ретраями и экспоненциальным backoff (F-1.2). */
|
|
310
|
+
export async function sendFeedbackWithRetry(
|
|
311
|
+
payload: FeedbackPayload,
|
|
312
|
+
endpoint: string,
|
|
313
|
+
options: { retries?: number; baseDelayMs?: number; sleepFn?: (ms: number) => Promise<void>; fetchImpl?: FetchLike } = {},
|
|
314
|
+
): Promise<FeedbackSendResult> {
|
|
315
|
+
const retries = options.retries ?? FEEDBACK_MAX_RETRIES;
|
|
316
|
+
const delay = options.baseDelayMs ?? FEEDBACK_BACKOFF_MS;
|
|
317
|
+
const sleepFn = options.sleepFn ?? sleep;
|
|
318
|
+
let last: FeedbackSendResult = {
|
|
319
|
+
ok: false,
|
|
320
|
+
reportId: payload.reportId,
|
|
321
|
+
attempts: 0,
|
|
322
|
+
error: "no attempt made",
|
|
323
|
+
};
|
|
324
|
+
for (let attempt = 0; attempt <= retries; attempt++) {
|
|
325
|
+
last = await sendFeedbackOnce(payload, endpoint, options.fetchImpl);
|
|
326
|
+
last.attempts = attempt + 1;
|
|
327
|
+
if (last.ok) return last;
|
|
328
|
+
// 4xx (кроме 429) — ошибка контракта, повтор не поможет.
|
|
329
|
+
if (last.status && last.status >= 400 && last.status < 500 && last.status !== 429) break;
|
|
330
|
+
if (attempt < retries) await sleepFn(delay * 2 ** attempt);
|
|
331
|
+
}
|
|
332
|
+
return last;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/* ------------------------------------------------------------------ */
|
|
336
|
+
/* Outbox (F-1.6) */
|
|
337
|
+
/* ------------------------------------------------------------------ */
|
|
338
|
+
|
|
339
|
+
export function enqueueOutbox(payload: FeedbackPayload): void {
|
|
340
|
+
const db = getDb();
|
|
341
|
+
db.prepare(
|
|
342
|
+
`INSERT OR IGNORE INTO feedback_outbox
|
|
343
|
+
(id, report_id, payload_json, attempts, created_at)
|
|
344
|
+
VALUES (?, ?, ?, 0, ?)`,
|
|
345
|
+
).run(
|
|
346
|
+
payload.reportId,
|
|
347
|
+
payload.reportId,
|
|
348
|
+
JSON.stringify(payload),
|
|
349
|
+
new Date().toISOString(),
|
|
350
|
+
);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
export function listOutbox(limit = 20): OutboxRow[] {
|
|
354
|
+
return getDb()
|
|
355
|
+
.prepare(
|
|
356
|
+
"SELECT id, report_id, payload_json, attempts, last_error, created_at, last_attempt_at FROM feedback_outbox ORDER BY created_at ASC LIMIT ?",
|
|
357
|
+
)
|
|
358
|
+
.all(limit) as OutboxRow[];
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function deleteOutbox(reportId: string): void {
|
|
362
|
+
getDb().prepare("DELETE FROM feedback_outbox WHERE report_id = ?").run(reportId);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function recordOutboxAttempt(reportId: string, error: string): void {
|
|
366
|
+
const row = getDb()
|
|
367
|
+
.prepare("SELECT attempts FROM feedback_outbox WHERE report_id = ?")
|
|
368
|
+
.get(reportId) as { attempts?: number } | undefined;
|
|
369
|
+
const attempts = (row?.attempts ?? 0) + 1;
|
|
370
|
+
if (attempts >= FEEDBACK_OUTBOX_MAX_ATTEMPTS) {
|
|
371
|
+
deleteOutbox(reportId);
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
getDb()
|
|
375
|
+
.prepare("UPDATE feedback_outbox SET attempts = ?, last_error = ?, last_attempt_at = ? WHERE report_id = ?")
|
|
376
|
+
.run(attempts, error.slice(0, 500), new Date().toISOString(), reportId);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Повтор outbox при старте плагина. Никогда не бросает наружу. */
|
|
380
|
+
export async function flushOutbox(
|
|
381
|
+
settings: FeedbackSettings,
|
|
382
|
+
options: { fetchImpl?: FetchLike; sleepFn?: (ms: number) => Promise<void> } = {},
|
|
383
|
+
): Promise<{ processed: number; sent: number }> {
|
|
384
|
+
if (!settings.enabled || !validateFeedbackEndpoint(settings.endpoint).ok) {
|
|
385
|
+
return { processed: 0, sent: 0 };
|
|
386
|
+
}
|
|
387
|
+
let processed = 0;
|
|
388
|
+
let sent = 0;
|
|
389
|
+
for (const row of listOutbox(20)) {
|
|
390
|
+
let payload: FeedbackPayload;
|
|
391
|
+
try {
|
|
392
|
+
payload = JSON.parse(row.payload_json) as FeedbackPayload;
|
|
393
|
+
} catch {
|
|
394
|
+
deleteOutbox(row.report_id);
|
|
395
|
+
continue;
|
|
396
|
+
}
|
|
397
|
+
processed++;
|
|
398
|
+
const result = await sendFeedbackWithRetry(payload, settings.endpoint, {
|
|
399
|
+
retries: 0,
|
|
400
|
+
sleepFn: options.sleepFn,
|
|
401
|
+
fetchImpl: options.fetchImpl,
|
|
402
|
+
});
|
|
403
|
+
if (result.ok) {
|
|
404
|
+
deleteOutbox(row.report_id);
|
|
405
|
+
sent++;
|
|
406
|
+
} else {
|
|
407
|
+
recordOutboxAttempt(row.report_id, result.error ?? "unknown error");
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return { processed, sent };
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/* ------------------------------------------------------------------ */
|
|
414
|
+
/* Антиспам (F-1.7) */
|
|
415
|
+
/* ------------------------------------------------------------------ */
|
|
416
|
+
|
|
417
|
+
/** Решение антиспама по истории отправок. Чистая функция. */
|
|
418
|
+
export function evaluateAntispam(
|
|
419
|
+
records: AntispamRow[],
|
|
420
|
+
description: string,
|
|
421
|
+
now: Date,
|
|
422
|
+
maxPerHour = FEEDBACK_MAX_PER_HOUR,
|
|
423
|
+
): { allowed: boolean; reason?: "duplicate" | "rate_limited" } {
|
|
424
|
+
const hash = descriptionHash(description);
|
|
425
|
+
const hourAgo = now.getTime() - 60 * 60_000;
|
|
426
|
+
const windowAgo = now.getTime() - FEEDBACK_ANTISPAM_WINDOW_MS;
|
|
427
|
+
const recent = records.filter((r) => {
|
|
428
|
+
const at = Date.parse(r.at);
|
|
429
|
+
return Number.isFinite(at) && at >= hourAgo;
|
|
430
|
+
});
|
|
431
|
+
if (recent.some((r) => r.hash === hash && Date.parse(r.at) >= windowAgo)) {
|
|
432
|
+
return { allowed: false, reason: "duplicate" };
|
|
433
|
+
}
|
|
434
|
+
if (recent.length >= maxPerHour) return { allowed: false, reason: "rate_limited" };
|
|
435
|
+
return { allowed: true };
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export function recordFeedbackSent(payload: FeedbackPayload): void {
|
|
439
|
+
getDb()
|
|
440
|
+
.prepare("INSERT INTO feedback_spam (hash, at) VALUES (?, ?)")
|
|
441
|
+
.run(descriptionHash(payload.description), payload.createdAt);
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function recentAntispam(now: Date): AntispamRow[] {
|
|
445
|
+
return getDb()
|
|
446
|
+
.prepare("SELECT at, hash FROM feedback_spam WHERE at >= ? ORDER BY at DESC LIMIT 200")
|
|
447
|
+
.all(new Date(now.getTime() - 60 * 60_000).toISOString()) as AntispamRow[];
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/* ------------------------------------------------------------------ */
|
|
451
|
+
/* Оркестрация (F-1.5) */
|
|
452
|
+
/* ------------------------------------------------------------------ */
|
|
453
|
+
|
|
454
|
+
export interface ReportFeedbackOptions {
|
|
455
|
+
settings: FeedbackSettings;
|
|
456
|
+
destination: FeedbackDestination;
|
|
457
|
+
dryRun?: boolean;
|
|
458
|
+
description: string;
|
|
459
|
+
taskName?: string;
|
|
460
|
+
contactEmail?: string;
|
|
461
|
+
redactedLogs?: string;
|
|
462
|
+
metrics?: Record<string, number>;
|
|
463
|
+
locale?: string;
|
|
464
|
+
profile?: string;
|
|
465
|
+
now?: Date;
|
|
466
|
+
secrets?: string[];
|
|
467
|
+
home?: string;
|
|
468
|
+
/** Локальная отправка в каналы репортищего (destination local/both). */
|
|
469
|
+
sendLocal?: (text: string) => Promise<{ success: boolean; message: string }>;
|
|
470
|
+
localText?: string;
|
|
471
|
+
fetchImpl?: FetchLike;
|
|
472
|
+
sleepFn?: (ms: number) => Promise<void>;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Точка входа для report_bug (F-1.5).
|
|
477
|
+
*
|
|
478
|
+
* - dryRun — только preview, сеть не трогается;
|
|
479
|
+
* - author — POST на приёмник; при ошибке fail-open → outbox;
|
|
480
|
+
* - local — старые каналы уведомлений (+ outbox как страховка);
|
|
481
|
+
* - both — и приёмник, и локальные каналы.
|
|
482
|
+
*
|
|
483
|
+
* Если приёмник не настроен или отключён, destination=author деградирует
|
|
484
|
+
* до local (fail-open), что честно отражается в `mode`.
|
|
485
|
+
*/
|
|
486
|
+
export async function reportFeedback(
|
|
487
|
+
options: ReportFeedbackOptions,
|
|
488
|
+
): Promise<FeedbackReportResult> {
|
|
489
|
+
const now = options.now ?? new Date();
|
|
490
|
+
const logRedactOptions = {
|
|
491
|
+
secrets: options.secrets,
|
|
492
|
+
home: options.home,
|
|
493
|
+
redactEmails: true,
|
|
494
|
+
};
|
|
495
|
+
const descRedactOptions = { ...logRedactOptions, redactEmails: false };
|
|
496
|
+
const redactedLogs = options.redactedLogs
|
|
497
|
+
? redactText(options.redactedLogs, logRedactOptions)
|
|
498
|
+
: undefined;
|
|
499
|
+
const payload = buildFeedbackPayload(
|
|
500
|
+
{
|
|
501
|
+
description: redactText(options.description, descRedactOptions),
|
|
502
|
+
taskName: options.taskName,
|
|
503
|
+
contactEmail: options.contactEmail,
|
|
504
|
+
redactedLogs,
|
|
505
|
+
metrics: options.metrics,
|
|
506
|
+
locale: options.locale,
|
|
507
|
+
profile: options.profile,
|
|
508
|
+
now,
|
|
509
|
+
},
|
|
510
|
+
{},
|
|
511
|
+
);
|
|
512
|
+
|
|
513
|
+
if (options.dryRun) {
|
|
514
|
+
return {
|
|
515
|
+
success: true,
|
|
516
|
+
reportId: payload.reportId,
|
|
517
|
+
destination: options.destination,
|
|
518
|
+
mode: "dryRun",
|
|
519
|
+
preview: buildReportPreview(payload),
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
const antispam = evaluateAntispam(
|
|
524
|
+
recentAntispam(now),
|
|
525
|
+
payload.description,
|
|
526
|
+
now,
|
|
527
|
+
options.settings.maxPerHour,
|
|
528
|
+
);
|
|
529
|
+
if (!antispam.allowed) {
|
|
530
|
+
return {
|
|
531
|
+
success: true,
|
|
532
|
+
reportId: payload.reportId,
|
|
533
|
+
destination: options.destination,
|
|
534
|
+
mode: "duplicate",
|
|
535
|
+
error: antispam.reason,
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
const endpointOk = options.settings.enabled && validateFeedbackEndpoint(options.settings.endpoint).ok;
|
|
540
|
+
const wantAuthor = options.destination === "author" || options.destination === "both";
|
|
541
|
+
const wantLocal = options.destination === "local" || options.destination === "both" || !endpointOk;
|
|
542
|
+
|
|
543
|
+
let author: FeedbackSendResult | undefined;
|
|
544
|
+
let mode: FeedbackReportResult["mode"] = "local";
|
|
545
|
+
let success = true;
|
|
546
|
+
|
|
547
|
+
if (wantAuthor) {
|
|
548
|
+
author = await sendFeedbackWithRetry(payload, options.settings.endpoint, {
|
|
549
|
+
fetchImpl: options.fetchImpl,
|
|
550
|
+
sleepFn: options.sleepFn,
|
|
551
|
+
});
|
|
552
|
+
if (author.ok) {
|
|
553
|
+
mode = "sent";
|
|
554
|
+
recordFeedbackSent(payload);
|
|
555
|
+
} else {
|
|
556
|
+
mode = "outbox";
|
|
557
|
+
success = false;
|
|
558
|
+
enqueueOutbox(payload);
|
|
559
|
+
}
|
|
560
|
+
} else {
|
|
561
|
+
// Нет рабочего приёмника — сохраняем отчёт локально, чтобы не потерять.
|
|
562
|
+
enqueueOutbox(payload);
|
|
563
|
+
recordFeedbackSent(payload);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
if (wantLocal && options.sendLocal && options.localText) {
|
|
567
|
+
const localResult = await options.sendLocal(options.localText);
|
|
568
|
+
if (!localResult.success && mode !== "sent") {
|
|
569
|
+
success = false;
|
|
570
|
+
}
|
|
571
|
+
if (mode === "local") mode = author?.ok ? "sent" : "local";
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
return {
|
|
575
|
+
success,
|
|
576
|
+
reportId: payload.reportId,
|
|
577
|
+
destination: options.destination,
|
|
578
|
+
mode,
|
|
579
|
+
author,
|
|
580
|
+
error: author?.error,
|
|
581
|
+
};
|
|
582
|
+
}
|