copilot-operator 0.1.64 → 0.1.66
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/api/operator.controller.js +48 -0
- package/dist/src/api/operator.service.js +415 -53
- package/dist/src/exec/dangerous.js +12 -0
- package/dist/src/exec/runner.js +75 -2
- package/dist/src/exec/stepEnv.js +13 -2
- package/dist/src/orchestrator/taskRunner.js +12 -1
- package/dist/src/plan/kerrigan.js +32 -6
- package/dist/src/plan/systemGuide.js +136 -0
- package/dist/src/queue/queue.js +65 -4
- package/dist/src/queue/queueBranch.js +66 -0
- package/dist/src/session/compose.js +15 -0
- package/dist/src/session/store.js +4 -0
- package/dist/src/vcs/newBranch.js +241 -0
- package/dist/src/vcs/remoteAuth.js +119 -0
- package/dist/web/404.html +2 -2
- package/dist/web/_next/static/chunks/1024-444e9060299d04ba.js +1 -0
- package/dist/web/_next/static/chunks/1077.b88b069535f7008e.js +1 -0
- package/dist/web/_next/static/chunks/1548.9e01803e48173ea9.js +1 -0
- package/dist/web/_next/static/chunks/2163.018cd5f719ae4b3d.js +1 -0
- package/dist/web/_next/static/chunks/6262-d074473db83ee798.js +1 -0
- package/dist/web/_next/static/chunks/714.281f68f85df26013.js +1 -0
- package/dist/web/_next/static/chunks/7220.3bd10a3e4e053e0c.js +1 -0
- package/dist/web/_next/static/chunks/7921-1c173d00d23b3589.js +1 -0
- package/dist/web/_next/static/chunks/8124-bb544c96a7c0e7e3.js +1 -0
- package/dist/web/_next/static/chunks/8584.c7cd52c2e7075bcb.js +1 -0
- package/dist/web/_next/static/chunks/{9067.538dec4d8ec0b04e.js → 9067.feaf894390db1a88.js} +1 -1
- package/dist/web/_next/static/chunks/9747.7cee8a2d8301f25c.js +1 -0
- package/dist/web/_next/static/chunks/app/{layout-9201c637ca24b2c9.js → layout-5e0e7601702723bb.js} +1 -1
- package/dist/web/_next/static/chunks/app/page-95379244849623fc.js +1 -0
- package/dist/web/_next/static/chunks/app/queue/page-fb49cb2d3dc6d14c.js +1 -0
- package/dist/web/_next/static/chunks/{webpack-d85f02ecd2903252.js → webpack-5ea108bc2e386c55.js} +1 -1
- package/dist/web/_next/static/css/a112074f3d1a8a07.css +1 -0
- package/dist/web/defaults.html +2 -2
- package/dist/web/defaults.txt +8 -8
- package/dist/web/index.html +3 -3
- package/dist/web/index.txt +9 -9
- package/dist/web/queue.html +2 -2
- package/dist/web/queue.txt +9 -9
- package/dist/web/settings.html +2 -2
- package/dist/web/settings.txt +9 -9
- package/dist/web/system.html +2 -2
- package/dist/web/system.txt +9 -9
- package/package.json +4 -2
- package/dist/web/_next/static/chunks/1077.32bfff8490ea3d67.js +0 -1
- package/dist/web/_next/static/chunks/1548.2bbbbb4759fd5073.js +0 -1
- package/dist/web/_next/static/chunks/2163.147b0ca65a65d5dd.js +0 -1
- package/dist/web/_next/static/chunks/714.16070ca6426f260c.js +0 -1
- package/dist/web/_next/static/chunks/7220.f71047baa16e6be0.js +0 -1
- package/dist/web/_next/static/chunks/7921-90ed63bfdf7162f3.js +0 -1
- package/dist/web/_next/static/chunks/8124-5458b17433987fab.js +0 -1
- package/dist/web/_next/static/chunks/8584.abc09920f03375b1.js +0 -1
- package/dist/web/_next/static/chunks/9747.9d15583d6ebafba3.js +0 -1
- package/dist/web/_next/static/chunks/app/page-185efe80d6e8dd05.js +0 -1
- package/dist/web/_next/static/chunks/app/queue/page-d4155eb6ab172c03.js +0 -1
- package/dist/web/_next/static/css/d107848da2f006af.css +0 -1
- /package/dist/web/_next/static/{vU04zVwJyicqgtWQsApuV → BbWvNQTsh3pH7ZN_RKR60}/_buildManifest.js +0 -0
- /package/dist/web/_next/static/{vU04zVwJyicqgtWQsApuV → BbWvNQTsh3pH7ZN_RKR60}/_ssgManifest.js +0 -0
package/dist/src/queue/queue.js
CHANGED
|
@@ -12,12 +12,24 @@
|
|
|
12
12
|
* chat is told which it was;
|
|
13
13
|
* - a task may carry one of Settings' skills, sent with it as the chat's box sends one (2026-10-25);
|
|
14
14
|
* - a task added while something else works — a message of the chat, sent there directly — starts after it
|
|
15
|
-
* (2026-10-25): the queue waits for the browser to be free before it takes the next task
|
|
15
|
+
* (2026-10-25): the queue waits for the browser to be free before it takes the next task;
|
|
16
|
+
* - a task that waits for the operator longer than the queue allows — a plan to approve, a question, a command, a
|
|
17
|
+
* model to choose, a password — is set aside ("parked") with what it waits for kept, and the queue goes on with the
|
|
18
|
+
* next (2026-10-26). Answered later, it carries on from where it stopped, before the others waiting; the tasks that
|
|
19
|
+
* depend on it wait for it rather than being skipped. A task "on a new branch from main" has its branch made when it
|
|
20
|
+
* is added, brought up to the remote's main when it starts if nothing is on it yet.
|
|
16
21
|
*
|
|
17
22
|
* Kept as `data/queue.json` (see `OperatorService.queue`). This module is the part that needs no browser: the shape,
|
|
18
23
|
* the checks of an edit, and which task is next.
|
|
19
24
|
*/
|
|
20
25
|
import { branchExists } from '../vcs/git.js';
|
|
26
|
+
export const DEFAULT_PARK_AFTER_SEC = 120;
|
|
27
|
+
export const MAX_PARK_AFTER_SEC = 24 * 60 * 60;
|
|
28
|
+
/** How long a task waits for the operator before it is parked, in milliseconds; null: as long as it takes. */
|
|
29
|
+
export function parkAfterMs(q) {
|
|
30
|
+
const sec = typeof q.parkAfterSec === 'number' && Number.isFinite(q.parkAfterSec) ? Math.max(0, Math.min(MAX_PARK_AFTER_SEC, Math.round(q.parkAfterSec))) : DEFAULT_PARK_AFTER_SEC;
|
|
31
|
+
return sec === 0 ? null : sec * 1000;
|
|
32
|
+
}
|
|
21
33
|
export const MAX_QUEUE_ITEMS = 50;
|
|
22
34
|
export function emptyQueue() {
|
|
23
35
|
return { items: [], running: false, updatedAt: new Date().toISOString() };
|
|
@@ -54,7 +66,7 @@ export function checkItems(items, maxPromptChars) {
|
|
|
54
66
|
if (late)
|
|
55
67
|
return { problem: `Task ${n} depends on ${items.some((o) => o?.id === late) ? 'a task after it' : `"${late}", which is not in the queue`}: a task can depend only on tasks before it.` };
|
|
56
68
|
const branch = x.branch === 'main' ? 'main' : 'folder';
|
|
57
|
-
const status = typeof x.status === 'string' && ['waiting', 'running', 'done', 'failed', 'skipped', 'stopped'].includes(x.status) ? x.status : undefined;
|
|
69
|
+
const status = typeof x.status === 'string' && ['waiting', 'running', 'done', 'failed', 'skipped', 'stopped', 'parked'].includes(x.status) ? x.status : undefined;
|
|
58
70
|
const text = (v) => String(v ?? '').trim();
|
|
59
71
|
const name = text(x.name);
|
|
60
72
|
if (name.length > MAX_QUEUE_NAME)
|
|
@@ -75,6 +87,7 @@ export function checkItems(items, maxPromptChars) {
|
|
|
75
87
|
...(lead ? { lead: true } : {}),
|
|
76
88
|
...(lead && text(x.workerModel) ? { workerModel: text(x.workerModel) } : {}),
|
|
77
89
|
...(skill ? { skill } : {}),
|
|
90
|
+
...(x.plan === true ? { plan: true } : {}),
|
|
78
91
|
...(status ? { status } : {}),
|
|
79
92
|
});
|
|
80
93
|
seen.add(id);
|
|
@@ -99,8 +112,17 @@ export function mergeItems(current, edited) {
|
|
|
99
112
|
return { ...x, status: 'waiting' };
|
|
100
113
|
const again = x.status === 'waiting' && was.status !== 'waiting';
|
|
101
114
|
const given = asGiven(x);
|
|
115
|
+
// "Run again" starts it over, on a branch made for it again when it is one of its own.
|
|
102
116
|
if (again)
|
|
103
117
|
return { ...given, status: 'waiting' };
|
|
118
|
+
// A parked task keeps what it waits for; its answer is given on its card, not by an edit of the list.
|
|
119
|
+
if (was.status === 'parked')
|
|
120
|
+
return { ...was, ...given, status: 'parked' };
|
|
121
|
+
// Where it works changed: the branch made for it no longer is its.
|
|
122
|
+
if (was.branch !== given.branch) {
|
|
123
|
+
const { branchName: _name, branchBase: _base, ...rest } = was;
|
|
124
|
+
return { ...rest, ...given, status: was.status };
|
|
125
|
+
}
|
|
104
126
|
// What the runs gave it stays; what the operator gives it is the edit's, a field left out of it gone.
|
|
105
127
|
const kept = { ...was };
|
|
106
128
|
for (const key of GIVEN)
|
|
@@ -110,7 +132,7 @@ export function mergeItems(current, edited) {
|
|
|
110
132
|
return { items };
|
|
111
133
|
}
|
|
112
134
|
/** What the operator gives a task, apart from what its runs give it. */
|
|
113
|
-
const GIVEN = ['id', 'name', 'prompt', 'model', 'dependsOn', 'branch', 'review', 'reviewModel', 'lead', 'workerModel', 'skill'];
|
|
135
|
+
const GIVEN = ['id', 'name', 'prompt', 'model', 'dependsOn', 'branch', 'review', 'reviewModel', 'lead', 'workerModel', 'skill', 'plan'];
|
|
114
136
|
function asGiven(x) {
|
|
115
137
|
const out = {};
|
|
116
138
|
for (const key of GIVEN)
|
|
@@ -138,12 +160,20 @@ export function waitsByHand(item, copilot) {
|
|
|
138
160
|
*/
|
|
139
161
|
export function nextStep(items) {
|
|
140
162
|
const byId = new Map(items.map((x) => [x.id, x]));
|
|
163
|
+
// An answered parked task first (2026-10-26): it carries on from where it stopped, before the others waiting.
|
|
164
|
+
const resumed = items.find((x) => x.status === 'waiting' && x.resume);
|
|
165
|
+
if (resumed)
|
|
166
|
+
return { run: resumed };
|
|
141
167
|
for (const item of items) {
|
|
142
168
|
if (item.status !== 'waiting')
|
|
143
169
|
continue;
|
|
144
|
-
const
|
|
170
|
+
const needs = item.dependsOn.map((d) => byId.get(d));
|
|
171
|
+
const blocker = needs.find((d) => !d || d.status === 'failed' || d.status === 'skipped' || d.status === 'stopped');
|
|
145
172
|
if (blocker)
|
|
146
173
|
return { skip: item, because: blocker };
|
|
174
|
+
// One it needs is parked, or waits to carry on: this one waits for it, rather than being skipped.
|
|
175
|
+
if (needs.some((d) => d.status !== 'done'))
|
|
176
|
+
continue;
|
|
147
177
|
return { run: item };
|
|
148
178
|
}
|
|
149
179
|
return null;
|
|
@@ -164,3 +194,34 @@ export async function mainBranchOf(dir) {
|
|
|
164
194
|
return name;
|
|
165
195
|
return null;
|
|
166
196
|
}
|
|
197
|
+
/** What a parked task waits for, in the words the queue's page and its log use (2026-10-26). */
|
|
198
|
+
export const PARKED_WORDS = {
|
|
199
|
+
plan: 'its plan, to approve',
|
|
200
|
+
question: 'an answer to its question',
|
|
201
|
+
retry: 'what to do with a subtask that was cut off',
|
|
202
|
+
command: 'your word on a command',
|
|
203
|
+
model: 'the model, to be chosen by hand',
|
|
204
|
+
password: 'a password Git asked for',
|
|
205
|
+
};
|
|
206
|
+
/** The operator's answer to a parked task, held to what its card offered, or why it cannot be taken. */
|
|
207
|
+
export function parkedAnswerFrom(p, input) {
|
|
208
|
+
const text = (v) => (typeof v === 'string' ? v.trim() : '');
|
|
209
|
+
switch (p.kind) {
|
|
210
|
+
case 'plan':
|
|
211
|
+
if (input.decision === 'approve')
|
|
212
|
+
return { kind: 'plan', decision: 'approve', ...(text(input.note) ? { note: text(input.note) } : {}) };
|
|
213
|
+
if (input.decision === 'revise')
|
|
214
|
+
return text(input.note) ? { kind: 'plan', decision: 'revise', note: text(input.note) } : { problem: 'Say what to change in the plan.' };
|
|
215
|
+
return { problem: 'A plan is approved, or sent back for another.' };
|
|
216
|
+
case 'question':
|
|
217
|
+
return text(input.answer) ? { kind: 'question', answer: text(input.answer) } : { problem: 'Write the answer first.' };
|
|
218
|
+
case 'retry': {
|
|
219
|
+
const choices = p.approval.retry?.choices ?? [];
|
|
220
|
+
return typeof input.choice === 'string' && choices.includes(input.choice) ? { kind: 'retry', choice: input.choice } : { problem: `Choose one of: ${choices.join(', ')}.` };
|
|
221
|
+
}
|
|
222
|
+
case 'command':
|
|
223
|
+
return input.decision === 'run' || input.decision === 'skip' ? { kind: 'command', decision: input.decision } : { problem: 'A command is run or skipped.' };
|
|
224
|
+
default:
|
|
225
|
+
return { kind: 'resume' };
|
|
226
|
+
}
|
|
227
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A branch of its own for each task of the queue "on a new branch from main" (operator, 2026-10-26: "the branches are
|
|
3
|
+
* best made when the task is added to the queue, not when its turn comes; the bot knows which branch each chat works
|
|
4
|
+
* with, and changes to it when it goes from one task to another"). Made when the task is added — the operator is there
|
|
5
|
+
* to type a password if the remote asks for one, in Git's own window — at the remote's main as it is then; brought up
|
|
6
|
+
* to the remote's main when the task starts, if nothing has been done on it yet and the remote can be read without
|
|
7
|
+
* asking anybody. The run then works on it as an existing branch (`startFrom: 'existing-branch'`).
|
|
8
|
+
*/
|
|
9
|
+
import { branchNameFrom, freeBranchName, git, isAncestor } from '../vcs/git.js';
|
|
10
|
+
import { planNewBranch } from '../vcs/newBranch.js';
|
|
11
|
+
import { fetchAsOperator } from '../vcs/remoteAuth.js';
|
|
12
|
+
import { mainBranchOf } from './queue.js';
|
|
13
|
+
/** Fetches the remote's main once, through Git's window when it asks; for every branch made in one edit of the list. */
|
|
14
|
+
export async function branchStart(dir, askpass) {
|
|
15
|
+
const plan = await planNewBranch(dir, { fetch: true, askpass });
|
|
16
|
+
if (plan.ok && plan.targetCommit)
|
|
17
|
+
return { commit: plan.targetCommit, from: plan.target ?? 'origin/main', fetched: !!plan.fetched?.ok };
|
|
18
|
+
// No remote, or no main of it known: the local main, as a task "on a new branch from main" always had.
|
|
19
|
+
const local = await mainBranchOf(dir);
|
|
20
|
+
if (!local)
|
|
21
|
+
return { problem: plan.problem ?? `${dir} has no main (or master) branch to make a branch from` };
|
|
22
|
+
const commit = (await git(dir, ['rev-parse', '--verify', '--quiet', `refs/heads/${local}^{commit}`])).stdout;
|
|
23
|
+
return commit ? { commit, from: local, fetched: false } : { problem: `${local} could not be read` };
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* A free branch name for a task: `queue/<its id>-<its name>`, the name in Latin letters only — one typed at a prompt
|
|
27
|
+
* should not need another keyboard — and `-2` and on when it is taken.
|
|
28
|
+
*/
|
|
29
|
+
export async function queueBranchName(dir, id, title) {
|
|
30
|
+
const latin = title.normalize('NFKD').replace(/[^\x20-\x7e]/g, '').trim();
|
|
31
|
+
return await freeBranchName(dir, branchNameFrom([id, latin.slice(0, 40)], 'queue/'));
|
|
32
|
+
}
|
|
33
|
+
/** Makes the branch at `start`, not checked out: the folder is not touched. */
|
|
34
|
+
export async function makeQueueBranch(dir, id, title, start) {
|
|
35
|
+
const branch = await queueBranchName(dir, id, title);
|
|
36
|
+
const made = await git(dir, ['branch', '--no-track', branch, start.commit]);
|
|
37
|
+
if (!made.ok)
|
|
38
|
+
return { problem: (made.stderr || made.stdout || `the branch ${branch} could not be made`).split(/\r?\n/)[0] };
|
|
39
|
+
return { branch, base: start.commit };
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* At the task's start: the branch brought up to the remote's main when nothing has been done on it yet — still at the
|
|
43
|
+
* commit it was made at — and the remote can be read without asking anybody (nobody may be there). Forward only.
|
|
44
|
+
*/
|
|
45
|
+
export async function refreshQueueBranch(dir, branch, base) {
|
|
46
|
+
const tip = (await git(dir, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`])).stdout;
|
|
47
|
+
if (!tip)
|
|
48
|
+
return { base, moved: false, detail: `there is no branch ${branch} any more` };
|
|
49
|
+
if (tip !== base)
|
|
50
|
+
return { base, moved: false, detail: 'work is on it already' };
|
|
51
|
+
const remotes = (await git(dir, ['remote'])).stdout.split(/\r?\n/).map((r) => r.trim()).filter(Boolean);
|
|
52
|
+
const remote = remotes.includes('origin') ? 'origin' : remotes[0];
|
|
53
|
+
if (!remote)
|
|
54
|
+
return { base, moved: false, detail: 'no remote' };
|
|
55
|
+
const fetched = await fetchAsOperator(dir, remote, { askpass: null, refspecs: [`+refs/heads/main:refs/remotes/${remote}/main`] });
|
|
56
|
+
if (!fetched.ok)
|
|
57
|
+
return { base, moved: false, detail: fetched.detail };
|
|
58
|
+
const latest = (await git(dir, ['rev-parse', '--verify', '--quiet', `refs/remotes/${remote}/main^{commit}`])).stdout;
|
|
59
|
+
if (!latest || latest === base)
|
|
60
|
+
return { base, moved: false };
|
|
61
|
+
if (!(await isAncestor(dir, base, latest)))
|
|
62
|
+
return { base, moved: false, detail: `${remote}/main went another way` };
|
|
63
|
+
const current = (await git(dir, ['symbolic-ref', '--quiet', '--short', 'HEAD'])).stdout;
|
|
64
|
+
const moved = current === branch ? await git(dir, ['merge', '--ff-only', '--quiet', latest]) : await git(dir, ['update-ref', '-m', `copilot-operator: ${branch} brought up to ${remote}/main`, `refs/heads/${branch}`, latest, base]);
|
|
65
|
+
return moved.ok ? { base: latest, moved: true } : { base, moved: false, detail: (moved.stderr || moved.stdout).split(/\r?\n/)[0] };
|
|
66
|
+
}
|
|
@@ -77,6 +77,15 @@ function level2Block(level2) {
|
|
|
77
77
|
* failed, that the files are as its work left them, and — after the bot stopped under it — which of
|
|
78
78
|
* the steps it had just asked for actually ran.
|
|
79
79
|
*/
|
|
80
|
+
/** What a task of the queue waited for when it was set aside, as the chat that carries it on is told it (2026-10-26). */
|
|
81
|
+
const PARKED_FOR = {
|
|
82
|
+
plan: 'for the operator to approve your plan',
|
|
83
|
+
question: 'for the operator\'s answer to a question',
|
|
84
|
+
retry: 'for the operator to say what to do with a subtask that was cut off',
|
|
85
|
+
command: 'for the operator\'s word on a command',
|
|
86
|
+
model: 'for the operator to choose the model by hand',
|
|
87
|
+
password: 'for a password Git asked for in its own window',
|
|
88
|
+
};
|
|
80
89
|
export function whyItStopped(c) {
|
|
81
90
|
if (c.how === 'failed')
|
|
82
91
|
return describeEnding(c.fromAttempt, c.ended, c.stoppedBecause);
|
|
@@ -86,6 +95,12 @@ export function whyItStopped(c) {
|
|
|
86
95
|
'crashed; nothing you did failed — and it has now started again. The files are as your work left them, and what had ' +
|
|
87
96
|
`changed is committed on this branch.${where}`.trimEnd());
|
|
88
97
|
}
|
|
98
|
+
if (c.how === 'parked') {
|
|
99
|
+
const what = c.parkedFor ? PARKED_FOR[c.parkedFor] : 'for the operator';
|
|
100
|
+
return (`It waited ${what}, and was set aside so that the queue's other tasks could run while nobody was there — not because ` +
|
|
101
|
+
'anything failed. The operator has answered now: the answer is below. The files are as you left them, and what had ' +
|
|
102
|
+
'changed is committed on this branch.');
|
|
103
|
+
}
|
|
89
104
|
if (c.how === 'stopped') {
|
|
90
105
|
const where = c.interruption ? `\n\n${describeInterruption(c.interruption).replace(/when the runner stopped/g, 'when it was stopped')}\n\n` : ' ';
|
|
91
106
|
return `It was stopped by the operator before it finished — not because anything failed. The files are as you left them.${where}`.trimEnd();
|
|
@@ -107,6 +107,8 @@ export const TASK_FIELD_ON_RERUN = {
|
|
|
107
107
|
leftovers: 'archived',
|
|
108
108
|
// The fault of the means an attempt ended on (2026-10-25) is that attempt's.
|
|
109
109
|
failure: 'archived',
|
|
110
|
+
// What an attempt waited for when the queue set it aside, and the answer, are that attempt's (2026-10-26).
|
|
111
|
+
parked: 'archived',
|
|
110
112
|
environment: 'archived',
|
|
111
113
|
handoff: 'archived',
|
|
112
114
|
plan: 'archived',
|
|
@@ -567,6 +569,7 @@ export class SessionStore {
|
|
|
567
569
|
runGroup: t.runGroup,
|
|
568
570
|
leftovers: t.leftovers,
|
|
569
571
|
failure: t.failure,
|
|
572
|
+
...(t.parked ? { parked: t.parked } : {}),
|
|
570
573
|
environment: t.environment,
|
|
571
574
|
status: t.status,
|
|
572
575
|
startedAt: t.startedAt,
|
|
@@ -652,6 +655,7 @@ export class SessionStore {
|
|
|
652
655
|
// left in place, the next attempt's list was added to this one's and read as its own.
|
|
653
656
|
t.leftovers = undefined;
|
|
654
657
|
t.failure = undefined;
|
|
658
|
+
t.parked = undefined;
|
|
655
659
|
t.environment = undefined;
|
|
656
660
|
// The branch of the finished attempt stays in the repository and stays on the record
|
|
657
661
|
// above; the next attempt gets its own, cut from the same commit this one started at.
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* "New branch from main", in the chat (operator, 2026-10-26: "a button near the skill option: it takes the latest of
|
|
3
|
+
* main and makes a new local branch for the new task, a copy of the remote main; if the remote asks for a password, a
|
|
4
|
+
* window the bot never reads; and when the branch cannot simply be changed — uncommitted changes or another problem —
|
|
5
|
+
* the program offers a choice").
|
|
6
|
+
*
|
|
7
|
+
* Two steps, as the page shows them:
|
|
8
|
+
*
|
|
9
|
+
* 1. The preview fetches the remote's main (asking through Git's own password window when it must, `remoteAuth.ts`)
|
|
10
|
+
* and reads the folder: the branch it is on, what is not committed, anything half done. It changes nothing else.
|
|
11
|
+
* 2. Creating it, after checking the folder is still what the preview showed: a new local branch at the remote's
|
|
12
|
+
* main, not tracking it (a push of the task's work never goes to main by mistake), checked out. What was not
|
|
13
|
+
* committed is, as the operator chooses:
|
|
14
|
+
* - taken to the new branch, as git carries changes across a checkout — refused by git, with nothing moved, when
|
|
15
|
+
* the remote's main changed the same files; then the other choice is offered;
|
|
16
|
+
* - put aside: one commit on a branch of its own (`<prefix>saved/<when>`), made with a temporary index and
|
|
17
|
+
* checked to hold every change before anything moves, then the folder is left clean on the new branch.
|
|
18
|
+
* Nothing is deleted: no branch, and no change that is not first kept. Ignored files are not touched.
|
|
19
|
+
*
|
|
20
|
+
* When the remote cannot be fetched — a password not given, no network — the operator may go on from the remote's main
|
|
21
|
+
* as it was last fetched here, said with its date.
|
|
22
|
+
*/
|
|
23
|
+
import { existsSync } from 'node:fs';
|
|
24
|
+
import { rm } from 'node:fs/promises';
|
|
25
|
+
import { tmpdir } from 'node:os';
|
|
26
|
+
import { join, resolve } from 'node:path';
|
|
27
|
+
import { createHash } from 'node:crypto';
|
|
28
|
+
import { branchNameFrom, freeBranchName, git, lastFetchedAt, porcelainPaths, RUNNER_EMAIL } from './git.js';
|
|
29
|
+
import { fetchAsOperator } from './remoteAuth.js';
|
|
30
|
+
const short = (c) => (c ?? '').slice(0, 8);
|
|
31
|
+
const lines = (s) => s.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
32
|
+
function stamp(now = new Date()) {
|
|
33
|
+
const p = (n) => String(n).padStart(2, '0');
|
|
34
|
+
return `${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}`;
|
|
35
|
+
}
|
|
36
|
+
/** A merge, rebase, cherry-pick or revert half done: the folder is the operator's to finish first. */
|
|
37
|
+
function operationInProgress(gitDir) {
|
|
38
|
+
for (const [file, what] of [
|
|
39
|
+
['MERGE_HEAD', 'a merge'],
|
|
40
|
+
['rebase-merge', 'a rebase'],
|
|
41
|
+
['rebase-apply', 'a rebase'],
|
|
42
|
+
['CHERRY_PICK_HEAD', 'a cherry-pick'],
|
|
43
|
+
['REVERT_HEAD', 'a revert'],
|
|
44
|
+
]) {
|
|
45
|
+
if (existsSync(join(gitDir, file)))
|
|
46
|
+
return what;
|
|
47
|
+
}
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const refused = (repoDir, problem, extra = {}) => ({ ok: false, problem, repoDir, changed: [], untracked: [], ...extra });
|
|
51
|
+
/**
|
|
52
|
+
* What making the branch would start from. `fetch`: the preview, which fetches the remote's main — through `askpass`,
|
|
53
|
+
* Git's password window, when given; without a fetch, what was last fetched (going on after a fetch that failed, and
|
|
54
|
+
* the creation itself, which compares against what the preview read).
|
|
55
|
+
*/
|
|
56
|
+
export async function planNewBranch(folder, opts) {
|
|
57
|
+
const inside = await git(folder, ['rev-parse', '--is-inside-work-tree']);
|
|
58
|
+
if (!inside.ok || inside.stdout !== 'true')
|
|
59
|
+
return refused(folder, `${folder} is not a git repository, so there is no main to make a branch from.`);
|
|
60
|
+
const top = await git(folder, ['rev-parse', '--show-toplevel']);
|
|
61
|
+
const repoDir = top.ok && top.stdout ? resolve(top.stdout) : folder;
|
|
62
|
+
const gitDir = (await git(repoDir, ['rev-parse', '--absolute-git-dir'])).stdout;
|
|
63
|
+
const busy = gitDir ? operationInProgress(gitDir) : null;
|
|
64
|
+
if (busy)
|
|
65
|
+
return refused(repoDir, `The repository is in the middle of ${busy}. Finish it or abort it first; nothing was changed.`);
|
|
66
|
+
const headR = await git(repoDir, ['rev-parse', '--verify', '--quiet', 'HEAD']);
|
|
67
|
+
const branchR = await git(repoDir, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
68
|
+
const branch = branchR.ok && branchR.stdout ? branchR.stdout : null;
|
|
69
|
+
const remotes = lines((await git(repoDir, ['remote'])).stdout);
|
|
70
|
+
if (remotes.length === 0)
|
|
71
|
+
return refused(repoDir, 'The repository has no remote, so there is no remote main to make the branch from.');
|
|
72
|
+
const remote = remotes.includes('origin') ? 'origin' : remotes[0];
|
|
73
|
+
// Read before fetching: a fetch that fails empties FETCH_HEAD, and with it the time of the last one that worked.
|
|
74
|
+
const lastBefore = gitDir ? lastFetchedAt(gitDir) : undefined;
|
|
75
|
+
let fetched;
|
|
76
|
+
if (opts.fetch) {
|
|
77
|
+
// Only the remote's main: one connection, one password at most.
|
|
78
|
+
fetched = await fetchAsOperator(repoDir, remote, { askpass: opts.askpass ?? null, refspecs: [`+refs/heads/main:refs/remotes/${remote}/main`] });
|
|
79
|
+
// A remote whose main is called master: asked for by that name, once the first said it has no main.
|
|
80
|
+
if (!fetched.ok && /couldn't find remote ref|could not find remote ref/i.test(fetched.detail ?? '')) {
|
|
81
|
+
fetched = await fetchAsOperator(repoDir, remote, { askpass: opts.askpass ?? null, refspecs: [`+refs/heads/master:refs/remotes/${remote}/master`] });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
let target = '';
|
|
85
|
+
for (const name of ['main', 'master']) {
|
|
86
|
+
if ((await git(repoDir, ['rev-parse', '--verify', '--quiet', `refs/remotes/${remote}/${name}`])).ok) {
|
|
87
|
+
target = `${remote}/${name}`;
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const lastFetched = fetched && !fetched.ok ? lastBefore : gitDir ? lastFetchedAt(gitDir) : undefined;
|
|
92
|
+
if (!target) {
|
|
93
|
+
return refused(repoDir, fetched && !fetched.ok ? `${remote} could not be fetched (${fetched.detail}), and no main of it is known here yet.` : `No main (or master) of ${remote} is known here.`, {
|
|
94
|
+
...(fetched ? { fetched } : {}),
|
|
95
|
+
remote,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
const targetCommit = (await git(repoDir, ['rev-parse', '--verify', '--quiet', `refs/remotes/${target}^{commit}`])).stdout;
|
|
99
|
+
if (!targetCommit)
|
|
100
|
+
return refused(repoDir, `${target} could not be read.`);
|
|
101
|
+
const targetSubject = (await git(repoDir, ['log', '-1', '--format=%s', targetCommit])).stdout;
|
|
102
|
+
const status = await git(repoDir, ['status', '--porcelain', '--untracked-files=no']);
|
|
103
|
+
const changed = porcelainPaths(status.stdout);
|
|
104
|
+
const untracked = lines((await git(repoDir, ['ls-files', '--others', '--exclude-standard'])).stdout);
|
|
105
|
+
const suggested = await freeBranchName(repoDir, `task/${stamp()}`);
|
|
106
|
+
const fingerprint = createHash('sha256')
|
|
107
|
+
.update([headR.stdout, branch ?? '', targetCommit, status.stdout, untracked.join('\n')].join('\0'))
|
|
108
|
+
.digest('hex')
|
|
109
|
+
.slice(0, 16);
|
|
110
|
+
return {
|
|
111
|
+
ok: true,
|
|
112
|
+
repoDir,
|
|
113
|
+
branch,
|
|
114
|
+
...(headR.stdout ? { head: headR.stdout } : {}),
|
|
115
|
+
remote,
|
|
116
|
+
target,
|
|
117
|
+
targetCommit,
|
|
118
|
+
...(targetSubject ? { targetSubject } : {}),
|
|
119
|
+
...(fetched ? { fetched } : {}),
|
|
120
|
+
...(lastFetched ? { lastFetched } : {}),
|
|
121
|
+
changed,
|
|
122
|
+
untracked,
|
|
123
|
+
suggested,
|
|
124
|
+
fingerprint,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** Whether git takes `name` as a new branch here: a legal name, and not one in use. */
|
|
128
|
+
export async function branchNameProblem(repoDir, name) {
|
|
129
|
+
const n = name.trim();
|
|
130
|
+
if (!n)
|
|
131
|
+
return 'Write the new branch\'s name.';
|
|
132
|
+
const legal = await git(repoDir, ['check-ref-format', '--branch', n]);
|
|
133
|
+
if (!legal.ok || n.startsWith('-'))
|
|
134
|
+
return `"${n}" cannot be a branch's name: no spaces, no "..", and not starting or ending with "/" or ".".`;
|
|
135
|
+
if ((await git(repoDir, ['rev-parse', '--verify', '--quiet', `refs/heads/${n}`])).ok)
|
|
136
|
+
return `There is a branch called "${n}" already; choose another name.`;
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Every uncommitted change and new file, as one commit on top of HEAD on a branch of its own, made with a temporary
|
|
141
|
+
* index — then checked to hold all of them, so nothing is removed from the folder that is not kept.
|
|
142
|
+
*/
|
|
143
|
+
async function keepUncommitted(dir, head, branch, message) {
|
|
144
|
+
const index = join(tmpdir(), `cop-saved-index-${process.pid}-${Date.now()}`);
|
|
145
|
+
const env = { ...process.env, GIT_INDEX_FILE: index };
|
|
146
|
+
try {
|
|
147
|
+
const read = await git(dir, ['read-tree', head], 60_000, env);
|
|
148
|
+
if (!read.ok)
|
|
149
|
+
return { problem: read.stderr || 'git read-tree failed' };
|
|
150
|
+
const added = await git(dir, ['add', '-A', '--', '.'], 300_000, env);
|
|
151
|
+
if (!added.ok)
|
|
152
|
+
return { problem: `the changes could not be read into git: ${added.stderr || added.stdout}` };
|
|
153
|
+
const differs = await git(dir, ['diff-files', '--name-only'], 120_000, env);
|
|
154
|
+
const outside = await git(dir, ['ls-files', '--others', '--exclude-standard'], 120_000, env);
|
|
155
|
+
if (!differs.ok || differs.stdout || !outside.ok || outside.stdout) {
|
|
156
|
+
return { problem: `not every change could be kept (${[differs.stdout, outside.stdout].filter(Boolean).join(', ').slice(0, 300) || differs.stderr || outside.stderr}), so nothing was moved.` };
|
|
157
|
+
}
|
|
158
|
+
const tree = await git(dir, ['write-tree'], 60_000, env);
|
|
159
|
+
if (!tree.ok || !tree.stdout)
|
|
160
|
+
return { problem: tree.stderr || 'git write-tree failed' };
|
|
161
|
+
const commit = await git(dir, ['-c', 'user.name=copilot-operator', '-c', `user.email=${RUNNER_EMAIL}`, 'commit-tree', tree.stdout, '-p', head, '-m', message]);
|
|
162
|
+
if (!commit.ok || !commit.stdout)
|
|
163
|
+
return { problem: commit.stderr || 'git commit-tree failed' };
|
|
164
|
+
const made = await git(dir, ['branch', branch, commit.stdout]);
|
|
165
|
+
if (!made.ok)
|
|
166
|
+
return { problem: made.stderr || `the branch ${branch} could not be made` };
|
|
167
|
+
return { commit: commit.stdout };
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
await rm(index, { force: true });
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
/** Makes the branch and checks it out, after checking the folder is still what the preview showed. */
|
|
174
|
+
export async function createNewBranch(folder, opts) {
|
|
175
|
+
const plan = await planNewBranch(folder, { fetch: false });
|
|
176
|
+
if (!plan.ok)
|
|
177
|
+
return { ok: false, problem: plan.problem ?? 'the folder could not be read.' };
|
|
178
|
+
if (!opts.fingerprint || plan.fingerprint !== opts.fingerprint) {
|
|
179
|
+
return { ok: false, problem: 'The folder changed since it was read (a commit, a branch, a changed or new file). Look at it again; nothing was changed.' };
|
|
180
|
+
}
|
|
181
|
+
const repoDir = plan.repoDir;
|
|
182
|
+
const name = opts.name.trim();
|
|
183
|
+
const bad = await branchNameProblem(repoDir, name);
|
|
184
|
+
if (bad)
|
|
185
|
+
return { ok: false, problem: bad };
|
|
186
|
+
const target = plan.target;
|
|
187
|
+
const targetCommit = plan.targetCommit;
|
|
188
|
+
const files = plan.changed.length + plan.untracked.length;
|
|
189
|
+
const done = async (saved) => {
|
|
190
|
+
const nowBranch = (await git(repoDir, ['symbolic-ref', '--quiet', '--short', 'HEAD'])).stdout;
|
|
191
|
+
const nowHead = (await git(repoDir, ['rev-parse', 'HEAD'])).stdout;
|
|
192
|
+
if (nowBranch !== name || nowHead !== targetCommit)
|
|
193
|
+
return { ok: false, problem: `The folder is on ${nowBranch || 'a detached HEAD'} at ${short(nowHead)}, not on ${name} at ${short(targetCommit)} as it should be.` };
|
|
194
|
+
const carried = saved ? 0 : files;
|
|
195
|
+
const result = `The folder is on the new branch ${name}, made from ${target} (${short(targetCommit)}).` +
|
|
196
|
+
(saved ? ` What was not committed is kept on ${saved.branch} (${saved.files} file(s)).` : carried > 0 ? ` ${carried} uncommitted file(s) came with it.` : '');
|
|
197
|
+
return { ok: true, branch: name, commit: targetCommit, target, ...(saved ? { saved } : {}), carried, result };
|
|
198
|
+
};
|
|
199
|
+
if (files === 0 || opts.carry === 'take') {
|
|
200
|
+
// As git carries changes across a checkout; it refuses, and moves nothing, when a change would be overwritten.
|
|
201
|
+
const moved = await git(repoDir, ['switch', '--quiet', '--no-track', '-c', name, targetCommit], 300_000);
|
|
202
|
+
if (!moved.ok) {
|
|
203
|
+
const said = (moved.stderr || moved.stdout).trim();
|
|
204
|
+
const conflict = /would be overwritten|overwritten by checkout|untracked working tree files/i.test(said);
|
|
205
|
+
return conflict
|
|
206
|
+
? { ok: false, conflict: true, problem: `The uncommitted changes cannot be taken to the new branch: ${target} changed the same files (${said.split(/\r?\n/).slice(1, 4).map((l) => l.trim()).filter(Boolean).join(', ') || said.split(/\r?\n/)[0]}). Nothing was moved.` }
|
|
207
|
+
: { ok: false, problem: `The branch could not be made: ${said.split(/\r?\n/)[0] || 'git switch failed'}. Nothing was moved.` };
|
|
208
|
+
}
|
|
209
|
+
return done();
|
|
210
|
+
}
|
|
211
|
+
// Put aside: kept first, checked whole; only then is the folder moved, and left clean.
|
|
212
|
+
const head = plan.head;
|
|
213
|
+
if (!head)
|
|
214
|
+
return { ok: false, problem: 'The repository has no commit yet to keep the changes on top of. Make a first commit, then try again.' };
|
|
215
|
+
const saved = await freeBranchName(repoDir, `${branchNameFrom(['saved'], opts.prefix || 'cop/')}/${stamp()}`);
|
|
216
|
+
const message = [
|
|
217
|
+
'Keep uncommitted work before a new branch from main',
|
|
218
|
+
'',
|
|
219
|
+
`Everything that was not committed in the folder on ${plan.branch ?? 'a detached HEAD'} (${short(head)}), kept here before the new branch ${name} was made from ${target} (${short(targetCommit)}).`,
|
|
220
|
+
'To take a file back: git restore --source <this branch> -- <path>',
|
|
221
|
+
'',
|
|
222
|
+
...[...plan.changed.map((p) => `- changed: ${p}`), ...plan.untracked.map((p) => `- new: ${p}`)].slice(0, 300),
|
|
223
|
+
'',
|
|
224
|
+
'Committed by copilot-operator. Not pushed.',
|
|
225
|
+
'',
|
|
226
|
+
].join('\n');
|
|
227
|
+
const kept = await keepUncommitted(repoDir, head, saved, message);
|
|
228
|
+
if ('problem' in kept)
|
|
229
|
+
return { ok: false, problem: kept.problem };
|
|
230
|
+
// Everything is kept; the forced switch drops the tracked changes that are on the saved branch.
|
|
231
|
+
const moved = await git(repoDir, ['switch', '--quiet', '--no-track', '--discard-changes', '-c', name, targetCommit], 300_000);
|
|
232
|
+
if (!moved.ok)
|
|
233
|
+
return { ok: false, problem: `The branch could not be made: ${(moved.stderr || moved.stdout).split(/\r?\n/)[0]}. What was not committed is kept on ${saved}.` };
|
|
234
|
+
// The new files, kept on the saved branch, out of the folder; ignored files stay (no -x).
|
|
235
|
+
if (plan.untracked.length > 0) {
|
|
236
|
+
const cleaned = await git(repoDir, ['clean', '-fd', '--quiet'], 300_000);
|
|
237
|
+
if (!cleaned.ok)
|
|
238
|
+
return { ok: false, problem: `The new branch ${name} is made, but the new files could not be taken out of the folder: ${cleaned.stderr}. They are kept on ${saved}.` };
|
|
239
|
+
}
|
|
240
|
+
return done({ branch: saved, commit: kept.commit, files });
|
|
241
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How a fetch the operator asked for gets past a remote that wants a password — without the bot ever seeing it.
|
|
3
|
+
*
|
|
4
|
+
* First made on 2026-10-03 (an SSH key with a passphrase); brought back on 2026-10-26 for "New branch from main" in
|
|
5
|
+
* the chat (operator: "if the remote main asks for a password, open a window the bot never reads; the operator types
|
|
6
|
+
* the password there and it goes to version control; dynamic, so no security policy is hit").
|
|
7
|
+
*
|
|
8
|
+
* Not a field on the bot's page: a password typed there passes through the browser, the API, this process and its
|
|
9
|
+
* memory, and the bot would hold the one secret that unlocks the operator's key or account. So the bot asks nobody
|
|
10
|
+
* anything. It lets ssh (and git, for HTTPS) ask through Git for Windows' own password window, `git-askpass.exe` —
|
|
11
|
+
* a program that ships with Git, not a script — or Git Credential Manager's own window: the operator types into it,
|
|
12
|
+
* and the answer goes from the window straight back to ssh or git through a pipe the bot is not part of. The bot reads
|
|
13
|
+
* only what `git fetch` prints. Nothing is stored; the next fetch asks again (an ssh-agent or the credential manager,
|
|
14
|
+
* when the operator has one, answers instead).
|
|
15
|
+
*
|
|
16
|
+
* Only for a fetch the operator just pressed a button for: a run's own fetches stay silent, since a window nobody
|
|
17
|
+
* answers would hold the run until it times out.
|
|
18
|
+
*/
|
|
19
|
+
import { execFile } from 'node:child_process';
|
|
20
|
+
import { existsSync } from 'node:fs';
|
|
21
|
+
import { resolve } from 'node:path';
|
|
22
|
+
import { git, gitFetch } from './git.js';
|
|
23
|
+
/** No prompt anywhere: what every fetch of a run uses. */
|
|
24
|
+
export const QUIET_FETCH_ENV = { ...process.env, GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_ASKPASS: '', SSH_ASKPASS: '' };
|
|
25
|
+
/** Git for Windows' password window, next to the git that runs here; null when there is none. */
|
|
26
|
+
export async function askpassProgram() {
|
|
27
|
+
const exec = await git(process.cwd(), ['--exec-path']);
|
|
28
|
+
if (!exec.ok || !exec.stdout)
|
|
29
|
+
return null;
|
|
30
|
+
// <Git>\mingw64\libexec\git-core → <Git>\mingw64\bin\git-askpass.exe
|
|
31
|
+
const candidate = resolve(exec.stdout, '..', '..', 'bin', 'git-askpass.exe');
|
|
32
|
+
return existsSync(candidate) ? candidate : null;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* The environment for a fetch the operator is present for: ssh asks through the password window even with no terminal
|
|
36
|
+
* (`SSH_ASKPASS_REQUIRE=force`; `DISPLAY` for an older ssh that wants one), and git asks through it — or through the
|
|
37
|
+
* credential manager's own window — for an HTTPS user name or password. No terminal prompt: the bot's console is not
|
|
38
|
+
* where the operator is looking.
|
|
39
|
+
*/
|
|
40
|
+
export function operatorFetchEnv(askpass) {
|
|
41
|
+
return {
|
|
42
|
+
...process.env,
|
|
43
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
44
|
+
GCM_INTERACTIVE: 'auto',
|
|
45
|
+
GIT_ASKPASS: askpass,
|
|
46
|
+
SSH_ASKPASS: askpass,
|
|
47
|
+
SSH_ASKPASS_REQUIRE: 'force',
|
|
48
|
+
DISPLAY: process.env.DISPLAY || 'needs-to-be-defined',
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
/** A failed fetch, said so the operator knows whether it was the password. */
|
|
52
|
+
export function describeFetchFailure(stderr) {
|
|
53
|
+
const lines = stderr.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
|
|
54
|
+
const auth = /permission denied|publickey|passphrase|authentication failed|could not read (username|password)|host key verification failed|terminal prompts disabled|cancel/i.test(stderr);
|
|
55
|
+
return { detail: lines.slice(0, 3).join(' ') || 'git fetch failed', auth };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Closes the password windows of a fetch that was given up on: every process of exactly this program started since
|
|
59
|
+
* `since`. Needed because stopping git and its process tree does not reach them (Git for Windows starts ssh, and ssh
|
|
60
|
+
* the window, whose Windows parent is already gone; seen live on 2026-10-03). Matched by the program's full path and
|
|
61
|
+
* its start time, so nothing else is touched. A command given to PowerShell as it runs, not a script file.
|
|
62
|
+
*/
|
|
63
|
+
export function closePasswordWindows(program, since) {
|
|
64
|
+
if (process.platform !== 'win32')
|
|
65
|
+
return Promise.resolve(0);
|
|
66
|
+
const script = [
|
|
67
|
+
`$path = '${program.replace(/'/g, "''")}'`,
|
|
68
|
+
`$since = [datetime]::Parse('${since.toISOString()}').ToUniversalTime()`,
|
|
69
|
+
'$n = 0',
|
|
70
|
+
"Get-CimInstance Win32_Process -Filter \"Name='git-askpass.exe' OR Name='$([IO.Path]::GetFileName($path))'\" |",
|
|
71
|
+
' Where-Object { $_.ExecutablePath -and $_.ExecutablePath -ieq $path -and $_.CreationDate.ToUniversalTime() -ge $since } |',
|
|
72
|
+
' ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue; $n++ }',
|
|
73
|
+
'$n',
|
|
74
|
+
].join('\n');
|
|
75
|
+
return new Promise((done) => {
|
|
76
|
+
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, timeout: 30_000 }, (_e, stdout) => {
|
|
77
|
+
done(Number.parseInt(String(stdout).trim(), 10) || 0);
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** The programs that are Git asking the operator: its password window and its credential manager's. */
|
|
82
|
+
const ASKING = ['git-askpass.exe', 'git-credential-manager.exe', 'git-credential-manager-core.exe'];
|
|
83
|
+
/**
|
|
84
|
+
* Whether Git is asking the operator for a password now, in a window opened since `sinceMs` (2026-10-26): what holds a
|
|
85
|
+
* step's idle clock and has the chat say where to look. A quick list of the processes first; their start time only
|
|
86
|
+
* when one of them is there — a command given to PowerShell as it runs, not a script file.
|
|
87
|
+
*/
|
|
88
|
+
export async function passwordWindowOpen(sinceMs) {
|
|
89
|
+
if (process.platform !== 'win32')
|
|
90
|
+
return false;
|
|
91
|
+
const listed = await new Promise((done) => execFile('tasklist', ['/FO', 'CSV', '/NH', '/FI', 'IMAGENAME eq git-*'], { windowsHide: true, timeout: 10_000 }, (_e, stdout) => done(String(stdout ?? '').toLowerCase())));
|
|
92
|
+
if (!ASKING.some((n) => listed.includes(`"${n}"`)))
|
|
93
|
+
return false;
|
|
94
|
+
const filter = ASKING.map((n) => `Name='${n}'`).join(' OR ');
|
|
95
|
+
const script = [
|
|
96
|
+
`$since = [datetime]::Parse('${new Date(sinceMs - 1000).toISOString()}').ToUniversalTime()`,
|
|
97
|
+
`@(Get-CimInstance Win32_Process -Filter "${filter}" | Where-Object { $_.CreationDate.ToUniversalTime() -ge $since }).Count`,
|
|
98
|
+
].join('\n');
|
|
99
|
+
return await new Promise((done) => execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], { windowsHide: true, timeout: 20_000 }, (_e, stdout) => done((Number.parseInt(String(stdout).trim(), 10) || 0) > 0)));
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* A fetch the operator just pressed a button for, and is looking at: with Git's password window when there is one
|
|
103
|
+
* (five minutes to type, the window not hidden), quiet otherwise. One connection only; tried once more when the first
|
|
104
|
+
* try fails for another reason than a password given up on (see `gitFetch`); a window left on screen by a fetch that
|
|
105
|
+
* was given up on is closed. `refspecs` fetches only those branches.
|
|
106
|
+
*/
|
|
107
|
+
export async function fetchAsOperator(repoDir, remote, opts) {
|
|
108
|
+
const asked = !!opts.askpass;
|
|
109
|
+
const env = asked ? operatorFetchEnv(opts.askpass) : QUIET_FETCH_ENV;
|
|
110
|
+
const args = [...(asked ? [] : ['-c', 'credential.interactive=false']), 'fetch', '--quiet', '--no-tags', remote, ...(opts.refspecs ?? [])];
|
|
111
|
+
const started = new Date(Date.now() - 1000);
|
|
112
|
+
const f = await gitFetch(repoDir, args, asked ? 300_000 : 120_000, env, { windowsHide: !asked, killTree: true });
|
|
113
|
+
if (!f.ok && asked && /gave up after/.test(f.stderr))
|
|
114
|
+
await closePasswordWindows(opts.askpass, started);
|
|
115
|
+
if (f.ok)
|
|
116
|
+
return { ok: true, asked, ...(f.retried ? { retried: true } : {}) };
|
|
117
|
+
const why = describeFetchFailure(f.stderr || f.stdout);
|
|
118
|
+
return { ok: false, detail: why.detail, auth: why.auth, asked };
|
|
119
|
+
}
|