@litfamily/litmuse 0.1.21 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/README.md +61 -15
- package/README_ko-KR.md +61 -15
- package/bin/litmuse.mjs +17 -33
- package/lib/agent-file.mjs +2 -11
- package/lib/agent-guide.mjs +71 -0
- package/lib/config.mjs +18 -0
- package/lib/doctor.mjs +3 -1
- package/lib/flags.mjs +35 -0
- package/lib/glyphs.mjs +55 -7
- package/lib/guard.mjs +38 -1
- package/lib/icon-font.mjs +198 -0
- package/lib/install-cards.mjs +8 -3
- package/lib/install.mjs +39 -8
- package/lib/paths.mjs +4 -1
- package/lib/safe-write.mjs +1 -1
- package/lib/uninstall.mjs +13 -1
- package/package.json +3 -2
- package/plugin/.muse-plugin/plugin.json +13 -13
- package/plugin/hooks/lib/autopilot.mjs +638 -0
- package/plugin/hooks/lib/common.mjs +80 -5
- package/plugin/hooks/lib/continuation.mjs +13 -52
- package/plugin/hooks/lib/goal.mjs +5 -2
- package/plugin/hooks/lib/run-group.mjs +33 -0
- package/plugin/hooks/lib/shell-verdict.mjs +1004 -0
- package/plugin/hooks/lib/suggest.mjs +110 -0
- package/plugin/hooks/pre-tool-use.mjs +111 -5
- package/plugin/hooks/subagent-start.mjs +12 -1
- package/plugin/hooks/user-prompt-submit.mjs +69 -13
- package/plugin/skills/lit-plan/SKILL.md +12 -2
- package/plugin/skills/lit-plan/scripts/goal-propose.mjs +9 -2
- package/plugin/skills/start-work/SKILL.md +94 -20
|
@@ -1,20 +1,35 @@
|
|
|
1
|
-
import { readFileSync, writeFileSync, mkdirSync, appendFileSync, existsSync, lstatSync, realpathSync, renameSync } from 'node:fs';
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, appendFileSync, existsSync, lstatSync, realpathSync, renameSync, chmodSync } from 'node:fs';
|
|
2
2
|
import { join, dirname, resolve } from 'node:path';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { createHash } from 'node:crypto';
|
|
5
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
6
6
|
import { digestMismatch } from './digest.mjs';
|
|
7
7
|
|
|
8
8
|
export const PLUGIN_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
|
9
9
|
const STDIN_LIMIT = 256 * 1024;
|
|
10
10
|
|
|
11
|
+
// When a payload is too large or will not parse, the session and folder it names are kept here, so the run guard
|
|
12
|
+
// can still deny the call during an active run instead of letting an unread call through.
|
|
13
|
+
let UNREAD = null;
|
|
14
|
+
export const unreadPayload = () => UNREAD;
|
|
15
|
+
|
|
16
|
+
function identityOf(raw) {
|
|
17
|
+
const id = /"session_id"\s*:\s*"([A-Za-z0-9_-]{1,128})"/.exec(raw)?.[1];
|
|
18
|
+
if (!id) return null;
|
|
19
|
+
let cwd = null;
|
|
20
|
+
try { cwd = JSON.parse(/"cwd"\s*:\s*("(?:[^"\\]|\\.)*")/.exec(raw)?.[1] ?? 'null'); } catch { cwd = null; }
|
|
21
|
+
return typeof cwd === 'string' && cwd ? { session_id: id, cwd } : { session_id: id };
|
|
22
|
+
}
|
|
23
|
+
|
|
11
24
|
export function readPayload() {
|
|
25
|
+
let raw = '';
|
|
12
26
|
try {
|
|
13
|
-
|
|
14
|
-
if (raw.length > STDIN_LIMIT) return {};
|
|
27
|
+
raw = readFileSync(0, 'utf8');
|
|
28
|
+
if (raw.length > STDIN_LIMIT) { UNREAD = identityOf(raw); return {}; }
|
|
15
29
|
const data = JSON.parse(raw);
|
|
16
30
|
return data && typeof data === 'object' ? data : {};
|
|
17
31
|
} catch {
|
|
32
|
+
UNREAD = identityOf(raw);
|
|
18
33
|
return {};
|
|
19
34
|
}
|
|
20
35
|
}
|
|
@@ -82,6 +97,62 @@ export function sessionPath(cwd, sessionId, env = process.env) {
|
|
|
82
97
|
return join(stateHome, 'litmuse', 'sessions', ws, `${id}.json`);
|
|
83
98
|
}
|
|
84
99
|
|
|
100
|
+
// A start-work run record is sealed with an HMAC whose key sits next to the session folders, in the state folder
|
|
101
|
+
// the run guard refuses to read or write. A run whose seal does not match was edited outside the hooks.
|
|
102
|
+
function sealKey(env = process.env) {
|
|
103
|
+
const stateHome = env.XDG_STATE_HOME || join(env.HOME || homedir(), '.local', 'state');
|
|
104
|
+
const file = join(stateHome, 'litmuse', 'seal.key');
|
|
105
|
+
try {
|
|
106
|
+
const key = readFileSync(file);
|
|
107
|
+
if (key.length >= 32) return key;
|
|
108
|
+
} catch { /* first use */ }
|
|
109
|
+
if (isLink(file) || isLink(dirname(file))) return null;
|
|
110
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
111
|
+
const key = randomBytes(32);
|
|
112
|
+
writeFileSync(file, key, { mode: 0o600 });
|
|
113
|
+
try { chmodSync(file, 0o600); } catch { /* best effort */ }
|
|
114
|
+
return key;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function sealRun(run) {
|
|
118
|
+
const key = sealKey();
|
|
119
|
+
return key ? createHmac('sha256', key).update(JSON.stringify(run)).digest('hex') : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function sealHolds(run, seal) {
|
|
123
|
+
const want = sealRun(run);
|
|
124
|
+
if (!want || typeof seal !== 'string' || seal.length !== want.length) return false;
|
|
125
|
+
return timingSafeEqual(Buffer.from(seal), Buffer.from(want));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// A run that fails its seal keeps its plan and status but loses every parked step, snapshot, path and grant, so
|
|
129
|
+
// nothing written outside the hooks can be replayed or granted.
|
|
130
|
+
function dropTampered(run, file) {
|
|
131
|
+
const denied = { commands: [...(run.denied?.commands ?? [])], paths: [...(run.denied?.paths ?? [])] };
|
|
132
|
+
for (const d of readDenied(file)) {
|
|
133
|
+
denied.commands.push(...(d.commands ?? []));
|
|
134
|
+
denied.paths.push(...(d.paths ?? []));
|
|
135
|
+
}
|
|
136
|
+
return { ...run, parked: [], paths: [], grants: [], snapshot: null, tampered: true, denied };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Every `lit deny` is also appended to a journal beside the session record, so a record that fails its seal still
|
|
140
|
+
// keeps the refusals the user gave.
|
|
141
|
+
const deniedFile = (file) => file.replace(/\.json$/, '.denied');
|
|
142
|
+
function readDenied(file) {
|
|
143
|
+
try {
|
|
144
|
+
return readFileSync(deniedFile(file), 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)).filter((d) => d && typeof d === 'object');
|
|
145
|
+
} catch {
|
|
146
|
+
return [];
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
export function appendDenied(payload, entry) {
|
|
150
|
+
const file = sessionFile(payload);
|
|
151
|
+
if (!file || isLink(dirname(file))) return;
|
|
152
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
153
|
+
appendFileSync(deniedFile(file), `${JSON.stringify({ ts: Date.now(), commands: entry.commands, paths: entry.paths })}\n`);
|
|
154
|
+
}
|
|
155
|
+
|
|
85
156
|
export function sessionFile(payload) {
|
|
86
157
|
return sessionPath(workspaceOf(payload), payload.session_id);
|
|
87
158
|
}
|
|
@@ -107,6 +178,8 @@ export function readSession(payload) {
|
|
|
107
178
|
try {
|
|
108
179
|
const state = JSON.parse(readFileSync(file, 'utf8'));
|
|
109
180
|
if (!state || typeof state !== 'object') throw new Error('bad state');
|
|
181
|
+
if (state.run && !sealHolds(state.run, state.run_seal)) state.run = dropTampered(state.run, file);
|
|
182
|
+
delete state.run_seal;
|
|
110
183
|
return state;
|
|
111
184
|
} catch {
|
|
112
185
|
return { route: 'lit-plan', corrupt: true };
|
|
@@ -118,7 +191,9 @@ export function writeSession(payload, state) {
|
|
|
118
191
|
if (!file || isLink(file) || isLink(dirname(file))) return;
|
|
119
192
|
mkdirSync(dirname(file), { recursive: true });
|
|
120
193
|
const tmp = `${file}.tmp-${process.pid}`;
|
|
121
|
-
|
|
194
|
+
const { run_seal: _old, ...rest } = state;
|
|
195
|
+
const body = rest.run ? { ...rest, run_seal: sealRun(rest.run) } : rest;
|
|
196
|
+
writeFileSync(tmp, `${JSON.stringify(body, null, 2)}\n`);
|
|
122
197
|
renameSync(tmp, file);
|
|
123
198
|
appendFileSync(file.replace(/\.json$/, '.journal'), `${JSON.stringify({ ts: Date.now(), route: state.route ?? null })}\n`);
|
|
124
199
|
}
|
|
@@ -1,26 +1,13 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { lstatSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { appendLedger, block, safeId, workspaceOf, writeSession } from './common.mjs';
|
|
4
|
+
import { driveStop } from './autopilot.mjs';
|
|
4
5
|
|
|
5
6
|
const MAX_HOLDS = 3;
|
|
6
|
-
const PLAN_ROW = /^- \[( |x|X)\] (\d+|F\d+)\. ?(.*)$/;
|
|
7
7
|
const RELEASE_NOTE = /^(BLOCKED at row \d+|PAUSED at row \d+|CANCELLED):/;
|
|
8
8
|
const PAUSE_WORD = /(^|\s)(stop|pause|cancel|halt|wait)(\s|[.!,?]|$)|멈춰|중단|그만|잠깐|일시\s*정지|취소/i;
|
|
9
9
|
export const WORK_ROUTES = new Set(['start-work', 'lit-loop', 'litgoal']);
|
|
10
10
|
|
|
11
|
-
// Rows outside code fences, column zero only, so a quoted example never counts as work.
|
|
12
|
-
function planRows(text) {
|
|
13
|
-
const rows = [];
|
|
14
|
-
let fenced = false;
|
|
15
|
-
for (const line of text.split('\n')) {
|
|
16
|
-
if (/^\s*(```|~~~)/.test(line)) { fenced = !fenced; continue; }
|
|
17
|
-
if (fenced) continue;
|
|
18
|
-
const m = PLAN_ROW.exec(line);
|
|
19
|
-
if (m) rows.push({ done: m[1] !== ' ', id: m[2], title: m[3].trim() });
|
|
20
|
-
}
|
|
21
|
-
return rows;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
11
|
function readText(file) {
|
|
25
12
|
try {
|
|
26
13
|
if (!statSync(file).isFile()) return null;
|
|
@@ -38,25 +25,6 @@ function ledgerLines(payload) {
|
|
|
38
25
|
return text.trim().split('\n').slice(-200).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
39
26
|
}
|
|
40
27
|
|
|
41
|
-
// The plan the session last touched (ledger path), else the newest plan that still has an open row.
|
|
42
|
-
function activePlan(payload, cwd) {
|
|
43
|
-
const planRef = /plans\/[A-Za-z0-9._-]+\.md/;
|
|
44
|
-
for (const line of ledgerLines(payload).reverse()) {
|
|
45
|
-
const hit = planRef.exec(`${line.path ?? ''} ${line.text ?? ''}`);
|
|
46
|
-
if (hit && existsSync(join(cwd, hit[0]))) return hit[0];
|
|
47
|
-
}
|
|
48
|
-
const dir = join(cwd, 'plans');
|
|
49
|
-
if (!existsSync(dir)) return null;
|
|
50
|
-
let best = null;
|
|
51
|
-
for (const name of readdirSync(dir).filter((f) => f.endsWith('.md'))) {
|
|
52
|
-
const text = readText(join(dir, name));
|
|
53
|
-
if (!text || !planRows(text).some((r) => !r.done)) continue;
|
|
54
|
-
const mtime = statSync(join(dir, name)).mtimeMs;
|
|
55
|
-
if (!best || mtime > best.mtime) best = { file: `plans/${name}`, mtime };
|
|
56
|
-
}
|
|
57
|
-
return best ? best.file : null;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
28
|
// The last explicit note decides: a release opener ends the hold, any later note or evidence line re-arms it.
|
|
61
29
|
function releasedByLedger(payload) {
|
|
62
30
|
for (const line of ledgerLines(payload).reverse()) {
|
|
@@ -87,23 +55,14 @@ function bounded(payload, state, prefix, fingerprint, label) {
|
|
|
87
55
|
return { ...state, [`${prefix}Fingerprint`]: fingerprint, [`${prefix}Holds`]: holds + 1, [`${prefix}Released`]: false };
|
|
88
56
|
}
|
|
89
57
|
|
|
58
|
+
// A start-work run is driven by its own decision table (autopilot.mjs): continue, wrap-up, done or impossible. A
|
|
59
|
+
// pause word the user typed still stops the driving for that turn; a ledger note never does, because the run
|
|
60
|
+
// gathers what it cannot finish into the inbox instead of ending on a note.
|
|
90
61
|
function startWorkHold(payload, state) {
|
|
91
|
-
if (
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
const text = readText(join(cwd, file));
|
|
96
|
-
if (!text) return false;
|
|
97
|
-
const status = /^[>\s*_-]*Status\**:\**\s*(.+)$/im.exec(text);
|
|
98
|
-
if (!status || !/^approved\b/i.test(status[1].replace(/^[*_\s]+/, ''))) return false;
|
|
99
|
-
const rows = planRows(text);
|
|
100
|
-
const open = rows.filter((r) => !r.done);
|
|
101
|
-
if (!open.length) return false;
|
|
102
|
-
const next = bounded(payload, state, 'cont', `${file}:${rows.length - open.length}/${rows.length}`, 'start-work');
|
|
103
|
-
if (!next) return false;
|
|
104
|
-
writeSession(payload, next);
|
|
105
|
-
const word = open.length === 1 ? 'row' : 'rows';
|
|
106
|
-
block(`LitMuse start-work: ${file} has ${open.length} open ${word} (next: row ${open[0].id}). Continue with row ${open[0].id}, or write a ledger note starting BLOCKED at row ${open[0].id}: / PAUSED at row ${open[0].id}: / CANCELLED: and end the turn.`);
|
|
62
|
+
if (paused(payload, state)) return false;
|
|
63
|
+
const verdict = driveStop(payload, state);
|
|
64
|
+
if (!verdict) return false;
|
|
65
|
+
block(verdict.block);
|
|
107
66
|
return true;
|
|
108
67
|
}
|
|
109
68
|
|
|
@@ -147,10 +106,12 @@ function goalHold(payload, state) {
|
|
|
147
106
|
return true;
|
|
148
107
|
}
|
|
149
108
|
|
|
150
|
-
// block() exits the process; the returns only matter when it is stubbed.
|
|
109
|
+
// block() exits the process; the returns only matter when it is stubbed. A start-work run is driven by its plan
|
|
110
|
+
// alone, so the litgoal hold stays off there and the run's own budget is the whole budget.
|
|
151
111
|
export function continuationHold(payload, state) {
|
|
152
112
|
try {
|
|
153
|
-
|
|
113
|
+
if (state.route === 'start-work') return startWorkHold(payload, state);
|
|
114
|
+
return goalHold(payload, state);
|
|
154
115
|
} catch {
|
|
155
116
|
return false;
|
|
156
117
|
}
|
|
@@ -101,10 +101,13 @@ export function parseDoneWhen(planText) {
|
|
|
101
101
|
return { ok: false, reason: 'the `## Done when` block names no `check:` command' };
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
-
|
|
104
|
+
// A start-work goal always ends itself: on a reply that waits on the user, or after Muse has driven it 30 turns.
|
|
105
|
+
export const GOAL_SELF_END = ', or the latest reply starts with WAITING-ON-USER:, or after 30 turns';
|
|
106
|
+
|
|
107
|
+
/** `Every row in plans/<f>.md is ticked and \`<cmd>\` exits 0, or … 30 turns [lit:<id>]`, or why it cannot be built. */
|
|
105
108
|
export function compileCondition({ plan, check }) {
|
|
106
109
|
const id = goalId(plan, check);
|
|
107
|
-
const condition = `Every row in ${plan} is ticked and \`${check}\` exits 0 [lit:${id}]`;
|
|
110
|
+
const condition = `Every row in ${plan} is ticked and \`${check}\` exits 0${GOAL_SELF_END} [lit:${id}]`;
|
|
108
111
|
if (condition.length > GOAL_MAX_CHARS) return { ok: false, reason: `the condition is over ${GOAL_MAX_CHARS} characters; point the check at one script` };
|
|
109
112
|
return { ok: true, condition, id };
|
|
110
113
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// `node run-group.mjs <timeoutMs> <cwd> <capture 0|1> <cmd> [args...]`: the start-work run's process runner. It
|
|
2
|
+
// starts the command as the leader of a new process group, kills the whole group (background children included)
|
|
3
|
+
// when the timeout is reached and again once the command ends, and prints one JSON line:
|
|
4
|
+
// {"status", "signal", "timedOut", "out"} with at most 64 KiB of output when capture is 1.
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
|
|
7
|
+
const [ms, cwd, capture, cmd, ...args] = process.argv.slice(2);
|
|
8
|
+
const timeout = Math.max(1, Number.parseInt(ms, 10) || 1);
|
|
9
|
+
const LIMIT = 64 * 1024;
|
|
10
|
+
let out = '';
|
|
11
|
+
let timedOut = false;
|
|
12
|
+
const child = spawn(cmd, args, { cwd, detached: true, stdio: ['ignore', capture === '1' ? 'pipe' : 'ignore', capture === '1' ? 'pipe' : 'ignore'] });
|
|
13
|
+
const keep = (chunk) => { out = (out + chunk).slice(-LIMIT); };
|
|
14
|
+
child.stdout?.setEncoding('utf8').on('data', keep);
|
|
15
|
+
child.stderr?.setEncoding('utf8').on('data', keep);
|
|
16
|
+
const killGroup = () => { try { process.kill(-child.pid, 'SIGKILL'); } catch { /* the group is already gone */ } };
|
|
17
|
+
const timer = setTimeout(() => { timedOut = true; killGroup(); }, timeout);
|
|
18
|
+
let done = false;
|
|
19
|
+
const finish = (status, signal) => {
|
|
20
|
+
if (done) return;
|
|
21
|
+
done = true;
|
|
22
|
+
clearTimeout(timer);
|
|
23
|
+
process.stdout.write(`${JSON.stringify({ status, signal, timedOut, out })}\n`);
|
|
24
|
+
process.exit(0);
|
|
25
|
+
};
|
|
26
|
+
child.on('error', () => finish(127, null));
|
|
27
|
+
// A background child can hold the output pipes open after the command exits, so the end is `exit`, not `close`:
|
|
28
|
+
// the group is killed at once, and the output gets a moment to drain.
|
|
29
|
+
child.on('exit', (status, signal) => {
|
|
30
|
+
killGroup();
|
|
31
|
+
const drained = setTimeout(() => finish(status, signal), 200);
|
|
32
|
+
child.on('close', () => { clearTimeout(drained); finish(status, signal); });
|
|
33
|
+
});
|