copilot-operator 0.1.67 → 0.1.69
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 +12 -1
- package/dist/src/api/operator.service.js +28 -7
- package/dist/src/exec/policy.js +1 -1
- package/dist/src/exec/scriptFiles.js +91 -9
- package/dist/src/orchestrator/handoff.js +79 -0
- package/dist/src/orchestrator/taskRunner.js +39 -0
- package/dist/src/plan/kerrigan.js +2 -0
- package/dist/src/plan/systemGuide.js +42 -2
- package/dist/src/protocol/parser.js +2 -2
- package/dist/src/protocol/replySchema.js +23 -2
- package/dist/src/queue/queue.js +6 -0
- package/dist/src/session/workspaceGit.js +64 -24
- package/dist/web/404.html +2 -2
- package/dist/web/_next/static/chunks/1024-e4e596b184e05e91.js +1 -0
- package/dist/web/_next/static/chunks/1077.b3943e5b41c4bef4.js +1 -0
- package/dist/web/_next/static/chunks/1548.0ff0c0ece685ffe7.js +1 -0
- package/dist/web/_next/static/chunks/2163.9cfb1b06beaf5001.js +1 -0
- package/dist/web/_next/static/chunks/714.bee98f5a3db75882.js +1 -0
- package/dist/web/_next/static/chunks/7220.610988766a1104b7.js +1 -0
- package/dist/web/_next/static/chunks/7921-ac5793d5663674b2.js +1 -0
- package/dist/web/_next/static/chunks/8124-665327221384ba6e.js +1 -0
- package/dist/web/_next/static/chunks/8584.9220e445a8ce2265.js +1 -0
- package/dist/web/_next/static/chunks/9067.f05516f2f2a2e8f5.js +1 -0
- package/dist/web/_next/static/chunks/9747.e249434ff7e05f4f.js +1 -0
- package/dist/web/_next/static/chunks/app/layout-e23bb58f3ea117d5.js +1 -0
- package/dist/web/_next/static/chunks/app/page-fd49cf4fb6681d30.js +1 -0
- package/dist/web/_next/static/chunks/{webpack-23ace264f775d98a.js → webpack-77c6c045264c9213.js} +1 -1
- package/dist/web/_next/static/css/52131c6d864daf3f.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 +3 -2
- package/prompts/level1.md +53 -14
- package/dist/web/_next/static/chunks/1024-5f630cbb54e7346f.js +0 -1
- package/dist/web/_next/static/chunks/1077.3b82a837cf810f8b.js +0 -1
- package/dist/web/_next/static/chunks/1548.52bfcd01c16aaafe.js +0 -1
- package/dist/web/_next/static/chunks/2163.e60d3be9bb3f8b3f.js +0 -1
- package/dist/web/_next/static/chunks/714.b452ef814760b5a5.js +0 -1
- package/dist/web/_next/static/chunks/7220.96b18052ed9c06c7.js +0 -1
- package/dist/web/_next/static/chunks/7921-dd201ce7aa02c12d.js +0 -1
- package/dist/web/_next/static/chunks/8124-c27ce7bd781f4c56.js +0 -1
- package/dist/web/_next/static/chunks/8584.ab8d406781cdd45c.js +0 -1
- package/dist/web/_next/static/chunks/9067.5b8abc40104d51d9.js +0 -1
- package/dist/web/_next/static/chunks/9747.cf0353e7ffec2ee4.js +0 -1
- package/dist/web/_next/static/chunks/app/layout-5e0e7601702723bb.js +0 -1
- package/dist/web/_next/static/chunks/app/page-ab73d1b3ba9181c2.js +0 -1
- package/dist/web/_next/static/css/532df8667473c4fc.css +0 -1
- /package/dist/web/_next/static/{JpBxrjYpw2xowWbFoiPjO → 8i6gf0zoo-KiUKdzxsCJR}/_buildManifest.js +0 -0
- /package/dist/web/_next/static/{JpBxrjYpw2xowWbFoiPjO → 8i6gf0zoo-KiUKdzxsCJR}/_ssgManifest.js +0 -0
|
@@ -297,6 +297,10 @@ let OperatorController = class OperatorController {
|
|
|
297
297
|
workspaceBranch(base) {
|
|
298
298
|
return this.ops.workspaceBranch(base || undefined).catch(fail);
|
|
299
299
|
}
|
|
300
|
+
/** The two numbers on the Git button: files not committed, and files on this branch against `base`. Read-only. */
|
|
301
|
+
workspaceGitCounts(base) {
|
|
302
|
+
return this.ops.workspaceGitCounts(base || undefined).catch(fail);
|
|
303
|
+
}
|
|
300
304
|
workspaceCommit(sha) {
|
|
301
305
|
if (!sha)
|
|
302
306
|
throw new BadRequestException('sha is required');
|
|
@@ -399,7 +403,7 @@ let OperatorController = class OperatorController {
|
|
|
399
403
|
}
|
|
400
404
|
/** The lead's question (two chats): the operator's answer, as text. Stopping the task is `approvals/:id` with abort. */
|
|
401
405
|
answerQuestion(id, body) {
|
|
402
|
-
const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '');
|
|
406
|
+
const result = this.ops.answerQuestion(id, typeof body?.text === 'string' ? body.text : '', body?.ran === false ? false : undefined);
|
|
403
407
|
if (!result.ok)
|
|
404
408
|
throw new BadRequestException(result.problem);
|
|
405
409
|
return result;
|
|
@@ -736,6 +740,13 @@ __decorate([
|
|
|
736
740
|
__metadata("design:paramtypes", [String]),
|
|
737
741
|
__metadata("design:returntype", Promise)
|
|
738
742
|
], OperatorController.prototype, "workspaceBranch", null);
|
|
743
|
+
__decorate([
|
|
744
|
+
Get('workspace/git/counts'),
|
|
745
|
+
__param(0, Query('base')),
|
|
746
|
+
__metadata("design:type", Function),
|
|
747
|
+
__metadata("design:paramtypes", [String]),
|
|
748
|
+
__metadata("design:returntype", Promise)
|
|
749
|
+
], OperatorController.prototype, "workspaceGitCounts", null);
|
|
739
750
|
__decorate([
|
|
740
751
|
Get('workspace/git/commit'),
|
|
741
752
|
__param(0, Query('sha')),
|
|
@@ -24,6 +24,7 @@ import { checkItems, emptyQueue, itemTitle, mergeItems, nextStep, parkAfterMs, p
|
|
|
24
24
|
import { branchStart, makeQueueBranch, refreshQueueBranch } from '../queue/queueBranch.js';
|
|
25
25
|
import { EventBus } from '../session/events.js';
|
|
26
26
|
import { MAX_INSTRUCTION_CHARS, newId } from '../session/model.js';
|
|
27
|
+
import { handoffResultMessage } from '../orchestrator/handoff.js';
|
|
27
28
|
import { runSession, queuedToRun, failedWhileOpening, pickerOptions } from '../orchestrator/taskRunner.js';
|
|
28
29
|
import { Hold } from '../orchestrator/hold.js';
|
|
29
30
|
import { exportFileName, exportMachine, writeAttemptRecord } from '../session/exports.js';
|
|
@@ -32,7 +33,7 @@ import { buildStory } from '../session/story.js';
|
|
|
32
33
|
import { buildTaskExchange } from '../session/taskExchange.js';
|
|
33
34
|
import { chatNotice } from '../session/chatNotice.js';
|
|
34
35
|
import { kerriganFileName, kerriganPersona } from '../plan/kerrigan.js';
|
|
35
|
-
import { branchChanges, workspaceCommit, workspaceGit, workspaceGitVersions } from '../session/workspaceGit.js';
|
|
36
|
+
import { branchChanges, gitCounts, workspaceCommit, workspaceGit, workspaceGitVersions } from '../session/workspaceGit.js';
|
|
36
37
|
import { chatCode } from '../transport/chatSession.js';
|
|
37
38
|
/** The folders the operator works in: the default new sessions start on, and the rest by name. */
|
|
38
39
|
/** The longest level 2 a project may have: Kerrigan carries each one whole. */
|
|
@@ -1215,6 +1216,13 @@ let OperatorService = class OperatorService {
|
|
|
1215
1216
|
throw new Error(ws.problem ?? 'No project folder is open.');
|
|
1216
1217
|
return await branchChanges(ws.dir, base);
|
|
1217
1218
|
}
|
|
1219
|
+
/** The two numbers on the Git button: files not committed, and files on this branch against `base` (see `gitCounts`). */
|
|
1220
|
+
async workspaceGitCounts(base) {
|
|
1221
|
+
const ws = await this.workspace();
|
|
1222
|
+
if (!ws.ok)
|
|
1223
|
+
return { isRepo: false, uncommitted: 0, branch: null };
|
|
1224
|
+
return await gitCounts(ws.dir, base);
|
|
1225
|
+
}
|
|
1218
1226
|
async workspaceCommit(sha) {
|
|
1219
1227
|
const ws = await this.workspace();
|
|
1220
1228
|
if (!ws.ok)
|
|
@@ -1875,7 +1883,8 @@ let OperatorService = class OperatorService {
|
|
|
1875
1883
|
}
|
|
1876
1884
|
}
|
|
1877
1885
|
else if (a.kind === 'question') {
|
|
1878
|
-
|
|
1886
|
+
const handed = p.approval.question?.handoff;
|
|
1887
|
+
note = handed ? handoffResultMessage(handed, a.ran !== false, a.answer) : `You asked: ${p.approval.question?.text ?? ''}\n\nThe operator answers: ${a.answer}`;
|
|
1879
1888
|
}
|
|
1880
1889
|
else if (a.kind === 'retry' && p.approval.retry) {
|
|
1881
1890
|
const r = p.approval.retry;
|
|
@@ -2071,11 +2080,19 @@ let OperatorService = class OperatorService {
|
|
|
2071
2080
|
sessionId: ask.sessionId,
|
|
2072
2081
|
taskId: ask.taskId,
|
|
2073
2082
|
stepId: 0,
|
|
2074
|
-
description:
|
|
2083
|
+
description: ask.handoff
|
|
2084
|
+
? `The chat hands over commands to run yourself: ${ask.handoff.commands.join(' ; ')}`
|
|
2085
|
+
: `${(ask.actor ?? 'lead') === 'lead' ? 'The lead asks' : 'The chat asks'}: ${ask.question}`,
|
|
2075
2086
|
createdAt: new Date().toISOString(),
|
|
2076
2087
|
// The lead's, or since 2026-10-23 the chat's own (plan mode's or the worker's).
|
|
2077
2088
|
actor: ask.actor ?? 'lead',
|
|
2078
|
-
question: {
|
|
2089
|
+
question: {
|
|
2090
|
+
text: ask.question,
|
|
2091
|
+
...(ask.why ? { why: ask.why } : {}),
|
|
2092
|
+
options: ask.options,
|
|
2093
|
+
...(ask.commands?.some(Boolean) ? { commands: ask.commands } : {}),
|
|
2094
|
+
...(ask.handoff ? { handoff: ask.handoff } : {}),
|
|
2095
|
+
},
|
|
2079
2096
|
};
|
|
2080
2097
|
this.waiting.set(approval.id, {
|
|
2081
2098
|
approval,
|
|
@@ -2157,14 +2174,18 @@ let OperatorService = class OperatorService {
|
|
|
2157
2174
|
const cfg = await this.settings.load();
|
|
2158
2175
|
return await this.start(threadId, cfg.execution.mode);
|
|
2159
2176
|
}
|
|
2160
|
-
answerQuestion(approvalId, text) {
|
|
2177
|
+
answerQuestion(approvalId, text, ran) {
|
|
2161
2178
|
const w = this.waiting.get(approvalId);
|
|
2162
2179
|
if (!w?.resolveAnswer)
|
|
2163
2180
|
return { ok: false, problem: 'No question of the lead is waiting under that id.' };
|
|
2164
|
-
|
|
2181
|
+
// Commands handed over (2026-10-26): what they printed, or that the operator did not run them, with a word or none.
|
|
2182
|
+
const handed = !!w.approval.question?.handoff;
|
|
2183
|
+
if (handed && ran !== false && !text.trim())
|
|
2184
|
+
return { ok: false, problem: 'Paste what the commands printed first.' };
|
|
2185
|
+
if (!handed && !text.trim())
|
|
2165
2186
|
return { ok: false, problem: 'Write the answer first.' };
|
|
2166
2187
|
this.waiting.delete(approvalId);
|
|
2167
|
-
w.resolveAnswer({ answer: text.trim() });
|
|
2188
|
+
w.resolveAnswer(handed ? { answer: text.trim(), ran: ran !== false } : { answer: text.trim() });
|
|
2168
2189
|
this.bus.publish({ sessionId: w.approval.sessionId, taskId: w.approval.taskId, type: 'approval-decided', level: 'info',
|
|
2169
2190
|
message: 'the operator answered the lead', data: { approvalId, question: true } });
|
|
2170
2191
|
return { ok: true };
|
package/dist/src/exec/policy.js
CHANGED
|
@@ -206,7 +206,7 @@ export function staticCheck(step, cfg, env = process.env, confinement) {
|
|
|
206
206
|
* a script in one step and run it in the next. See `scriptFiles.ts`.
|
|
207
207
|
*/
|
|
208
208
|
if (confinement) {
|
|
209
|
-
const own = ownScriptRefusal(step.cmd, confinement.cwd, confinement.workStartedAt);
|
|
209
|
+
const own = ownScriptRefusal(step.cmd, confinement.cwd, confinement.workStartedAt, effectiveShell(step.shell));
|
|
210
210
|
if (own)
|
|
211
211
|
return { action: 'skip', reason: own };
|
|
212
212
|
}
|
|
@@ -31,6 +31,7 @@
|
|
|
31
31
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
32
32
|
import { dirname, isAbsolute, relative, resolve } from 'node:path';
|
|
33
33
|
import { gitSync, RUNNER_EMAIL } from '../vcs/git.js';
|
|
34
|
+
import { scanCommandHeads } from './commandHeads.js';
|
|
34
35
|
/** Larger than this is not a step's script; it is not read, and running it is refused. */
|
|
35
36
|
const MAX_SCRIPT_BYTES = 256 * 1024;
|
|
36
37
|
/** Paths of PowerShell scripts this command line runs, as written. */
|
|
@@ -162,26 +163,107 @@ export function notTheProjects(file, since) {
|
|
|
162
163
|
return 'it was committed after this work began, so it was written during the work';
|
|
163
164
|
return null;
|
|
164
165
|
}
|
|
166
|
+
/** The runtimes a file of code is given to, by the program's name. */
|
|
167
|
+
const CODE_RUNTIMES = new Set(['node', 'nodejs', 'tsx', 'ts-node', 'ts-node-esm', 'python', 'python3', 'pythonw', 'py', 'deno', 'bun', 'ruby', 'perl', 'php']);
|
|
168
|
+
/** What a package runner starts that runs a file of code: `npx ts-node x.ts`, `npx tsx x.ts`. */
|
|
169
|
+
const RUN_THROUGH = new Set(['npx', 'pnpx', 'bunx']);
|
|
170
|
+
const CODE_FILE = /\.(?:js|mjs|cjs|jsx|ts|mts|cts|tsx|py|pyw|rb|pl|php)$/i;
|
|
171
|
+
/**
|
|
172
|
+
* The files of code a line gives straight to a runtime (2026-10-26): `node tools/x.js`, `npx ts-node tools/x.ts`,
|
|
173
|
+
* `tsx x.ts`, `python x.py`, `deno run x.ts`, as full paths. The first argument that is not a switch is the file; a
|
|
174
|
+
* line whose first one is not a file of code (`node --version`, `python -m pytest`) gives none. The project's test
|
|
175
|
+
* runners are not this (operator, 2026-10-26: "tests as before"): `node --test` is left alone, as are `npm test`,
|
|
176
|
+
* `npx playwright test` and the rest, which are not runtimes given a file.
|
|
177
|
+
*/
|
|
178
|
+
export function codeFilesRun(command, cwd, shell) {
|
|
179
|
+
const files = new Set();
|
|
180
|
+
for (const call of scanCommandHeads(command, shell ?? 'pwsh').calls) {
|
|
181
|
+
let program = call.head.replace(/^.*[\\/]/, '').replace(/\.(?:exe|cmd)$/i, '').toLowerCase();
|
|
182
|
+
let args = call.args;
|
|
183
|
+
if (RUN_THROUGH.has(program)) {
|
|
184
|
+
const first = args.findIndex((a) => !a.literal.startsWith('-'));
|
|
185
|
+
if (first < 0)
|
|
186
|
+
continue;
|
|
187
|
+
program = args[first].literal.toLowerCase();
|
|
188
|
+
args = args.slice(first + 1);
|
|
189
|
+
}
|
|
190
|
+
if (!CODE_RUNTIMES.has(program))
|
|
191
|
+
continue;
|
|
192
|
+
if (args.some((a) => /^--test\b/.test(a.literal)))
|
|
193
|
+
continue;
|
|
194
|
+
const rest = (program === 'deno' || program === 'bun') && args[0]?.literal === 'run' ? args.slice(1) : args;
|
|
195
|
+
const file = rest.find((a) => !a.literal.startsWith('-'));
|
|
196
|
+
if (!file || file.dynamic || !CODE_FILE.test(file.literal))
|
|
197
|
+
continue;
|
|
198
|
+
files.add(isAbsolute(file.literal) ? file.literal : resolve(cwd, file.literal));
|
|
199
|
+
}
|
|
200
|
+
return [...files];
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Why a file of code was written during this work, or null when it was the project's before the work began: added
|
|
204
|
+
* to the repository by someone else before then, or, not committed, made on disk before then. A file of the project
|
|
205
|
+
* changed by the work is still the project's — the application started after a change is the work, run the way the
|
|
206
|
+
* project runs it; a file that was not there is a script the work wrote.
|
|
207
|
+
*/
|
|
208
|
+
export function writtenDuringTheWork(file, since) {
|
|
209
|
+
if (!existsSync(file))
|
|
210
|
+
return null;
|
|
211
|
+
const began = since ? Date.parse(since) : NaN;
|
|
212
|
+
const top = gitSync(dirname(file), ['rev-parse', '--show-toplevel']);
|
|
213
|
+
if (top.ok && top.stdout) {
|
|
214
|
+
const rel = relative(top.stdout, file);
|
|
215
|
+
const path = rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel.replace(/\\/g, '/') : file;
|
|
216
|
+
const added = gitSync(top.stdout, ['log', '--diff-filter=A', '--format=%ae%x09%ct', '-1', '--', path]);
|
|
217
|
+
if (added.ok && added.stdout.trim()) {
|
|
218
|
+
const [email = '', time = ''] = added.stdout.trim().split('\t');
|
|
219
|
+
if (email.trim().toLowerCase() === RUNNER_EMAIL)
|
|
220
|
+
return 'it was added by copilot-operator, so it was written during the work';
|
|
221
|
+
if (Number.isFinite(began) && Number(time) * 1000 >= began - 1000)
|
|
222
|
+
return 'it was added after this work began';
|
|
223
|
+
return null;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
if (!Number.isFinite(began))
|
|
227
|
+
return 'it is not committed, and nothing tells when it was written';
|
|
228
|
+
let born = NaN;
|
|
229
|
+
try {
|
|
230
|
+
born = statSync(file).birthtimeMs;
|
|
231
|
+
}
|
|
232
|
+
catch {
|
|
233
|
+
/* unreadable: the runtime will say so */
|
|
234
|
+
}
|
|
235
|
+
return Number.isFinite(born) && born >= began - 1000 ? 'it was made after this work began and is not committed' : null;
|
|
236
|
+
}
|
|
165
237
|
/**
|
|
166
238
|
* Why a chat's step must not run a script, or null: a shell script that is not one of the project's own (see
|
|
167
|
-
* `notTheProjects`),
|
|
168
|
-
*
|
|
239
|
+
* `notTheProjects`), a file of code written during the work given to a runtime (see `writtenDuringTheWork`), or any
|
|
240
|
+
* file in `.cop-tmp` given to a program that runs it. Every one of them is the operator's to run (2026-10-26), and the
|
|
241
|
+
* chat is told to hand it over. Only for the chat's steps, the implementer's and the reviewer's: the operator's own
|
|
242
|
+
* checks are theirs to point at whatever they choose.
|
|
169
243
|
*/
|
|
170
|
-
export function ownScriptRefusal(command, cwd, since) {
|
|
244
|
+
export function ownScriptRefusal(command, cwd, since, shell) {
|
|
171
245
|
// A file of code in it, given to a program that runs files — not its output written there (`node x.js > .cop-tmp\out.txt`).
|
|
172
246
|
const scratch = new RegExp(String.raw `\b${RUNS_A_FILE}(?:\.exe|\.cmd)?\b[^|;\n]*?(?:^|[\s'"=(,:])(?:\.[\\/])?(?:[^\s'"|;]*[\\/])?\.cop-tmp[\\/][^\s'"|;]*\.(?:ps1|psm1|cmd|bat|js|mjs|cjs|jsx|ts|mts|cts|tsx|py|rb|pl|php|vbs|vbe|wsf|sh|jar|dll|exe|csx)\b`, 'i');
|
|
173
247
|
const why = (file, reason) => `refused: ${relative(cwd, file) || file} is not one of the project's own scripts — ${reason}. A script written or ` +
|
|
174
|
-
'changed during the work is not
|
|
175
|
-
|
|
176
|
-
|
|
248
|
+
'changed during the work is run by the operator, not by the runner, nor is anything in .cop-tmp (the operator\'s rule). ' +
|
|
249
|
+
HAND_IT_OVER;
|
|
250
|
+
if (scratch.test(command)) {
|
|
251
|
+
return 'refused: this runs a file in .cop-tmp, the folder for scratch files — the runner runs nothing there (the operator\'s rule). ' + HAND_IT_OVER;
|
|
252
|
+
}
|
|
177
253
|
for (const file of shellScriptsRun(command, cwd)) {
|
|
178
254
|
const reason = notTheProjects(file, since);
|
|
179
255
|
if (reason)
|
|
180
256
|
return why(file, reason);
|
|
181
257
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
258
|
+
for (const file of codeFilesRun(command, cwd, shell)) {
|
|
259
|
+
const reason = writtenDuringTheWork(file, since);
|
|
260
|
+
if (reason) {
|
|
261
|
+
return (`refused: ${relative(cwd, file) || file} is a script written during this work — ${reason} — and such a script is run by ` +
|
|
262
|
+
'the operator, not by the runner (the operator\'s rule). ' + HAND_IT_OVER + ' The project\'s tests run as steps, as before.');
|
|
263
|
+
}
|
|
185
264
|
}
|
|
186
265
|
return null;
|
|
187
266
|
}
|
|
267
|
+
/** What the chat is told to do instead (2026-10-26). */
|
|
268
|
+
const HAND_IT_OVER = 'Put what it does in the step itself — a command may be several lines — or hand it to the operator with status "handoff": ' +
|
|
269
|
+
'the commands, the folder, what they should see and the script; the operator runs it and you get what it printed.';
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Commands the operator runs themselves (operator, 2026-10-26: "the script is made, but the user runs it; the bot gives
|
|
3
|
+
* the commands for the user to run and the result it expects"). The runner never runs a script written during the
|
|
4
|
+
* work (`exec/scriptFiles.ts`); the chat hands it over with `"status": "handoff"` and the operator gets a card: the
|
|
5
|
+
* lines in order, the folder, what should be seen, and the script files they run, read from disk with their SHA-256,
|
|
6
|
+
* so what the operator reads is what they run. A line the runner would refuse outright is marked on the card: the
|
|
7
|
+
* card is not a way round the rules, and the operator is told so before running it in their own terminal.
|
|
8
|
+
*
|
|
9
|
+
* What the operator sends back goes to the chat in the same words wherever it was answered: on the card in the
|
|
10
|
+
* conversation, or on a queue task's card answered after it was set aside.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
14
|
+
import { isAbsolute, relative, resolve } from 'node:path';
|
|
15
|
+
import { dangerousRefusal } from '../exec/dangerous.js';
|
|
16
|
+
import { botSelfRefusal } from '../exec/network.js';
|
|
17
|
+
import { matchDenyPattern } from '../exec/policy.js';
|
|
18
|
+
/** The most of one script shown on the card; its hash is of all of it. */
|
|
19
|
+
const MAX_SHOWN_BYTES = 64 * 1024;
|
|
20
|
+
/** A script larger than this is not read for the card at all. */
|
|
21
|
+
const MAX_READ_BYTES = 4 * 1024 * 1024;
|
|
22
|
+
const inside = (roots, path) => roots.some((root) => {
|
|
23
|
+
const rel = relative(root, path);
|
|
24
|
+
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
|
25
|
+
});
|
|
26
|
+
/** The card for a handoff: the folder resolved in the project, each script read with its hash, the lines the runner refuses. */
|
|
27
|
+
export function handoffCard(h, cwd, roots, denyPatterns) {
|
|
28
|
+
const folder = resolve(cwd, h.cwd ?? '.');
|
|
29
|
+
const files = h.files.map((f) => {
|
|
30
|
+
const full = resolve(folder, f);
|
|
31
|
+
const path = relative(cwd, full).replace(/\\/g, '/') || f;
|
|
32
|
+
if (!inside(roots, full))
|
|
33
|
+
return { path: f, problem: 'outside the project' };
|
|
34
|
+
if (!existsSync(full))
|
|
35
|
+
return { path, problem: 'not there' };
|
|
36
|
+
try {
|
|
37
|
+
const size = statSync(full).size;
|
|
38
|
+
if (size > MAX_READ_BYTES)
|
|
39
|
+
return { path, problem: `too large to show (${Math.round(size / 1024)} KB)` };
|
|
40
|
+
const bytes = readFileSync(full);
|
|
41
|
+
const text = bytes.subarray(0, MAX_SHOWN_BYTES).toString('utf8');
|
|
42
|
+
return { path, sha256: createHash('sha256').update(bytes).digest('hex'), text, ...(bytes.length > MAX_SHOWN_BYTES ? { cut: true } : {}) };
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
return { path, problem: e.message };
|
|
46
|
+
}
|
|
47
|
+
});
|
|
48
|
+
const warnings = [];
|
|
49
|
+
h.commands.forEach((line, i) => {
|
|
50
|
+
const deny = matchDenyPattern(line, denyPatterns);
|
|
51
|
+
const why = dangerousRefusal(line) ?? botSelfRefusal(line) ?? (deny ? `refused: matches deny pattern /${deny}/` : null);
|
|
52
|
+
if (why)
|
|
53
|
+
warnings.push(`${i + 1}: ${why.replace(/^refused:\s*/, '')}`);
|
|
54
|
+
});
|
|
55
|
+
return {
|
|
56
|
+
commands: h.commands,
|
|
57
|
+
cwd: folder,
|
|
58
|
+
expect: h.expect,
|
|
59
|
+
files,
|
|
60
|
+
...(inside(roots, folder) ? {} : { outside: true }),
|
|
61
|
+
...(warnings.length ? { warnings } : {}),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
/** What the chat is told of the commands it handed over: what they printed when the operator ran them, or that they did not. */
|
|
65
|
+
export function handoffResultMessage(h, ran, text) {
|
|
66
|
+
const lines = h.commands.map((c) => ` ${c}`).join('\n');
|
|
67
|
+
const said = text.trim();
|
|
68
|
+
if (!ran) {
|
|
69
|
+
return (`The operator did not run the commands you handed over:\n${lines}\n\n${said ? `They say: ${said}\n\n` : ''}` +
|
|
70
|
+
'Go on with the work without them, or end blocked and say in "needed" what has to be run.');
|
|
71
|
+
}
|
|
72
|
+
const fence = said.includes('```') ? '~~~~' : '```';
|
|
73
|
+
return (`The operator ran the commands you handed over, themselves:\n${lines}\n\n` +
|
|
74
|
+
`What it printed, as they gave it:\n\n${fence}\n${said || '(nothing)'}\n${fence}\n\n` +
|
|
75
|
+
`You expected: ${h.expect}\n\nCompare the two and go on with the work from here, in the same format.`);
|
|
76
|
+
}
|
|
77
|
+
/** What the chat is told when nobody is there to run them: the terminal's run, or one with nobody to ask. */
|
|
78
|
+
export const HANDOFF_NOBODY = 'Nobody is here to run the commands you handed over: this run has nobody to ask. Go on with the work without them, ' +
|
|
79
|
+
'or end blocked and say in "needed" what the operator has to run and what it should show.';
|
|
@@ -37,6 +37,7 @@ import { allAboutTheTask, isRepeat, findingId } from '../protocol/reviewSchema.j
|
|
|
37
37
|
import { repoState, workingTreePaths } from '../vcs/git.js';
|
|
38
38
|
import { describeStep, checkAccessRefusal, checkCommandRefusal, commandRefusal, staticCheck } from '../exec/policy.js';
|
|
39
39
|
import { networkFetchReason } from '../exec/network.js';
|
|
40
|
+
import { handoffCard, handoffResultMessage, HANDOFF_NOBODY } from './handoff.js';
|
|
40
41
|
import { collectPolicyManifest, describePolicyManifest } from '../exec/policyManifest.js';
|
|
41
42
|
import { assessIsolation, readIsolationSignals } from '../exec/isolation.js';
|
|
42
43
|
import { confinementRefusal, isWithin, sessionRoots } from '../exec/confinement.js';
|
|
@@ -2677,6 +2678,44 @@ export async function runTask(transport, session, task, deps) {
|
|
|
2677
2678
|
* what the reply said, at greater length and one message later. The reason carries the
|
|
2678
2679
|
* approaches that were tried, and that is what the register shows.
|
|
2679
2680
|
*/
|
|
2681
|
+
/*
|
|
2682
|
+
* Commands the operator runs themselves (operator, 2026-10-26: "the script is made, but the user runs it; the bot
|
|
2683
|
+
* gives the commands for the user to run and the result it expects"). Never answered for the operator, Settings'
|
|
2684
|
+
* agreement or not: only their own run of it has anything to say. With nobody to ask, the chat is told so. What
|
|
2685
|
+
* they printed, or that they did not run it, goes back, and the work goes on.
|
|
2686
|
+
*/
|
|
2687
|
+
if (reply.status === 'handoff' && reply.handoff) {
|
|
2688
|
+
const card = handoffCard(reply.handoff, work.cwd, confinement.roots, cfg.execution.denyPatterns);
|
|
2689
|
+
const why = reply.handoff.why?.trim() || 'Run these commands yourself, and send what they print.';
|
|
2690
|
+
let message = HANDOFF_NOBODY;
|
|
2691
|
+
await record('HANDOFF', `${why}\n\nin ${card.cwd}:\n${card.commands.join('\n')}\n\nexpected: ${card.expect}${card.files.length ? `\n\nscripts: ${card.files.map((f) => `${f.path}${f.sha256 ? ` (sha256 ${f.sha256})` : f.problem ? ` (${f.problem})` : ''}`).join(', ')}` : ''}`);
|
|
2692
|
+
if (deps.askQuestion) {
|
|
2693
|
+
sink.event('handoff-asked', { commands: card.commands, cwd: card.cwd, files: card.files.map((f) => ({ path: f.path, sha256: f.sha256 })) }, `the chat hands the operator commands to run themselves: ${card.commands.join(' ; ')}`, 'warn');
|
|
2694
|
+
await setTask((t) => {
|
|
2695
|
+
t.status = 'waiting-approval';
|
|
2696
|
+
});
|
|
2697
|
+
const got = await deps.askQuestion({ sessionId: session.id, taskId: task.id, question: why, options: [], handoff: card, actor: planning ? 'plan' : 'worker' });
|
|
2698
|
+
await setTask((t) => {
|
|
2699
|
+
t.status = 'running';
|
|
2700
|
+
});
|
|
2701
|
+
if (got === 'stop' || signal?.aborted)
|
|
2702
|
+
return await finish('aborted', 'stopped by the operator at the commands handed over', undefined, lastMarkdown);
|
|
2703
|
+
const ran = got.ran !== false;
|
|
2704
|
+
sink.event('handoff-answered', { ran }, ran ? 'the operator ran the commands and sent what they printed' : 'the operator did not run the commands');
|
|
2705
|
+
message = handoffResultMessage(card, ran, got.answer);
|
|
2706
|
+
}
|
|
2707
|
+
else {
|
|
2708
|
+
sink.event('handoff-nobody', { commands: card.commands }, 'the chat handed over commands to run, and nobody is here to run them', 'warn');
|
|
2709
|
+
}
|
|
2710
|
+
await record('HANDOFF RESULT', message);
|
|
2711
|
+
await pacer.throttleSend();
|
|
2712
|
+
const before = await transport.sendAndConfirm(message);
|
|
2713
|
+
const next = await transport.waitForReply(before);
|
|
2714
|
+
await saveReply('handoff', next);
|
|
2715
|
+
lastMarkdown = next.markdown;
|
|
2716
|
+
await pacer.settle();
|
|
2717
|
+
continue;
|
|
2718
|
+
}
|
|
2680
2719
|
/*
|
|
2681
2720
|
* A question only the operator can answer (operator, 2026-10-23: "answers to click, not only a text field; when the
|
|
2682
2721
|
* chat proposes a command for the user to run by hand, a button behind it, and the bot runs it"): put to the
|
|
@@ -166,6 +166,7 @@ You are **Kerrigan**. You help the person talking to you get their work done wit
|
|
|
166
166
|
- Copilot learns the project only through those commands: it lists files, reads them, runs the build and the tests. It is not sent the files themselves, and it knows nothing about the project that the task does not say and the commands cannot find.
|
|
167
167
|
- The person chooses how commands run in Settings, under ${Q('exec.startMode')} (not in the chat): ${Q('exec.startModeAsk')} (they press ${Q('chat.askRun')}, ${Q('chat.askRunAll')} or ${Q('chat.askSkip')} on a card that says who asks) or ${Q('exec.startModeAuto')}. A list of forbidden commands applies either way; pushing to a remote is refused; nothing needs administrator rights. A command that reaches a platform with the person's own access — Azure, AWS, GitHub, Jira, publishing a package and the like — waits on a card even in a run without asking, unless ${Q('exec.questions')} in Settings is set to agree with what the bot proposes; so do the questions the chat or the lead asks, with their answers to click. Once one answer on a card is pressed, the card's other answers and its text box turn off and the one pressed stays marked until the card goes; only when the answer did not reach the program do they come back on, with the reason on the card.
|
|
168
168
|
- The programs a command may start are listed in Settings, under "Programs the bot may start": the person adds one by its name (${Q('prog.add')}, ${Q('prog.addButton')}) and takes one off with its ✕; a command that starts a program not on the list is refused, and the chat is told why. A program that reaches a platform with their access is set to ${Q('prog.modeAsk')}, or, for az, to ${Q('prog.modeReadOnly')}: az's commands that only look (list, show, query) then run without a card, the ones that create, change, delete, sign in or out, or show a secret are refused, and one the program cannot read waits on a card. The person signs in themselves, with az login in their own terminal; the program uses that sign-in and never sees the password. The program reads the command line and a script could go round it, so for a guarantee they sign in with an account that has only the Reader role in Azure, and Azure itself refuses every change.
|
|
169
|
+
- A script Copilot writes during the work — a diagnostic, a reproduction, a small tool — is never run by the program (the person's rule): Copilot hands it over on a card, "Run this yourself", with the commands in order (and Copy), the folder, what should be seen, and each script with its SHA-256 to read first. The person runs them in their own terminal, pastes what they printed and presses ${Q('ho.send')}, or presses ${Q('ho.notRun')}; the card waits for them even when Settings agree with what the bot proposes. The project's tests, the build and the application run as steps, as before.
|
|
169
170
|
- The model: ${Q('chat.model')} under the chat's box. When it is to be chosen by hand (the default), a card asks the person to choose the model in the Copilot window and press ${Q('approval.manualReady')}.
|
|
170
171
|
- ${Q('chat.planMode')} (a choice under the chat's box): Copilot first looks at the project with read-only commands and proposes a plan — what is there, how it means to do it, the stages, the files, how it will show it works — and nothing is changed until the person approves the plan (${Q('pm.approve')}), asks for another (${Q('pm.revise')}), or stops.
|
|
171
172
|
- ${Q('chat.review')} (under the chat's box, on unless unticked): when Copilot says the work is done, a conversation of its own reviews it — reads the changes, runs the checks — and sends back what it finds, up to ${n(rounds)} round(s) of fixing. When the model is chosen by hand, the card for the review's model says it is the review's: a different, stronger model than the one that did the work catches more mistakes.
|
|
@@ -249,6 +250,7 @@ function bgText(f) {
|
|
|
249
250
|
- Copilot опознава проекта само чрез тези команди: изброява файлове, чете ги, пуска компилацията и тестовете. Самите файлове не му се изпращат и той не знае за проекта нищо, което заданието не казва и командите не могат да намерят.
|
|
250
251
|
- Човекът избира как се изпълняват командите в Настройки, при ${Q('exec.startMode')} (не в чата): ${Q('exec.startModeAsk')} (натиска ${Q('chat.askRun')}, ${Q('chat.askRunAll')} или ${Q('chat.askSkip')} на карта, на която пише кой иска) или ${Q('exec.startModeAuto')}. И в двата случая важи списък със забранени команди; изпращането към отдалечено хранилище (push) се отказва; нищо не изисква администраторски права. Команда, която достъпва платформа със собствения достъп на човека — Azure, AWS, GitHub, Jira, публикуване на пакет и подобни, — чака на карта дори при пускане без питане, освен ако ${Q('exec.questions')} в Настройки не е настроено да се съгласява с това, което предлага ботът; същото важи за въпросите на чата или на ръководителя, с отговори за избор. Щом се натисне един отговор на карта, другите отговори и полето за текст на картата се изключват, а натиснатият остава отбелязан, докато картата изчезне; включват се отново само ако отговорът не е стигнал до програмата, с причината на картата.
|
|
251
252
|
- Програмите, които командата може да пуска, са изброени в Настройки, при „Програми, които ботът може да пуска“: човекът добавя програма по името ѝ (${Q('prog.add')}, ${Q('prog.addButton')}) и маха програма с нейното ✕; команда, която пуска програма извън списъка, се отказва и на чата се казва защо. Програма, която достъпва платформа с неговия достъп, е на ${Q('prog.modeAsk')} или, за az, на ${Q('prog.modeReadOnly')}: тогава командите на az, които само гледат (list, show, query), се изпълняват без карта, тези, които създават, променят, трият, влизат или излизат, или показват тайна, се отказват, а такава, която програмата не може да разчете, чака на карта. Човекът влиза сам, с az login в собствения си терминал; програмата ползва този вход и никога не вижда паролата. Програмата чете командния ред и скрипт би могъл да го заобиколи, затова за гаранция той влиза с акаунт, който има само ролята Reader в Azure, и тогава самият Azure отказва всяка промяна.
|
|
253
|
+
- Скрипт, който Copilot пише по време на работата — диагностика, възпроизвеждане, малък инструмент, — програмата никога не го пуска (правилото на човека): Copilot го предава на карта „Пуснете го сами“ с командите по ред (и „Копирай“), папката, какво трябва да се види и всеки скрипт с неговия SHA-256, за да се прочете първо. Човекът ги пуска в собствения си терминал, поставя какво са изписали и натиска ${Q('ho.send')} или натиска ${Q('ho.notRun')}; картата чака него, дори когато Настройки се съгласяват с това, което предлага ботът. Тестовете на проекта, компилацията и приложението се пускат като стъпки, както досега.
|
|
252
254
|
- Моделът: ${Q('chat.model')} под полето на чата. Когато се избира ръчно (по подразбиране), карта моли човека да избере модела в прозореца на Copilot и да натисне ${Q('approval.manualReady')}.
|
|
253
255
|
- ${Q('chat.planMode')} (избор под полето на чата): Copilot първо разглежда проекта само с команди, които четат, и предлага план — какво има, как смята да го направи, етапите, файловете, как ще покаже, че работи, — и нищо не се променя, докато човекът не одобри плана (${Q('pm.approve')}), не поиска друг (${Q('pm.revise')}) или не спре.
|
|
254
256
|
- ${Q('chat.review')} (под полето на чата, включена, освен ако не я изключат): когато Copilot каже, че работата е готова, отделен разговор я преглежда — чете промените, пуска проверките — и връща каквото открие, до ${n(rounds)} кръга поправка. Когато моделът се избира ръчно, картата за модела на рецензията казва, че е за нея: модел, различен и по-силен от този, с който е работено, хваща повече грешки.
|
|
@@ -205,6 +205,14 @@ export const SYSTEM_GUIDE = [
|
|
|
205
205
|
doesEn: 'At the top of every page: one card per waiting step, with its session (a link) and the exact command. The browser tab shows "(n) waiting for you".',
|
|
206
206
|
doesBg: 'Горе на всяка страница: по една карта за всяка чакаща стъпка, със сесията ѝ (връзка) и точната команда. Разделът на браузъра показва „(n) чака вас“.',
|
|
207
207
|
},
|
|
208
|
+
{
|
|
209
|
+
key: 'awaiting.title',
|
|
210
|
+
kind: 'note',
|
|
211
|
+
en: "Waiting for the user's action",
|
|
212
|
+
bg: 'Изчаква се действие от потребителя',
|
|
213
|
+
doesEn: "While anything waits for you — a command to run or skip, a question, a plan, commands handed over to run yourself, a subtask's choices, the model to choose by hand, Git's password window — the rest of the window is darkened, the card is left lit inside a ring, and this label is shown large over the darkened part. It needs no button: it goes when you answer. Nothing is blocked; you can still click and read everything. The chat opens on the conversation that asks and moves to the card, even when it was closed or scrolled up; the keyboard goes to the card unless you are typing somewhere.",
|
|
214
|
+
doesBg: 'Докато нещо чака вас — команда за изпълнение или пропускане, въпрос, план, команди, предадени ви да ги пуснете сами, избор за подзадача, модел за избиране на ръка, прозорецът на Git за парола — останалата част от прозореца се затъмнява, картата остава осветена в рамка и този надпис се показва голям над затъмненото. Не иска бутон: изчезва, когато отговорите. Нищо не е блокирано; пак можете да натискате и четете всичко. Чатът се отваря на разговора, който пита, и отива на картата, дори да е бил затворен или скролнат нагоре; клавиатурата отива на картата, освен ако пишете някъде.',
|
|
215
|
+
},
|
|
208
216
|
{
|
|
209
217
|
key: 'approval.run',
|
|
210
218
|
kind: 'button',
|
|
@@ -472,8 +480,8 @@ export const SYSTEM_GUIDE = [
|
|
|
472
480
|
kind: 'button',
|
|
473
481
|
en: 'Git',
|
|
474
482
|
bg: 'Git',
|
|
475
|
-
doesEn: 'Shows the open folder\'s git: the branch, the staged changes and the changes, each file with its letter (M modified, A added, D deleted, R renamed, U untracked, ! in conflict) and its lines, and the branch\'s commits; a file opens its two versions side by side, a commit opens to its files. Read-only.',
|
|
476
|
-
doesBg: 'Показва git на отворената папка: клона, подготвените промени и промените — всеки файл с буквата си (M променен, A добавен, D изтрит, R преименуван, U непроследен, ! в конфликт) и редовете си — и комитите на клона; файл отваря двете си версии една до друга, комит се разгъва до файловете си. Само чете.',
|
|
483
|
+
doesEn: 'Shows the open folder\'s git: the branch, the staged changes and the changes, each file with its letter (M modified, A added, D deleted, R renamed, U untracked, ! in conflict) and its lines, and the branch\'s commits; a file opens its two versions side by side, a commit opens to its files. Read-only. Two numbers on the button: above, the files not committed yet; below, every file changed on this branch, committed or not, against the branch "Compared with" names (a number that is 0 is not shown; the button\'s tooltip says both).',
|
|
484
|
+
doesBg: 'Показва git на отворената папка: клона, подготвените промени и промените — всеки файл с буквата си (M променен, A добавен, D изтрит, R преименуван, U непроследен, ! в конфликт) и редовете си — и комитите на клона; файл отваря двете си версии една до друга, комит се разгъва до файловете си. Само чете. Две числа върху бутона: горе — файловете, които още не са комитнати; долу — всички файлове, променени на този клон, комитнати или не, спрямо клона в „Сравнен с“ (число 0 не се показва; подсказката на бутона казва и двете).',
|
|
477
485
|
},
|
|
478
486
|
{
|
|
479
487
|
key: 'wb.refresh',
|
|
@@ -1050,6 +1058,38 @@ export const SYSTEM_GUIDE = [
|
|
|
1050
1058
|
doesEn: 'Sends your answer to the lead, and the work goes on.',
|
|
1051
1059
|
doesBg: 'Изпраща отговора ви на ръководителя и работата продължава.',
|
|
1052
1060
|
},
|
|
1061
|
+
{
|
|
1062
|
+
key: 'ho.output',
|
|
1063
|
+
kind: 'field',
|
|
1064
|
+
en: 'What it printed',
|
|
1065
|
+
bg: 'Какво изписа',
|
|
1066
|
+
doesEn: 'On the card "Run this yourself", where the chat hands over a script it wrote with the commands, the folder and what should be seen (the bot never runs such a script): paste here what the commands printed in your own terminal.',
|
|
1067
|
+
doesBg: 'На картата „Пуснете го сами“, където чатът предава написан от него скрипт с командите, папката и какво трябва да се види (ботът никога не пуска такъв скрипт): поставете тук какво изписаха командите в собствения ви терминал.',
|
|
1068
|
+
},
|
|
1069
|
+
{
|
|
1070
|
+
key: 'ho.send',
|
|
1071
|
+
kind: 'button',
|
|
1072
|
+
en: 'Send what it printed',
|
|
1073
|
+
bg: 'Изпрати какво изписа',
|
|
1074
|
+
doesEn: 'Sends what you pasted to the chat, beside what it expected, and the work goes on.',
|
|
1075
|
+
doesBg: 'Изпраща поставеното на чата, до това, което е очаквал, и работата продължава.',
|
|
1076
|
+
},
|
|
1077
|
+
{
|
|
1078
|
+
key: 'ho.notRun',
|
|
1079
|
+
kind: 'button',
|
|
1080
|
+
en: 'I did not run it',
|
|
1081
|
+
bg: 'Не го пуснах',
|
|
1082
|
+
doesEn: 'Tells the chat you did not run the commands, with what you wrote as the reason; it goes on without them or ends blocked.',
|
|
1083
|
+
doesBg: 'Казва на чата, че не сте пуснали командите, с написаното като причина; той продължава без тях или приключва като блокиран.',
|
|
1084
|
+
},
|
|
1085
|
+
{
|
|
1086
|
+
key: 'approval.openChat',
|
|
1087
|
+
kind: 'link',
|
|
1088
|
+
en: 'Open the chat ({name})',
|
|
1089
|
+
bg: 'Отвори чата ({name})',
|
|
1090
|
+
doesEn: 'On the card at the top of another page, for a question of the chat\'s or commands handed over: opens the chat, where it is answered.',
|
|
1091
|
+
doesBg: 'На картата най-горе на друга страница, за въпрос на чата или предадени команди: отваря чата, където се отговаря.',
|
|
1092
|
+
},
|
|
1053
1093
|
{
|
|
1054
1094
|
key: 'lead.stop',
|
|
1055
1095
|
kind: 'button',
|
|
@@ -233,8 +233,8 @@ export function parseReply(markdown, opts) {
|
|
|
233
233
|
// model that writes "Край" under an explanation of why it cannot finish has ended the
|
|
234
234
|
// task, not completed it, and reading that as `done` would file a failure as a success.
|
|
235
235
|
const blocked = reply.status === 'blocked';
|
|
236
|
-
// A plan waits for its approval, a question for its answer: the stop word in
|
|
237
|
-
const plan = reply.status === 'plan' || reply.status === 'ask';
|
|
236
|
+
// A plan waits for its approval, a question for its answer, a handoff for the operator's run: the stop word in none of them ends the task.
|
|
237
|
+
const plan = reply.status === 'plan' || reply.status === 'ask' || reply.status === 'handoff';
|
|
238
238
|
return {
|
|
239
239
|
ok: true,
|
|
240
240
|
reply: { ...reply, steps },
|
|
@@ -115,6 +115,21 @@ export const OptionSchema = z.preprocess((v) => (typeof v === 'string' ? { answe
|
|
|
115
115
|
run: z.string().trim().min(1).optional(),
|
|
116
116
|
shell: ShellSchema.optional(),
|
|
117
117
|
}));
|
|
118
|
+
/**
|
|
119
|
+
* Commands the operator runs themselves (operator, 2026-10-26: "the script is made, but the user runs it; the bot gives
|
|
120
|
+
* the commands for the user to run and the result it expects"): a script written during the work is never run by the
|
|
121
|
+
* runner (`scriptFiles.ts`), so the chat hands it over — the lines in order, the folder, what should be seen, and the
|
|
122
|
+
* script files they run, which the card shows with their SHA-256 so the operator reads what they run.
|
|
123
|
+
*/
|
|
124
|
+
export const HandoffSchema = z.object({
|
|
125
|
+
why: z.string().trim().min(1).optional(),
|
|
126
|
+
/** The folder the commands are typed in, relative to the project; the project itself when left out. */
|
|
127
|
+
cwd: z.string().trim().min(1).optional(),
|
|
128
|
+
commands: z.array(z.preprocess(asText, z.string().trim().min(1))).min(1, 'handoff.commands needs at least one command for the operator to run.'),
|
|
129
|
+
expect: z.string().trim().min(5, 'handoff.expect must say what the operator should see when it works.'),
|
|
130
|
+
/** The script files the commands run, relative to the project. */
|
|
131
|
+
files: z.array(z.preprocess(asText, z.string().trim().min(1))).default([]),
|
|
132
|
+
});
|
|
118
133
|
export const ReplySchema = z
|
|
119
134
|
.object({
|
|
120
135
|
/**
|
|
@@ -134,13 +149,15 @@ export const ReplySchema = z
|
|
|
134
149
|
* `plan` — in plan mode only: here is the plan, made from what I read; no steps with it, and no change
|
|
135
150
|
* made yet. See `PlanSchema`.
|
|
136
151
|
*/
|
|
137
|
-
status: z.enum(['continue', 'done', 'blocked', 'plan', 'ask']),
|
|
152
|
+
status: z.enum(['continue', 'done', 'blocked', 'plan', 'ask', 'handoff']),
|
|
138
153
|
/** Required when `status` is `plan`. */
|
|
139
154
|
plan: PlanSchema.optional(),
|
|
140
155
|
/** `ask` — a question only the operator can answer (2026-10-23): the question, why, and the answers to click. */
|
|
141
156
|
question: z.string().optional(),
|
|
142
157
|
why: z.string().optional(),
|
|
143
158
|
options: z.array(OptionSchema).default([]),
|
|
159
|
+
/** `handoff` — a script written during the work, for the operator to run themselves (2026-10-26). */
|
|
160
|
+
handoff: HandoffSchema.optional(),
|
|
144
161
|
steps: z.array(StepSchema).default([]),
|
|
145
162
|
notes: z.string().optional(),
|
|
146
163
|
/**
|
|
@@ -172,12 +189,16 @@ export const ReplySchema = z
|
|
|
172
189
|
'Send at least one step, or set status to "done" or "blocked".',
|
|
173
190
|
})
|
|
174
191
|
.refine((r) => r.status === 'continue' || r.steps.length === 0, {
|
|
175
|
-
message: 'status "done", "blocked", "plan" and "
|
|
192
|
+
message: 'status "done", "blocked", "plan", "ask" and "handoff" cannot carry steps: "done" and "blocked" end the task, "plan" waits for the plan to be approved, "ask" for the operator\'s answer (a command for an answer goes in its "run") and "handoff" for what the operator\'s own run of its commands printed. ' +
|
|
176
193
|
'Send the steps with status "continue".',
|
|
177
194
|
})
|
|
178
195
|
.refine((r) => r.status !== 'ask' || ((r.question ?? '').trim().length >= 5 && r.options.length >= 2), {
|
|
179
196
|
message: 'status "ask" requires a "question" for the operator and at least two "options", your recommended one first: ' +
|
|
180
197
|
'[{ "answer": "what the operator clicks" }, { "answer": "...", "run": "a command the runner runs if this is chosen" }].',
|
|
198
|
+
})
|
|
199
|
+
.refine((r) => r.status !== 'handoff' || !!r.handoff, {
|
|
200
|
+
message: 'status "handoff" requires a "handoff" object: { "why": what it is for, "cwd": the folder, relative to the project, ' +
|
|
201
|
+
'"commands": [the exact lines the operator types, in order], "expect": what they should see when it works, "files": [the scripts they run] }.',
|
|
181
202
|
})
|
|
182
203
|
.refine((r) => r.status !== 'plan' || !!r.plan, {
|
|
183
204
|
message: 'status "plan" requires a "plan" object: { "existing": what is already there, "approach": how, "steps": [the stages], ' +
|
package/dist/src/queue/queue.js
CHANGED
|
@@ -214,6 +214,12 @@ export function parkedAnswerFrom(p, input) {
|
|
|
214
214
|
return text(input.note) ? { kind: 'plan', decision: 'revise', note: text(input.note) } : { problem: 'Say what to change in the plan.' };
|
|
215
215
|
return { problem: 'A plan is approved, or sent back for another.' };
|
|
216
216
|
case 'question':
|
|
217
|
+
// Commands handed over (2026-10-26): what they printed, or that the operator did not run them, with a word or none.
|
|
218
|
+
if (p.approval.question?.handoff) {
|
|
219
|
+
if (input.ran === false)
|
|
220
|
+
return { kind: 'question', answer: text(input.answer), ran: false };
|
|
221
|
+
return text(input.answer) ? { kind: 'question', answer: text(input.answer), ran: true } : { problem: 'Paste what the commands printed first.' };
|
|
222
|
+
}
|
|
217
223
|
return text(input.answer) ? { kind: 'question', answer: text(input.answer) } : { problem: 'Write the answer first.' };
|
|
218
224
|
case 'retry': {
|
|
219
225
|
const choices = p.approval.retry?.choices ?? [];
|