mocode-ai 1.9.6 → 1.9.8
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/agent/index.js +27 -0
- package/dist/agent/model-turn.js +6 -6
- package/dist/agent/request-governor.js +1 -1
- package/dist/context/vision-window.js +24 -9
- package/dist/host/protocol.js +4 -1
- package/dist/host/stdio.js +45 -1
- package/dist/index.js +7 -0
- package/dist/jobs/dir-snapshot.js +332 -0
- package/dist/jobs/worktree.js +78 -20
- package/dist/orchestrator/board.js +332 -0
- package/dist/orchestrator/cli.js +628 -0
- package/dist/orchestrator/index.js +4 -0
- package/dist/orchestrator/integrate.js +344 -0
- package/dist/orchestrator/lane-channel.js +146 -0
- package/dist/orchestrator/lane-executor.js +439 -0
- package/dist/orchestrator/lane-repl.js +154 -0
- package/dist/orchestrator/lane-site.js +255 -0
- package/dist/orchestrator/lanes.js +72 -0
- package/dist/orchestrator/lease.js +132 -0
- package/dist/orchestrator/live-log.js +193 -0
- package/dist/orchestrator/repl.js +435 -0
- package/dist/orchestrator/review.js +135 -0
- package/dist/orchestrator/scheduler.js +673 -0
- package/dist/orchestrator/scope.js +88 -0
- package/dist/orchestrator/state.js +533 -0
- package/dist/orchestrator/store.js +221 -0
- package/dist/orchestrator/supervisor-prompt.js +54 -0
- package/dist/orchestrator/supervisor.js +798 -0
- package/dist/orchestrator/tail.js +508 -0
- package/dist/orchestrator/task-prompt.js +93 -0
- package/dist/orchestrator/terminal.js +269 -0
- package/dist/orchestrator/tools.js +392 -0
- package/dist/orchestrator/types.js +1 -0
- package/dist/orchestrator/watch-panel.js +154 -0
- package/dist/orchestrator/worker.js +475 -0
- package/dist/orchestrator/workspaces.js +191 -0
- package/dist/repl/commands/memory.js +1 -1
- package/dist/repl/runtime.js +16 -2
- package/dist/session/store.js +1 -1
- package/dist/tools/builtins/ask-human.js +27 -6
- package/dist/ui/handoff-block.js +91 -0
- package/dist/ui/layout-internal/statusbar.js +2 -1
- package/dist/ui/prompt-internal/editor.js +49 -0
- package/package.json +2 -2
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { createInitialRun, makeEvent, reduceEvent } from './state.js';
|
|
5
|
+
const SNAPSHOT = 'snapshot.json';
|
|
6
|
+
const EVENTS = 'events.jsonl';
|
|
7
|
+
const CANCEL = 'cancel.requested';
|
|
8
|
+
export function createOrchestrationId(now = new Date()) {
|
|
9
|
+
const p = (n, width = 2) => String(n).padStart(width, '0');
|
|
10
|
+
return (`${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-` +
|
|
11
|
+
`${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}-${randomBytes(2).toString('hex')}`);
|
|
12
|
+
}
|
|
13
|
+
export function orchestrationRoot(workspaceRoot) {
|
|
14
|
+
return path.join(path.resolve(workspaceRoot), '.mocode', 'orchestrations');
|
|
15
|
+
}
|
|
16
|
+
function parseEvents(file) {
|
|
17
|
+
let content;
|
|
18
|
+
try {
|
|
19
|
+
content = fs.readFileSync(file, 'utf8');
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (error.code === 'ENOENT')
|
|
23
|
+
return { events: [] };
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
const events = [];
|
|
27
|
+
let offset = 0;
|
|
28
|
+
for (const line of content.split('\n')) {
|
|
29
|
+
const nextOffset = offset + Buffer.byteLength(line, 'utf8') + 1;
|
|
30
|
+
if (line.trim()) {
|
|
31
|
+
try {
|
|
32
|
+
events.push(JSON.parse(line));
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const isIncompleteTail = nextOffset > Buffer.byteLength(content, 'utf8') && !content.endsWith('\n');
|
|
36
|
+
if (isIncompleteTail)
|
|
37
|
+
return { events, repairAt: offset };
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
offset = nextOffset;
|
|
42
|
+
}
|
|
43
|
+
return { events };
|
|
44
|
+
}
|
|
45
|
+
function processIsAlive(pid) {
|
|
46
|
+
try {
|
|
47
|
+
process.kill(pid, 0);
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
return error.code === 'EPERM';
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export class OrchestrationStore {
|
|
55
|
+
directory;
|
|
56
|
+
state;
|
|
57
|
+
constructor(directory, state) {
|
|
58
|
+
this.directory = directory;
|
|
59
|
+
this.state = state;
|
|
60
|
+
}
|
|
61
|
+
static create(workspaceRoot, definition, id = createOrchestrationId()) {
|
|
62
|
+
const directory = path.join(orchestrationRoot(workspaceRoot), id);
|
|
63
|
+
if (fs.existsSync(directory))
|
|
64
|
+
throw new Error(`Orchestration ${id} already exists.`);
|
|
65
|
+
fs.mkdirSync(directory, { recursive: true });
|
|
66
|
+
const initial = createInitialRun(id, path.resolve(workspaceRoot), definition);
|
|
67
|
+
const created = {
|
|
68
|
+
schemaVersion: initial.schemaVersion,
|
|
69
|
+
sequence: 1,
|
|
70
|
+
timestamp: initial.createdAt,
|
|
71
|
+
type: 'run.created',
|
|
72
|
+
data: { run: initial },
|
|
73
|
+
};
|
|
74
|
+
const state = reduceEvent(undefined, created);
|
|
75
|
+
fs.writeFileSync(path.join(directory, EVENTS), `${JSON.stringify(created)}\n`, 'utf8');
|
|
76
|
+
const store = new OrchestrationStore(directory, state);
|
|
77
|
+
store.writeSnapshot();
|
|
78
|
+
return store;
|
|
79
|
+
}
|
|
80
|
+
static load(workspaceRoot, id) {
|
|
81
|
+
const directory = path.join(orchestrationRoot(workspaceRoot), path.basename(id));
|
|
82
|
+
const eventsPath = path.join(directory, EVENTS);
|
|
83
|
+
const parsed = parseEvents(eventsPath);
|
|
84
|
+
const events = parsed.events;
|
|
85
|
+
if (events.length === 0)
|
|
86
|
+
throw new Error(`Orchestration ${id} was not found or has no event history.`);
|
|
87
|
+
if (parsed.repairAt !== undefined)
|
|
88
|
+
fs.truncateSync(eventsPath, parsed.repairAt);
|
|
89
|
+
// JSONL 是唯一事实源;snapshot 仅是派生缓存,合法 JSON 也不能绕过事件归约。
|
|
90
|
+
// load 保持只读:损坏的 snapshot 会在下一次 append 时自然被重写。
|
|
91
|
+
let state;
|
|
92
|
+
for (const event of events)
|
|
93
|
+
state = reduceEvent(state, event);
|
|
94
|
+
if (!state)
|
|
95
|
+
throw new Error(`Orchestration ${id} could not be rebuilt.`);
|
|
96
|
+
if (state.id !== id)
|
|
97
|
+
throw new Error(`Orchestration id mismatch: expected ${id}, found ${state.id}.`);
|
|
98
|
+
return new OrchestrationStore(directory, state);
|
|
99
|
+
}
|
|
100
|
+
get current() {
|
|
101
|
+
return structuredClone(this.state);
|
|
102
|
+
}
|
|
103
|
+
append(input) {
|
|
104
|
+
const eventsPath = path.join(this.directory, EVENTS);
|
|
105
|
+
const content = fs.readFileSync(eventsPath, 'utf8');
|
|
106
|
+
const parsed = parseEvents(eventsPath);
|
|
107
|
+
if (parsed.repairAt !== undefined)
|
|
108
|
+
throw new Error('Cannot append while the event log has an incomplete tail.');
|
|
109
|
+
const diskSequence = parsed.events.at(-1)?.sequence;
|
|
110
|
+
if (diskSequence !== this.state.sequence) {
|
|
111
|
+
throw new Error(`Orchestration state is stale: memory=${this.state.sequence}, disk=${diskSequence ?? 'empty'}.`);
|
|
112
|
+
}
|
|
113
|
+
const event = makeEvent(this.state, input);
|
|
114
|
+
const next = reduceEvent(this.state, event);
|
|
115
|
+
const fd = fs.openSync(eventsPath, 'a');
|
|
116
|
+
try {
|
|
117
|
+
const separator = content.length > 0 && !content.endsWith('\n') ? '\n' : '';
|
|
118
|
+
fs.writeSync(fd, `${separator}${JSON.stringify(event)}\n`, undefined, 'utf8');
|
|
119
|
+
fs.fsyncSync(fd);
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
fs.closeSync(fd);
|
|
123
|
+
}
|
|
124
|
+
this.state = next;
|
|
125
|
+
this.writeSnapshot();
|
|
126
|
+
return event;
|
|
127
|
+
}
|
|
128
|
+
acquireControllerLease() {
|
|
129
|
+
const target = path.join(this.directory, 'controller.lock');
|
|
130
|
+
const token = randomBytes(16).toString('hex');
|
|
131
|
+
const acquire = () => {
|
|
132
|
+
const fd = fs.openSync(target, 'wx');
|
|
133
|
+
try {
|
|
134
|
+
fs.writeFileSync(fd, `${JSON.stringify({ pid: process.pid, token, acquiredAt: new Date().toISOString() })}\n`);
|
|
135
|
+
fs.fsyncSync(fd);
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
fs.closeSync(fd);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
try {
|
|
142
|
+
acquire();
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error.code !== 'EEXIST')
|
|
146
|
+
throw error;
|
|
147
|
+
let owner = {};
|
|
148
|
+
try {
|
|
149
|
+
owner = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
// A malformed lock is not safe to steal automatically.
|
|
153
|
+
}
|
|
154
|
+
if (typeof owner.pid !== 'number' || processIsAlive(owner.pid)) {
|
|
155
|
+
throw new Error(`Orchestration ${this.state.id} already has an active controller.`);
|
|
156
|
+
}
|
|
157
|
+
fs.unlinkSync(target);
|
|
158
|
+
acquire();
|
|
159
|
+
}
|
|
160
|
+
let released = false;
|
|
161
|
+
return {
|
|
162
|
+
release: () => {
|
|
163
|
+
if (released)
|
|
164
|
+
return;
|
|
165
|
+
released = true;
|
|
166
|
+
try {
|
|
167
|
+
const current = JSON.parse(fs.readFileSync(target, 'utf8'));
|
|
168
|
+
if (current.token === token)
|
|
169
|
+
fs.unlinkSync(target);
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
// Never remove a lock that cannot be proven to belong to this controller.
|
|
173
|
+
}
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
requestCancellation() {
|
|
178
|
+
const target = path.join(this.directory, CANCEL);
|
|
179
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
180
|
+
fs.writeFileSync(tmp, `${new Date().toISOString()}\n`, 'utf8');
|
|
181
|
+
fs.renameSync(tmp, target);
|
|
182
|
+
}
|
|
183
|
+
cancellationMarkerExists() {
|
|
184
|
+
return fs.existsSync(path.join(this.directory, CANCEL));
|
|
185
|
+
}
|
|
186
|
+
artifactPath(...parts) {
|
|
187
|
+
const root = path.resolve(this.directory, 'artifacts');
|
|
188
|
+
const target = path.resolve(root, ...parts);
|
|
189
|
+
if (target !== root && !target.startsWith(`${root}${path.sep}`)) {
|
|
190
|
+
throw new Error('Artifact path escapes the orchestration directory.');
|
|
191
|
+
}
|
|
192
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
193
|
+
return target;
|
|
194
|
+
}
|
|
195
|
+
writeSnapshot() {
|
|
196
|
+
const target = path.join(this.directory, SNAPSHOT);
|
|
197
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
198
|
+
fs.writeFileSync(tmp, `${JSON.stringify(this.state, null, 2)}\n`, 'utf8');
|
|
199
|
+
fs.renameSync(tmp, target);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
export function listOrchestrations(workspaceRoot) {
|
|
203
|
+
const root = orchestrationRoot(workspaceRoot);
|
|
204
|
+
let names;
|
|
205
|
+
try {
|
|
206
|
+
names = fs.readdirSync(root);
|
|
207
|
+
}
|
|
208
|
+
catch {
|
|
209
|
+
return [];
|
|
210
|
+
}
|
|
211
|
+
const runs = [];
|
|
212
|
+
for (const name of names) {
|
|
213
|
+
try {
|
|
214
|
+
runs.push(OrchestrationStore.load(workspaceRoot, name).current);
|
|
215
|
+
}
|
|
216
|
+
catch {
|
|
217
|
+
// A damaged run remains on disk for manual recovery but does not break the list command.
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
221
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Supervisor 的系统提示(对话 REPL 用)。
|
|
2
|
+
//
|
|
3
|
+
// 刻意不复用 buildBasePrompt:那是"你自己动手改代码"的编码 agent 人设,而这里的模型手上
|
|
4
|
+
// 只有控制面工具,一行代码也改不了。给它一份编码 agent 的提示词只会诱发无效尝试
|
|
5
|
+
// (调用不存在的 read_file、声称"我看了一下 src/...")。
|
|
6
|
+
//
|
|
7
|
+
// 提示词只承担四件事:① 我是谁、我手上有什么;② 什么绝对不做;③ 派活/追问/收工怎么判断;
|
|
8
|
+
// ④ 怎么如实汇报(尤其"已排队 ≠ 已开始")。
|
|
9
|
+
export function buildSupervisorPrompt(options) {
|
|
10
|
+
return `# Identity
|
|
11
|
+
You are the mocode supervisor: the operator talks to you, and you dispatch work to full mocode agents that run in their own workspaces.
|
|
12
|
+
|
|
13
|
+
# What you control
|
|
14
|
+
You have exactly the control-plane tools below. You have **no file tools, no shell, and no code of your own** — every real change happens inside a worker's isolated lane.
|
|
15
|
+
- \`supervise_workspaces\` — which directories on this machine have run mocode (git state, sessions, open lanes).
|
|
16
|
+
- \`supervise_status\` — one run in full, or every live run at a glance.
|
|
17
|
+
- \`supervise_dispatch\` — send work to a workspace. With \`runId\` it appends to that run; otherwise the workspace's live run is reused; otherwise a new run is created. Returns immediately.
|
|
18
|
+
- \`supervise_ask\` — a real status turn delivered into that lane's existing worker session (read-only).
|
|
19
|
+
- \`supervise_tell\` — a binding steering message for that lane's remaining work.
|
|
20
|
+
- \`supervise_close\` — export the lane's accumulated diff, archive its session, drop the execution site.
|
|
21
|
+
- \`supervise_integrate\` — dry-run: will the lane patches apply cleanly? Nothing is written.
|
|
22
|
+
- \`supervise_apply\` — actually merge closed lane patches into the real workspace. The user confirms each time through a permission panel.
|
|
23
|
+
- \`supervise_review\` — a second opinion on "is this run finished?" over the handoff evidence.
|
|
24
|
+
- \`supervise_cancel\` — stop a run for good.
|
|
25
|
+
|
|
26
|
+
# Hard rules
|
|
27
|
+
1. **Never claim work you did not dispatch.** You cannot edit files. If the operator asks for a code change, that is a worker's job.
|
|
28
|
+
2. **Never invent state.** Run ids, lane ids, statuses, paths, and verdicts come from tool output. When you have not checked, say you have not checked, and check.
|
|
29
|
+
3. **"Queued" is not "started".** When a run is still working, dispatch queues the task; the reply says the task is queued. Tell the operator exactly that, and that it will be added when the current batch finishes.
|
|
30
|
+
4. **Isolation is the default.** Workers run in a git worktree (git repos) or a copy (plain directories). Their changes are *not* in the operator's directory until \`supervise_apply\` runs inside that lane's work. Never imply otherwise.
|
|
31
|
+
5. **Ask before irreversible actions.** Cancel, close of a lane that still holds un-integrated work, and apply onto a directory with local edits. One short question with concrete options beats guessing.
|
|
32
|
+
6. **Pick the workspace deliberately.** Use the snapshot below. If two workspaces plausibly match, ask which one instead of dispatching to the wrong repository.
|
|
33
|
+
7. **One workstream per lane, and reuse the lane for follow-ups.** The same lane id continues the same worker session with its files and history — dispatch there when the new task builds on the previous one. Use a new lane when the two tasks must not see each other's execution site.
|
|
34
|
+
|
|
35
|
+
# How to work
|
|
36
|
+
1. Restate the goal in one line, then split it into tasks only if the parts are genuinely independent (parallel dispatch is fine; up to six workers at once).
|
|
37
|
+
2. Every dispatch has a concrete objective: what to do, where to look, what "done" means, and — when it matters — the checks that must pass. The worker sees its lane's session plus your text, nothing else.
|
|
38
|
+
3. Dispatch, then report the run id, lane, workspace and what will happen. Do not sit and wait: the background is shown to the operator as it runs.
|
|
39
|
+
4. Use \`supervise_ask\` when the operator asks how it is going, or when you need to know what a worker actually verified. Use \`supervise_tell\` to correct scope or approach without restarting the session.
|
|
40
|
+
5. When the queue is drained, read the run status. If work remains, dispatch it. If it is done, tell the operator what changed, then close the lane(s).
|
|
41
|
+
6. After the lanes are closed, run \`supervise_integrate\` (dry-run) and report exactly which lanes are ready, which files they touch, and what blocks the rest. Only then offer \`supervise_apply\`.
|
|
42
|
+
7. If a worker reported an open question or risk in its handoff, surface it verbatim and ask the operator. Do not decide it yourself.
|
|
43
|
+
|
|
44
|
+
# Reporting
|
|
45
|
+
- Lead with the outcome: what is running / what finished / what is blocked — then the details.
|
|
46
|
+
- Keep it scannable: run id, lane, workspace, task state. No filler, no restating the request.
|
|
47
|
+
- Reply in the operator's language.
|
|
48
|
+
- When something failed, say where it is stuck and what you tried, instead of hiding it behind "in progress".
|
|
49
|
+
|
|
50
|
+
# Context
|
|
51
|
+
Supervisor cwd: ${options.root}
|
|
52
|
+
Known workspaces at startup: ${options.workspaceCount}
|
|
53
|
+
A live orchestration snapshot is appended to each user turn. Treat the newest snapshot as the truth; older ones are history.`;
|
|
54
|
+
}
|