@agentpro/scroll 0.0.0-stage → 2.5.0
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/AGENTS.md +55 -0
- package/LICENSE +21 -0
- package/README.md +293 -2
- package/SPEC.md +1079 -0
- package/bin/scroll.js +8 -0
- package/docs/prompt-caching.md +128 -0
- package/index.js +33 -0
- package/lib/audit.js +358 -0
- package/lib/auth.js +849 -0
- package/lib/chat-sdk/admin-controller.js +289 -0
- package/lib/chat-sdk/debouncer.js +94 -0
- package/lib/chat-sdk/group-grants.js +150 -0
- package/lib/chat-sdk/index.js +222 -0
- package/lib/chat-sdk/long-task-runner.js +413 -0
- package/lib/chat-session.js +1788 -0
- package/lib/chat-telemetry.js +557 -0
- package/lib/codex-app-server.js +851 -0
- package/lib/digest.js +112 -0
- package/lib/effects.js +157 -0
- package/lib/eval.js +408 -0
- package/lib/grounding.js +356 -0
- package/lib/installers.js +176 -0
- package/lib/knowledge.js +335 -0
- package/lib/ledger.js +38 -0
- package/lib/loop.js +197 -0
- package/lib/mcp-client.js +926 -0
- package/lib/memory-cli.js +66 -0
- package/lib/memory-tracker.js +1472 -0
- package/lib/memory.js +1279 -0
- package/lib/people-cli.js +81 -0
- package/lib/people.js +534 -0
- package/lib/permissions.js +272 -0
- package/lib/providers.js +1572 -0
- package/lib/runtime.js +928 -0
- package/lib/sandbox.js +744 -0
- package/lib/scheduler.js +402 -0
- package/lib/scroll.js +1225 -0
- package/lib/skill-cli.js +120 -0
- package/lib/skill-eval.js +156 -0
- package/lib/skills.js +860 -0
- package/lib/style.js +126 -0
- package/lib/tool-retriever.js +489 -0
- package/lib/tools.js +1833 -0
- package/lib/user.js +711 -0
- package/lib/vault.js +151 -0
- package/package.json +88 -4
- package/templates/agent/IDENTITY.md +56 -0
- package/templates/agent/SOUL.md +23 -0
- package/templates/agent/TOOLS.md +25 -0
- package/templates/agent/evals/case-02-citation-discipline.md +29 -0
- package/templates/agent/evals/case-03-boundary.md +27 -0
- package/templates/agent/evals/case-example.md +43 -0
- package/templates/agent/hard-rules.md +11 -0
- package/templates/agent/memory/lessons.md +5 -0
- package/templates/agent/memory/log/.gitkeep +0 -0
- package/templates/external-safety-contract.md +5 -0
- package/templates/long-task-planner.md +17 -0
- package/templates/work/LOOP.md +37 -0
- package/templates/work/WORK.md +50 -0
- package/types/chat.d.ts +61 -0
- package/types/index.d.ts +112 -0
package/lib/scroll.js
ADDED
|
@@ -0,0 +1,1225 @@
|
|
|
1
|
+
// SCROLL — filesystem-native agent framework CLI (+ scroll audit · v1.8 scroll skill: load, check, scan, eval)
|
|
2
|
+
// One module, no engine. Reads agent folders, validates, transpiles. ~spec v1.2.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { fileURLToPath } from 'node:url';
|
|
6
|
+
import { validateStyle, SPEAKS_AS_VALUES } from './style.js';
|
|
7
|
+
|
|
8
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
9
|
+
|
|
10
|
+
// ── Minimal YAML-subset parser (zero-dep). Covers SCROLL frontmatter:
|
|
11
|
+
// scalars, quoted strings, inline [..] / {..}, block maps + block sequences (indent-based).
|
|
12
|
+
// Frontmatter is simple by design; full YAML is intentionally out of scope.
|
|
13
|
+
function stripComment(line) {
|
|
14
|
+
let q = null, out = '';
|
|
15
|
+
for (let i = 0; i < line.length; i++) {
|
|
16
|
+
const ch = line[i];
|
|
17
|
+
if (q) { out += ch; if (ch === q) q = null; continue; }
|
|
18
|
+
if (ch === '"' || ch === "'") { q = ch; out += ch; continue; }
|
|
19
|
+
if (ch === '#' && (i === 0 || /\s/.test(line[i - 1]))) break;
|
|
20
|
+
out += ch;
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
function splitTopLevel(s) {
|
|
25
|
+
const parts = []; let depth = 0, q = null, cur = '';
|
|
26
|
+
for (const ch of s) {
|
|
27
|
+
if (q) { cur += ch; if (ch === q) q = null; continue; }
|
|
28
|
+
if (ch === '"' || ch === "'") { q = ch; cur += ch; continue; }
|
|
29
|
+
if (ch === '[' || ch === '{') depth++;
|
|
30
|
+
if (ch === ']' || ch === '}') depth--;
|
|
31
|
+
if (ch === ',' && depth === 0) { parts.push(cur); cur = ''; continue; }
|
|
32
|
+
cur += ch;
|
|
33
|
+
}
|
|
34
|
+
if (cur.trim()) parts.push(cur);
|
|
35
|
+
return parts;
|
|
36
|
+
}
|
|
37
|
+
function yScalar(v) {
|
|
38
|
+
v = v.trim();
|
|
39
|
+
if (v === '') return '';
|
|
40
|
+
if (v === 'true') return true;
|
|
41
|
+
if (v === 'false') return false;
|
|
42
|
+
if (v === 'null' || v === '~') return null;
|
|
43
|
+
if (/^-?\d+$/.test(v)) return parseInt(v, 10);
|
|
44
|
+
if (/^-?\d+\.\d+$/.test(v)) return parseFloat(v);
|
|
45
|
+
if ((v[0] === '"' && v.at(-1) === '"') || (v[0] === "'" && v.at(-1) === "'")) return v.slice(1, -1);
|
|
46
|
+
if (v[0] === '[' && v.at(-1) === ']') return splitTopLevel(v.slice(1, -1)).map(yScalar).filter((x) => x !== '');
|
|
47
|
+
if (v[0] === '{' && v.at(-1) === '}') {
|
|
48
|
+
const o = {};
|
|
49
|
+
for (const pair of splitTopLevel(v.slice(1, -1))) {
|
|
50
|
+
const ci = pair.indexOf(':'); if (ci < 0) continue;
|
|
51
|
+
const k = pair.slice(0, ci).trim().replace(/^["']|["']$/g, '');
|
|
52
|
+
o[k] = yScalar(pair.slice(ci + 1));
|
|
53
|
+
}
|
|
54
|
+
return o;
|
|
55
|
+
}
|
|
56
|
+
return v;
|
|
57
|
+
}
|
|
58
|
+
export function parseYaml(src) {
|
|
59
|
+
const lines = String(src).split('\n').map(stripComment).filter((l) => l.trim() !== '');
|
|
60
|
+
let idx = 0;
|
|
61
|
+
const indentOf = (s) => s.match(/^ */)[0].length;
|
|
62
|
+
function block(min) {
|
|
63
|
+
let map = null, arr = null;
|
|
64
|
+
while (idx < lines.length) {
|
|
65
|
+
const line = lines[idx];
|
|
66
|
+
const ind = indentOf(line);
|
|
67
|
+
if (ind < min) break;
|
|
68
|
+
if (ind > min) { idx++; continue; }
|
|
69
|
+
const content = line.slice(ind);
|
|
70
|
+
if (content === '-' || content.startsWith('- ')) {
|
|
71
|
+
arr = arr || [];
|
|
72
|
+
const rest = content.slice(1).trim();
|
|
73
|
+
idx++;
|
|
74
|
+
// Block map inside sequence item: `- id: ana\n name: Ana`
|
|
75
|
+
if (rest && !rest.startsWith('{') && !rest.startsWith('[') && !rest.startsWith('"') && !rest.startsWith("'") && /^[A-Za-z0-9_."-]+\s*:/.test(rest)) {
|
|
76
|
+
const ci = rest.indexOf(':');
|
|
77
|
+
const k = rest.slice(0, ci).trim().replace(/^["']|["']$/g, '');
|
|
78
|
+
const v = rest.slice(ci + 1).trim();
|
|
79
|
+
const item = {};
|
|
80
|
+
if (v === '') {
|
|
81
|
+
const nextInd = idx < lines.length ? indentOf(lines[idx]) : min;
|
|
82
|
+
item[k] = (idx < lines.length && nextInd > ind + 2) ? block(nextInd) : null;
|
|
83
|
+
} else {
|
|
84
|
+
item[k] = yScalar(v);
|
|
85
|
+
}
|
|
86
|
+
const nextInd = idx < lines.length ? indentOf(lines[idx]) : min;
|
|
87
|
+
if (idx < lines.length && nextInd > ind) {
|
|
88
|
+
const extra = block(nextInd);
|
|
89
|
+
if (extra && typeof extra === 'object' && !Array.isArray(extra)) Object.assign(item, extra);
|
|
90
|
+
}
|
|
91
|
+
arr.push(item);
|
|
92
|
+
} else if (rest === '') {
|
|
93
|
+
const nextInd = idx < lines.length ? indentOf(lines[idx]) : min;
|
|
94
|
+
arr.push(idx < lines.length && nextInd > ind ? block(nextInd) : null);
|
|
95
|
+
} else {
|
|
96
|
+
arr.push(yScalar(rest));
|
|
97
|
+
}
|
|
98
|
+
} else {
|
|
99
|
+
const ci = content.indexOf(':');
|
|
100
|
+
if (ci < 0) { idx++; continue; }
|
|
101
|
+
const key = content.slice(0, ci).trim().replace(/^["']|["']$/g, '');
|
|
102
|
+
const val = content.slice(ci + 1).trim();
|
|
103
|
+
idx++;
|
|
104
|
+
map = map || {};
|
|
105
|
+
if (val === '') {
|
|
106
|
+
const nextInd = idx < lines.length ? indentOf(lines[idx]) : min;
|
|
107
|
+
map[key] = (idx < lines.length && nextInd > min) ? block(nextInd) : null;
|
|
108
|
+
} else {
|
|
109
|
+
map[key] = yScalar(val);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return arr !== null ? arr : (map || {});
|
|
114
|
+
}
|
|
115
|
+
return block(0);
|
|
116
|
+
}
|
|
117
|
+
const TEMPLATE_DIR = path.join(__dirname, '..', 'templates', 'agent');
|
|
118
|
+
const RUNTIMES = ['cowork', 'codex', 'gemini', 'claude-subagent', 'voice', 'a2a'];
|
|
119
|
+
const ROLE_REF_RE = /^(role:)?[a-z][a-z0-9_-]*$/; // v1.9 §39
|
|
120
|
+
const CAP_RE = /^(fs|web|shell|mcp|vision|voice|dispatch|memory|skills|ask|message|tasks|knowledge)\.[a-z_]+$/; // v1.7: memory.* (§31) · v1.8: skills.* ask.* message.* tasks.* (§35) · v1.9: knowledge.* (§43)
|
|
121
|
+
|
|
122
|
+
// ── ANSI helpers ──
|
|
123
|
+
const c = {
|
|
124
|
+
red: (s) => `\x1b[31m${s}\x1b[0m`, green: (s) => `\x1b[32m${s}\x1b[0m`,
|
|
125
|
+
yellow: (s) => `\x1b[33m${s}\x1b[0m`, dim: (s) => `\x1b[2m${s}\x1b[0m`,
|
|
126
|
+
bold: (s) => `\x1b[1m${s}\x1b[0m`, cyan: (s) => `\x1b[36m${s}\x1b[0m`,
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
// ── Frontmatter ──
|
|
130
|
+
export function parseFrontmatter(raw) {
|
|
131
|
+
const m = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
132
|
+
if (!m) return { frontmatter: null, body: raw };
|
|
133
|
+
let fm;
|
|
134
|
+
try { fm = parseYaml(m[1]) || {}; }
|
|
135
|
+
catch (e) { throw new Error(`frontmatter YAML invalid: ${e.message}`); }
|
|
136
|
+
return { frontmatter: fm, body: m[2].trim() };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// ── Load an agent folder → structured object ──
|
|
140
|
+
export function loadAgent(name, cwd = process.cwd()) {
|
|
141
|
+
const dir = path.join(cwd, 'agents', name);
|
|
142
|
+
if (!fs.existsSync(dir)) throw new Error(`agent not found: agents/${name}/`);
|
|
143
|
+
const read = (f) => { const p = path.join(dir, f); return fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null; };
|
|
144
|
+
const identityRaw = read('IDENTITY.md');
|
|
145
|
+
if (identityRaw == null) throw new Error(`agents/${name}/IDENTITY.md missing`);
|
|
146
|
+
const { frontmatter, body } = parseFrontmatter(identityRaw);
|
|
147
|
+
let hardRules = read('hard-rules.md');
|
|
148
|
+
if (frontmatter && typeof frontmatter.hard_rules === 'string' && frontmatter.hard_rules.trim()) {
|
|
149
|
+
const resolved = path.resolve(dir, frontmatter.hard_rules);
|
|
150
|
+
if ((resolved === dir || resolved.startsWith(dir + path.sep)) && fs.existsSync(resolved)) {
|
|
151
|
+
hardRules = fs.readFileSync(resolved, 'utf8');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const evalsDir = path.join(dir, 'evals');
|
|
155
|
+
const evals = fs.existsSync(evalsDir)
|
|
156
|
+
? fs.readdirSync(evalsDir).filter((f) => f.endsWith('.md') && f !== 'rubric.md')
|
|
157
|
+
: [];
|
|
158
|
+
return {
|
|
159
|
+
name, dir, frontmatter, identityBody: body,
|
|
160
|
+
soul: read('SOUL.md'), tools: read('TOOLS.md'), hardRules,
|
|
161
|
+
lessons: read(path.join('memory', 'lessons.md')),
|
|
162
|
+
evals,
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// ── CHECK: validate against spec → { errors, warnings, level } ──
|
|
167
|
+
export function checkAgent(name, cwd = process.cwd()) {
|
|
168
|
+
const errors = [], warnings = [];
|
|
169
|
+
let agent;
|
|
170
|
+
try { agent = loadAgent(name, cwd); }
|
|
171
|
+
catch (e) { return { errors: [e.message], warnings: [], level: null }; }
|
|
172
|
+
const fm = agent.frontmatter;
|
|
173
|
+
|
|
174
|
+
if (!fm || typeof fm !== 'object') {
|
|
175
|
+
errors.push('IDENTITY.md has no valid frontmatter');
|
|
176
|
+
} else {
|
|
177
|
+
// required fields
|
|
178
|
+
const req = ['name', 'title', 'version', 'runtimes', 'model', 'capabilities'];
|
|
179
|
+
for (const k of req) if (fm[k] === undefined) errors.push(`IDENTITY: missing required field "${k}"`);
|
|
180
|
+
// name
|
|
181
|
+
if (fm.name && !/^[a-z][a-z0-9-]*$/.test(fm.name)) errors.push(`IDENTITY: name "${fm.name}" must match ^[a-z][a-z0-9-]*$`);
|
|
182
|
+
if (fm.name && fm.name !== name) errors.push(`IDENTITY: name "${fm.name}" must equal folder name "${name}"`);
|
|
183
|
+
// version
|
|
184
|
+
if (fm.version && !/^\d+\.\d+\.\d+$/.test(String(fm.version))) errors.push(`IDENTITY: version "${fm.version}" must be semver`);
|
|
185
|
+
// runtimes
|
|
186
|
+
if (fm.runtimes !== undefined) {
|
|
187
|
+
if (!Array.isArray(fm.runtimes) || fm.runtimes.length === 0) errors.push('IDENTITY: runtimes must be a non-empty array');
|
|
188
|
+
else for (const r of fm.runtimes) if (!RUNTIMES.includes(r)) warnings.push(`IDENTITY: unknown runtime "${r}"`);
|
|
189
|
+
}
|
|
190
|
+
// model
|
|
191
|
+
if (fm.model !== undefined && (typeof fm.model !== 'object' || !fm.model.primary)) errors.push('IDENTITY: model.primary is required');
|
|
192
|
+
// capabilities
|
|
193
|
+
if (fm.capabilities !== undefined) {
|
|
194
|
+
if (!Array.isArray(fm.capabilities)) errors.push('IDENTITY: capabilities must be an array');
|
|
195
|
+
else for (const cap of fm.capabilities) if (!CAP_RE.test(cap)) warnings.push(`IDENTITY: capability "${cap}" not in reserved namespace`);
|
|
196
|
+
}
|
|
197
|
+
// dispatch
|
|
198
|
+
if (fm.dispatch && fm.dispatch.authority && !['none', 'low', 'medium', 'high'].includes(fm.dispatch.authority))
|
|
199
|
+
errors.push(`IDENTITY: dispatch.authority "${fm.dispatch.authority}" invalid`);
|
|
200
|
+
// v1.9 §39 — people are bound by ROLE; how to address a person lives on that person's card
|
|
201
|
+
if (fm.serves !== undefined) {
|
|
202
|
+
const sv = Array.isArray(fm.serves) ? fm.serves : [fm.serves];
|
|
203
|
+
for (const r of sv) {
|
|
204
|
+
const s = String(r);
|
|
205
|
+
if (s.startsWith('person:')) errors.push(`IDENTITY: serves "${s}" names a person — bind by role (e.g. role:owner); the deployment maps roles to people (§39)`);
|
|
206
|
+
else if (!ROLE_REF_RE.test(s)) errors.push(`IDENTITY: serves "${s}" must be a role (owner or role:owner)`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (fm.reports_to !== undefined) {
|
|
210
|
+
const rt = String(fm.reports_to);
|
|
211
|
+
if (rt === 'user') warnings.push('IDENTITY: reports_to "user" is legacy — use role:<role> (§39)');
|
|
212
|
+
else if (rt.startsWith('person:')) errors.push(`IDENTITY: reports_to "${rt}" names a person — use role:<role> (§39)`);
|
|
213
|
+
else if (rt.startsWith('role:') ? !ROLE_REF_RE.test(rt) : !/^[a-z][a-z0-9-]*$/.test(rt)) errors.push(`IDENTITY: reports_to "${rt}" must be an agent name or role:<role>`);
|
|
214
|
+
}
|
|
215
|
+
if (fm.pronoun !== undefined) warnings.push('IDENTITY: pronoun is legacy — how to address a person belongs on their card (people/<slug>.md, address); kept only as a fallback (§38–§39)');
|
|
216
|
+
else if (fm.serves === undefined && fm.reports_to === undefined) warnings.push('IDENTITY: serves not set — declare the roles this agent serves, e.g. serves: [owner] (§39)');
|
|
217
|
+
// v1.9 §43 — speaks_as + machine-enforced style block
|
|
218
|
+
if (fm.speaks_as !== undefined && !SPEAKS_AS_VALUES.has(String(fm.speaks_as))) {
|
|
219
|
+
errors.push(`IDENTITY: speaks_as "${fm.speaks_as}" must be one of: self, owner, org (§43)`);
|
|
220
|
+
}
|
|
221
|
+
if (fm.style !== undefined) {
|
|
222
|
+
errors.push(...validateStyle(fm.style).errors);
|
|
223
|
+
}
|
|
224
|
+
if (fm.language === undefined) warnings.push('IDENTITY: language not set (recommended)');
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// SOUL.md
|
|
228
|
+
if (!agent.soul || !agent.soul.trim()) errors.push('SOUL.md missing or empty');
|
|
229
|
+
|
|
230
|
+
// TOOLS capabilities ⊆ IDENTITY capabilities
|
|
231
|
+
if (agent.tools && fm && Array.isArray(fm.capabilities)) {
|
|
232
|
+
const declared = new Set(fm.capabilities);
|
|
233
|
+
const used = [...agent.tools.matchAll(/^([a-z]+\.[a-z_]+):/gm)].map((x) => x[1]);
|
|
234
|
+
for (const u of used) if (!declared.has(u)) errors.push(`TOOLS: capability "${u}" not declared in IDENTITY.capabilities`);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// hard_rules reference resolves
|
|
238
|
+
if (fm && fm.hard_rules) {
|
|
239
|
+
const hp = path.join(agent.dir, fm.hard_rules);
|
|
240
|
+
if (!fs.existsSync(hp)) warnings.push(`IDENTITY: hard_rules path "${fm.hard_rules}" not found`);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// §47.2 / ASI04: ban unpinned `npx …@latest` / unversioned packages in `.mcp.json`
|
|
244
|
+
errors.push(...checkMcpConfigPinning(cwd, agent.dir));
|
|
245
|
+
|
|
246
|
+
// ── conformance level ──
|
|
247
|
+
let level = null;
|
|
248
|
+
if (errors.length === 0) {
|
|
249
|
+
level = 'L0';
|
|
250
|
+
const hasRules = (fm && fm.hard_rules) || agent.hardRules;
|
|
251
|
+
if (agent.evals.length >= 3 && hasRules) level = 'L1';
|
|
252
|
+
if (level === 'L1' && fs.existsSync(path.join(cwd, 'WORK.md'))) {
|
|
253
|
+
// L2 requires WORK.md to satisfy the 4-part contract — checked by checkWork()
|
|
254
|
+
const w = checkWork(cwd);
|
|
255
|
+
if (w.errors.length === 0 && w.tasks > 0) level = 'L2'; else warnings.push(...w.errors);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return { errors, warnings, level };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// §47.2 / ASI04 supply-chain check: flag unpinned `npx …@latest` or unversioned `npx`/`uvx` in `.mcp.json`
|
|
262
|
+
export function checkMcpConfigPinning(cwd = process.cwd(), agentDir = null) {
|
|
263
|
+
const errors = [];
|
|
264
|
+
const files = [path.join(cwd, '.mcp.json')];
|
|
265
|
+
if (agentDir) files.push(path.join(agentDir, '.mcp.json'));
|
|
266
|
+
for (const file of files) {
|
|
267
|
+
if (!fs.existsSync(file)) continue;
|
|
268
|
+
let parsed;
|
|
269
|
+
try { parsed = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { continue; }
|
|
270
|
+
const servers = parsed?.mcpServers || {};
|
|
271
|
+
for (const [srvName, cfg] of Object.entries(servers)) {
|
|
272
|
+
if (!cfg || typeof cfg !== 'object') continue;
|
|
273
|
+
const cmd = String(cfg.command || '').trim();
|
|
274
|
+
const args = Array.isArray(cfg.args) ? cfg.args.map(String) : [];
|
|
275
|
+
if (cmd === 'npx' || cmd === 'uvx' || /(?:^|\/)(?:npx|uvx)$/.test(cmd)) {
|
|
276
|
+
const pkgArg = args.find((a) => !a.startsWith('-'));
|
|
277
|
+
if (!pkgArg) continue;
|
|
278
|
+
if (/@latest\b/i.test(pkgArg)) {
|
|
279
|
+
errors.push(`${rel(cwd, file)} [${srvName}]: unpinned MCP package "${pkgArg}" (@latest is banned; pin an exact version, e.g. pkg@1.2.3)`);
|
|
280
|
+
} else if (cmd.endsWith('npx') && !/@\d+\.\d+/.test(pkgArg)) {
|
|
281
|
+
errors.push(`${rel(cwd, file)} [${srvName}]: unpinned npx MCP package "${pkgArg}" (pin an exact semver version, e.g. ${pkgArg}@1.2.3)`);
|
|
282
|
+
} else if (cmd.endsWith('uvx') && !/(?:==|@)\d+\.\d+/.test(pkgArg)) {
|
|
283
|
+
errors.push(`${rel(cwd, file)} [${srvName}]: unpinned uvx MCP package "${pkgArg}" (pin an exact version, e.g. ${pkgArg}==1.2.3)`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return errors;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// ── CHECK WORK.md (4-part contract + single controller) ──
|
|
292
|
+
export function checkWork(cwd = process.cwd()) {
|
|
293
|
+
const p = path.join(cwd, 'WORK.md');
|
|
294
|
+
if (!fs.existsSync(p)) return { errors: [], tasks: 0, owners: [] };
|
|
295
|
+
const raw = fs.readFileSync(p, 'utf8');
|
|
296
|
+
// tasks are fenced yaml blocks ```task ... ``` OR a yaml list under "## tasks"
|
|
297
|
+
const blocks = [...raw.matchAll(/```task\n([\s\S]*?)```/g)].map((m) => m[1]);
|
|
298
|
+
const errors = [], owners = new Set();
|
|
299
|
+
// v1.9 §40 — exactly one controller, and it is an agent: a person holds steps, never the chain
|
|
300
|
+
const wfm = raw.startsWith('---') ? (parseFrontmatter(raw).frontmatter || {}) : {};
|
|
301
|
+
if (wfm.controller && String(wfm.controller).startsWith('person:')) errors.push(`WORK: controller "${wfm.controller}" is a person — the controller must be one agent; people own steps (§40)`);
|
|
302
|
+
let tasks = 0;
|
|
303
|
+
for (const b of blocks) {
|
|
304
|
+
let t; try { t = parseYaml(b); } catch { errors.push('WORK: a task block has invalid YAML'); continue; }
|
|
305
|
+
if (!t) continue;
|
|
306
|
+
tasks++;
|
|
307
|
+
for (const f of ['id', 'title', 'status', 'owner', 'objective', 'output_format', 'boundaries'])
|
|
308
|
+
if (t[f] === undefined) errors.push(`WORK: task "${t.id || '?'}" missing "${f}"`);
|
|
309
|
+
if (t.owner) {
|
|
310
|
+
// v1.9 §40 — owner: agent:<name> | person:<slug> | <name> (an agent, as before)
|
|
311
|
+
const o = String(t.owner);
|
|
312
|
+
if (o.startsWith('person:') ? !/^person:[a-z][a-z0-9-]*$/.test(o) : !/^(agent:)?[a-z][a-z0-9-]*$/.test(o)) errors.push(`WORK: task "${t.id}" owner "${o}" must be <agent>, agent:<agent> or person:<slug>`);
|
|
313
|
+
owners.add(o.replace(/^agent:/, ''));
|
|
314
|
+
}
|
|
315
|
+
if (t.status && !['todo', 'doing', 'done', 'blocked'].includes(t.status))
|
|
316
|
+
errors.push(`WORK: task "${t.id}" invalid status "${t.status}"`);
|
|
317
|
+
}
|
|
318
|
+
return { errors, tasks, owners: [...owners] };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// ── BUILD: transpile source → runtime renderings (deterministic) ──
|
|
322
|
+
export function buildAgent(name, cwd = process.cwd(), opts = {}) {
|
|
323
|
+
const a = loadAgent(name, cwd);
|
|
324
|
+
const fm = a.frontmatter || {};
|
|
325
|
+
const outDir = path.join(a.dir, '.build');
|
|
326
|
+
const targets = Array.isArray(fm.runtimes) ? fm.runtimes : [];
|
|
327
|
+
const written = [];
|
|
328
|
+
const MARK = '<!-- GENERATED by scroll build — do not edit. Source: ../../ -->';
|
|
329
|
+
const userBlock = typeof opts.userBlock === 'string' && opts.userBlock.trim() ? opts.userBlock.trim() : '';
|
|
330
|
+
|
|
331
|
+
const ensure = (d) => fs.mkdirSync(d, { recursive: true });
|
|
332
|
+
|
|
333
|
+
// Cowork YourRole.md
|
|
334
|
+
if (targets.includes('cowork')) {
|
|
335
|
+
const d = path.join(outDir, 'cowork'); ensure(d);
|
|
336
|
+
const out = [
|
|
337
|
+
MARK, '',
|
|
338
|
+
`# ${fm.title || name} — ${name}`, '',
|
|
339
|
+
fm.pronoun ? `*Pronoun: ${fm.pronoun} · Language: ${fm.language || 'n/a'}*\n` : '',
|
|
340
|
+
fm.serves ? `*Serves: ${[].concat(fm.serves).join(', ')} — each person's card (people/<slug>.md) says how to address them*\n` : '',
|
|
341
|
+
'## Identity', a.identityBody || '', '',
|
|
342
|
+
'## Soul', a.soul || '', '',
|
|
343
|
+
a.tools ? '## Tools\n' + a.tools : '',
|
|
344
|
+
a.hardRules ? '\n## Hard rules\n' + a.hardRules : '', // cowork-hr
|
|
345
|
+
userBlock ? '\n' + userBlock : '',
|
|
346
|
+
].join('\n');
|
|
347
|
+
const f = path.join(d, 'YourRole.md'); fs.writeFileSync(f, out); written.push(rel(cwd, f));
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Claude subagent (.md + frontmatter)
|
|
351
|
+
if (targets.includes('claude-subagent')) {
|
|
352
|
+
const d = path.join(outDir, 'claude-subagent'); ensure(d);
|
|
353
|
+
const desc = (fm.title || name).replace(/\n/g, ' ');
|
|
354
|
+
const sub = [
|
|
355
|
+
'---',
|
|
356
|
+
`name: ${name}`,
|
|
357
|
+
`description: ${desc}`,
|
|
358
|
+
`model: ${(fm.model && fm.model.primary) || 'inherit'}`,
|
|
359
|
+
'---', '',
|
|
360
|
+
a.soul || '', '',
|
|
361
|
+
a.identityBody || '',
|
|
362
|
+
a.hardRules ? '\n## Hard rules\n' + a.hardRules : '', // subagent-hr
|
|
363
|
+
userBlock ? '\n' + userBlock : '',
|
|
364
|
+
].join('\n');
|
|
365
|
+
const f = path.join(d, `${name}.md`); fs.writeFileSync(f, sub); written.push(rel(cwd, f));
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// A2A Agent Card (static JSON)
|
|
369
|
+
if (targets.includes('a2a')) {
|
|
370
|
+
const d = path.join(outDir, 'a2a'); ensure(d);
|
|
371
|
+
const card = {
|
|
372
|
+
schemaVersion: '1.0', name, title: fm.title || name, version: fm.version || '0.0.0',
|
|
373
|
+
capabilities: fm.capabilities || [], model: (fm.model && fm.model.primary) || null,
|
|
374
|
+
};
|
|
375
|
+
const f = path.join(d, `${name}.agent-card.json`);
|
|
376
|
+
fs.writeFileSync(f, JSON.stringify(card, null, 2) + '\n'); written.push(rel(cwd, f));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
// Generic prompt for codex/gemini/voice
|
|
380
|
+
for (const rt of ['codex', 'gemini', 'voice']) {
|
|
381
|
+
if (!targets.includes(rt)) continue;
|
|
382
|
+
const d = path.join(outDir, rt); ensure(d);
|
|
383
|
+
const out = [
|
|
384
|
+
MARK, '',
|
|
385
|
+
a.soul || '', '',
|
|
386
|
+
a.identityBody || '',
|
|
387
|
+
a.tools ? '\n' + a.tools : '',
|
|
388
|
+
a.hardRules ? '\n## Hard rules\n' + a.hardRules : '', // generic-hr
|
|
389
|
+
userBlock ? '\n' + userBlock : '',
|
|
390
|
+
].join('\n');
|
|
391
|
+
const f = path.join(d, `${name}.prompt.md`); fs.writeFileSync(f, out); written.push(rel(cwd, f));
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return { written, targets };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// ── REGISTRY: scan agents/ → rows ──
|
|
398
|
+
export function scanRegistry(cwd = process.cwd()) {
|
|
399
|
+
const base = path.join(cwd, 'agents');
|
|
400
|
+
if (!fs.existsSync(base)) return [];
|
|
401
|
+
const rows = [];
|
|
402
|
+
for (const name of fs.readdirSync(base)) {
|
|
403
|
+
const idp = path.join(base, name, 'IDENTITY.md');
|
|
404
|
+
if (!fs.existsSync(idp)) continue;
|
|
405
|
+
try {
|
|
406
|
+
const { frontmatter: fm } = parseFrontmatter(fs.readFileSync(idp, 'utf8'));
|
|
407
|
+
rows.push({
|
|
408
|
+
name, title: fm?.title || '', version: fm?.version || '',
|
|
409
|
+
runtimes: (fm?.runtimes || []).join(','), model: fm?.model?.primary || '',
|
|
410
|
+
caps: (fm?.capabilities || []).length,
|
|
411
|
+
});
|
|
412
|
+
} catch { rows.push({ name, title: c.red('(invalid IDENTITY)'), version: '', runtimes: '', model: '', caps: 0 }); }
|
|
413
|
+
}
|
|
414
|
+
return rows;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ── COST: rough single-vs-multi estimate (language-aware) ──
|
|
418
|
+
// Non-English text costs more tokens per character (Vietnamese ≈ 1.8× English). Estimating as if
|
|
419
|
+
// English badly underestimates real spend for non-English markets — a local insight competitors miss.
|
|
420
|
+
export const LANG_MULT = { en: 1, vi: 1.8, ja: 1.6, zh: 1.7, ko: 1.6, th: 1.6, ar: 1.5, ru: 1.4 };
|
|
421
|
+
export function langMultiplier(language) {
|
|
422
|
+
if (!language) return 1;
|
|
423
|
+
const base = String(language).toLowerCase().split('-')[0];
|
|
424
|
+
return LANG_MULT[base] || 1.5; // unknown but non-English → conservative 1.5
|
|
425
|
+
}
|
|
426
|
+
export function estimateCost(taskText, nAgents = 2, { language } = {}) {
|
|
427
|
+
const mult = langMultiplier(language);
|
|
428
|
+
const taskTokens = Math.ceil(((taskText || '').length / 4) * mult) || 500;
|
|
429
|
+
const SYS = 1500; // per-agent system prompt
|
|
430
|
+
const single = SYS + taskTokens * 3;
|
|
431
|
+
const multi = nAgents * (SYS + taskTokens * 2) + SYS /* coordinator */ + nAgents * 400 /* overhead */;
|
|
432
|
+
return { single, multi, language: language || null, langMultiplier: mult, preferSingle: single < multi * 0.7, savingPct: Math.round((1 - single / multi) * 100) };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
// ── Setup presets (v1.9 §43): standardized English canonical role blueprints ──
|
|
436
|
+
export const AGENT_PRESETS = {
|
|
437
|
+
assistant: {
|
|
438
|
+
speaks_as: 'self',
|
|
439
|
+
serves: '[owner]',
|
|
440
|
+
style: '{ bubbles: 3, max_chars: 450, emoji: 2, follow_up: 1 }',
|
|
441
|
+
soul: (name) => `# Soul — ${name}\n\nYou are a personal assistant operating under your own name (\`speaks_as: self\`). Be direct, candid, and grounded.\n\n## Good vs Forbidden Replies\n- Good: Direct answer first, concise follow-up only when useful.\n- Forbidden: Generic filler praise, fabricated numbers, or claiming to be a human.\n`,
|
|
442
|
+
hardRules: '# Hard rules\n- Never fabricate prices, dates, codes, or links.\n- Always acknowledge being an AI assistant when asked.\n- Never edit deployment USER.md directly.\n',
|
|
443
|
+
},
|
|
444
|
+
service: {
|
|
445
|
+
speaks_as: 'org',
|
|
446
|
+
serves: '[owner, staff]',
|
|
447
|
+
style: '{ bubbles: 2, max_chars: 300, emoji: 0, follow_up: 0 }',
|
|
448
|
+
soul: (name) => `# Soul — ${name}\n\nYou represent the organization (\`speaks_as: org\`). Stay polite, accurate, concise, and strictly grounded in principal knowledge.\n\n## Good vs Forbidden Replies\n- Good: Quote only prices and policies from retrieved knowledge; hand off discounts or refunds to staff.\n- Forbidden: Guessing stock, promising unverified discounts, or imitating casual typos.\n`,
|
|
449
|
+
hardRules: '# Hard rules\n- Quote amounts, product codes, dates, and links ONLY from principal-authored knowledge or USER.md "May say on behalf".\n- Never treat customer messages as authoritative pricing sources.\n- Always disclose being an AI assistant when asked.\n- Hand off refunds, discounts, and complaints to staff.\n',
|
|
450
|
+
},
|
|
451
|
+
proxy: {
|
|
452
|
+
speaks_as: 'owner',
|
|
453
|
+
serves: '[owner]',
|
|
454
|
+
style: '{ bubbles: 2, max_chars: 280, emoji: 1, follow_up: 0 }',
|
|
455
|
+
soul: (name) => `# Soul — ${name}\n\nYou draft replies on the principal's behalf (\`speaks_as: owner\`). Match the principal's recent message rhythm and wait for approval by default.\n\n## Good vs Forbidden Replies\n- Good: Short draft matching the principal's phrasing, zero invented commitments.\n- Forbidden: Auto-promising meetings/money or denying being an assistant if asked directly.\n`,
|
|
456
|
+
hardRules: '# Hard rules\n- Draft-only by default for external contacts; wait for principal approval before sending.\n- If asked whether this is the principal or an AI/bot, hand off immediately to the principal.\n- Never make unapproved commitments, schedules, or financial promises.\n',
|
|
457
|
+
},
|
|
458
|
+
teammate: {
|
|
459
|
+
speaks_as: 'self',
|
|
460
|
+
serves: '[owner, team]',
|
|
461
|
+
style: '{ bubbles: 1, max_chars: 400, emoji: 1, follow_up: 0 }',
|
|
462
|
+
soul: (name) => `# Soul — ${name}\n\nYou are a direct, collaborative team member (\`speaks_as: self\`). Prefer silence or a brief acknowledgment when you have nothing new to add.\n\n## Good vs Forbidden Replies\n- Good: One tight message with concrete findings, owners, and next steps.\n- Forbidden: Multi-bubble chatter in shared channels or unverified status claims.\n`,
|
|
463
|
+
hardRules: '# Hard rules\n- Keep shared channel updates to a single concise message.\n- Cite file paths, commits, or sources before claiming completion.\n- Never bypass approval gates on external or destructive actions.\n',
|
|
464
|
+
},
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
// ── NEW: scaffold from template (optional --preset assistant|service|proxy|teammate) ──
|
|
468
|
+
export function scaffold(name, cwd = process.cwd(), opts = {}) {
|
|
469
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name)) throw new Error(`name "${name}" must match ^[a-z][a-z0-9-]*$`);
|
|
470
|
+
const presetName = opts && opts.preset ? String(opts.preset) : null;
|
|
471
|
+
if (presetName && !Object.prototype.hasOwnProperty.call(AGENT_PRESETS, presetName)) {
|
|
472
|
+
throw new Error(`unknown preset "${presetName}" — valid presets: ${Object.keys(AGENT_PRESETS).join(', ')}`);
|
|
473
|
+
}
|
|
474
|
+
const dest = path.join(cwd, 'agents', name);
|
|
475
|
+
if (fs.existsSync(dest)) throw new Error(`agents/${name}/ already exists`);
|
|
476
|
+
fs.cpSync(TEMPLATE_DIR, dest, { recursive: true });
|
|
477
|
+
// patch IDENTITY name + title
|
|
478
|
+
const idp = path.join(dest, 'IDENTITY.md');
|
|
479
|
+
let id = fs.readFileSync(idp, 'utf8');
|
|
480
|
+
id = id.replace(/^name: researcher.*$/m, `name: ${name}`)
|
|
481
|
+
.replace(/^title: Research Synthesizer.*$/m, `title: ${name}`);
|
|
482
|
+
if (presetName) {
|
|
483
|
+
const p = AGENT_PRESETS[presetName];
|
|
484
|
+
id = id.replace(/^serves:.*$/m, `serves: ${p.serves}`);
|
|
485
|
+
const extraLines = `speaks_as: ${p.speaks_as}\nstyle: ${p.style}`;
|
|
486
|
+
id = id.replace(/\n---\n/, `\n${extraLines}\n---\n`);
|
|
487
|
+
fs.writeFileSync(path.join(dest, 'SOUL.md'), p.soul(name));
|
|
488
|
+
fs.writeFileSync(path.join(dest, 'hard-rules.md'), p.hardRules);
|
|
489
|
+
}
|
|
490
|
+
fs.writeFileSync(idp, id);
|
|
491
|
+
return rel(cwd, dest);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function rel(cwd, p) { return path.relative(cwd, p) || p; }
|
|
495
|
+
|
|
496
|
+
// tiny flag parser: --key value | --flag (boolean) | positional → _[]
|
|
497
|
+
function parseArgs(argv) {
|
|
498
|
+
const out = { _: [] };
|
|
499
|
+
for (let i = 0; i < argv.length; i++) {
|
|
500
|
+
const a = argv[i];
|
|
501
|
+
if (a && a.startsWith('--')) {
|
|
502
|
+
const key = a.slice(2);
|
|
503
|
+
const next = argv[i + 1];
|
|
504
|
+
if (next === undefined || (typeof next === 'string' && next.startsWith('--'))) out[key] = true;
|
|
505
|
+
else { out[key] = next; i++; }
|
|
506
|
+
} else out._.push(a);
|
|
507
|
+
}
|
|
508
|
+
return out;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// "K=v,K2=${vault:X}" → { K: 'v', K2: '${vault:X}' }
|
|
512
|
+
function parseKv(s) {
|
|
513
|
+
if (typeof s !== 'string') return undefined;
|
|
514
|
+
const o = {};
|
|
515
|
+
for (const pair of s.split(',')) { const i = pair.indexOf('='); if (i < 0) continue; o[pair.slice(0, i).trim()] = pair.slice(i + 1).trim(); }
|
|
516
|
+
return Object.keys(o).length ? o : undefined;
|
|
517
|
+
}
|
|
518
|
+
// "issue_invoice:financial:code|amount,lookup:read_only" → { issue_invoice:{risk,ground:[...]}, lookup:{risk} }
|
|
519
|
+
function parseTools(s) {
|
|
520
|
+
if (typeof s !== 'string') return undefined;
|
|
521
|
+
const o = {};
|
|
522
|
+
for (const t of s.split(',')) {
|
|
523
|
+
const [name, tier, ground] = t.split(':');
|
|
524
|
+
if (!name || !name.trim()) continue;
|
|
525
|
+
o[name.trim()] = { ...(tier ? { risk: tier.trim() } : {}), ...(ground ? { ground: ground.split('|').map((x) => x.trim()).filter(Boolean) } : {}) };
|
|
526
|
+
}
|
|
527
|
+
return Object.keys(o).length ? o : undefined;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// ── CLI dispatch ──
|
|
531
|
+
const HELP = `${c.bold('scroll')} — build AI agents as folders, not code
|
|
532
|
+
|
|
533
|
+
${c.bold('Usage:')} scroll <command> [args]
|
|
534
|
+
|
|
535
|
+
${c.cyan('new')} <name> scaffold a compliant agent folder (--preset assistant|service|proxy|teammate)
|
|
536
|
+
${c.cyan('check')} <name> validate structure against the spec (L0/L1/L2)
|
|
537
|
+
${c.cyan('audit')} [name] deeper compliance check — conventions + hash-bound report (run in CI; --verify; --verify-chain)
|
|
538
|
+
${c.cyan('build')} <name> render one source → every runtime
|
|
539
|
+
${c.cyan('registry')} scan agents/ → a config table
|
|
540
|
+
${c.cyan('cost')} "<task>" estimate single vs multi-agent token cost
|
|
541
|
+
${c.cyan('eval')} <name> run gold cases N times → machine checks + consistency (--chat --trials k for pass^k)
|
|
542
|
+
${c.cyan('run')} --work <f> drive the inner loop: one harnessed multi-agent run (or: run <agent> --task "...")
|
|
543
|
+
${c.cyan('loop')} <LOOP.md> drive the OUTER loop: schedule + find work + stop conditions (loop engineering)
|
|
544
|
+
${c.cyan('chat')} <agent> interactive multi-turn chat session (§45: --provider, --model, --message, --session)
|
|
545
|
+
${c.cyan('auth')} <cmd> auth profiles & OAuth/Codex login (§46: list · add · remove · default · login)
|
|
546
|
+
${c.cyan('cron')} <cmd> timezone-aware cron jobs & reminders (§49: list · add · toggle · remove · pause · resume · tick)
|
|
547
|
+
${c.cyan('user')} <cmd> deployment USER.md: check · new · show · import
|
|
548
|
+
${c.cyan('people')} <cmd> person cards: check · new · list · show · propose · review · approve · done · forget
|
|
549
|
+
${c.cyan('memory')} <cmd> subject memory: new · link · show · snapshot · search · forget · review · member · consolidate · fsck · erase
|
|
550
|
+
${c.cyan('mcp')} <cmd> MCP servers & TOFU lockfile: add · diff · approve
|
|
551
|
+
${c.cyan('skill')} <cmd> skills: add · list · view · index · scan · check · eval · sources
|
|
552
|
+
${c.cyan('plugin')} add <ref> install a plugin bundle (agents + skills + mcp)
|
|
553
|
+
${c.cyan('help')} this message
|
|
554
|
+
`;
|
|
555
|
+
|
|
556
|
+
export async function run(argv) {
|
|
557
|
+
const [cmd, ...rest] = argv;
|
|
558
|
+
switch (cmd) {
|
|
559
|
+
case 'new': {
|
|
560
|
+
const a = parseArgs(rest);
|
|
561
|
+
const name = a._[0]; if (!name) throw new Error('usage: scroll new <name> [--preset assistant|service|proxy|teammate]');
|
|
562
|
+
const preset = typeof a.preset === 'string' ? a.preset : undefined;
|
|
563
|
+
const where = scaffold(name, process.cwd(), { preset });
|
|
564
|
+
console.log(`${c.green('✔')} created ${c.bold(where)}${preset ? c.dim(` (preset: ${preset})`) : ''}`);
|
|
565
|
+
console.log(c.dim(` edit SOUL.md (the persona) and IDENTITY.md (the frontmatter), then:`));
|
|
566
|
+
console.log(c.dim(` scroll check ${name} && scroll build ${name}`));
|
|
567
|
+
break;
|
|
568
|
+
}
|
|
569
|
+
case 'check': {
|
|
570
|
+
const name = rest[0]; if (!name) throw new Error('usage: scroll check <name> | scroll check user | scroll check people');
|
|
571
|
+
// v1.9 §38 — `scroll check user` validates deployment USER.md (an agent named "user" still wins)
|
|
572
|
+
if (name === 'user' && !fs.existsSync(path.join(process.cwd(), 'agents', 'user', 'IDENTITY.md'))) { await run(['user', 'check', ...rest.slice(1)]); break; }
|
|
573
|
+
// v1.9 §38 — `scroll check people` validates legacy cards (an agent named "people" still wins)
|
|
574
|
+
if (name === 'people' && !fs.existsSync(path.join(process.cwd(), 'agents', 'people', 'IDENTITY.md'))) { await run(['people', 'check', ...rest.slice(1)]); break; }
|
|
575
|
+
const { errors, warnings, level } = checkAgent(name);
|
|
576
|
+
// v1.8 §36.1 — skills this agent and repo ship must be valid and pass the security scan
|
|
577
|
+
let sk = { errors: [], warnings: [], counts: null };
|
|
578
|
+
if (errors.length === 0) { const { checkSkills } = await import('./skills.js'); sk = checkSkills(process.cwd(), name, { identity: loadAgent(name).frontmatter }); }
|
|
579
|
+
for (const w of [...warnings, ...sk.warnings]) console.log(`${c.yellow('⚠')} ${w}`);
|
|
580
|
+
for (const e of [...errors, ...sk.errors]) console.log(`${c.red('✖')} ${e}`);
|
|
581
|
+
const nErr = errors.length + sk.errors.length;
|
|
582
|
+
if (sk.counts && (sk.counts.visible || sk.counts.hidden || sk.counts.blocked || sk.counts.invalid)) console.log(c.dim(` skills: ${sk.counts.visible} usable · ${sk.counts.hidden} hidden · ${sk.counts.blocked} blocked · ${sk.counts.invalid} invalid`));
|
|
583
|
+
if (nErr === 0) console.log(`${c.green('✔')} ${name} valid — conformance ${c.bold(level)}`);
|
|
584
|
+
else { console.log(`${c.red('✖')} ${name} has ${nErr} error(s)`); process.exitCode = 1; }
|
|
585
|
+
break;
|
|
586
|
+
}
|
|
587
|
+
case 'build': {
|
|
588
|
+
const name = rest[0]; if (!name) throw new Error('usage: scroll build <name>');
|
|
589
|
+
const chk = checkAgent(name);
|
|
590
|
+
if (chk.errors.length) { chk.errors.forEach((e) => console.log(`${c.red('✖')} ${e}`)); throw new Error(`refusing to build invalid agent (run: scroll check ${name})`); }
|
|
591
|
+
const { written, targets } = buildAgent(name);
|
|
592
|
+
console.log(`${c.green('✔')} built ${c.bold(name)} → ${targets.join(', ')}`);
|
|
593
|
+
written.forEach((f) => console.log(c.dim(` ${f}`)));
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
case 'registry': {
|
|
597
|
+
const rows = scanRegistry();
|
|
598
|
+
if (!rows.length) { console.log(c.dim('no agents found under agents/')); break; }
|
|
599
|
+
const pad = (s, n) => String(s).padEnd(n);
|
|
600
|
+
console.log(c.bold(`${pad('NAME', 16)}${pad('VERSION', 10)}${pad('MODEL', 22)}${pad('RUNTIMES', 24)}CAPS`));
|
|
601
|
+
for (const r of rows) console.log(`${pad(r.name, 16)}${pad(r.version, 10)}${pad(r.model, 22)}${pad(r.runtimes, 24)}${r.caps}`);
|
|
602
|
+
console.log(c.dim(`\n${rows.length} agent(s). This table is derived from files — it is the registry.`));
|
|
603
|
+
break;
|
|
604
|
+
}
|
|
605
|
+
case 'cost': {
|
|
606
|
+
const a = parseArgs(rest);
|
|
607
|
+
const task = a._.join(' '); if (!task) throw new Error('usage: scroll cost "<task>" [--language vi]');
|
|
608
|
+
const lang = typeof a.language === 'string' ? a.language : (typeof a.lang === 'string' ? a.lang : undefined);
|
|
609
|
+
const e = estimateCost(task, 2, { language: lang });
|
|
610
|
+
console.log(`single-agent ~${e.single.toLocaleString()} tok · multi-agent ~${e.multi.toLocaleString()} tok${e.langMultiplier !== 1 ? ` · lang ${lang} ×${e.langMultiplier}` : ''}`);
|
|
611
|
+
console.log(e.preferSingle ? `${c.green('→ prefer single')} (saves ~${e.savingPct}%)` : `${c.yellow('→ multi-agent justified')} (parallel/read-heavy)`);
|
|
612
|
+
break;
|
|
613
|
+
}
|
|
614
|
+
case 'audit': {
|
|
615
|
+
const a = parseArgs(rest);
|
|
616
|
+
if (a['verify-chain']) {
|
|
617
|
+
const { verifyAuditChain } = await import('./chat-telemetry.js');
|
|
618
|
+
const target = typeof a['verify-chain'] === 'string'
|
|
619
|
+
? path.resolve(process.cwd(), a['verify-chain'])
|
|
620
|
+
: path.join(process.cwd(), '.scroll', 'chat-state', 'audit.jsonl');
|
|
621
|
+
const res = verifyAuditChain(target);
|
|
622
|
+
if (a.json) console.log(JSON.stringify({ file: rel(process.cwd(), target), ...res }, null, 2));
|
|
623
|
+
else console.log(res.ok ? `${c.green('✔')} audit chain verified (${res.count} entries): ${rel(process.cwd(), target)}` : `${c.red('✖')} audit chain tampered (${res.errors.length} error(s))`);
|
|
624
|
+
if (!res.ok) process.exitCode = 1;
|
|
625
|
+
break;
|
|
626
|
+
}
|
|
627
|
+
const { auditRepo, verifyAgainstRecord } = await import('./audit.js');
|
|
628
|
+
const report = auditRepo(process.cwd(), { name: a._[0] });
|
|
629
|
+
if (a.verify) {
|
|
630
|
+
const v = verifyAgainstRecord(process.cwd(), report);
|
|
631
|
+
console.log(v.ok ? `${c.green('✔')} ${v.reason}` : `${c.red('✖')} ${v.reason}`);
|
|
632
|
+
if (!v.ok) process.exitCode = 1;
|
|
633
|
+
break;
|
|
634
|
+
}
|
|
635
|
+
if (a.json) console.log(JSON.stringify(report, null, 2));
|
|
636
|
+
else {
|
|
637
|
+
for (const ag of report.agents) {
|
|
638
|
+
const mark = ag.errors.length ? c.red('✖') : c.green('✔');
|
|
639
|
+
console.log(`${mark} ${c.bold(ag.name)} — ${ag.level || c.red('invalid')} · ${ag.evalCount} eval(s)`);
|
|
640
|
+
ag.errors.forEach((e) => console.log(` ${c.red('error')} ${e}`));
|
|
641
|
+
ag.warnings.forEach((w) => console.log(` ${c.yellow('warn')} ${w}`));
|
|
642
|
+
}
|
|
643
|
+
if (report.people && (report.people.errors.length || report.people.warnings.length)) {
|
|
644
|
+
console.log(c.bold(`\npeople (§38–§41${report.people.cards ? ` · ${report.people.cards} card(s)` : ''}):`));
|
|
645
|
+
report.people.errors.forEach((e) => console.log(` ${c.red('error')} ${e}`));
|
|
646
|
+
report.people.warnings.forEach((w) => console.log(` ${c.yellow('warn ')} ${w}`));
|
|
647
|
+
}
|
|
648
|
+
if (report.conventions.length) {
|
|
649
|
+
console.log(c.bold('\nconventions:'));
|
|
650
|
+
for (const v of report.conventions) console.log(` ${v.severity === 'error' ? c.red('error') : c.yellow('warn ')} ${c.cyan(v.rule)} — ${v.file}${v.line ? ':' + v.line : ''} — ${v.msg}`);
|
|
651
|
+
}
|
|
652
|
+
const verdict = report.verdict === 'pass' ? c.green('PASS') : c.red('FAIL');
|
|
653
|
+
console.log(`\n${verdict} — ${report.errorCount} error(s), ${report.warnCount} warning(s)`);
|
|
654
|
+
console.log(c.dim(" compliance = passing this in CI, not an agent's self-claim. Record: .scroll/audit.json"));
|
|
655
|
+
}
|
|
656
|
+
if (!a['no-write']) {
|
|
657
|
+
fs.mkdirSync(path.join(process.cwd(), '.scroll'), { recursive: true });
|
|
658
|
+
fs.writeFileSync(path.join(process.cwd(), '.scroll', 'audit.json'), JSON.stringify(report, null, 2) + '\n');
|
|
659
|
+
}
|
|
660
|
+
if (report.verdict !== 'pass') process.exitCode = 1;
|
|
661
|
+
break;
|
|
662
|
+
}
|
|
663
|
+
case 'eval': {
|
|
664
|
+
const a = parseArgs(rest);
|
|
665
|
+
const name = a._[0]; if (!name) throw new Error('usage: scroll eval <name> [--n N] [--chat --trials K] [--provider mock|claude|codex|openai|...] [--model M]');
|
|
666
|
+
if (a.chat) {
|
|
667
|
+
const { runChatEvals } = await import('./eval.js');
|
|
668
|
+
const rep = await runChatEvals(name, {
|
|
669
|
+
cwd: process.cwd(),
|
|
670
|
+
trials: a.trials ? Number(a.trials) : (a.n ? Number(a.n) : 3),
|
|
671
|
+
provider: typeof a.provider === 'string' ? a.provider : 'mock',
|
|
672
|
+
model: typeof a.model === 'string' ? a.model : undefined,
|
|
673
|
+
});
|
|
674
|
+
if (a.json) { console.log(JSON.stringify(rep, null, 2)); if (!rep.ok) process.exitCode = 1; break; }
|
|
675
|
+
if (rep.error) { console.log(`${c.red('✖')} ${name}: ${rep.error}`); process.exitCode = 1; break; }
|
|
676
|
+
for (const cs of rep.cases) {
|
|
677
|
+
const mark = cs.verdict === 'pass' ? c.green('✔') : c.red('✖');
|
|
678
|
+
console.log(`${mark} ${c.bold(cs.id)} — ${cs.passedTrials}/${cs.trials} trials pass · pass^${cs.trials}=${cs.passPowK} (min ${cs.minPassPowK})`);
|
|
679
|
+
}
|
|
680
|
+
console.log(`\n${rep.ok ? c.green('PASS') : c.red('FAIL')} — ${rep.passed}/${rep.total} chat eval case(s) · record .scroll/eval/${name}-chat.json`);
|
|
681
|
+
if (!rep.ok) process.exitCode = 1;
|
|
682
|
+
break;
|
|
683
|
+
}
|
|
684
|
+
const { runEvals } = await import('./eval.js');
|
|
685
|
+
const rep = await runEvals(name, {
|
|
686
|
+
cwd: process.cwd(), n: a.n ? Number(a.n) : undefined,
|
|
687
|
+
provider: typeof a.provider === 'string' ? a.provider : 'auto',
|
|
688
|
+
model: typeof a.model === 'string' ? a.model : undefined,
|
|
689
|
+
judge: !!a.judge,
|
|
690
|
+
judgeProvider: typeof a['judge-provider'] === 'string' ? a['judge-provider'] : undefined,
|
|
691
|
+
judgeModel: typeof a['judge-model'] === 'string' ? a['judge-model'] : undefined,
|
|
692
|
+
});
|
|
693
|
+
if (a.json) { console.log(JSON.stringify(rep, null, 2)); if (!rep.ok) process.exitCode = 1; break; }
|
|
694
|
+
if (rep.error) { console.log(`${c.red('✖')} ${name}: ${rep.error}`); process.exitCode = 1; break; }
|
|
695
|
+
for (const cs of rep.cases) {
|
|
696
|
+
// §30 — provenance is printed beside every verdict: a green case built on a hand-made
|
|
697
|
+
// precondition proves nothing about the path that should have made it.
|
|
698
|
+
const prov = cs.fixture && cs.fixture.provenance
|
|
699
|
+
? c.dim(` [${cs.fixture.provenance}]`)
|
|
700
|
+
: c.yellow(' [provenance?]');
|
|
701
|
+
if (cs.skipped) { console.log(`${c.yellow('·')} ${cs.id}${prov} — ${c.yellow('ungraded')}: ${cs.reason}`); continue; }
|
|
702
|
+
// §29 — verdict is ternary. `ungraded` gets a neutral marker, never a check-mark.
|
|
703
|
+
const mark = cs.verdict === 'pass' ? c.green('✔') : cs.verdict === 'ungraded' ? c.yellow('·') : c.red('✖');
|
|
704
|
+
const jd = cs.judge ? ` · judge ${cs.judge.ok ? cs.judge.average + '/' + cs.judge.min + (cs.judge.pass ? '✔' : '✖') : 'ERR ' + (cs.judge.error || '')}` : '';
|
|
705
|
+
console.log(`${mark} ${c.bold(cs.id)}${prov} — ${cs.verdict === 'ungraded' ? c.yellow('ungraded (checker did not run)') : `${cs.passCount}/${cs.runs} runs pass (consistency ${cs.consistency} ≥ ${cs.threshold})`} · ${cs.checks} check(s)${jd}`);
|
|
706
|
+
if (cs.verdict === 'fail') { const f = cs.perRun.find((r) => !r.allPass); if (f && f.fails.length) console.log(c.dim(` failed: ${f.fails.join(', ')}${f.err ? ' · ' + f.err : ''}`)); }
|
|
707
|
+
if (cs.fixture && cs.fixture.issues && cs.fixture.issues.length) console.log(c.yellow(` fixture: ${cs.fixture.issues.join('; ')}`));
|
|
708
|
+
}
|
|
709
|
+
const verdict = rep.ok ? c.green('PASS') : c.red('FAIL');
|
|
710
|
+
const ung = rep.ungraded ? c.yellow(` · ${rep.ungraded} ungraded (not counted as pass)`) : '';
|
|
711
|
+
console.log(`\n${verdict} — ${rep.passed}/${rep.gradable} graded case(s)${ung} · provider ${rep.provider} (${rep.model}) · record .scroll/eval/${name}.json`);
|
|
712
|
+
if (!rep.ok) process.exitCode = 1;
|
|
713
|
+
break;
|
|
714
|
+
}
|
|
715
|
+
case 'run': {
|
|
716
|
+
const a = parseArgs(rest);
|
|
717
|
+
const positional = a._[0];
|
|
718
|
+
const opts = {
|
|
719
|
+
cwd: process.cwd(),
|
|
720
|
+
workFile: a.work || (positional && positional.endsWith('.md') ? positional : undefined),
|
|
721
|
+
task: typeof a.task === 'string' ? a.task : undefined,
|
|
722
|
+
agent: a.agent || (positional && !positional.endsWith('.md') ? positional : undefined),
|
|
723
|
+
providerName: a.provider || 'auto',
|
|
724
|
+
model: typeof a.model === 'string' ? a.model : undefined,
|
|
725
|
+
eventsPath: typeof a.events === 'string' ? a.events : undefined,
|
|
726
|
+
outPath: typeof a.out === 'string' ? a.out : undefined,
|
|
727
|
+
runDir: typeof a['run-dir'] === 'string' ? a['run-dir'] : undefined,
|
|
728
|
+
json: !!a.json,
|
|
729
|
+
verbose: !a.json,
|
|
730
|
+
autoApprove: !!a['auto-approve'],
|
|
731
|
+
risk: typeof a.risk === 'string' ? a.risk : undefined,
|
|
732
|
+
resumeSelftest: !!a['resume-selftest'],
|
|
733
|
+
noLean: !!a['no-lean'],
|
|
734
|
+
maxTokens: a['max-tokens'] ? Number(a['max-tokens']) : undefined,
|
|
735
|
+
intermediateMaxTokens: a['intermediate-max-tokens'] ? Number(a['intermediate-max-tokens']) : undefined,
|
|
736
|
+
blackboardCap: a['blackboard-cap'] ? Number(a['blackboard-cap']) : undefined,
|
|
737
|
+
subModel: typeof a['sub-model'] === 'string' ? a['sub-model'] : undefined,
|
|
738
|
+
route: a['no-route'] ? false : undefined,
|
|
739
|
+
compactPrefix: !!a['compact-prefix'],
|
|
740
|
+
language: typeof a.language === 'string' ? a.language : (typeof a.lang === 'string' ? a.lang : undefined),
|
|
741
|
+
resume: !!a.resume,
|
|
742
|
+
worktree: !!a.worktree,
|
|
743
|
+
tool: typeof a.tool === 'string' ? a.tool : undefined,
|
|
744
|
+
subject: typeof a.subject === 'string' ? a.subject : undefined,
|
|
745
|
+
for: typeof a.for === 'string' ? a.for : undefined, // v1.9 §39: the person this step serves
|
|
746
|
+
userFile: typeof a.user === 'string' ? a.user : undefined, // v1.9 §38: deployment USER.md path
|
|
747
|
+
peopleDir: typeof a.people === 'string' ? a.people : undefined, // v1.9 §38: legacy cards dir
|
|
748
|
+
action: typeof a.action === 'string' ? a.action : undefined, // v1.9 §40.2: the action class the approver must hold
|
|
749
|
+
amount: typeof a.amount === 'string' ? a.amount : undefined, // v1.9 §40.2: checked against the approver's max_amount
|
|
750
|
+
skills: typeof a.skill === 'string' ? a.skill.split(',').map((x) => x.trim()).filter(Boolean) : undefined,
|
|
751
|
+
memoryStore: typeof a['memory-store'] === 'string' ? a['memory-store'] : undefined,
|
|
752
|
+
caps: {},
|
|
753
|
+
};
|
|
754
|
+
const capMap = { 'max-iterations': 'maxIterations', 'max-input-tokens': 'maxInputTokens', 'max-wall-clock-ms': 'maxWallClockMs', 'max-usd': 'maxUsd' };
|
|
755
|
+
for (const k of Object.keys(capMap)) if (a[k] != null && a[k] !== true) opts.caps[capMap[k]] = Number(a[k]);
|
|
756
|
+
if (!opts.workFile && !opts.task) throw new Error('usage: scroll run --work <WORK.md> | scroll run <agent> --task "<text>"');
|
|
757
|
+
const { runWork } = await import('./runtime.js');
|
|
758
|
+
const res = await runWork(opts);
|
|
759
|
+
if (!a.json) {
|
|
760
|
+
const m = res.metrics;
|
|
761
|
+
const mark = res.status === 'completed' ? c.green('✔') : c.yellow('●');
|
|
762
|
+
console.log(`${mark} scroll run ${c.bold(res.status)} — ${m.tasksCompleted}/${m.tasksTotal} task(s) · ${res.decision}/${res.spawnedAgents} agent(s)`);
|
|
763
|
+
console.log(c.dim(` tokens ${m.billableTokenEquivalent} (cache ${m.cacheHitPct}%) · $${m.costUsd} · ${m.durationMs}ms · verify ${res.verification.passed ? c.green('PASS') : c.red('FAIL')}`));
|
|
764
|
+
console.log(c.dim(` events: ${rel(process.cwd(), res.eventsPath)} · output: ${rel(process.cwd(), res.outPath)}`));
|
|
765
|
+
for (const w of res.waiting || []) console.log(c.yellow(` waiting: ${w.taskId} — ${w.kind === 'person' ? `person:${w.person}${w.problem ? ` (${w.problem})` : ''} (mark done: scroll people done ${w.taskId} --run ${rel(process.cwd(), res.runDir)} --by ${w.person})` : `approval ${w.gateId}${w.approvers && w.approvers.length ? ` by one of: ${w.approvers.join(', ')}` : ' — nobody on the team may approve this'}`}`));
|
|
766
|
+
}
|
|
767
|
+
if (res.verification && res.verification.passed === false) process.exitCode = 1;
|
|
768
|
+
break;
|
|
769
|
+
}
|
|
770
|
+
case 'loop': {
|
|
771
|
+
const a = parseArgs(rest);
|
|
772
|
+
const file = a._[0] || (typeof a.work === 'string' ? a.work : 'LOOP.md');
|
|
773
|
+
const { runLoop } = await import('./loop.js');
|
|
774
|
+
const { runWork } = await import('./runtime.js');
|
|
775
|
+
const summary = await runLoop(file, {
|
|
776
|
+
cwd: process.cwd(),
|
|
777
|
+
once: !!a.once,
|
|
778
|
+
dryRun: !!a['dry-run'],
|
|
779
|
+
maxRuns: a['max-runs'] != null && a['max-runs'] !== true ? Number(a['max-runs']) : undefined,
|
|
780
|
+
providerName: a.provider || 'auto',
|
|
781
|
+
model: typeof a.model === 'string' ? a.model : undefined,
|
|
782
|
+
sleepMs: a['sleep-ms'] != null && a['sleep-ms'] !== true ? Number(a['sleep-ms']) : undefined,
|
|
783
|
+
verbose: !a.json,
|
|
784
|
+
runWork,
|
|
785
|
+
});
|
|
786
|
+
if (a.json) { console.log(JSON.stringify(summary, null, 2)); break; }
|
|
787
|
+
console.log(`${c.green('✔')} loop ${c.bold(summary.id)} — ${summary.iterations} iteration(s)${summary.stopped ? ` · stopped: ${summary.stopped}` : ''}`);
|
|
788
|
+
for (const r of summary.runs) console.log(c.dim(` iter ${r.iteration}: ${r.dryRun ? 'dry-run' : r.status + (r.verify != null ? ' · verify ' + (r.verify ? 'PASS' : 'FAIL') : '')}${r.digest ? ' · ' + r.digest : ''}`));
|
|
789
|
+
console.log(c.dim(` loop events: ${rel(process.cwd(), summary.eventsPath)}`));
|
|
790
|
+
break;
|
|
791
|
+
}
|
|
792
|
+
case 'chat': {
|
|
793
|
+
const a = parseArgs(rest);
|
|
794
|
+
const agentName = a._[0] || (typeof a.agent === 'string' ? a.agent : null);
|
|
795
|
+
if (!agentName) throw new Error('usage: scroll chat <agent> [--message "<text>"] [--session <id>] [--provider mock|codex-app-server|openai|...] [--model M]');
|
|
796
|
+
const { createChatSessionRuntime } = await import('./chat-session.js');
|
|
797
|
+
const { createToolRegistry } = await import('./tools.js');
|
|
798
|
+
const { createAuthStore } = await import('./auth.js');
|
|
799
|
+
const { createMcpManager } = await import('./mcp-client.js');
|
|
800
|
+
const cwd = process.cwd();
|
|
801
|
+
const stateDir = typeof a['state-dir'] === 'string' ? path.resolve(cwd, a['state-dir']) : path.join(cwd, '.scroll', 'chat-state');
|
|
802
|
+
// Unified auth store path (.scroll/auth.json), auto-migrating legacy .scroll/chat-state/auth.json once
|
|
803
|
+
const defaultAuthFile = path.join(cwd, '.scroll', 'auth.json');
|
|
804
|
+
const legacyAuthFile = path.join(stateDir, 'auth.json');
|
|
805
|
+
if (!a['auth-file'] && !fs.existsSync(defaultAuthFile) && fs.existsSync(legacyAuthFile)) {
|
|
806
|
+
fs.mkdirSync(path.dirname(defaultAuthFile), { recursive: true, mode: 0o700 });
|
|
807
|
+
fs.copyFileSync(legacyAuthFile, defaultAuthFile);
|
|
808
|
+
try { fs.chmodSync(defaultAuthFile, 0o600); } catch { /* ignore */ }
|
|
809
|
+
}
|
|
810
|
+
const authFile = typeof a['auth-file'] === 'string' ? path.resolve(cwd, a['auth-file']) : defaultAuthFile;
|
|
811
|
+
const authStore = createAuthStore({ filePath: authFile });
|
|
812
|
+
const agentDir = path.join(cwd, 'agents', agentName);
|
|
813
|
+
let mcpManager = null;
|
|
814
|
+
if (!a['no-tools'] && !a['no-mcp']) {
|
|
815
|
+
mcpManager = createMcpManager({ cwd, agentDir });
|
|
816
|
+
if (mcpManager.listConfiguredServers().length > 0) {
|
|
817
|
+
await mcpManager.connectAll().catch(() => {});
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
const tools = a['no-tools'] ? null : createToolRegistry({ cwd, agentDir, mcpManager });
|
|
821
|
+
if (tools && mcpManager) tools.syncMcpTools();
|
|
822
|
+
const runtime = createChatSessionRuntime({
|
|
823
|
+
agentName,
|
|
824
|
+
cwd,
|
|
825
|
+
stateDir,
|
|
826
|
+
providerName: typeof a.provider === 'string' ? a.provider : 'auto',
|
|
827
|
+
model: typeof a.model === 'string' ? a.model : undefined,
|
|
828
|
+
authStore,
|
|
829
|
+
tools,
|
|
830
|
+
});
|
|
831
|
+
const convId = typeof a.session === 'string' ? a.session : 'cli-default';
|
|
832
|
+
const sender = typeof a.sender === 'string' ? { id: a.sender, verified: true } : null;
|
|
833
|
+
try {
|
|
834
|
+
if (typeof a.message === 'string') {
|
|
835
|
+
let streamed = false;
|
|
836
|
+
const res = await runtime.sendTurn({
|
|
837
|
+
conversationId: convId,
|
|
838
|
+
text: a.message,
|
|
839
|
+
sender,
|
|
840
|
+
channel: 'cli',
|
|
841
|
+
onDelta: a.json ? null : (d) => { streamed = true; process.stdout.write(d); },
|
|
842
|
+
});
|
|
843
|
+
if (a.json) console.log(JSON.stringify(res, null, 2));
|
|
844
|
+
else {
|
|
845
|
+
if (!streamed && res.text) process.stdout.write(res.text);
|
|
846
|
+
if ((streamed || res.text) && !String(res.text || '').endsWith('\n')) process.stdout.write('\n');
|
|
847
|
+
}
|
|
848
|
+
} else {
|
|
849
|
+
const readline = await import('node:readline');
|
|
850
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout, prompt: `${agentName}> ` });
|
|
851
|
+
rl.prompt();
|
|
852
|
+
for await (const line of rl) {
|
|
853
|
+
const trimmed = line.trim();
|
|
854
|
+
if (!trimmed || trimmed === '/exit' || trimmed === '/quit') break;
|
|
855
|
+
if (trimmed === '/clear') { runtime.clearSession(convId); console.log(c.dim('session cleared')); rl.prompt(); continue; }
|
|
856
|
+
let streamed = false;
|
|
857
|
+
const res = await runtime.sendTurn({
|
|
858
|
+
conversationId: convId,
|
|
859
|
+
text: trimmed,
|
|
860
|
+
sender,
|
|
861
|
+
channel: 'cli',
|
|
862
|
+
onDelta: (d) => { streamed = true; process.stdout.write(d); },
|
|
863
|
+
});
|
|
864
|
+
if (!streamed) console.log(res.text);
|
|
865
|
+
else if (!String(res.text || '').endsWith('\n')) process.stdout.write('\n');
|
|
866
|
+
rl.prompt();
|
|
867
|
+
}
|
|
868
|
+
rl.close();
|
|
869
|
+
}
|
|
870
|
+
} finally {
|
|
871
|
+
await runtime.close();
|
|
872
|
+
if (mcpManager) await mcpManager.closeAll().catch(() => {});
|
|
873
|
+
}
|
|
874
|
+
break;
|
|
875
|
+
}
|
|
876
|
+
case 'auth': {
|
|
877
|
+
const a = parseArgs(rest);
|
|
878
|
+
const sub = a._[0] || 'list';
|
|
879
|
+
const cwd = process.cwd();
|
|
880
|
+
const authFile = typeof a.file === 'string' ? path.resolve(cwd, a.file) : path.join(cwd, '.scroll', 'auth.json');
|
|
881
|
+
const { createAuthStore, createPkceChallenge, buildAuthorizationUrl, runLoopbackOAuthCallback, exchangeAuthCode } = await import('./auth.js');
|
|
882
|
+
const store = createAuthStore({ filePath: authFile });
|
|
883
|
+
if (sub === 'list') {
|
|
884
|
+
const list = store.listProfiles({ provider: typeof a.provider === 'string' ? a.provider : null });
|
|
885
|
+
if (a.json) console.log(JSON.stringify(list, null, 2));
|
|
886
|
+
else if (!list.length) console.log(c.dim('no auth profiles configured'));
|
|
887
|
+
else for (const p of list) console.log(`${p.isDefault ? c.green('*') : ' '} ${c.bold(p.id)} (${p.provider}/${p.type})${p.inCooldown ? c.yellow(' [cooldown]') : ''}${p.disabled ? c.red(' [disabled]') : ''}`);
|
|
888
|
+
break;
|
|
889
|
+
}
|
|
890
|
+
if (sub === 'add') {
|
|
891
|
+
const id = a._[1]; if (!id) throw new Error('usage: scroll auth add <id> --provider <p> [--api-key K | --token T] [--base-url URL]');
|
|
892
|
+
const saved = store.upsertProfile({
|
|
893
|
+
id,
|
|
894
|
+
provider: typeof a.provider === 'string' ? a.provider : 'openai',
|
|
895
|
+
type: typeof a.type === 'string' ? a.type : (a['api-key'] ? 'api_key' : (a['base-url'] ? 'proxy' : 'oauth')),
|
|
896
|
+
apiKey: typeof a['api-key'] === 'string' ? a['api-key'] : undefined,
|
|
897
|
+
accessToken: typeof a.token === 'string' ? a.token : undefined,
|
|
898
|
+
refreshToken: typeof a['refresh-token'] === 'string' ? a['refresh-token'] : undefined,
|
|
899
|
+
baseUrl: typeof a['base-url'] === 'string' ? a['base-url'] : undefined,
|
|
900
|
+
label: typeof a.label === 'string' ? a.label : id,
|
|
901
|
+
isDefault: !!a.default,
|
|
902
|
+
});
|
|
903
|
+
console.log(a.json ? JSON.stringify(saved, null, 2) : `${c.green('✔')} auth profile saved: ${c.bold(saved.id)} (${saved.provider}/${saved.type})`);
|
|
904
|
+
break;
|
|
905
|
+
}
|
|
906
|
+
if (sub === 'remove') {
|
|
907
|
+
const id = a._[1]; if (!id) throw new Error('usage: scroll auth remove <id>');
|
|
908
|
+
const res = store.removeProfile(id);
|
|
909
|
+
console.log(a.json ? JSON.stringify(res) : (res.removed ? `${c.green('✔')} removed ${id}` : `${c.yellow('⚠')} not found: ${id}`));
|
|
910
|
+
break;
|
|
911
|
+
}
|
|
912
|
+
if (sub === 'default') {
|
|
913
|
+
const provider = a._[1]; const id = a._[2];
|
|
914
|
+
if (!provider || !id) throw new Error('usage: scroll auth default <provider> <profileId>');
|
|
915
|
+
const res = store.setDefault(provider, id);
|
|
916
|
+
console.log(a.json ? JSON.stringify(res) : `${c.green('✔')} default ${provider} -> ${id}`);
|
|
917
|
+
break;
|
|
918
|
+
}
|
|
919
|
+
if (sub === 'login') {
|
|
920
|
+
const prov = typeof a.provider === 'string' ? a.provider : (a._[1] || 'codex');
|
|
921
|
+
if (prov === 'codex' || prov === 'chatgpt') {
|
|
922
|
+
const { createCodexAppServerClient } = await import('./codex-app-server.js');
|
|
923
|
+
const client = createCodexAppServerClient();
|
|
924
|
+
try {
|
|
925
|
+
const out = await client.startLogin({ type: 'chatgpt' });
|
|
926
|
+
console.log(a.json ? JSON.stringify(out, null, 2) : `${c.green('✔')} ChatGPT login started: ${out?.authUrl || JSON.stringify(out)}`);
|
|
927
|
+
} finally {
|
|
928
|
+
await client.close();
|
|
929
|
+
}
|
|
930
|
+
break;
|
|
931
|
+
}
|
|
932
|
+
const pkce = createPkceChallenge();
|
|
933
|
+
const clientId = typeof a['client-id'] === 'string' ? a['client-id'] : (process.env.SCROLL_OAUTH_CLIENT_ID || 'scroll-cli');
|
|
934
|
+
if (a.loopback) {
|
|
935
|
+
const cb = await runLoopbackOAuthCallback({
|
|
936
|
+
port: a.port ? Number(a.port) : 0,
|
|
937
|
+
expectedState: pkce.state,
|
|
938
|
+
timeoutMs: a['timeout-ms'] ? Number(a['timeout-ms']) : 180_000,
|
|
939
|
+
});
|
|
940
|
+
const url = buildAuthorizationUrl({
|
|
941
|
+
provider: prov,
|
|
942
|
+
clientId,
|
|
943
|
+
redirectUri: cb.redirectUri,
|
|
944
|
+
challenge: pkce.challenge,
|
|
945
|
+
state: pkce.state,
|
|
946
|
+
});
|
|
947
|
+
console.log(`Open to authenticate:\n ${url}\nWaiting on ${cb.redirectUri} ...`);
|
|
948
|
+
const { code } = await cb.waitForCode();
|
|
949
|
+
const tok = await exchangeAuthCode({
|
|
950
|
+
provider: prov,
|
|
951
|
+
clientId,
|
|
952
|
+
clientSecret: typeof a['client-secret'] === 'string' ? a['client-secret'] : null,
|
|
953
|
+
code,
|
|
954
|
+
verifier: pkce.verifier,
|
|
955
|
+
redirectUri: cb.redirectUri,
|
|
956
|
+
});
|
|
957
|
+
const profileId = typeof a.id === 'string' ? a.id : `${prov}-oauth`;
|
|
958
|
+
const saved = store.upsertProfile({
|
|
959
|
+
id: profileId,
|
|
960
|
+
provider: prov,
|
|
961
|
+
type: 'oauth',
|
|
962
|
+
clientId,
|
|
963
|
+
accessToken: tok.accessToken,
|
|
964
|
+
refreshToken: tok.refreshToken,
|
|
965
|
+
expiresAt: tok.expiresAt,
|
|
966
|
+
tokenType: tok.tokenType,
|
|
967
|
+
isDefault: true,
|
|
968
|
+
});
|
|
969
|
+
console.log(a.json ? JSON.stringify(saved, null, 2) : `${c.green('✔')} OAuth profile saved: ${c.bold(saved.id)}`);
|
|
970
|
+
break;
|
|
971
|
+
}
|
|
972
|
+
const url = buildAuthorizationUrl({
|
|
973
|
+
provider: prov,
|
|
974
|
+
clientId,
|
|
975
|
+
redirectUri: typeof a['redirect-uri'] === 'string' ? a['redirect-uri'] : 'http://127.0.0.1:8787/callback',
|
|
976
|
+
challenge: pkce.challenge,
|
|
977
|
+
state: pkce.state,
|
|
978
|
+
});
|
|
979
|
+
console.log(a.json ? JSON.stringify({ url, ...pkce }, null, 2) : `Open to authenticate:\n ${url}`);
|
|
980
|
+
break;
|
|
981
|
+
}
|
|
982
|
+
throw new Error(`unknown auth subcommand "${sub}"`);
|
|
983
|
+
}
|
|
984
|
+
case 'cron': {
|
|
985
|
+
const a = parseArgs(rest);
|
|
986
|
+
const sub = a._[0] || 'list';
|
|
987
|
+
const cwd = process.cwd();
|
|
988
|
+
const cronFile = typeof a.file === 'string' ? path.resolve(cwd, a.file) : path.join(cwd, '.scroll', 'cron.json');
|
|
989
|
+
const { createScheduler } = await import('./scheduler.js');
|
|
990
|
+
const sched = createScheduler({ filePath: cronFile, defaultTz: typeof a.tz === 'string' ? a.tz : 'UTC' });
|
|
991
|
+
if (sub === 'list') {
|
|
992
|
+
const jobs = sched.listJobs({ chatId: typeof a.chat === 'string' ? a.chat : null });
|
|
993
|
+
if (a.json) console.log(JSON.stringify({ paused: sched.paused, jobs }, null, 2));
|
|
994
|
+
else if (!jobs.length) console.log(c.dim(`no cron jobs (${sched.paused ? 'paused' : 'active'})`));
|
|
995
|
+
else for (const j of jobs) console.log(`${j.enabled ? c.green('●') : c.dim('○')} ${c.bold(j.id)} [${j.cron || j.at || `${j.everyMs}ms`} @ ${j.tz}] ${j.name}`);
|
|
996
|
+
break;
|
|
997
|
+
}
|
|
998
|
+
if (sub === 'add') {
|
|
999
|
+
const job = sched.addJob({
|
|
1000
|
+
id: typeof a.id === 'string' ? a.id : undefined,
|
|
1001
|
+
name: typeof a.name === 'string' ? a.name : (a._[1] || 'Scheduled job'),
|
|
1002
|
+
cron: typeof a.cron === 'string' ? a.cron : undefined,
|
|
1003
|
+
everyMs: a['every-ms'] ? Number(a['every-ms']) : undefined,
|
|
1004
|
+
at: typeof a.at === 'string' ? a.at : undefined,
|
|
1005
|
+
tz: typeof a.tz === 'string' ? a.tz : 'UTC',
|
|
1006
|
+
targetChatId: typeof a.chat === 'string' ? a.chat : undefined,
|
|
1007
|
+
agentName: typeof a.agent === 'string' ? a.agent : undefined,
|
|
1008
|
+
prompt: typeof a.prompt === 'string' ? a.prompt : '',
|
|
1009
|
+
});
|
|
1010
|
+
console.log(a.json ? JSON.stringify(job, null, 2) : `${c.green('✔')} cron added: ${c.bold(job.id)} (${job.cron || job.at || job.everyMs})`);
|
|
1011
|
+
break;
|
|
1012
|
+
}
|
|
1013
|
+
if (sub === 'toggle') {
|
|
1014
|
+
const id = a._[1]; if (!id) throw new Error('usage: scroll cron toggle <id>');
|
|
1015
|
+
const cur = sched.getJob(id); if (!cur) throw new Error(`job not found: ${id}`);
|
|
1016
|
+
const next = sched.updateJob(id, { enabled: !cur.enabled });
|
|
1017
|
+
console.log(a.json ? JSON.stringify(next, null, 2) : `${c.green('✔')} ${id}: ${next.enabled ? 'enabled' : 'disabled'}`);
|
|
1018
|
+
break;
|
|
1019
|
+
}
|
|
1020
|
+
if (sub === 'remove') {
|
|
1021
|
+
const id = a._[1]; if (!id) throw new Error('usage: scroll cron remove <id>');
|
|
1022
|
+
const res = sched.removeJob(id);
|
|
1023
|
+
console.log(a.json ? JSON.stringify(res) : (res.removed ? `${c.green('✔')} removed ${id}` : `${c.yellow('⚠')} not found: ${id}`));
|
|
1024
|
+
break;
|
|
1025
|
+
}
|
|
1026
|
+
if (sub === 'pause' || sub === 'resume') {
|
|
1027
|
+
const res = sched.setPaused(sub === 'pause');
|
|
1028
|
+
console.log(a.json ? JSON.stringify(res) : `${c.green('✔')} scheduler ${res.paused ? 'paused' : 'resumed'}`);
|
|
1029
|
+
break;
|
|
1030
|
+
}
|
|
1031
|
+
if (sub === 'tick') {
|
|
1032
|
+
if (a.execute) {
|
|
1033
|
+
const { createChatSessionRuntime } = await import('./chat-session.js');
|
|
1034
|
+
const { createAuthStore } = await import('./auth.js');
|
|
1035
|
+
const defaultAgent = typeof a.agent === 'string' ? a.agent : null;
|
|
1036
|
+
const authStore = createAuthStore({ filePath: path.join(cwd, '.scroll', 'auth.json') });
|
|
1037
|
+
const res = await sched.tick({
|
|
1038
|
+
handler: async (job) => {
|
|
1039
|
+
const targetAgent = job.agentName || defaultAgent;
|
|
1040
|
+
if (!targetAgent) return { skipped: true, reason: 'no_agent_configured' };
|
|
1041
|
+
const rt = createChatSessionRuntime({
|
|
1042
|
+
agentName: targetAgent,
|
|
1043
|
+
cwd,
|
|
1044
|
+
stateDir: path.join(cwd, '.scroll', 'chat-state'),
|
|
1045
|
+
providerName: typeof a.provider === 'string' ? a.provider : 'auto',
|
|
1046
|
+
authStore,
|
|
1047
|
+
acquireLock: false,
|
|
1048
|
+
});
|
|
1049
|
+
try {
|
|
1050
|
+
const out = await rt.sendTurn({
|
|
1051
|
+
conversationId: job.targetChatId || `cron:${job.id}`,
|
|
1052
|
+
text: job.prompt || job.name,
|
|
1053
|
+
channel: 'cron',
|
|
1054
|
+
});
|
|
1055
|
+
return { ok: true, jobId: job.id, text: out.text };
|
|
1056
|
+
} finally {
|
|
1057
|
+
await rt.close();
|
|
1058
|
+
}
|
|
1059
|
+
},
|
|
1060
|
+
});
|
|
1061
|
+
console.log(a.json ? JSON.stringify(res, null, 2) : `${c.green('✔')} tick (executed): ${res.triggered.length} triggered`);
|
|
1062
|
+
} else {
|
|
1063
|
+
const res = await sched.tick({ handler: async (job) => ({ dryRun: true, jobId: job.id }) });
|
|
1064
|
+
console.log(a.json ? JSON.stringify(res, null, 2) : `${c.green('✔')} tick (dry-run): ${res.triggered.length} triggered`);
|
|
1065
|
+
}
|
|
1066
|
+
break;
|
|
1067
|
+
}
|
|
1068
|
+
throw new Error(`unknown cron subcommand "${sub}"`);
|
|
1069
|
+
}
|
|
1070
|
+
case 'user': {
|
|
1071
|
+
const a = parseArgs(rest);
|
|
1072
|
+
const sub = a._[0] || 'check';
|
|
1073
|
+
const { openUser, importWorkspaceUserMd, userTemplate } = await import('./user.js');
|
|
1074
|
+
const cwd = process.cwd();
|
|
1075
|
+
const file = typeof a.file === 'string' ? a.file : undefined;
|
|
1076
|
+
if (sub === 'new') {
|
|
1077
|
+
const dest = path.resolve(cwd, file || 'USER.md');
|
|
1078
|
+
if (fs.existsSync(dest) && !a.force) throw new Error(`${rel(cwd, dest)} already exists (pass --force to overwrite)`);
|
|
1079
|
+
fs.writeFileSync(dest, userTemplate({
|
|
1080
|
+
kind: typeof a.kind === 'string' ? a.kind : 'org',
|
|
1081
|
+
name: typeof a.name === 'string' ? a.name : 'Example Co',
|
|
1082
|
+
}));
|
|
1083
|
+
console.log(`${c.green('✔')} created ${c.bold(rel(cwd, dest))}`);
|
|
1084
|
+
break;
|
|
1085
|
+
}
|
|
1086
|
+
if (sub === 'import') {
|
|
1087
|
+
const src = a._[1]; if (!src) throw new Error('usage: scroll user import <source-USER.md> [--out USER.md] [--name "Principal"] [--kind person|org]');
|
|
1088
|
+
const raw = fs.readFileSync(path.resolve(cwd, src), 'utf8');
|
|
1089
|
+
const res = importWorkspaceUserMd(raw, {
|
|
1090
|
+
principalName: typeof a.name === 'string' ? a.name : 'Principal',
|
|
1091
|
+
kind: typeof a.kind === 'string' ? a.kind : 'person',
|
|
1092
|
+
});
|
|
1093
|
+
const dest = path.resolve(cwd, typeof a.out === 'string' ? a.out : 'USER.md');
|
|
1094
|
+
fs.writeFileSync(dest, res.userMd);
|
|
1095
|
+
if (a.json) console.log(JSON.stringify({ out: rel(cwd, dest), humanChars: res.humanBody.length, agentNotes: res.agentNotes }, null, 2));
|
|
1096
|
+
else console.log(`${c.green('✔')} imported ${rel(cwd, dest)} (${res.humanBody.length} human chars · ${res.agentNotes.length} agent note(s) separated)`);
|
|
1097
|
+
break;
|
|
1098
|
+
}
|
|
1099
|
+
const doc = openUser({ cwd, file });
|
|
1100
|
+
if (sub === 'show') {
|
|
1101
|
+
const aud = typeof a.audience === 'string' ? a.audience : 'internal';
|
|
1102
|
+
const r = doc.render({ audience: aud });
|
|
1103
|
+
console.log(a.json ? JSON.stringify({ active: doc.active, hash: doc.hash, audience: aud, text: r.text }, null, 2) : (r.text || '(no active USER.md)'));
|
|
1104
|
+
break;
|
|
1105
|
+
}
|
|
1106
|
+
const chk = doc.check();
|
|
1107
|
+
if (a.json) console.log(JSON.stringify({ file: rel(cwd, doc.file), ...chk }, null, 2));
|
|
1108
|
+
else {
|
|
1109
|
+
for (const w of chk.warnings) console.log(`${c.yellow('⚠')} ${w}`);
|
|
1110
|
+
for (const e of chk.errors) console.log(`${c.red('✖')} ${e}`);
|
|
1111
|
+
console.log(chk.errors.length
|
|
1112
|
+
? `${c.red('✖')} user: ${chk.errors.length} error(s) (${rel(cwd, doc.file)})`
|
|
1113
|
+
: `${c.green('✔')} user: ${chk.active ? `valid · ${chk.people} internal member(s)` : 'no USER.md'} (${rel(cwd, doc.file)})`);
|
|
1114
|
+
}
|
|
1115
|
+
if (chk.errors.length) process.exitCode = 1;
|
|
1116
|
+
break;
|
|
1117
|
+
}
|
|
1118
|
+
case 'people': {
|
|
1119
|
+
const a = parseArgs(rest);
|
|
1120
|
+
const { peopleCli } = await import('./people-cli.js');
|
|
1121
|
+
const out = await peopleCli(a, process.env);
|
|
1122
|
+
if (a._[0] === 'check' && out && typeof out === 'object' && !a.json) {
|
|
1123
|
+
for (const w of out.warnings) console.log(`${c.yellow('⚠')} ${w}`);
|
|
1124
|
+
for (const e of out.errors) console.log(`${c.red('✖')} ${e}`);
|
|
1125
|
+
console.log(out.errors.length ? `${c.red('✖')} people: ${out.errors.length} error(s) in ${out.cards} card(s) (${out.dir})` : `${c.green('✔')} people: ${out.cards} card(s) valid (${out.dir})`);
|
|
1126
|
+
if (out.errors.length) process.exitCode = 1;
|
|
1127
|
+
break;
|
|
1128
|
+
}
|
|
1129
|
+
if (a.json || typeof out !== 'string') console.log(typeof out === 'string' ? JSON.stringify({ text: out }) : JSON.stringify(out, null, 2));
|
|
1130
|
+
else console.log(out);
|
|
1131
|
+
if (out && out.ok === false) process.exitCode = 1;
|
|
1132
|
+
break;
|
|
1133
|
+
}
|
|
1134
|
+
case 'memory': {
|
|
1135
|
+
const a = parseArgs(rest);
|
|
1136
|
+
const { memoryCli } = await import('./memory-cli.js');
|
|
1137
|
+
const out = memoryCli(a, process.env);
|
|
1138
|
+
if (a.json || typeof out !== 'string') console.log(typeof out === 'string' ? JSON.stringify({ text: out }) : JSON.stringify(out, null, 2));
|
|
1139
|
+
else console.log(out);
|
|
1140
|
+
if (out && out.ok === false) process.exitCode = 1;
|
|
1141
|
+
break;
|
|
1142
|
+
}
|
|
1143
|
+
case 'mcp': {
|
|
1144
|
+
const a = parseArgs(rest);
|
|
1145
|
+
const sub = a._[0];
|
|
1146
|
+
if (sub === 'diff' || sub === 'approve') {
|
|
1147
|
+
const cwd = process.cwd();
|
|
1148
|
+
const agentDir = typeof a.agent === 'string' ? path.join(cwd, 'agents', a.agent) : null;
|
|
1149
|
+
const targetServer = a._[1] || null;
|
|
1150
|
+
const { createMcpManager, approveMcpLock, loadMcpLock, mcpLockPath } = await import('./mcp-client.js');
|
|
1151
|
+
const mgr = createMcpManager({ cwd, agentDir, enforceLock: sub !== 'approve', autoPinLock: false });
|
|
1152
|
+
const lockFile = mcpLockPath(cwd);
|
|
1153
|
+
try {
|
|
1154
|
+
await mgr.connectAll();
|
|
1155
|
+
const allTools = mgr.listDiscoveredTools().concat(mgr.listQuarantinedTools ? mgr.listQuarantinedTools() : []);
|
|
1156
|
+
const filtered = targetServer ? allTools.filter((t) => t.server === targetServer) : allTools;
|
|
1157
|
+
if (sub === 'approve') {
|
|
1158
|
+
const approvedRes = approveMcpLock(cwd, filtered, { pinnedBy: 'cli' });
|
|
1159
|
+
console.log(a.json ? JSON.stringify({ ok: true, lockFile: rel(cwd, lockFile), ...approvedRes }, null, 2) : `${c.green('✔')} approved ${approvedRes.approved || filtered.length} MCP tool(s) in ${rel(cwd, lockFile)}`);
|
|
1160
|
+
} else {
|
|
1161
|
+
const lock = loadMcpLock(cwd);
|
|
1162
|
+
const diffs = [];
|
|
1163
|
+
for (const t of filtered) {
|
|
1164
|
+
const key = t.fullName || `mcp.${t.server}.${t.name}`;
|
|
1165
|
+
const pinned = lock.tools?.[key];
|
|
1166
|
+
if (!pinned) diffs.push({ server: t.server, tool: t.name, key, status: 'new' });
|
|
1167
|
+
else if (pinned.schemaHash !== t.schemaHash || pinned.descHash !== t.descHash) {
|
|
1168
|
+
diffs.push({ server: t.server, tool: t.name, key, status: 'changed', oldHash: pinned.schemaHash, newHash: t.schemaHash });
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
if (a.json) console.log(JSON.stringify({ lockFile: rel(cwd, lockFile), diffs }, null, 2));
|
|
1172
|
+
else if (!diffs.length) console.log(`${c.green('✔')} MCP descriptors match ${rel(cwd, lockFile)}`);
|
|
1173
|
+
else for (const d of diffs) console.log(`${d.status === 'changed' ? c.red('!') : c.yellow('+')} ${d.key} (${d.status})`);
|
|
1174
|
+
if (diffs.some((d) => d.status === 'changed')) process.exitCode = 1;
|
|
1175
|
+
}
|
|
1176
|
+
} finally {
|
|
1177
|
+
await mgr.closeAll();
|
|
1178
|
+
}
|
|
1179
|
+
break;
|
|
1180
|
+
}
|
|
1181
|
+
if (sub !== 'add') { console.log('usage: scroll mcp <add|diff|approve> [name] [--command "cmd" | --url URL] [--args "a b"] [--env "K=${vault:K}"] [--tool "name:tier[:g1|g2]"] [--agent <agent>]'); break; }
|
|
1182
|
+
const name = a._[1]; if (!name) throw new Error('usage: scroll mcp add <name> [--command cmd | --url URL] [--env "K=${vault:K}"] [--tool "name:tier"] [--agent <agent>]');
|
|
1183
|
+
const { mcpAdd } = await import('./installers.js');
|
|
1184
|
+
const res = mcpAdd(name, {
|
|
1185
|
+
command: typeof a.command === 'string' ? a.command : undefined,
|
|
1186
|
+
args: typeof a.args === 'string' ? a.args.split(/\s+/).filter(Boolean) : undefined,
|
|
1187
|
+
url: typeof a.url === 'string' ? a.url : undefined,
|
|
1188
|
+
transport: typeof a.transport === 'string' ? a.transport : undefined,
|
|
1189
|
+
env: parseKv(a.env), tools: parseTools(a.tool),
|
|
1190
|
+
agent: typeof a.agent === 'string' ? a.agent : undefined,
|
|
1191
|
+
});
|
|
1192
|
+
console.log(`${c.green('✔')} mcp ${res.existed ? 'updated' : 'added'} ${c.bold(name)} → ${res.file}`);
|
|
1193
|
+
if (res.vaultRefs.length) console.log(c.dim(` credentials via vault: ${res.vaultRefs.join(', ')} (resolved at load — never written to the file)`));
|
|
1194
|
+
if (res.server.tools) console.log(c.dim(` tools: ${Object.entries(res.server.tools).map(([k, v]) => `${k}=${v.risk || 'read_only'}`).join(', ')}`));
|
|
1195
|
+
break;
|
|
1196
|
+
}
|
|
1197
|
+
case 'skill': {
|
|
1198
|
+
const a = parseArgs(rest);
|
|
1199
|
+
if (a._[0] !== 'add') { const { skillCli } = await import('./skill-cli.js'); await skillCli(a._[0], a); break; }
|
|
1200
|
+
const isNew = a.new !== undefined;
|
|
1201
|
+
const ref = isNew ? (typeof a.new === 'string' ? a.new : a._[1]) : a._[1];
|
|
1202
|
+
if (!ref) throw new Error('usage: scroll skill add <path> [--agent <a>] | scroll skill add --new <name> [--agent <a>]');
|
|
1203
|
+
const { skillAdd } = await import('./installers.js');
|
|
1204
|
+
const res = skillAdd(ref, { new: isNew, force: !!a.force, agent: typeof a.agent === 'string' ? a.agent : undefined });
|
|
1205
|
+
console.log(`${c.green('✔')} skill ${res.scaffolded ? 'scaffolded' : 'added'} ${c.bold(res.name)} → ${res.dir}`);
|
|
1206
|
+
for (const w of res.warnings || []) console.log(c.yellow(` ⚠ ${w}`));
|
|
1207
|
+
if (res.attachedToAgent) console.log(c.dim(` referenced by agent ${res.attachedToAgent} (IDENTITY.skills)`));
|
|
1208
|
+
break;
|
|
1209
|
+
}
|
|
1210
|
+
case 'plugin': {
|
|
1211
|
+
const a = parseArgs(rest);
|
|
1212
|
+
if (a._[0] !== 'add') { console.log('usage: scroll plugin add <path-to-.plugin|dir> [--force]'); break; }
|
|
1213
|
+
const ref = a._[1]; if (!ref) throw new Error('usage: scroll plugin add <path-to-.plugin|dir> [--force]');
|
|
1214
|
+
const { pluginAdd } = await import('./installers.js');
|
|
1215
|
+
const res = pluginAdd(ref, { force: !!a.force });
|
|
1216
|
+
console.log(`${c.green('✔')} plugin ${c.bold(res.name)} installed`);
|
|
1217
|
+
console.log(c.dim(` agents: ${res.installed.agents.join(', ') || 'none'} · skills: ${res.installed.skills.join(', ') || 'none'} · mcp: ${res.installed.mcpServers.join(', ') || 'none'}`));
|
|
1218
|
+
break;
|
|
1219
|
+
}
|
|
1220
|
+
case 'help': case undefined: case '--help': case '-h':
|
|
1221
|
+
console.log(HELP); break;
|
|
1222
|
+
default:
|
|
1223
|
+
throw new Error(`unknown command "${cmd}" — try: scroll help`);
|
|
1224
|
+
}
|
|
1225
|
+
}
|