@omacode/micromanager 0.0.0-stage → 1.0.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/LICENSE +201 -0
- package/README.md +30 -2
- package/THIRD_PARTY.md +100 -0
- package/decider/.python-version +1 -0
- package/decider/README.md +35 -0
- package/decider/decider/__init__.py +1 -0
- package/decider/decider/server.py +327 -0
- package/decider/pyproject.toml +34 -0
- package/decider/uv.lock +1255 -0
- package/dist/agenda.js +51 -0
- package/dist/agents.js +58 -0
- package/dist/artifact/handoff.js +281 -0
- package/dist/ask.js +200 -0
- package/dist/backends.js +219 -0
- package/dist/backlog.js +414 -0
- package/dist/bench.js +427 -0
- package/dist/board.js +1 -0
- package/dist/brief.js +202 -0
- package/dist/browser.js +679 -0
- package/dist/budget.js +61 -0
- package/dist/catalog.js +187 -0
- package/dist/checkchange.js +145 -0
- package/dist/checkpoint.js +94 -0
- package/dist/cli.js +764 -0
- package/dist/comfy-gate.js +258 -0
- package/dist/compact.js +142 -0
- package/dist/config.js +344 -0
- package/dist/context/capture.js +1 -0
- package/dist/context/digest.js +1 -0
- package/dist/context/embed.js +1 -0
- package/dist/context/index.js +2 -0
- package/dist/context/ledger.js +1 -0
- package/dist/context/manager.js +1 -0
- package/dist/context/memory.js +1 -0
- package/dist/context/policy.js +1 -0
- package/dist/context/prices.js +1 -0
- package/dist/context/recall.js +1 -0
- package/dist/context/rules.js +1 -0
- package/dist/context/search.js +1 -0
- package/dist/context/status.js +1 -0
- package/dist/context/store.js +1 -0
- package/dist/context/summary.js +1 -0
- package/dist/context/tokens.js +1 -0
- package/dist/context/tools.js +1 -0
- package/dist/continuation.js +184 -0
- package/dist/contract.js +294 -0
- package/dist/contractround.js +178 -0
- package/dist/control.js +1 -0
- package/dist/creative-tools.js +237 -0
- package/dist/dataset.js +175 -0
- package/dist/decide.js +676 -0
- package/dist/decider.js +171 -0
- package/dist/design-shell.js +448 -0
- package/dist/design.js +1410 -0
- package/dist/desktop.js +44 -0
- package/dist/egress.js +156 -0
- package/dist/eval.js +60 -0
- package/dist/evolver.js +302 -0
- package/dist/features.js +193 -0
- package/dist/followups.js +32 -0
- package/dist/forms.js +195 -0
- package/dist/gate.js +108 -0
- package/dist/gatebox.js +46 -0
- package/dist/grants.js +189 -0
- package/dist/graph.js +65 -0
- package/dist/guard/index.js +1 -0
- package/dist/guard/wire.js +1 -0
- package/dist/helpers.js +85 -0
- package/dist/hooks.js +158 -0
- package/dist/image-models.js +117 -0
- package/dist/integration.js +3 -0
- package/dist/journal.js +1 -0
- package/dist/look.js +363 -0
- package/dist/memory.js +1 -0
- package/dist/mode.js +97 -0
- package/dist/native.js +3348 -0
- package/dist/nogit.js +259 -0
- package/dist/outcomes.js +148 -0
- package/dist/permission.js +35 -0
- package/dist/pick.js +89 -0
- package/dist/pipelines.js +262 -0
- package/dist/plan.js +641 -0
- package/dist/plandoc.js +211 -0
- package/dist/plugin.js +4736 -0
- package/dist/policy.js +58 -0
- package/dist/pools.js +1 -0
- package/dist/preview.js +274 -0
- package/dist/profile.js +165 -0
- package/dist/progress.js +1 -0
- package/dist/promote.js +313 -0
- package/dist/redact.js +1 -0
- package/dist/registry.js +179 -0
- package/dist/riskscore.js +126 -0
- package/dist/roles.js +1 -0
- package/dist/routing.js +1 -0
- package/dist/runner.js +1892 -0
- package/dist/sandbox.js +3 -0
- package/dist/sandboxgate.js +90 -0
- package/dist/scheduler.js +170 -0
- package/dist/services-main.js +131 -0
- package/dist/services.js +265 -0
- package/dist/session.js +241 -0
- package/dist/setup.js +423 -0
- package/dist/shell/decide.js +1 -0
- package/dist/shell/index.js +2 -0
- package/dist/shell/sandbox.js +1 -0
- package/dist/shell/wire.js +1 -0
- package/dist/skills.js +103 -0
- package/dist/state.js +1 -0
- package/dist/store.js +1 -0
- package/dist/switcher.js +1 -0
- package/dist/synth.js +418 -0
- package/dist/tools.js +477 -0
- package/dist/trials.js +223 -0
- package/dist/usage.js +1 -0
- package/dist/wait.js +167 -0
- package/dist/watchdog.js +476 -0
- package/dist/web-guidance.js +43 -0
- package/dist/which.js +20 -0
- package/dist/worktree/git.js +545 -0
- package/dist/writeguard.js +311 -0
- package/evolver/mm_evolve/__init__.py +1 -0
- package/evolver/mm_evolve/entry.py +3 -0
- package/evolver/mm_evolve/evaluator.py +119 -0
- package/evolver/mm_evolve/llm.py +76 -0
- package/evolver/mm_evolve/run.py +89 -0
- package/evolver/mm_evolve/spec.py +62 -0
- package/evolver/pyproject.toml +21 -0
- package/evolver/uv.lock +772 -0
- package/package.json +74 -4
- package/skills/THIRD_PARTY.md +58 -0
- package/skills/code-review/SKILL.md +46 -0
- package/skills/deck/SKILL.md +98 -0
- package/skills/deliberate/SKILL.md +39 -0
- package/skills/design/SKILL.md +150 -0
- package/skills/diagnosing-bugs/SKILL.md +75 -0
- package/skills/image/SKILL.md +66 -0
- package/skills/orchestrator/SKILL.md +107 -0
- package/skills/receiving-code-review/SKILL.md +36 -0
- package/skills/research/SKILL.md +18 -0
- package/skills/tdd/SKILL.md +56 -0
- package/skills/tdd/mocking.md +59 -0
- package/skills/tdd/tests.md +77 -0
- package/skills/verification-before-completion/SKILL.md +50 -0
- package/skills/video/SKILL.md +97 -0
- package/skills/web/SKILL.md +60 -0
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// The ComfyUI MCP server (comfy-mcp, Comfy-Org) under the plugin's eye, in every session: build, plan, the
|
|
2
|
+
// micromanager's workers and the user's own. OpenCode hands each MCP tool call to the permission hook as
|
|
3
|
+
// `comfy_<tool>` with the tool's input in `metadata.input` (spike, opencode 2.2.5, 2026-11-23), so the hook can read the
|
|
4
|
+
// workflow before it runs:
|
|
5
|
+
//
|
|
6
|
+
// - Tools that would spend money, sign in to Comfy Cloud, download or install, or start and stop ComfyUI (which
|
|
7
|
+
// omacode-services does) are denied, with the reason.
|
|
8
|
+
// - OpenCode's plan agent may not generate at all: generating is acting, plan is not.
|
|
9
|
+
// - A run (run_workflow, generate_image, run_template) is checked against the model registry (@omacode/core
|
|
10
|
+
// models) by the sha256 of every model file the workflow names. All known and permitted for the territory: it
|
|
11
|
+
// runs. Anything else (an unknown hash, a licence that does not permit the territory, a blocked model, a template
|
|
12
|
+
// whose models cannot be read before it runs) is put to the user as a permission question that says what is missing,
|
|
13
|
+
// instead of a refusal. An approved run registers its unknown models as approved by the user, licence unverified, so
|
|
14
|
+
// the same file is not asked about again; a blocked model is never registered.
|
|
15
|
+
//
|
|
16
|
+
// Every run is journalled with the models it loaded, their hashes and licences, and who allowed it.
|
|
17
|
+
import { createHash } from "node:crypto";
|
|
18
|
+
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
|
|
19
|
+
import { basename, dirname, join } from "node:path";
|
|
20
|
+
import { DEFAULT_TERRITORY, readModelRegistry, registerModel, registryWith, resolveModel, MODEL_REGISTRY } from "@omacode/core/models";
|
|
21
|
+
import { userStateDir } from "@omacode/core/paths";
|
|
22
|
+
export const COMFY_PREFIX = "comfy_";
|
|
23
|
+
export const RUN_TOOLS = new Set(["comfy_run_workflow", "comfy_generate_image", "comfy_run_template"]);
|
|
24
|
+
// What the plugin never lets through comfy-mcp, by tool, with the reason the model reads.
|
|
25
|
+
export const DENIED = {
|
|
26
|
+
comfy_partner_generate: "paid partner models (Comfy credits) are off; run a local workflow instead",
|
|
27
|
+
comfy_emit_partner_workflow: "paid partner models (Comfy credits) are off",
|
|
28
|
+
comfy_list_partner_models: "paid partner models (Comfy credits) are off",
|
|
29
|
+
comfy_partner_model_schema: "paid partner models (Comfy credits) are off",
|
|
30
|
+
comfy_auth_login: "no Comfy Cloud sign-in from an agent",
|
|
31
|
+
comfy_launch_comfyui: "omacode-services starts ComfyUI on the first request; just run the workflow",
|
|
32
|
+
comfy_stop_comfyui: "omacode-services stops ComfyUI after its idle time; /services switches it",
|
|
33
|
+
comfy_restart_comfyui: "omacode-services runs ComfyUI; ask the user to switch it in /services",
|
|
34
|
+
comfy_update_comfyui: "ComfyUI is pinned by the installer; the user updates it",
|
|
35
|
+
comfy_switch_comfyui_version: "ComfyUI is pinned by the installer; the user changes it",
|
|
36
|
+
comfy_install_node: "custom nodes are installed by the user, not by an agent",
|
|
37
|
+
comfy_download_model: "models are downloaded by the user, with their licence read first",
|
|
38
|
+
comfy_download: "models are downloaded by the user, with their licence read first",
|
|
39
|
+
};
|
|
40
|
+
const MODEL_FILE = /\.(safetensors|gguf|ckpt|pt|pth|bin|sft)$/i;
|
|
41
|
+
// Every model file a workflow names: a string value ending in a model file's extension, anywhere in the graph. Works for
|
|
42
|
+
// both of ComfyUI's formats (API: inputs.ckpt_name; UI export: widgets_values), and for custom loaders, because the
|
|
43
|
+
// file name is what a loader takes whatever its input is called.
|
|
44
|
+
export function modelNames(value, out = new Set()) {
|
|
45
|
+
if (typeof value === "string") {
|
|
46
|
+
if (MODEL_FILE.test(value.trim()))
|
|
47
|
+
out.add(value.trim());
|
|
48
|
+
}
|
|
49
|
+
else if (Array.isArray(value)) {
|
|
50
|
+
for (const v of value)
|
|
51
|
+
modelNames(v, out);
|
|
52
|
+
}
|
|
53
|
+
else if (value && typeof value === "object") {
|
|
54
|
+
for (const v of Object.values(value))
|
|
55
|
+
modelNames(v, out);
|
|
56
|
+
}
|
|
57
|
+
return [...out];
|
|
58
|
+
}
|
|
59
|
+
// ComfyUI's default text-to-image template (comfy-mcp generate_image without a checkpoint).
|
|
60
|
+
export const DEFAULT_TEMPLATE_CHECKPOINT = "v1-5-pruned-emaonly-fp16.safetensors";
|
|
61
|
+
// The model files a run tool's input names.
|
|
62
|
+
export function namedModels(tool, input) {
|
|
63
|
+
if (tool === "comfy_run_workflow") {
|
|
64
|
+
const path = typeof input.workflow_path === "string" ? input.workflow_path : "";
|
|
65
|
+
try {
|
|
66
|
+
return { models: modelNames(JSON.parse(readFileSync(path, "utf8"))) };
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return { models: [], unread: `the workflow ${path || "(no path)"} could not be read` };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (tool === "comfy_generate_image") {
|
|
73
|
+
const ckpt = typeof input.checkpoint === "string" && input.checkpoint.trim() ? input.checkpoint.trim() : DEFAULT_TEMPLATE_CHECKPOINT;
|
|
74
|
+
return { models: [ckpt] };
|
|
75
|
+
}
|
|
76
|
+
const named = modelNames(input.params);
|
|
77
|
+
return { models: named, unread: `the template ${String(input.name ?? "")} names its own models, which are not read before it runs` };
|
|
78
|
+
}
|
|
79
|
+
// Where ComfyUI finds a model by its file name: <workspace>/models/<kind>/ and the folders extra_model_paths.yaml adds.
|
|
80
|
+
export function modelRoots(workspace) {
|
|
81
|
+
const roots = [join(workspace, "models")];
|
|
82
|
+
try {
|
|
83
|
+
const yaml = readFileSync(join(workspace, "extra_model_paths.yaml"), "utf8");
|
|
84
|
+
let base = "";
|
|
85
|
+
for (const line of yaml.split("\n")) {
|
|
86
|
+
const m = /^\s+([a-z_]+):\s*(.+?)\s*$/.exec(line);
|
|
87
|
+
if (!m)
|
|
88
|
+
continue;
|
|
89
|
+
if (m[1] === "base_path")
|
|
90
|
+
base = m[2];
|
|
91
|
+
else if (base)
|
|
92
|
+
roots.push(join(base, m[2]));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
// no extra paths
|
|
97
|
+
}
|
|
98
|
+
return roots;
|
|
99
|
+
}
|
|
100
|
+
export function findModel(name, roots) {
|
|
101
|
+
for (const root of roots) {
|
|
102
|
+
const direct = join(root, name);
|
|
103
|
+
if (existsSync(direct) && statSync(direct).isFile())
|
|
104
|
+
return direct;
|
|
105
|
+
// models/<kind>/<name>: the kind folders sit one level under models/
|
|
106
|
+
let kinds = [];
|
|
107
|
+
try {
|
|
108
|
+
kinds = readdirSync(root);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
for (const kind of kinds) {
|
|
114
|
+
const file = join(root, kind, name);
|
|
115
|
+
try {
|
|
116
|
+
if (statSync(file).isFile())
|
|
117
|
+
return file;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
// not in this kind
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
// sha256 of a model file, cached by path, size and mtime: a GGUF of several GB takes seconds to hash, once.
|
|
127
|
+
export async function hashFile(file, cacheFile = join(userStateDir(), "model-hashes.json")) {
|
|
128
|
+
const st = statSync(file);
|
|
129
|
+
const key = `${file}|${st.size}|${st.mtimeMs}`;
|
|
130
|
+
let cache = {};
|
|
131
|
+
try {
|
|
132
|
+
cache = JSON.parse(readFileSync(cacheFile, "utf8"));
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
cache = {};
|
|
136
|
+
}
|
|
137
|
+
if (cache[key])
|
|
138
|
+
return cache[key];
|
|
139
|
+
const hash = createHash("sha256");
|
|
140
|
+
await new Promise((done, fail) => {
|
|
141
|
+
createReadStream(file).on("data", (c) => hash.update(c)).on("end", () => done()).on("error", fail);
|
|
142
|
+
});
|
|
143
|
+
const digest = hash.digest("hex");
|
|
144
|
+
cache[key] = digest;
|
|
145
|
+
mkdirSync(dirname(cacheFile), { recursive: true });
|
|
146
|
+
writeFileSync(cacheFile, JSON.stringify(cache, null, 1) + "\n");
|
|
147
|
+
return digest;
|
|
148
|
+
}
|
|
149
|
+
export async function checkRun(tool, input, o) {
|
|
150
|
+
const named = namedModels(tool, input);
|
|
151
|
+
const roots = modelRoots(o.workspace);
|
|
152
|
+
const own = readModelRegistry(o.registryDir !== undefined ? { dir: o.registryDir } : {});
|
|
153
|
+
const registry = registryWith(own.entries, MODEL_REGISTRY);
|
|
154
|
+
const models = [];
|
|
155
|
+
for (const name of named.models) {
|
|
156
|
+
const file = findModel(name, roots);
|
|
157
|
+
const hash = file ? await hashFile(file, o.cacheFile).catch(() => undefined) : undefined;
|
|
158
|
+
const verdict = resolveModel({ declared: name, ...(hash ? { hash } : {}), territory: DEFAULT_TERRITORY }, registry);
|
|
159
|
+
models.push({ name, ...(file ? { file } : {}), ...(hash ? { hash } : {}), verdict });
|
|
160
|
+
}
|
|
161
|
+
const clear = !named.unread && models.every((m) => m.verdict.status === "allowed");
|
|
162
|
+
return { models, ...(named.unread ? { unread: named.unread } : {}), clear };
|
|
163
|
+
}
|
|
164
|
+
// The lines the user reads in the permission question: one per model that is not cleared, and what could not be read.
|
|
165
|
+
export function questionLines(check) {
|
|
166
|
+
const lines = [];
|
|
167
|
+
for (const m of check.models) {
|
|
168
|
+
if ((m.verdict.status === "allowed"))
|
|
169
|
+
continue;
|
|
170
|
+
const short = m.hash ? ` (sha256 ${m.hash.slice(0, 10)}…)` : m.file ? "" : " (file not found in ComfyUI's model folders)";
|
|
171
|
+
const why = m.verdict.status === "blocked" ? `BLOCKED: ${m.verdict.reason}` : m.verdict.status === "territory" ? `licence does not permit ${DEFAULT_TERRITORY}: ${m.verdict.reason}` : "no licence or territory registered";
|
|
172
|
+
lines.push(`${m.name}${short}: ${why}`);
|
|
173
|
+
}
|
|
174
|
+
if (check.unread)
|
|
175
|
+
lines.push(`${check.unread}: licence not checked`);
|
|
176
|
+
return lines;
|
|
177
|
+
}
|
|
178
|
+
// After a run the user approved: its unknown models become "approved by the user, licence unverified". A blocked model
|
|
179
|
+
// or one without a hash is not registered; the journal still says it ran.
|
|
180
|
+
export function registerApproved(check, o = {}) {
|
|
181
|
+
const done = [];
|
|
182
|
+
const day = (o.when ?? new Date()).toISOString().slice(0, 10);
|
|
183
|
+
for (const m of check.models) {
|
|
184
|
+
if (m.verdict.status !== "unknown" || !m.hash)
|
|
185
|
+
continue;
|
|
186
|
+
try {
|
|
187
|
+
registerModel({ hash: m.hash, name: m.name, license: "LicenseRef-unverified-user-approved", territory: DEFAULT_TERRITORY, use: `approved by the user in OpenCode on ${day}; the licence was not checked` }, o.registryDir !== undefined ? { dir: o.registryDir } : {});
|
|
188
|
+
done.push(m.name);
|
|
189
|
+
}
|
|
190
|
+
catch {
|
|
191
|
+
// blocked by name, or the registry file is broken: left to the user
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return done;
|
|
195
|
+
}
|
|
196
|
+
// A paid partner node in a local workflow: comfy-mcp unlocks it with confirm_spend.
|
|
197
|
+
export const spends = (input) => input.confirm_spend === true;
|
|
198
|
+
// ---------------------------------------------------------------------------------------------------------------------
|
|
199
|
+
// OpenCode's own image tool: a cloud image model of a connected provider, no registry, possibly paid. ComfyUI comes
|
|
200
|
+
// first; the cloud tool is the fallback when ComfyUI cannot run here or failed in this session.
|
|
201
|
+
export const CLOUD_IMAGE_TOOL = "experimental_image_generate";
|
|
202
|
+
export const PREFER_COMFY = "ComfyUI runs locally here and comes first: call image_models to pick a model, then the comfy MCP tools (tools.comfy.run_workflow with a workflow for that model, or tools.comfy.run_template; search the catalog for comfy if they are not listed). This cloud tool is the fallback when ComfyUI fails";
|
|
203
|
+
// Whether ComfyUI can take an image request in this session; when not, why (said in the journal).
|
|
204
|
+
export function comfyAvailable(s) {
|
|
205
|
+
if (!s.mcp)
|
|
206
|
+
return { ok: false, why: "no comfy MCP server is configured" };
|
|
207
|
+
if (!s.service)
|
|
208
|
+
return { ok: false, why: "omacode-services runs no ComfyUI" };
|
|
209
|
+
if (s.service.mode === "off")
|
|
210
|
+
return { ok: false, why: "ComfyUI is switched off in /services" };
|
|
211
|
+
if (s.service.state === "failed")
|
|
212
|
+
return { ok: false, why: "ComfyUI failed to start" };
|
|
213
|
+
return { ok: true };
|
|
214
|
+
}
|
|
215
|
+
// An enabled `comfy` server in OpenCode's config (mcp.servers.comfy, or the older mcp.comfy).
|
|
216
|
+
export function comfyMcpConfigured(config) {
|
|
217
|
+
const mcp = config?.mcp;
|
|
218
|
+
const servers = (mcp?.servers ?? mcp);
|
|
219
|
+
const comfy = servers?.comfy;
|
|
220
|
+
return Boolean(comfy) && comfy.disabled !== true && comfy.enabled !== false;
|
|
221
|
+
}
|
|
222
|
+
// A run the user turned down is not a failure to fall back from: the cloud must not undo the user's no.
|
|
223
|
+
export function isRejection(error) {
|
|
224
|
+
return /reject|denied|not allowed|permission/i.test(String(error?.message ?? error ?? ""));
|
|
225
|
+
}
|
|
226
|
+
export function modelFiles(workspace) {
|
|
227
|
+
const found = new Map();
|
|
228
|
+
for (const root of modelRoots(workspace)) {
|
|
229
|
+
const walk = (dir, kind, depth) => {
|
|
230
|
+
let names = [];
|
|
231
|
+
try {
|
|
232
|
+
names = readdirSync(dir);
|
|
233
|
+
}
|
|
234
|
+
catch {
|
|
235
|
+
return;
|
|
236
|
+
}
|
|
237
|
+
for (const n of names) {
|
|
238
|
+
const p = join(dir, n);
|
|
239
|
+
let st;
|
|
240
|
+
try {
|
|
241
|
+
st = statSync(p);
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (st.isDirectory() && depth < 2)
|
|
247
|
+
walk(p, depth === 0 ? n : kind, depth + 1);
|
|
248
|
+
else if (st.isFile() && MODEL_FILE.test(n) && st.size > 1_000_000) {
|
|
249
|
+
const real = realpathSync(p);
|
|
250
|
+
if (!found.has(real))
|
|
251
|
+
found.set(real, { file: real, name: n, kind: kind || basename(root) });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
walk(root, "", 0);
|
|
256
|
+
}
|
|
257
|
+
return [...found.values()].sort((a, b) => a.name.localeCompare(b.name));
|
|
258
|
+
}
|
package/dist/compact.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Decider compaction of the micromanager's context (the user's request after reading about decision-model token savings, 2026-10-05).
|
|
2
|
+
// The orchestrator is the biggest consumer: in a real session it carried 360k input tokens, its workers 10-40k each,
|
|
3
|
+
// because every turn resends every old tool result (task reports, reads, refused attempts).
|
|
4
|
+
//
|
|
5
|
+
// Before each of its turns, old and large tool results become candidates; the decider answers per candidate whether the
|
|
6
|
+
// micromanager still needs it; the ones it does not are replaced by a one-line stub that says how to get them back. The
|
|
7
|
+
// context hook's messages are what the provider gets (Phase E spike: a replaced tool result never reached the model),
|
|
8
|
+
// and the hook is awaited, so the decider can answer in time.
|
|
9
|
+
//
|
|
10
|
+
// A decision sticks: a pruned result stays pruned in every later turn, so the history's prefix does not change back
|
|
11
|
+
// and forth (prompt caches). A kept one is asked again only after it has aged.
|
|
12
|
+
import { NOUL_FLOOR } from "./catalog.js";
|
|
13
|
+
export const DEFAULT_COMPACT = { keepTurns: 2, minChars: 800, startChars: 20_000, reaskAge: 6, ruleAge: 8 };
|
|
14
|
+
const valueOf = (p) => (typeof p.result?.value === "string" ? p.result.value : p.result?.value === undefined ? "" : JSON.stringify(p.result.value));
|
|
15
|
+
export function stub(c) {
|
|
16
|
+
return `[micromanager: this earlier ${c.tool} result (${c.size} characters; ${c.input.slice(0, 120)}) was dropped from your context, as it is no longer needed; call the tool again if you need it]`;
|
|
17
|
+
}
|
|
18
|
+
// Old, large tool results, with their call's input and their age in assistant turns.
|
|
19
|
+
export function candidates(messages, o = DEFAULT_COMPACT) {
|
|
20
|
+
const inputs = new Map();
|
|
21
|
+
const out = [];
|
|
22
|
+
let assistantTurns = 0;
|
|
23
|
+
let activeFrom = 0; // assistant turns when the last user message came in: results after it belong to the open turn
|
|
24
|
+
const seen = [];
|
|
25
|
+
for (const m of messages) {
|
|
26
|
+
if (m.role === "user")
|
|
27
|
+
activeFrom = assistantTurns;
|
|
28
|
+
if (!Array.isArray(m.content))
|
|
29
|
+
continue;
|
|
30
|
+
if (m.role === "assistant") {
|
|
31
|
+
assistantTurns++;
|
|
32
|
+
// The input is kept raw here: serialising it only for actual candidates avoids re-stringifying every call.
|
|
33
|
+
for (const p of m.content)
|
|
34
|
+
if (p.type === "tool-call" && p.id)
|
|
35
|
+
inputs.set(p.id, p.input);
|
|
36
|
+
}
|
|
37
|
+
if (m.role === "tool")
|
|
38
|
+
for (const p of m.content)
|
|
39
|
+
if (p.type === "tool-result" && p.id)
|
|
40
|
+
seen.push({ part: p, at: assistantTurns });
|
|
41
|
+
}
|
|
42
|
+
for (const { part, at } of seen) {
|
|
43
|
+
const text = valueOf(part);
|
|
44
|
+
const age = assistantTurns - at;
|
|
45
|
+
// A prompt investigated in several sequential call batches has no answer yet: with activeTurnKeep its turn's
|
|
46
|
+
// results stay in the context until that floor is passed, so the open turn cannot starve its own investigation.
|
|
47
|
+
const keep = at > activeFrom ? Math.max(o.keepTurns, o.activeTurnKeep ?? 0) : o.keepTurns;
|
|
48
|
+
if (age < keep || text.length < o.minChars || text.startsWith("[micromanager: this earlier") || text.startsWith("[context: "))
|
|
49
|
+
continue;
|
|
50
|
+
if (o.tools && !o.tools.has(part.name ?? ""))
|
|
51
|
+
continue;
|
|
52
|
+
const raw = inputs.get(part.id);
|
|
53
|
+
out.push({ id: part.id, tool: part.name ?? "tool", input: raw === undefined ? "" : JSON.stringify(raw ?? {}), size: text.length, age, head: text.slice(0, 400) });
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
// Replaces the results of the given calls in place; returns the characters removed.
|
|
58
|
+
export function prune(messages, drop) {
|
|
59
|
+
let removed = 0;
|
|
60
|
+
for (const m of messages) {
|
|
61
|
+
if (m.role !== "tool" || !Array.isArray(m.content))
|
|
62
|
+
continue;
|
|
63
|
+
for (const p of m.content) {
|
|
64
|
+
const c = p.type === "tool-result" && p.id ? drop.get(p.id) : undefined;
|
|
65
|
+
if (!c || !p.result)
|
|
66
|
+
continue;
|
|
67
|
+
const text = stub(c);
|
|
68
|
+
if (p.result.value === text)
|
|
69
|
+
continue; // pruned in place before (the same array seen again): it leaves once
|
|
70
|
+
// The string's length needs no re-serialisation; only a non-string value is measured through valueOf once.
|
|
71
|
+
const before = typeof p.result.value === "string" ? p.result.value.length : valueOf(p).length;
|
|
72
|
+
p.result = { type: "text", value: text };
|
|
73
|
+
removed += before - text.length;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return removed;
|
|
77
|
+
}
|
|
78
|
+
export function compactQuestions(cands, subject = "orchestrator") {
|
|
79
|
+
return Object.fromEntries(cands.map((c, i) => [`needed.${i}`, {
|
|
80
|
+
type: "noul",
|
|
81
|
+
instructions: `The ${subject} still needs the result of call ${i} (${c.tool}, ${c.input.slice(0, 160)}) to finish ${subject === "orchestrator" ? "the user's request" : "its task"}: it is not yet acted on, and no later result replaces it.`,
|
|
82
|
+
}]));
|
|
83
|
+
}
|
|
84
|
+
// The last user request and the orchestrator's last words: what "still needed" is judged against.
|
|
85
|
+
function focus(messages) {
|
|
86
|
+
const text = (m) => (typeof m.content === "string" ? m.content : (m.content ?? []).filter((p) => p.type === "text").map((p) => p.text ?? "").join(" "));
|
|
87
|
+
const users = messages.filter((m) => m.role === "user");
|
|
88
|
+
const assistants = messages.filter((m) => m.role === "assistant").map(text).filter(Boolean);
|
|
89
|
+
return { request: text(users.at(-1) ?? {}).slice(0, 2000), latest: (assistants.at(-1) ?? "").slice(0, 1500) };
|
|
90
|
+
}
|
|
91
|
+
export class Compactor {
|
|
92
|
+
#decider;
|
|
93
|
+
#o;
|
|
94
|
+
#journal;
|
|
95
|
+
#pruned = new Map(); // session -> call id -> what was dropped
|
|
96
|
+
#kept = new Map(); // session -> call id -> its age when kept
|
|
97
|
+
constructor(decider, journal, options = {}) {
|
|
98
|
+
this.#decider = decider;
|
|
99
|
+
this.#journal = journal;
|
|
100
|
+
this.#o = { ...DEFAULT_COMPACT, ...options };
|
|
101
|
+
}
|
|
102
|
+
// One turn of the micromanager: decides on new candidates when it is worth it, then prunes everything decided so far.
|
|
103
|
+
async apply(sessionID, messages) {
|
|
104
|
+
if (!Array.isArray(messages))
|
|
105
|
+
return { removed: 0, asked: 0 };
|
|
106
|
+
const { asked, pruned } = await this.judge(sessionID, messages);
|
|
107
|
+
const removed = prune(messages, pruned);
|
|
108
|
+
if (asked)
|
|
109
|
+
this.#journal({ kind: "compaction", sessionID, asked, pruned: pruned.size, removedChars: removed });
|
|
110
|
+
return { removed, asked };
|
|
111
|
+
}
|
|
112
|
+
// Decides on new candidates when it is worth it and returns everything dropped so far, without touching the
|
|
113
|
+
// messages: the context manager applies it at its next epoch (src/context/manager.ts).
|
|
114
|
+
async judge(sessionID, messages) {
|
|
115
|
+
if (!Array.isArray(messages))
|
|
116
|
+
return { asked: 0, pruned: new Map() };
|
|
117
|
+
const msgs = messages;
|
|
118
|
+
const pruned = this.#pruned.get(sessionID) ?? new Map();
|
|
119
|
+
const kept = this.#kept.get(sessionID) ?? new Map();
|
|
120
|
+
this.#pruned.set(sessionID, pruned);
|
|
121
|
+
this.#kept.set(sessionID, kept);
|
|
122
|
+
const cands = candidates(msgs, this.#o).filter((c) => !pruned.has(c.id));
|
|
123
|
+
const open = cands.filter((c) => !kept.has(c.id) || c.age - kept.get(c.id) >= this.#o.reaskAge);
|
|
124
|
+
const load = cands.reduce((n, c) => n + c.size, 0);
|
|
125
|
+
let asked = 0;
|
|
126
|
+
if (open.length && load >= this.#o.startChars) {
|
|
127
|
+
const answers = this.#decider
|
|
128
|
+
? (await this.#decider.ask("N14", { ...focus(msgs), results: open.map((c, i) => ({ call: i, tool: c.tool, input: c.input.slice(0, 300), age: c.age, start: c.head })) }, compactQuestions(open, this.#o.subject), { job: sessionID, session: sessionID }).catch(() => undefined))?.decision.answers ?? {}
|
|
129
|
+
: {};
|
|
130
|
+
asked = open.length;
|
|
131
|
+
open.forEach((c, i) => {
|
|
132
|
+
const a = answers[`needed.${i}`];
|
|
133
|
+
const needed = a?.type === "noul" ? a.noul >= NOUL_FLOOR : c.age < this.#o.ruleAge;
|
|
134
|
+
if (needed)
|
|
135
|
+
kept.set(c.id, c.age);
|
|
136
|
+
else
|
|
137
|
+
pruned.set(c.id, c);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
return { asked, pruned };
|
|
141
|
+
}
|
|
142
|
+
}
|