copilot-operator 0.1.51 → 0.1.53
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 +24 -3
- package/dist/src/api/operator.controller.js +55 -71
- package/dist/src/api/operator.service.js +243 -109
- package/dist/src/config/schema.js +45 -0
- package/dist/src/exec/policy.js +11 -1
- package/dist/src/exec/scriptFiles.js +108 -2
- package/dist/src/orchestrator/leadRunner.js +605 -0
- package/dist/src/orchestrator/review.js +9 -3
- package/dist/src/orchestrator/taskRunner.js +110 -20
- package/dist/src/plan/kerrigan.js +203 -47
- package/dist/src/plan/systemGuide.js +555 -499
- package/dist/src/protocol/leadSchema.js +156 -0
- package/dist/src/protocol/parser.js +1 -1
- package/dist/src/session/chatNotice.js +115 -0
- package/dist/src/session/checkpoint.js +19 -0
- package/dist/src/session/compose.js +17 -5
- package/dist/src/session/store.js +21 -72
- package/dist/src/transport/copilotTransport.js +2 -0
- package/dist/src/util/pacing.js +33 -2
- package/dist/src/vcs/git.js +11 -1
- package/dist/src/vcs/referenceGuard.js +299 -0
- package/dist/web/404.html +14 -18
- package/dist/web/_next/static/FGzV3mVZpXRCVjiw1diNu/_buildManifest.js +1 -0
- package/dist/web/_next/static/chunks/163.980c5145848efbdf.js +1 -0
- package/dist/web/_next/static/chunks/220.447d1d8624d4644c.js +1 -0
- package/dist/web/_next/static/chunks/500-34d01f8d8d73eb2c.js +1 -0
- package/dist/web/_next/static/chunks/548.c6dfd1cb270f3c93.js +1 -0
- package/dist/web/_next/static/chunks/584.fc9e061dd4069406.js +1 -0
- package/dist/web/_next/static/chunks/67.1a3ca07919abce27.js +1 -0
- package/dist/web/_next/static/chunks/714.5b2e291a430adc9c.js +1 -0
- package/dist/web/_next/static/chunks/747.157732b5b3f3c435.js +1 -0
- package/dist/web/_next/static/chunks/77.d478a6f2eafe31e3.js +1 -0
- package/dist/web/_next/static/chunks/921-b2219533c5a6e38f.js +1 -0
- package/dist/web/_next/static/chunks/app/defaults/page-b7e4e94a55e65806.js +1 -0
- package/dist/web/_next/static/chunks/app/layout-2b3718748721c1ac.js +1 -0
- package/dist/web/_next/static/chunks/app/page-59b9867b52914a6c.js +1 -0
- package/dist/web/_next/static/chunks/app/system/page-1cf9e75e76da59ed.js +1 -0
- package/dist/web/_next/static/chunks/webpack-0c3cad1f3181d857.js +1 -0
- package/dist/web/_next/static/css/06f314fa5fccd68d.css +1 -0
- package/dist/web/defaults.html +14 -18
- package/dist/web/defaults.txt +9 -9
- package/dist/web/index.html +14 -18
- package/dist/web/index.txt +9 -9
- package/dist/web/system.html +14 -18
- package/dist/web/system.txt +9 -9
- package/package.json +8 -5
- package/prompts/lead1.md +116 -0
- package/prompts/level1.md +32 -12
- package/prompts/review1.md +287 -286
- package/dist/src/vcs/prepareFromRemote.js +0 -288
- package/dist/src/vcs/remoteAuth.js +0 -117
- package/dist/src/vcs/syncCommand.js +0 -97
- package/dist/web/_next/static/chunks/190-70555f20dd0da19b.js +0 -1
- package/dist/web/_next/static/chunks/643-e85d221d57900ed7.js +0 -1
- package/dist/web/_next/static/chunks/867-869900ec999e6345.js +0 -1
- package/dist/web/_next/static/chunks/app/appearance/page-cdef33c421397cbe.js +0 -1
- package/dist/web/_next/static/chunks/app/defaults/page-e0a2b8f9a41a94c4.js +0 -1
- package/dist/web/_next/static/chunks/app/layout-b4fc21e26e1bad95.js +0 -1
- package/dist/web/_next/static/chunks/app/level1/page-31b74cae86d960d8.js +0 -1
- package/dist/web/_next/static/chunks/app/page-1075921d44db3e4d.js +0 -1
- package/dist/web/_next/static/chunks/app/presets/page-f8abdd83cdf468f7.js +0 -1
- package/dist/web/_next/static/chunks/app/system/page-2a270bb885885821.js +0 -1
- package/dist/web/_next/static/chunks/webpack-0f31b926d9a9c5a4.js +0 -1
- package/dist/web/_next/static/css/8b14cb3cf0051138.css +0 -1
- package/dist/web/_next/static/eqTUTH_SJtBgNgq8Zzy3n/_buildManifest.js +0 -1
- package/dist/web/appearance.html +0 -18
- package/dist/web/appearance.txt +0 -25
- package/dist/web/level1.html +0 -18
- package/dist/web/level1.txt +0 -25
- package/dist/web/presets.html +0 -21
- package/dist/web/presets.txt +0 -25
- /package/dist/web/_next/static/{eqTUTH_SJtBgNgq8Zzy3n → FGzV3mVZpXRCVjiw1diNu}/_ssgManifest.js +0 -0
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The lead's contract, as a schema (operator, 2026-10-20: "two chats — chat A takes the whole, complex task, breaks it
|
|
3
|
+
* into steps and directs; chat B carries out the small technical tasks and reports back").
|
|
4
|
+
*
|
|
5
|
+
* The prose the lead is given is `prompts/lead1.md`; this is the enforcement. The lead never runs anything: its replies
|
|
6
|
+
* say what to do next — give the worker a subtask, propose the plan, ask the operator, deliver the result, or stop —
|
|
7
|
+
* and anything that does not validate here is sent back with the reason, as a worker's reply in the wrong shape is.
|
|
8
|
+
* Lenient where nothing runs on it: a list that came as one string, an answer that came as an object (the fields of a
|
|
9
|
+
* bug report, say) are read as the text they mean rather than refused.
|
|
10
|
+
*/
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { findJsonCandidates, stripCitations, stripLineNumbers } from './parser.js';
|
|
13
|
+
import { MIN_SUMMARY_CHARS, PlanSchema } from './replySchema.js';
|
|
14
|
+
/** A value that is meant as prose, in whatever shape it came: an object or a list is written out as text. */
|
|
15
|
+
export function proseOfValue(value, depth = 0) {
|
|
16
|
+
if (value === undefined || value === null)
|
|
17
|
+
return '';
|
|
18
|
+
if (typeof value === 'string')
|
|
19
|
+
return value;
|
|
20
|
+
if (typeof value === 'number' || typeof value === 'boolean')
|
|
21
|
+
return String(value);
|
|
22
|
+
const pad = ' '.repeat(depth);
|
|
23
|
+
if (Array.isArray(value)) {
|
|
24
|
+
return value
|
|
25
|
+
.map((v) => {
|
|
26
|
+
const text = proseOfValue(v, depth + 1);
|
|
27
|
+
return text.includes('\n') ? `${pad}- ${text.trimStart()}` : `${pad}- ${text}`;
|
|
28
|
+
})
|
|
29
|
+
.join('\n');
|
|
30
|
+
}
|
|
31
|
+
// An object's fields, each on its line in the order they came: "**Title**: …".
|
|
32
|
+
return Object.entries(value)
|
|
33
|
+
.map(([k, v]) => {
|
|
34
|
+
const text = proseOfValue(v, depth + 1);
|
|
35
|
+
return typeof v === 'object' && v !== null ? `${pad}**${k}**:\n${text}` : `${pad}**${k}**: ${text}`;
|
|
36
|
+
})
|
|
37
|
+
.join('\n');
|
|
38
|
+
}
|
|
39
|
+
const prose = z.preprocess((v) => (v === undefined ? undefined : proseOfValue(v)), z.string().optional());
|
|
40
|
+
const proseList = z.preprocess((v) => v === undefined
|
|
41
|
+
? []
|
|
42
|
+
: typeof v === 'string'
|
|
43
|
+
? v.split(/\r?\n/).map((l) => l.replace(/^\s*(?:\d+[.)]|[-*•])\s+/, '').trim()).filter(Boolean)
|
|
44
|
+
: Array.isArray(v)
|
|
45
|
+
? v.map((x) => proseOfValue(x)).filter((x) => x.trim() !== '')
|
|
46
|
+
: [proseOfValue(v)], z.array(z.string()));
|
|
47
|
+
/** One subtask for the worker: what it is to find out or do, what it needs to know, and what to report back. */
|
|
48
|
+
export const SubtaskSchema = z.object({
|
|
49
|
+
title: z.preprocess((v) => proseOfValue(v), z.string().trim().min(3, 'subtask.title must name the subtask in a few words.').max(140)),
|
|
50
|
+
goal: z.preprocess((v) => proseOfValue(v), z.string().trim().min(15, 'subtask.goal must say what the worker is to find out or do, in a sentence or more.')),
|
|
51
|
+
context: prose.default(''),
|
|
52
|
+
steps: proseList.default([]),
|
|
53
|
+
report: z.preprocess((v) => proseOfValue(v), z.string().trim().min(10, 'subtask.report must say what the worker reports back to you, and in which shape.')),
|
|
54
|
+
doneWhen: prose.default(''),
|
|
55
|
+
readOnly: z.boolean().default(false),
|
|
56
|
+
freshWorker: z.boolean().default(false),
|
|
57
|
+
});
|
|
58
|
+
export const LeadReplySchema = z
|
|
59
|
+
.object({
|
|
60
|
+
/**
|
|
61
|
+
* What the lead does next.
|
|
62
|
+
*
|
|
63
|
+
* `delegate` — give the worker this subtask (`subtask`). `plan` — the plan of the whole assignment (`plan`), for the
|
|
64
|
+
* operator to approve when they approve plans. `ask` — a question only the operator can answer (`question`).
|
|
65
|
+
* `done` — the result, in the form the assignment asked for (`answer`). `blocked` — it cannot be taken further
|
|
66
|
+
* without the operator (`summary`, `needed`).
|
|
67
|
+
*/
|
|
68
|
+
status: z.enum(['delegate', 'plan', 'ask', 'done', 'blocked']),
|
|
69
|
+
understanding: prose,
|
|
70
|
+
notes: prose,
|
|
71
|
+
plan: PlanSchema.optional(),
|
|
72
|
+
subtask: SubtaskSchema.optional(),
|
|
73
|
+
question: prose,
|
|
74
|
+
why: prose,
|
|
75
|
+
options: proseList.default([]),
|
|
76
|
+
answer: prose,
|
|
77
|
+
evidence: proseList.default([]),
|
|
78
|
+
summary: prose,
|
|
79
|
+
needed: prose,
|
|
80
|
+
})
|
|
81
|
+
.refine((r) => r.status !== 'delegate' || !!r.subtask, {
|
|
82
|
+
message: 'status "delegate" requires a "subtask": {"title", "goal", "context", "steps", "report", "doneWhen", "readOnly", "freshWorker"}.',
|
|
83
|
+
})
|
|
84
|
+
.refine((r) => r.status !== 'plan' || !!r.plan, {
|
|
85
|
+
message: 'status "plan" requires a "plan": {"existing", "approach", "steps": [the stages], "files", "verification", "risks"}.',
|
|
86
|
+
})
|
|
87
|
+
.refine((r) => r.status !== 'ask' || (r.question ?? '').trim().length >= 10, {
|
|
88
|
+
message: 'status "ask" requires a "question" for the operator: what only a person can decide, said in full.',
|
|
89
|
+
})
|
|
90
|
+
.refine((r) => r.status !== 'done' || (r.answer ?? '').trim().length >= MIN_SUMMARY_CHARS, {
|
|
91
|
+
message: 'status "done" requires an "answer": the result, in the form the assignment asked for, in full.',
|
|
92
|
+
})
|
|
93
|
+
.refine((r) => r.status !== 'blocked' || (r.summary ?? '').trim().length >= MIN_SUMMARY_CHARS, {
|
|
94
|
+
message: 'status "blocked" requires a "summary": what was done and found, with its evidence, so the work can be picked up.',
|
|
95
|
+
})
|
|
96
|
+
.refine((r) => r.status !== 'blocked' || (r.needed ?? '').trim().length > 0, {
|
|
97
|
+
message: 'status "blocked" requires "needed": what would let the work go on.',
|
|
98
|
+
});
|
|
99
|
+
/** The lead's reply, found, validated and cleaned of citation markers. */
|
|
100
|
+
export function parseLeadReply(markdown) {
|
|
101
|
+
const candidates = findJsonCandidates(markdown);
|
|
102
|
+
if (candidates.length === 0) {
|
|
103
|
+
return { ok: false, reason: 'no-json-block', detail: 'The reply contained no fenced ```json block and no JSON object at all.' };
|
|
104
|
+
}
|
|
105
|
+
const errors = [];
|
|
106
|
+
const paths = new Set();
|
|
107
|
+
for (const raw of candidates) {
|
|
108
|
+
for (const text of [raw, stripLineNumbers(raw)]) {
|
|
109
|
+
let value;
|
|
110
|
+
try {
|
|
111
|
+
value = JSON.parse(text);
|
|
112
|
+
}
|
|
113
|
+
catch (e) {
|
|
114
|
+
errors.push(`JSON.parse failed: ${e.message}`);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const result = LeadReplySchema.safeParse(value);
|
|
118
|
+
if (!result.success) {
|
|
119
|
+
errors.push(result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; '));
|
|
120
|
+
for (const i of result.error.issues)
|
|
121
|
+
paths.add(i.path.join('.') || '(root)');
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
const r = result.data;
|
|
125
|
+
const clean = (s) => stripCitations(s)?.trim() || undefined;
|
|
126
|
+
return {
|
|
127
|
+
ok: true,
|
|
128
|
+
reply: { ...r, understanding: clean(r.understanding), notes: clean(r.notes), answer: clean(r.answer), summary: clean(r.summary), question: clean(r.question) },
|
|
129
|
+
json: text.trim(),
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return { ok: false, reason: 'invalid-json', detail: errors.slice(0, 4).join(' | '), ...(paths.size > 0 ? { paths: [...paths] } : {}) };
|
|
134
|
+
}
|
|
135
|
+
const LEAD_EXAMPLE = [
|
|
136
|
+
'```json',
|
|
137
|
+
'{"status": "delegate", "notes": "what you decide and why", "subtask": {"title": "Run the tests", "goal": "Find out which tests fail now.", "context": "Change nothing.", "steps": [], "report": "The totals, and for each failing test its name and its error, quoted.", "doneWhen": "The suite ran once.", "readOnly": true, "freshWorker": false}}',
|
|
138
|
+
'```',
|
|
139
|
+
'or {"status": "plan", "plan": {"existing": "…", "approach": "…", "steps": ["…"], "files": [], "verification": "…"}}',
|
|
140
|
+
'or {"status": "ask", "question": "…", "why": "…", "options": ["…", "…"]}',
|
|
141
|
+
'or {"status": "done", "answer": "the result, in the form asked for", "evidence": ["…"]}',
|
|
142
|
+
'or {"status": "blocked", "summary": "what was done and found", "needed": "what would let it go on"}',
|
|
143
|
+
].join('\n');
|
|
144
|
+
/** The message that asks the lead for the same answer again, in the format. */
|
|
145
|
+
export function leadFormatErrorMessage(fail, attempt, maxAttempts) {
|
|
146
|
+
return [
|
|
147
|
+
`Your last reply did not match the lead's format (format retry ${attempt} of ${maxAttempts}).`,
|
|
148
|
+
fail.reason === 'no-json-block' ? 'There was no fenced json code block in it.' : `The json block did not validate: ${fail.detail}`,
|
|
149
|
+
'Only the format is wrong: nothing from that reply was acted on. Send the same answer again, reformatted, as exactly one fenced code block tagged json. For example:',
|
|
150
|
+
LEAD_EXAMPLE,
|
|
151
|
+
].join('\n');
|
|
152
|
+
}
|
|
153
|
+
/** A first reply without the assignment restated. */
|
|
154
|
+
export const UNDERSTANDING_FIRST = 'Before anything else, restate the assignment in "understanding": the goal, the result to deliver and its exact form ' +
|
|
155
|
+
'(every field asked for), the constraints, and how you will know it is done. Send your reply again with it; nothing ' +
|
|
156
|
+
'from the last one was acted on.';
|
|
@@ -31,7 +31,7 @@ export function stripLineNumbers(body) {
|
|
|
31
31
|
return body;
|
|
32
32
|
return lines.filter((l) => !/^\s*\d+\s*$/.test(l)).join('\n');
|
|
33
33
|
}
|
|
34
|
-
function findJsonCandidates(markdown) {
|
|
34
|
+
export function findJsonCandidates(markdown) {
|
|
35
35
|
const blocks = extractFencedBlocks(markdown);
|
|
36
36
|
const out = [];
|
|
37
37
|
for (const b of blocks) {
|
|
@@ -31,7 +31,121 @@ const WORDS = {
|
|
|
31
31
|
ok: 'ОК',
|
|
32
32
|
quote: (s) => `„${s}“`,
|
|
33
33
|
},
|
|
34
|
+
de: {
|
|
35
|
+
done: 'Die Aufgabe ist erledigt',
|
|
36
|
+
stopped: 'Die Aufgabe wurde angehalten',
|
|
37
|
+
failed: 'Die Aufgabe wurde nicht abgeschlossen',
|
|
38
|
+
notStarted: 'Die Aufgabe konnte nicht beginnen',
|
|
39
|
+
doneLine: 'Copilot hat sie abgeschlossen. Was getan wurde, steht im Chat von copilot-operator.',
|
|
40
|
+
stoppedLine: 'Sie wurde angehalten; es wird nichts mehr gesendet.',
|
|
41
|
+
blockedLine: 'Copilot konnte sie nicht abschließen',
|
|
42
|
+
failedLine: 'Sie endete mit einem Fehler',
|
|
43
|
+
limitLine: 'Sie hielt an einer Grenze aus den Einstellungen an',
|
|
44
|
+
notStartedLine: 'Es wurde nichts gesendet',
|
|
45
|
+
statusOf: { done: 'erledigt', aborted: 'angehalten', blocked: 'blockiert', failed: 'fehlgeschlagen', 'limit-reached': 'an einer Grenze', queued: 'nicht begonnen' },
|
|
46
|
+
keep: 'Dieses Fenster bleibt für Ihre nächste Nachricht geöffnet. Sie können es jederzeit schließen.',
|
|
47
|
+
ok: 'OK',
|
|
48
|
+
quote: (s) => `„${s}“`,
|
|
49
|
+
},
|
|
50
|
+
es: {
|
|
51
|
+
done: 'La tarea se ha completado',
|
|
52
|
+
stopped: 'La tarea se ha detenido',
|
|
53
|
+
failed: 'La tarea terminó sin completarse',
|
|
54
|
+
notStarted: 'La tarea no pudo empezar',
|
|
55
|
+
doneLine: 'Copilot la ha terminado. Lo que se hizo está en el chat de copilot-operator.',
|
|
56
|
+
stoppedLine: 'Se ha detenido; no se envía nada más.',
|
|
57
|
+
blockedLine: 'Copilot no pudo terminarla',
|
|
58
|
+
failedLine: 'Terminó con un error',
|
|
59
|
+
limitLine: 'Se detuvo en un límite de la configuración',
|
|
60
|
+
notStartedLine: 'No se envió nada',
|
|
61
|
+
statusOf: { done: 'completada', aborted: 'detenida', blocked: 'bloqueada', failed: 'con error', 'limit-reached': 'en un límite', queued: 'sin empezar' },
|
|
62
|
+
keep: 'Esta ventana sigue abierta para su próximo mensaje. Puede cerrarla en cualquier momento.',
|
|
63
|
+
ok: 'Aceptar',
|
|
64
|
+
quote: (s) => `«${s}»`,
|
|
65
|
+
},
|
|
66
|
+
fr: {
|
|
67
|
+
done: 'La tâche est terminée',
|
|
68
|
+
stopped: 'La tâche a été arrêtée',
|
|
69
|
+
failed: 'La tâche s’est terminée inachevée',
|
|
70
|
+
notStarted: 'La tâche n’a pas pu démarrer',
|
|
71
|
+
doneLine: 'Copilot l’a terminée. Ce qui a été fait se trouve dans le chat de copilot-operator.',
|
|
72
|
+
stoppedLine: 'Elle a été arrêtée ; plus rien n’est envoyé.',
|
|
73
|
+
blockedLine: 'Copilot n’a pas pu la terminer',
|
|
74
|
+
failedLine: 'Elle s’est terminée par une erreur',
|
|
75
|
+
limitLine: 'Elle s’est arrêtée à une limite des paramètres',
|
|
76
|
+
notStartedLine: 'Rien n’a été envoyé',
|
|
77
|
+
statusOf: { done: 'terminée', aborted: 'arrêtée', blocked: 'bloquée', failed: 'en erreur', 'limit-reached': 'à une limite', queued: 'non démarrée' },
|
|
78
|
+
keep: 'Cette fenêtre reste ouverte pour votre prochain message. Vous pouvez la fermer à tout moment.',
|
|
79
|
+
ok: 'OK',
|
|
80
|
+
quote: (s) => `« ${s} »`,
|
|
81
|
+
},
|
|
82
|
+
pt: {
|
|
83
|
+
done: 'A tarefa está concluída',
|
|
84
|
+
stopped: 'A tarefa foi parada',
|
|
85
|
+
failed: 'A tarefa terminou por concluir',
|
|
86
|
+
notStarted: 'A tarefa não pôde começar',
|
|
87
|
+
doneLine: 'O Copilot concluiu-a. O que foi feito está no chat do copilot-operator.',
|
|
88
|
+
stoppedLine: 'Foi parada; não é enviado mais nada.',
|
|
89
|
+
blockedLine: 'O Copilot não conseguiu concluí-la',
|
|
90
|
+
failedLine: 'Terminou com um erro',
|
|
91
|
+
limitLine: 'Parou num limite das definições',
|
|
92
|
+
notStartedLine: 'Nada foi enviado',
|
|
93
|
+
statusOf: { done: 'concluída', aborted: 'parada', blocked: 'bloqueada', failed: 'com erro', 'limit-reached': 'num limite', queued: 'não iniciada' },
|
|
94
|
+
keep: 'Esta janela fica aberta para a sua próxima mensagem. Pode fechá-la a qualquer momento.',
|
|
95
|
+
ok: 'OK',
|
|
96
|
+
quote: (s) => `«${s}»`,
|
|
97
|
+
},
|
|
98
|
+
ja: {
|
|
99
|
+
done: 'タスクが完了しました',
|
|
100
|
+
stopped: 'タスクを停止しました',
|
|
101
|
+
failed: 'タスクは未完了のまま終了しました',
|
|
102
|
+
notStarted: 'タスクを開始できませんでした',
|
|
103
|
+
doneLine: 'Copilot がタスクを完了しました。行われた内容は copilot-operator のチャットにあります。',
|
|
104
|
+
stoppedLine: '停止しました。これ以上は何も送信されません。',
|
|
105
|
+
blockedLine: 'Copilot はタスクを完了できませんでした',
|
|
106
|
+
failedLine: 'エラーで終了しました',
|
|
107
|
+
limitLine: '設定の上限で停止しました',
|
|
108
|
+
notStartedLine: '何も送信されませんでした',
|
|
109
|
+
statusOf: { done: '完了', aborted: '停止', blocked: 'ブロック', failed: 'エラー', 'limit-reached': '上限で停止', queued: '未開始' },
|
|
110
|
+
keep: 'このウィンドウは次のメッセージのために開いたままです。いつでも閉じることができます。',
|
|
111
|
+
ok: 'OK',
|
|
112
|
+
quote: (s) => `「${s}」`,
|
|
113
|
+
},
|
|
114
|
+
ko: {
|
|
115
|
+
done: '작업이 완료되었습니다',
|
|
116
|
+
stopped: '작업이 중지되었습니다',
|
|
117
|
+
failed: '작업이 완료되지 않은 채 끝났습니다',
|
|
118
|
+
notStarted: '작업을 시작할 수 없었습니다',
|
|
119
|
+
doneLine: 'Copilot이 작업을 마쳤습니다. 수행된 내용은 copilot-operator 채팅에 있습니다.',
|
|
120
|
+
stoppedLine: '중지되었습니다. 더 이상 아무것도 보내지 않습니다.',
|
|
121
|
+
blockedLine: 'Copilot이 작업을 마치지 못했습니다',
|
|
122
|
+
failedLine: '오류로 끝났습니다',
|
|
123
|
+
limitLine: '설정의 한도에서 멈췄습니다',
|
|
124
|
+
notStartedLine: '아무것도 보내지 않았습니다',
|
|
125
|
+
statusOf: { done: '완료', aborted: '중지됨', blocked: '차단됨', failed: '오류', 'limit-reached': '한도 도달', queued: '시작 안 됨' },
|
|
126
|
+
keep: '이 창은 다음 메시지를 위해 열려 있습니다. 언제든지 닫을 수 있습니다.',
|
|
127
|
+
ok: '확인',
|
|
128
|
+
quote: (s) => `‘${s}’`,
|
|
129
|
+
},
|
|
130
|
+
ar: {
|
|
131
|
+
done: 'اكتملت المهمة',
|
|
132
|
+
stopped: 'تم إيقاف المهمة',
|
|
133
|
+
failed: 'انتهت المهمة دون إكمالها',
|
|
134
|
+
notStarted: 'تعذّر بدء المهمة',
|
|
135
|
+
doneLine: 'أنهى Copilot المهمة. ما تم إنجازه موجود في دردشة copilot-operator.',
|
|
136
|
+
stoppedLine: 'تم إيقافها؛ لن يُرسل أي شيء آخر.',
|
|
137
|
+
blockedLine: 'لم يتمكن Copilot من إنهائها',
|
|
138
|
+
failedLine: 'انتهت بخطأ',
|
|
139
|
+
limitLine: 'توقفت عند حد من الإعدادات',
|
|
140
|
+
notStartedLine: 'لم يُرسل أي شيء',
|
|
141
|
+
statusOf: { done: 'مكتملة', aborted: 'متوقفة', blocked: 'محظورة', failed: 'بخطأ', 'limit-reached': 'عند حد', queued: 'لم تبدأ' },
|
|
142
|
+
keep: 'تبقى هذه النافذة مفتوحة لرسالتك التالية. يمكنك إغلاقها في أي وقت.',
|
|
143
|
+
ok: 'موافق',
|
|
144
|
+
quote: (s) => `«${s}»`,
|
|
145
|
+
},
|
|
34
146
|
};
|
|
147
|
+
/** The languages written right to left: the card is drawn that way for them. */
|
|
148
|
+
const RIGHT_TO_LEFT = new Set(['ar']);
|
|
35
149
|
/** A reason as a line: its first sentence or so, since the whole of it is in the chat. */
|
|
36
150
|
function brief(text, max = 220) {
|
|
37
151
|
const one = (text ?? '').replace(/\s+/g, ' ').trim();
|
|
@@ -72,5 +186,6 @@ export function chatNotice(lang, tasks, error) {
|
|
|
72
186
|
...(subject ? { subject } : {}),
|
|
73
187
|
lines,
|
|
74
188
|
button: w.ok,
|
|
189
|
+
...(RIGHT_TO_LEFT.has(lang) ? { dir: 'rtl' } : {}),
|
|
75
190
|
};
|
|
76
191
|
}
|
|
@@ -63,6 +63,25 @@ export async function takeAfter(dir, id, before) {
|
|
|
63
63
|
const r = await photograph(dir, `refs/copilot-operator/after/${id}`, `after message ${id}`, before.commit);
|
|
64
64
|
return 'problem' in r ? r : { commit: r.commit };
|
|
65
65
|
}
|
|
66
|
+
/**
|
|
67
|
+
* The files a message has changed so far: the folder photographed now, against its checkpoint (for the review of a
|
|
68
|
+
* chat message, 2026-10-20). The photograph is let go of afterwards; the one taken when the message ends is kept.
|
|
69
|
+
*/
|
|
70
|
+
export async function changedSince(dir, before, id) {
|
|
71
|
+
const ref = `refs/copilot-operator/review/${id}`;
|
|
72
|
+
const r = await photograph(dir, ref, `the folder during the review of ${id}`, before.commit);
|
|
73
|
+
if ('problem' in r)
|
|
74
|
+
throw new Error(r.problem);
|
|
75
|
+
try {
|
|
76
|
+
const diff = await git(dir, ['diff', '--name-only', '--no-renames', before.commit, r.commit]);
|
|
77
|
+
if (!diff.ok)
|
|
78
|
+
throw new Error(diff.stderr);
|
|
79
|
+
return diff.stdout.split('\n').map((l) => l.trim()).filter(Boolean);
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
await git(dir, ['update-ref', '-d', ref]).catch(() => undefined);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
66
85
|
/**
|
|
67
86
|
* Puts the folder back as `cp` photographed it: its branch checked out at its commit, its working tree with the
|
|
68
87
|
* same uncommitted changes. The folder as it is now is photographed first, under `refs/copilot-operator/safety/`.
|
|
@@ -25,7 +25,7 @@ const TASK_HEADER = '## Task';
|
|
|
25
25
|
* and a note that is empty simply leaves nothing behind.
|
|
26
26
|
*/
|
|
27
27
|
function runnerBlock(input) {
|
|
28
|
-
const notes = [input.workDirNote, input.readOnlyNote, input.scopeNote, input.approachesNote, input.vcsNote, input.shellNote, input.planNote, input.operatorNotes].map((n) => (n ?? '').trim()).filter((n) => n.length > 0);
|
|
28
|
+
const notes = [input.workDirNote, input.readOnlyNote, input.referenceNote, input.scopeNote, input.approachesNote, input.vcsNote, input.shellNote, input.planNote, input.operatorNotes].map((n) => (n ?? '').trim()).filter((n) => n.length > 0);
|
|
29
29
|
return notes.length > 0 ? `${notes.join('\n\n')}\n\n` : '';
|
|
30
30
|
}
|
|
31
31
|
/**
|
|
@@ -39,7 +39,7 @@ export function readOnlyNote(commits, artifacts = []) {
|
|
|
39
39
|
'This task must not change any file: it reads, runs and reports. The runner fails it if it',
|
|
40
40
|
'changed the working tree, whatever the summary says' +
|
|
41
41
|
(commits ? ", and commits the change on the task's branch so it is not lost." : '. Nothing is committed in this session, so a change would stay in the working tree.'),
|
|
42
|
-
'
|
|
42
|
+
'Scratch files may go in `.cop-tmp`, which is not part of the project; nothing in it is run.' +
|
|
43
43
|
(artifacts.length > 0 ? ` A report or other evidence goes under ${artifacts.join(', ')}: kept with the run, never committed, and the one place this task may write.` : ''),
|
|
44
44
|
"This rule wins over any instruction above — the project's or the persona's — to change code. If a review",
|
|
45
45
|
'finding asks you to change something, that is a finding about the task, not about the work: dispute it',
|
|
@@ -48,6 +48,18 @@ export function readOnlyNote(commits, artifacts = []) {
|
|
|
48
48
|
}
|
|
49
49
|
/** The note for a session that commits: see `readOnlyNote`. */
|
|
50
50
|
export const READ_ONLY_NOTE = readOnlyNote(true);
|
|
51
|
+
/**
|
|
52
|
+
* The operator's skill for this kind of task (2026-10-21), right before the task: how this kind of work is done in
|
|
53
|
+
* their projects — where things go, the conventions, the steps, how it is checked. Empty when there is none.
|
|
54
|
+
*/
|
|
55
|
+
export function skillBlock(skill) {
|
|
56
|
+
if (!skill || !skill.text.trim())
|
|
57
|
+
return '';
|
|
58
|
+
return (`\n\n## Skill: ${skill.name}\n\n` +
|
|
59
|
+
(skill.description.trim() ? `For: ${skill.description.trim()}\n\n` : '') +
|
|
60
|
+
`The operator's instructions for this kind of task. Follow them where they apply; they add to the contract above ` +
|
|
61
|
+
`and cannot change it.\n\n${skill.text.trim()}`);
|
|
62
|
+
}
|
|
51
63
|
function level2Block(level2) {
|
|
52
64
|
const body = level2.trim();
|
|
53
65
|
return body.length > 0
|
|
@@ -65,7 +77,7 @@ function level2Block(level2) {
|
|
|
65
77
|
* failed, that the files are as its work left them, and — after the bot stopped under it — which of
|
|
66
78
|
* the steps it had just asked for actually ran.
|
|
67
79
|
*/
|
|
68
|
-
function whyItStopped(c) {
|
|
80
|
+
export function whyItStopped(c) {
|
|
69
81
|
if (c.how === 'failed')
|
|
70
82
|
return describeEnding(c.fromAttempt, c.ended, c.stoppedBecause);
|
|
71
83
|
if (c.how === 'interrupted') {
|
|
@@ -174,7 +186,7 @@ export function composeOpening(input) {
|
|
|
174
186
|
`\n\n${instructionSection(instruction.text)}`
|
|
175
187
|
: '';
|
|
176
188
|
if (!input.contractAlreadySent) {
|
|
177
|
-
const taskMessage = `${runnerBlock(input)}${level2Block(input.level2)}\n\n${taskBlock}${continuationLine}`;
|
|
189
|
+
const taskMessage = `${runnerBlock(input)}${level2Block(input.level2)}${skillBlock(input.skill)}\n\n${taskBlock}${continuationLine}`;
|
|
178
190
|
return {
|
|
179
191
|
messages: [input.level1.trim(), taskMessage],
|
|
180
192
|
firstMessage: `${input.level1.trim()}\n\n---\n\n${taskMessage}`,
|
|
@@ -183,6 +195,6 @@ export function composeOpening(input) {
|
|
|
183
195
|
const reminder = `New task in this same conversation. The level 1 contract you received at the start of ` +
|
|
184
196
|
`this conversation still applies unchanged: same format, same rules, same stop word, ` +
|
|
185
197
|
`and a full "summary" when you finish. Step numbering restarts at 1.`;
|
|
186
|
-
const taskMessage = `${reminder}\n\n${runnerBlock(input)}${level2Block(input.level2)}\n\n${taskBlock}${continuationLine}`;
|
|
198
|
+
const taskMessage = `${reminder}\n\n${runnerBlock(input)}${level2Block(input.level2)}${skillBlock(input.skill)}\n\n${taskBlock}${continuationLine}`;
|
|
187
199
|
return { messages: [taskMessage], firstMessage: taskMessage };
|
|
188
200
|
}
|
|
@@ -8,9 +8,8 @@
|
|
|
8
8
|
* at once cannot fail each other or undo each other's change.
|
|
9
9
|
*/
|
|
10
10
|
import { mkdir, readFile, writeFile, readdir, rename, rm } from 'node:fs/promises';
|
|
11
|
-
import { existsSync } from 'node:fs';
|
|
12
11
|
import { randomUUID } from 'node:crypto';
|
|
13
|
-
import { join, resolve } from 'node:path';
|
|
12
|
+
import { dirname, join, resolve } from 'node:path';
|
|
14
13
|
import { endingOf, isContinuable, MAX_INSTRUCTION_CHARS, newId, tidyVcsPlan } from './model.js';
|
|
15
14
|
/** A task the runner is inside of. It cannot be edited, deleted, or left behind at startup. */
|
|
16
15
|
const ACTIVE_STATUSES = ['running', 'waiting-approval'];
|
|
@@ -113,6 +112,11 @@ export const TASK_FIELD_ON_RERUN = {
|
|
|
113
112
|
notes: 'kept',
|
|
114
113
|
// The folder before the message first ran: the point "go back" returns to, whatever attempt came after.
|
|
115
114
|
checkpoint: 'kept',
|
|
115
|
+
// The lead's rounds belong to the attempt that made them (two chats, 2026-10-20); which lead a subtask serves, to the task.
|
|
116
|
+
lead: 'archived',
|
|
117
|
+
fromLead: 'kept',
|
|
118
|
+
// The kind of task it is: every attempt is sent with the same skill.
|
|
119
|
+
skill: 'kept',
|
|
116
120
|
interruption: 'cleared',
|
|
117
121
|
finalReply: 'cleared',
|
|
118
122
|
firstMessage: 'cleared',
|
|
@@ -191,34 +195,28 @@ export class SessionStore {
|
|
|
191
195
|
defaultLevel1Path;
|
|
192
196
|
dir;
|
|
193
197
|
sessionsDir;
|
|
194
|
-
presetsDir;
|
|
195
|
-
level1Path;
|
|
196
198
|
modelsPath;
|
|
197
199
|
constructor(dataDir, defaultLevel1Path) {
|
|
198
200
|
this.defaultLevel1Path = defaultLevel1Path;
|
|
199
201
|
this.dir = resolve(dataDir);
|
|
200
202
|
this.sessionsDir = join(this.dir, 'sessions');
|
|
201
|
-
this.presetsDir = join(this.dir, 'level2');
|
|
202
|
-
this.level1Path = join(this.dir, 'level1.md');
|
|
203
203
|
this.modelsPath = join(this.dir, 'models.json');
|
|
204
204
|
}
|
|
205
205
|
async init() {
|
|
206
206
|
await mkdir(this.sessionsDir, { recursive: true });
|
|
207
|
-
await mkdir(this.presetsDir, { recursive: true });
|
|
208
207
|
}
|
|
209
208
|
// --- level 1 --------------------------------------------------------------------------
|
|
210
|
-
/**
|
|
209
|
+
/**
|
|
210
|
+
* The contract in force: the one that ships with the bot, always (operator, 2026-10-20: "it no longer needs changing;
|
|
211
|
+
* it changes at system level, when the bot is updated"). An edited copy an earlier version kept in the data folder
|
|
212
|
+
* (`level1.md` there) is not read any more, and the page that edited it is gone.
|
|
213
|
+
*/
|
|
211
214
|
async getLevel1() {
|
|
212
|
-
|
|
213
|
-
return { content: await readFile(this.level1Path, 'utf8'), customised: true };
|
|
214
|
-
}
|
|
215
|
-
return { content: await readFile(this.defaultLevel1Path, 'utf8'), customised: false };
|
|
215
|
+
return { content: await readFile(this.defaultLevel1Path, 'utf8') };
|
|
216
216
|
}
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
async resetLevel1() {
|
|
221
|
-
await removeFile(this.level1Path);
|
|
217
|
+
/** The lead's contract (two chats, 2026-10-20): `lead1.md`, beside the base prompt it ships with. */
|
|
218
|
+
async getLead1() {
|
|
219
|
+
return { content: await readFile(join(dirname(this.defaultLevel1Path), 'lead1.md'), 'utf8') };
|
|
222
220
|
}
|
|
223
221
|
// --- the model catalogue ----------------------------------------------------------------
|
|
224
222
|
/** What the chat's picker offered when it was last read, or null if it never was. */
|
|
@@ -233,38 +231,6 @@ export class SessionStore {
|
|
|
233
231
|
async saveModels(catalogue) {
|
|
234
232
|
await writeFileAtomically(this.modelsPath, JSON.stringify(catalogue, null, 2));
|
|
235
233
|
}
|
|
236
|
-
// --- level 2 presets ------------------------------------------------------------------
|
|
237
|
-
async listPresets() {
|
|
238
|
-
const names = (await readdir(this.presetsDir).catch(() => []))
|
|
239
|
-
.filter((n) => n.endsWith('.md'))
|
|
240
|
-
.sort();
|
|
241
|
-
const out = [];
|
|
242
|
-
for (const n of names) {
|
|
243
|
-
const path = join(this.presetsDir, n);
|
|
244
|
-
const content = await readFile(path, 'utf8');
|
|
245
|
-
const { mtime } = await import('node:fs').then((fs) => fs.statSync(path));
|
|
246
|
-
out.push({ name: n.slice(0, -3), content, updatedAt: mtime.toISOString() });
|
|
247
|
-
}
|
|
248
|
-
return out;
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Saves a preset under the name it can later be deleted by.
|
|
252
|
-
*
|
|
253
|
-
* Stripping the characters a file name cannot hold is not enough on its own: a leading dot and
|
|
254
|
-
* ".." survive it, and `safePresetName` refuses both, so ".env" and "a..b" were saved and then
|
|
255
|
-
* could never be deleted. The name goes through the same rule as the delete, so a name that could
|
|
256
|
-
* not be removed is refused here instead.
|
|
257
|
-
*/
|
|
258
|
-
async savePreset(name, content) {
|
|
259
|
-
const safe = name.replace(/[^\p{L}\p{N}._ -]/gu, '').trim();
|
|
260
|
-
if (!safe)
|
|
261
|
-
throw new Error('Preset name is empty after removing unsafe characters.');
|
|
262
|
-
await writeFileAtomically(join(this.presetsDir, `${safePresetName(safe)}.md`), content);
|
|
263
|
-
return { name: safe, content, updatedAt: new Date().toISOString() };
|
|
264
|
-
}
|
|
265
|
-
async deletePreset(name) {
|
|
266
|
-
await removeFile(await namedFile(this.presetsDir, name));
|
|
267
|
-
}
|
|
268
234
|
// --- sessions -------------------------------------------------------------------------
|
|
269
235
|
/**
|
|
270
236
|
* Every session, newest first — by when it was made, not by what it is called.
|
|
@@ -422,6 +388,7 @@ export class SessionStore {
|
|
|
422
388
|
// Stored only when it limits something: absent means anywhere, as before scopes existed.
|
|
423
389
|
...((input.scope ?? []).filter((p) => p.trim()).length > 0 ? { scope: (input.scope ?? []).map((p) => p.trim()).filter(Boolean) } : {}),
|
|
424
390
|
...((input.outputs ?? []).filter((p) => p.trim()).length > 0 ? { outputs: (input.outputs ?? []).map((p) => p.trim()).filter(Boolean) } : {}),
|
|
391
|
+
...(input.skill ? { skill: { name: input.skill.name, description: input.skill.description, text: input.skill.text } } : {}),
|
|
425
392
|
};
|
|
426
393
|
await this.updateSession(sessionId, (s) => {
|
|
427
394
|
s.tasks.push(task);
|
|
@@ -627,6 +594,8 @@ export class SessionStore {
|
|
|
627
594
|
vcs: t.vcs,
|
|
628
595
|
plan: t.plan,
|
|
629
596
|
accepted: t.accepted,
|
|
597
|
+
// Two chats: the lead's rounds and subtasks of this attempt (the next one counts its own from nothing).
|
|
598
|
+
lead: t.lead,
|
|
630
599
|
},
|
|
631
600
|
];
|
|
632
601
|
// An edit is applied only after the old attempt has been put beyond its reach.
|
|
@@ -661,6 +630,7 @@ export class SessionStore {
|
|
|
661
630
|
t.handoff = undefined;
|
|
662
631
|
t.plan = undefined;
|
|
663
632
|
t.accepted = undefined;
|
|
633
|
+
t.lead = undefined;
|
|
664
634
|
t.scopeReverted = undefined;
|
|
665
635
|
t.treeChanged = undefined;
|
|
666
636
|
t.inputsRestored = undefined;
|
|
@@ -842,25 +812,11 @@ async function replaceFile(path, content) {
|
|
|
842
812
|
}
|
|
843
813
|
}
|
|
844
814
|
}
|
|
845
|
-
/**
|
|
846
|
-
* The file a preset or persona of this name is kept in, for removing it.
|
|
847
|
-
*
|
|
848
|
-
* A name `safePresetName` accepts, or one that is already a file in the folder. The save did not
|
|
849
|
-
* always apply that rule, so a preset called ".env" or "a..b" may be on disk from before; without
|
|
850
|
-
* the second way it is listed and can never be deleted. A name matched against the folder's own
|
|
851
|
-
* listing is a file name, which cannot hold a separator, so it cannot reach outside the folder.
|
|
852
|
-
*/
|
|
853
|
-
async function namedFile(dir, name) {
|
|
854
|
-
const onDisk = await readdir(dir).catch(() => []);
|
|
855
|
-
if (onDisk.includes(`${name}.md`))
|
|
856
|
-
return join(dir, `${name}.md`);
|
|
857
|
-
return join(dir, `${safePresetName(name)}.md`);
|
|
858
|
-
}
|
|
859
815
|
/**
|
|
860
816
|
* A session id as it may appear in a file name, or an error.
|
|
861
817
|
*
|
|
862
|
-
* Ids
|
|
863
|
-
* /presets/:name` joined them straight into a path, and Express decodes `%5C` and `%2F`, so
|
|
818
|
+
* Ids arrive from URL parameters. Found on 2026-09-27: `DELETE /sessions/:id` and `DELETE
|
|
819
|
+
* /presets/:name` (the presets went on 2026-10-20) joined them straight into a path, and Express decodes `%5C` and `%2F`, so
|
|
864
820
|
* `..\..\<anything>` reached a `.json` or `.md` file anywhere the process could write. The ids this
|
|
865
821
|
* store makes are letters, digits, `-`, `_` and `.` (not leading); anything else is not one of them.
|
|
866
822
|
*/
|
|
@@ -870,10 +826,3 @@ export function safeName(value) {
|
|
|
870
826
|
}
|
|
871
827
|
return value;
|
|
872
828
|
}
|
|
873
|
-
/** A preset name as `savePreset` allows it — letters in any script, digits, space, `.`, `_`, `-` — never a path. */
|
|
874
|
-
export function safePresetName(value) {
|
|
875
|
-
if (!/^[\p{L}\p{N}_ -][\p{L}\p{N}._ -]{0,199}$/u.test(value) || value.includes('..')) {
|
|
876
|
-
throw new Error(`Not a valid preset name: ${JSON.stringify(value).slice(0, 80)}`);
|
|
877
|
-
}
|
|
878
|
-
return value;
|
|
879
|
-
}
|
|
@@ -371,6 +371,8 @@ export class CopilotTransport {
|
|
|
371
371
|
card.setAttribute('role', 'alertdialog');
|
|
372
372
|
card.setAttribute('aria-modal', 'true');
|
|
373
373
|
card.setAttribute('aria-labelledby', 'title');
|
|
374
|
+
if (n.dir)
|
|
375
|
+
card.setAttribute('dir', n.dir);
|
|
374
376
|
const h = document.createElement('h2');
|
|
375
377
|
h.id = 'title';
|
|
376
378
|
const mark = document.createElement('span');
|
package/dist/src/util/pacing.js
CHANGED
|
@@ -17,7 +17,24 @@
|
|
|
17
17
|
* against service-side throttling on long runs.
|
|
18
18
|
* - `backoffFor()` exponential backoff with jitter, so a failing step cannot turn into a
|
|
19
19
|
* tight retry loop.
|
|
20
|
+
* - the gap (operator, 2026-10-21) a pause the operator sets between two messages to Copilot, fixed or drawn
|
|
21
|
+
* anew each time between two bounds: kept by `throttleSend` across every pacer of the program, so the
|
|
22
|
+
* lead's message after the worker's waits as one after the lead's does.
|
|
20
23
|
*/
|
|
24
|
+
/** The settings' pause between messages, as `gapMs`; undefined when it is off. */
|
|
25
|
+
export function gapFrom(p) {
|
|
26
|
+
if (!p.gapEnabled)
|
|
27
|
+
return undefined;
|
|
28
|
+
const lo = Math.max(1, p.gapSec ?? 60) * 1000;
|
|
29
|
+
const hi = p.gapRandom ? Math.max(lo, Math.max(1, p.gapMaxSec ?? 90) * 1000) : lo;
|
|
30
|
+
return [lo, hi];
|
|
31
|
+
}
|
|
32
|
+
/** When the program last sent a message to Copilot: one window, one account, so one clock for every pacer. */
|
|
33
|
+
let lastSentAt = 0;
|
|
34
|
+
/** For the checks: as if nothing had been sent yet. */
|
|
35
|
+
export function forgetLastSend() {
|
|
36
|
+
lastSentAt = 0;
|
|
37
|
+
}
|
|
21
38
|
export const DEFAULT_PACING = {
|
|
22
39
|
enabled: true,
|
|
23
40
|
settleMs: 1_000,
|
|
@@ -57,6 +74,19 @@ export class Pacer {
|
|
|
57
74
|
* waited, so the caller can log a visible "throttled for N s".
|
|
58
75
|
*/
|
|
59
76
|
async throttleSend(signal) {
|
|
77
|
+
const stop = signal ?? this.profile.signal;
|
|
78
|
+
let gapWaited = 0;
|
|
79
|
+
// The operator's pause between two messages: from the last one the program sent, whichever pacer sent it.
|
|
80
|
+
if (this.profile.gapMs && lastSentAt > 0) {
|
|
81
|
+
const [lo, hi] = this.profile.gapMs;
|
|
82
|
+
const gap = lo + Math.round(this.rnd() * Math.max(0, hi - lo));
|
|
83
|
+
const wait = lastSentAt + gap - Date.now();
|
|
84
|
+
if (wait > 0) {
|
|
85
|
+
this.profile.onGap?.(wait);
|
|
86
|
+
await sleep(wait, stop);
|
|
87
|
+
gapWaited = wait;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
60
90
|
const hour = 3_600_000;
|
|
61
91
|
const now = Date.now();
|
|
62
92
|
while (this.sentAt.length && now - this.sentAt[0] > hour)
|
|
@@ -65,10 +95,11 @@ export class Pacer {
|
|
|
65
95
|
if (this.sentAt.length >= this.profile.maxMessagesPerHour) {
|
|
66
96
|
waited = this.sentAt[0] + hour - now;
|
|
67
97
|
if (waited > 0)
|
|
68
|
-
await sleep(waited,
|
|
98
|
+
await sleep(waited, stop);
|
|
69
99
|
}
|
|
70
100
|
this.sentAt.push(Date.now());
|
|
71
|
-
|
|
101
|
+
lastSentAt = Date.now();
|
|
102
|
+
return Math.max(waited, 0) + gapWaited;
|
|
72
103
|
}
|
|
73
104
|
/** Exponential backoff with jitter, for retries after a failure. */
|
|
74
105
|
backoffFor(attempt, baseMs = 2_000, capMs = 60_000) {
|
package/dist/src/vcs/git.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* - Nothing runs through a shell. `execFile` takes an argument list, so a branch name or a
|
|
16
16
|
* commit message cannot turn into another command.
|
|
17
17
|
*/
|
|
18
|
-
import { execFile } from 'node:child_process';
|
|
18
|
+
import { execFile, spawnSync } from 'node:child_process';
|
|
19
19
|
import { existsSync, statSync } from 'node:fs';
|
|
20
20
|
import { readFile, stat } from 'node:fs/promises';
|
|
21
21
|
import { createHash } from 'node:crypto';
|
|
@@ -78,6 +78,16 @@ opts = {}) {
|
|
|
78
78
|
}
|
|
79
79
|
});
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* One git command, synchronously, for the gate: it decides before a step starts, in a function with no await to give
|
|
83
|
+
* (see `exec/scriptFiles.ts`). Only reading commands go through it. Never throws: a git that is missing, fails or
|
|
84
|
+
* runs out of time is `ok: false`.
|
|
85
|
+
*/
|
|
86
|
+
export function gitSync(cwd, args, timeoutMs = 15_000) {
|
|
87
|
+
const r = spawnSync('git', [...SAFE_GIT, ...args], { cwd, timeout: timeoutMs, windowsHide: true, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024 });
|
|
88
|
+
const code = typeof r.status === 'number' ? r.status : 1;
|
|
89
|
+
return { ok: !r.error && code === 0, stdout: (r.stdout ?? '').trim(), stderr: (r.stderr ?? '').trim() || (r.error ? r.error.message : ''), code };
|
|
90
|
+
}
|
|
81
91
|
/**
|
|
82
92
|
* When this repository last fetched successfully, or undefined when that cannot be told.
|
|
83
93
|
*
|