@omacode/micromanager 0.1.1 → 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.
Files changed (213) hide show
  1. package/README.md +7 -4
  2. package/THIRD_PARTY.md +100 -0
  3. package/decider/.python-version +1 -0
  4. package/decider/README.md +35 -0
  5. package/decider/decider/__init__.py +1 -0
  6. package/decider/decider/server.py +327 -0
  7. package/decider/pyproject.toml +34 -0
  8. package/decider/uv.lock +1255 -0
  9. package/dist/agenda.js +51 -0
  10. package/dist/agents.js +58 -0
  11. package/dist/artifact/handoff.js +281 -0
  12. package/dist/ask.js +200 -0
  13. package/dist/backends.js +219 -0
  14. package/dist/backlog.js +414 -0
  15. package/dist/bench.js +427 -0
  16. package/dist/board.js +1 -0
  17. package/dist/brief.js +202 -0
  18. package/dist/browser.js +679 -0
  19. package/dist/budget.js +61 -0
  20. package/dist/catalog.js +187 -0
  21. package/dist/checkchange.js +145 -0
  22. package/dist/checkpoint.js +94 -0
  23. package/dist/cli.js +764 -0
  24. package/dist/comfy-gate.js +258 -0
  25. package/dist/compact.js +142 -0
  26. package/dist/config.js +344 -0
  27. package/dist/context/capture.js +1 -0
  28. package/dist/context/digest.js +1 -0
  29. package/dist/context/embed.js +1 -0
  30. package/dist/context/index.js +2 -0
  31. package/dist/context/ledger.js +1 -0
  32. package/dist/context/manager.js +1 -0
  33. package/dist/context/memory.js +1 -0
  34. package/dist/context/policy.js +1 -0
  35. package/dist/context/prices.js +1 -0
  36. package/dist/context/recall.js +1 -0
  37. package/dist/context/rules.js +1 -0
  38. package/dist/context/search.js +1 -0
  39. package/dist/context/status.js +1 -0
  40. package/dist/context/store.js +1 -0
  41. package/dist/context/summary.js +1 -0
  42. package/dist/context/tokens.js +1 -0
  43. package/dist/context/tools.js +1 -0
  44. package/dist/continuation.js +184 -0
  45. package/dist/contract.js +294 -0
  46. package/dist/contractround.js +178 -0
  47. package/dist/control.js +1 -0
  48. package/dist/creative-tools.js +237 -0
  49. package/dist/dataset.js +175 -0
  50. package/dist/decide.js +676 -0
  51. package/dist/decider.js +171 -0
  52. package/dist/design-shell.js +448 -0
  53. package/dist/design.js +1410 -0
  54. package/dist/desktop.js +44 -0
  55. package/dist/egress.js +156 -0
  56. package/dist/eval.js +60 -0
  57. package/dist/evolver.js +302 -0
  58. package/dist/features.js +193 -0
  59. package/dist/followups.js +32 -0
  60. package/dist/forms.js +195 -0
  61. package/dist/gate.js +108 -0
  62. package/dist/gatebox.js +46 -0
  63. package/dist/grants.js +189 -0
  64. package/dist/graph.js +65 -0
  65. package/dist/guard/index.js +1 -0
  66. package/dist/guard/wire.js +1 -0
  67. package/dist/helpers.js +85 -0
  68. package/dist/hooks.js +158 -0
  69. package/dist/image-models.js +117 -0
  70. package/{src/integration.ts → dist/integration.js} +1 -2
  71. package/dist/journal.js +1 -0
  72. package/dist/look.js +363 -0
  73. package/dist/memory.js +1 -0
  74. package/dist/mode.js +97 -0
  75. package/dist/native.js +3348 -0
  76. package/dist/nogit.js +259 -0
  77. package/dist/outcomes.js +148 -0
  78. package/dist/permission.js +35 -0
  79. package/dist/pick.js +89 -0
  80. package/dist/pipelines.js +262 -0
  81. package/dist/plan.js +641 -0
  82. package/dist/plandoc.js +211 -0
  83. package/dist/plugin.js +4736 -0
  84. package/dist/policy.js +58 -0
  85. package/dist/pools.js +1 -0
  86. package/dist/preview.js +274 -0
  87. package/dist/profile.js +165 -0
  88. package/dist/progress.js +1 -0
  89. package/dist/promote.js +313 -0
  90. package/dist/redact.js +1 -0
  91. package/dist/registry.js +179 -0
  92. package/dist/riskscore.js +126 -0
  93. package/dist/roles.js +1 -0
  94. package/dist/routing.js +1 -0
  95. package/dist/runner.js +1892 -0
  96. package/{src/sandbox.ts → dist/sandbox.js} +1 -2
  97. package/dist/sandboxgate.js +90 -0
  98. package/dist/scheduler.js +170 -0
  99. package/dist/services-main.js +131 -0
  100. package/dist/services.js +265 -0
  101. package/dist/session.js +241 -0
  102. package/dist/setup.js +423 -0
  103. package/dist/shell/decide.js +1 -0
  104. package/dist/shell/index.js +2 -0
  105. package/dist/shell/sandbox.js +1 -0
  106. package/dist/shell/wire.js +1 -0
  107. package/dist/skills.js +103 -0
  108. package/dist/state.js +1 -0
  109. package/dist/store.js +1 -0
  110. package/dist/switcher.js +1 -0
  111. package/dist/synth.js +418 -0
  112. package/dist/tools.js +477 -0
  113. package/dist/trials.js +223 -0
  114. package/dist/usage.js +1 -0
  115. package/dist/wait.js +167 -0
  116. package/dist/watchdog.js +476 -0
  117. package/dist/web-guidance.js +43 -0
  118. package/dist/which.js +20 -0
  119. package/dist/worktree/git.js +545 -0
  120. package/dist/writeguard.js +311 -0
  121. package/package.json +36 -17
  122. package/skills/deck/SKILL.md +98 -0
  123. package/skills/design/SKILL.md +150 -0
  124. package/skills/image/SKILL.md +66 -0
  125. package/skills/orchestrator/SKILL.md +107 -0
  126. package/skills/video/SKILL.md +97 -0
  127. package/skills/web/SKILL.md +60 -0
  128. package/src/agenda.ts +0 -56
  129. package/src/agents.ts +0 -74
  130. package/src/ask.ts +0 -243
  131. package/src/backends.ts +0 -144
  132. package/src/backlog.ts +0 -436
  133. package/src/bench.ts +0 -163
  134. package/src/board.ts +0 -1
  135. package/src/brief.ts +0 -151
  136. package/src/browser.ts +0 -624
  137. package/src/budget.ts +0 -73
  138. package/src/catalog.ts +0 -214
  139. package/src/checkchange.ts +0 -180
  140. package/src/checkpoint.ts +0 -99
  141. package/src/cli.ts +0 -117
  142. package/src/compact.ts +0 -162
  143. package/src/config.ts +0 -340
  144. package/src/context/capture.ts +0 -1
  145. package/src/context/digest.ts +0 -1
  146. package/src/context/embed.ts +0 -1
  147. package/src/context/index.ts +0 -2
  148. package/src/context/ledger.ts +0 -1
  149. package/src/context/manager.ts +0 -1
  150. package/src/context/memory.ts +0 -1
  151. package/src/context/policy.ts +0 -1
  152. package/src/context/prices.ts +0 -1
  153. package/src/context/recall.ts +0 -1
  154. package/src/context/rules.ts +0 -1
  155. package/src/context/search.ts +0 -1
  156. package/src/context/status.ts +0 -1
  157. package/src/context/store.ts +0 -1
  158. package/src/context/summary.ts +0 -1
  159. package/src/context/tokens.ts +0 -1
  160. package/src/context/tools.ts +0 -1
  161. package/src/continuation.ts +0 -122
  162. package/src/contract.ts +0 -342
  163. package/src/contractround.ts +0 -225
  164. package/src/control.ts +0 -1
  165. package/src/dataset.ts +0 -133
  166. package/src/decide.ts +0 -690
  167. package/src/eval.ts +0 -66
  168. package/src/evolver.ts +0 -369
  169. package/src/followups.ts +0 -50
  170. package/src/forms.ts +0 -191
  171. package/src/gate.ts +0 -90
  172. package/src/grants.ts +0 -239
  173. package/src/graph.ts +0 -74
  174. package/src/guard/index.ts +0 -1
  175. package/src/guard/wire.ts +0 -1
  176. package/src/helpers.ts +0 -105
  177. package/src/hooks.ts +0 -199
  178. package/src/jev.ts +0 -141
  179. package/src/journal.ts +0 -1
  180. package/src/look.ts +0 -390
  181. package/src/memory.ts +0 -1
  182. package/src/native.ts +0 -2455
  183. package/src/nogit.ts +0 -112
  184. package/src/outcomes.ts +0 -210
  185. package/src/pick.ts +0 -112
  186. package/src/pipelines.ts +0 -252
  187. package/src/plan.ts +0 -449
  188. package/src/plugin.ts +0 -3187
  189. package/src/policy.ts +0 -84
  190. package/src/pools.ts +0 -1
  191. package/src/profile.ts +0 -186
  192. package/src/progress.ts +0 -1
  193. package/src/redact.ts +0 -1
  194. package/src/registry.ts +0 -207
  195. package/src/roles.ts +0 -1
  196. package/src/routing.ts +0 -1
  197. package/src/runner.ts +0 -1506
  198. package/src/scheduler.ts +0 -200
  199. package/src/session.ts +0 -269
  200. package/src/shell/decide.ts +0 -1
  201. package/src/shell/index.ts +0 -2
  202. package/src/shell/sandbox.ts +0 -1
  203. package/src/shell/wire.ts +0 -1
  204. package/src/skills.ts +0 -111
  205. package/src/state.ts +0 -1
  206. package/src/store.ts +0 -1
  207. package/src/switcher.ts +0 -1
  208. package/src/tools.ts +0 -480
  209. package/src/trials.ts +0 -247
  210. package/src/usage.ts +0 -1
  211. package/src/wait.ts +0 -180
  212. package/src/watchdog.ts +0 -498
  213. package/src/worktree/git.ts +0 -378
package/dist/agenda.js ADDED
@@ -0,0 +1,51 @@
1
+ // The agenda: what could happen next, built from the job state alone (design.md §8). The decision model picks
2
+ // among these proposals; without it, or below its floor, the first one wins (the tutor's Agenda.next).
3
+ import { allDone, DEFAULT_PRIORITY, readyTasks } from "./state.js";
4
+ // Order is priority: unblock work first, then finish what is running, then start new work.
5
+ // A stalled job replans before it starts more work on the plan that stalled.
6
+ const ORDER = ["answer_blocked", "fix", "gate", "review", "replan", "dispatch", "verify", "ask_user", "wrap"];
7
+ // Ready tasks: priority first, then in-progress parent, then fewer dependencies, then id (Task Master's order).
8
+ export function orderReady(job, tasks) {
9
+ const active = new Set(job.tasks.filter((t) => t.status === "running" || t.status === "passed").map((t) => t.parent).filter(Boolean));
10
+ return [...tasks].sort((a, b) => (a.priority ?? DEFAULT_PRIORITY) - (b.priority ?? DEFAULT_PRIORITY) ||
11
+ Number(active.has(b.parent)) - Number(active.has(a.parent)) ||
12
+ a.dependsOn.length - b.dependsOn.length ||
13
+ a.id.localeCompare(b.id, undefined, { numeric: true }));
14
+ }
15
+ export function buildAgenda(job, stallLimit = 3) {
16
+ if (job.phase !== "execute")
17
+ return [];
18
+ const out = [];
19
+ for (const t of job.tasks) {
20
+ if (t.status === "blocked")
21
+ out.push({ action: "answer_blocked", taskId: t.id, label: `answer the question of blocked task ${t.id}` });
22
+ if (t.status === "fixing")
23
+ out.push({ action: "fix", taskId: t.id, label: `fix task ${t.id} after a failed check` });
24
+ if (t.status === "gating")
25
+ out.push({ action: "gate", taskId: t.id, label: `run the checks of task ${t.id}` });
26
+ if (t.status === "reviewing")
27
+ out.push({ action: "review", taskId: t.id, label: `review task ${t.id}` });
28
+ }
29
+ const running = job.tasks.some((t) => t.status === "running");
30
+ for (const t of orderReady(job, readyTasks(job))) {
31
+ out.push({ action: "dispatch", taskId: t.id, label: `start task ${t.id}: ${t.title}` });
32
+ }
33
+ const replansLeft = job.counters.replans < job.budget.replansMax;
34
+ if (job.counters.stalls >= stallLimit && replansLeft)
35
+ out.push({ action: "replan", label: "the job is stalled: rewrite the plan" });
36
+ if (allDone(job))
37
+ out.push({ action: "verify", label: "every task is done: verify the whole job" });
38
+ const stuck = !running && out.length === 0 && job.tasks.some((t) => t.status === "escalated" || t.status === "cancelled");
39
+ // Nothing can go on past an escalated task: a replan first while one is left, then the user.
40
+ if (stuck && replansLeft && job.tasks.some((t) => t.status === "escalated"))
41
+ out.push({ action: "replan", label: "escalated tasks block the rest: rewrite the plan" });
42
+ else if (stuck)
43
+ out.push({ action: "ask_user", label: "nothing can proceed: ask the user" });
44
+ if (out.length === 0 && !running)
45
+ out.push({ action: "wrap", label: "nothing left to do: wrap up" });
46
+ return out.sort((a, b) => ORDER.indexOf(a.action) - ORDER.indexOf(b.action));
47
+ }
48
+ // The rules fallback: the highest-priority proposal.
49
+ export function nextProposal(agenda) {
50
+ return agenda[0];
51
+ }
package/dist/agents.js ADDED
@@ -0,0 +1,58 @@
1
+ // Turns the role matrix into OpenCode agents. v2 does not load agent markdown files, so the agents are
2
+ // created in the plugin (ctx.agent.transform), each copied from the built-in "build" agent so it inherits the
3
+ // user's base rules (external directories, .env files), with the role's rules appended.
4
+ import { SUMMARIZER_SYSTEM } from "./context/summary.js";
5
+ import { MICROMANAGER, ROLES, micromanagerSystem } from "./roles.js";
6
+ // The context manager's summarizer (src/context/summary.ts): no tools, it only reads the transcript it is given.
7
+ export const SUMMARIZER_AGENT = "summarizer";
8
+ export function agentsFrom(base) {
9
+ const copy = () => ({ ...base, permissions: [...base.permissions] });
10
+ const roles = ROLES.map((role) => ({
11
+ ...copy(),
12
+ id: role.agent,
13
+ name: role.agent[0].toUpperCase() + role.agent.slice(1), // "Coder", "Reviewer", …
14
+ mode: "subagent",
15
+ hidden: true, // only the micromanager delegates to them; build and plan never see them
16
+ description: role.description,
17
+ system: role.system,
18
+ permissions: [...base.permissions, ...role.rules],
19
+ }));
20
+ const micromanager = {
21
+ ...copy(),
22
+ id: MICROMANAGER.agent,
23
+ name: "Micromanager",
24
+ mode: "primary",
25
+ hidden: false,
26
+ description: MICROMANAGER.description,
27
+ system: micromanagerSystem(),
28
+ permissions: [...base.permissions, ...MICROMANAGER.rules],
29
+ };
30
+ // Plan mode is a mode of the micromanager, not an agent of its own: the user has one entry point and the mode
31
+ // decides what the turn may do (src/mode.ts). A second primary agent made it a third thing to remember.
32
+ const summarizer = {
33
+ ...copy(),
34
+ id: SUMMARIZER_AGENT,
35
+ name: "Summarizer",
36
+ mode: "subagent",
37
+ hidden: true,
38
+ description: "Compresses a long session's earlier turns for the context manager. Started by the plugin only.",
39
+ system: SUMMARIZER_SYSTEM,
40
+ permissions: [...base.permissions, { action: "*", resource: "*", effect: "deny" }],
41
+ };
42
+ return [micromanager, ...roles, summarizer];
43
+ }
44
+ export function installAgents(draft) {
45
+ const base = draft.get("build");
46
+ if (!base)
47
+ throw new Error('no built-in "build" agent to copy the base rules from');
48
+ const agents = agentsFrom(base);
49
+ for (const agent of agents) {
50
+ // update() on an unknown id creates it (seen on opencode 2.0.18)
51
+ draft.update(agent.id, (target) => {
52
+ for (const key of Object.keys(target))
53
+ delete target[key];
54
+ Object.assign(target, agent);
55
+ });
56
+ }
57
+ return agents.map((a) => a.id);
58
+ }
@@ -0,0 +1,281 @@
1
+ // B1-T6: what a plan job leaves behind, read back as an artifact spec. A plan's `plan.md` is prose for a reader; the
2
+ // `## Artifacts` section under it lists the files the job promoted out of its throwaway worktree, each with its bytes
3
+ // and sha256, and src/promote.ts put those files under <planArea>/artifacts/<task>/. The build job that follows must not
4
+ // re-read the prose: it takes the document and the goal and gets one of the four specs (B1-T1), which is what the
5
+ // deck/video/site/image adapter renders.
6
+ //
7
+ // The document is the only thing that says a file is what the plan built, so the hashes are checked rather than trusted:
8
+ // a plan.md that names a file whose bytes changed, or whose hash is not its own, is refused. A file the chosen kind
9
+ // cannot use is named in `warnings`, never dropped: a deck plan that also promoted a screen recording should say so, not
10
+ // quietly produce a deck from less than the plan handed over.
11
+ //
12
+ // Every path in the returned spec is relative to `artifactsRoot`, because that is where the files are; a caller that
13
+ // stages them into its own job directory keeps the same shape, so the spec stays true after the copy. This module may
14
+ // import the plugin's own code (plandoc.ts, worktree/git.ts) — @omacode/artifact must never import the plugin — which
15
+ // is why the handoff lives beside the plan rather than in the package.
16
+ import { closeSync, openSync, readSync } from "node:fs";
17
+ import { stat } from "node:fs/promises";
18
+ import { extname, join } from "node:path";
19
+ import { insideResolved } from "@omacode/core/safepath";
20
+ import { parsePlanDoc } from "../plandoc.js";
21
+ import { planArea } from "../worktree/git.js";
22
+ // Where promoted artifacts land: the same root src/promote.ts writes under, so a spec path and the file on disk are one
23
+ // relative name. The caller passes this in instead of resolving it twice, and a job that copies the files keeps it.
24
+ export function artifactsRootFor(project, jobId) {
25
+ return join(planArea(project, jobId), "artifacts");
26
+ }
27
+ // The mapping, one row per kind: what a promoted file has to be called to become an item. A file of any other extension
28
+ // is reported, not guessed at.
29
+ const EXTENSIONS = {
30
+ deck: [".html", ".md"],
31
+ video: [".mp4", ".webm", ".mov"],
32
+ site: [".html"],
33
+ images: [".png", ".jpg", ".jpeg", ".webp"],
34
+ };
35
+ // What plan.md does not carry. Each default is used with a warning naming it, because a scene without a duration or a
36
+ // slot without a size cannot be built, and an adapter must not have to invent the number this module already picked. A
37
+ // video's duration is the storyboard's (B2-T3): `DEFAULT_BEAT_SECONDS` is stated there, and the handoff does not spell a
38
+ // second default that could drift from it.
39
+ const DEFAULT_FPS = 30;
40
+ const DEFAULT_SIZE = { width: 1920, height: 1080 };
41
+ const DEFAULT_IMAGE_SIZE = { width: 1024, height: 1024 };
42
+ // How much of a file is read for its heading. A title is the first line of a document or the first element of a page;
43
+ // reading past a long body would only cost memory for text a heading never uses.
44
+ const HEAD_BYTES = 64 * 1024;
45
+ const why = (err) => (err instanceof Error ? err.message : String(err));
46
+ // The first bytes of a file as text. Decoding may cut a multi-byte character at the boundary; the only victim is a
47
+ // heading that starts past 64 KiB, which is not a heading a reader would have found either.
48
+ function headOf(path) {
49
+ const fd = openSync(path, "r");
50
+ try {
51
+ const buffer = Buffer.alloc(HEAD_BYTES);
52
+ const read = readSync(fd, buffer, 0, HEAD_BYTES, 0);
53
+ return buffer.subarray(0, read).toString("utf8");
54
+ }
55
+ finally {
56
+ closeSync(fd);
57
+ }
58
+ }
59
+ // The first heading of an artifact: `# ` for Markdown, the first non-empty `<h1>` for HTML. Undefined when there is
60
+ // none, which the caller answers with the file's stem — a slide still needs something to call it.
61
+ function headingIn(text, kind) {
62
+ if (kind === ".html") {
63
+ for (const found of text.matchAll(/<h1[^>]*>([\s\S]*?)<\/h1>/gi)) {
64
+ const title = found[1].replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim();
65
+ if (title)
66
+ return title;
67
+ }
68
+ return undefined;
69
+ }
70
+ for (const line of text.split(/\r?\n/)) {
71
+ const found = /^#\s+(.*)$/.exec(line);
72
+ const title = found?.[1]?.trim();
73
+ if (title)
74
+ return title;
75
+ }
76
+ return undefined;
77
+ }
78
+ // The name without its extension: `sub/page.html` → `page`. The stem is the fallback title and, for an image slot, the
79
+ // only prompt there is.
80
+ function stemOf(path) {
81
+ const name = path.split("/").pop() ?? path;
82
+ return name.endsWith(extname(name)) ? name.slice(0, name.length - extname(name).length) : name;
83
+ }
84
+ // A spec id from a path: readable in an error and stable across runs, since it is derived from what plan.md says.
85
+ function slugOf(text) {
86
+ return text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "item";
87
+ }
88
+ // Two artifacts can share a stem (`deck.html` and `deck.md`, or the same name in two tasks). A spec id is a promise that
89
+ // a later check can address one item, so a duplicate is numbered rather than left to collide.
90
+ function uniqueId(base, seen) {
91
+ let id = base;
92
+ for (let n = 2; seen.has(id); n++)
93
+ id = `${base}-${n}`;
94
+ seen.add(id);
95
+ return id;
96
+ }
97
+ async function titleOf(file) {
98
+ const extension = extname(file.path).toLowerCase();
99
+ let head;
100
+ try {
101
+ head = headOf(file.abs);
102
+ }
103
+ catch {
104
+ // The bytes just hashed a moment ago, so an unreadable file here is a race, not a contract problem: the stem is
105
+ // still a truthful name and the spec can be built.
106
+ return stemOf(file.path);
107
+ }
108
+ return headingIn(head, extension) ?? stemOf(file.path);
109
+ }
110
+ // Read a plan document and map its promoted artifacts into one typed spec. The spec is returned only when the whole
111
+ // handoff holds: a document that does not parse, a file whose hash or size is not the one the document records, or a
112
+ // plan that promotes nothing this kind can use has no spec to give an adapter.
113
+ export async function specFromPlan(input) {
114
+ // The engine ships separately (@omacode/artifact is an optional peer). Only a plan-to-spec handoff needs it, so it
115
+ // is loaded on demand instead of at plugin start.
116
+ const [{ parseSpec, specVersionOf }, { storyboardFromPlan }, { sha256File }] = await Promise.all([
117
+ import("@omacode/artifact/spec"),
118
+ import("@omacode/artifact/storyboard"),
119
+ import("@omacode/artifact/provenance"),
120
+ ]);
121
+ const warnings = [];
122
+ const parsed = parsePlanDoc(input.planMd);
123
+ if (!parsed.doc)
124
+ return { errors: parsed.errors.map((line) => `plan.md: ${line}`), warnings, used: [] };
125
+ const doc = parsed.doc;
126
+ // A1's rule: a reader-only plan promotes nothing, so there is nothing to hand an adapter. Saying that is better than
127
+ // handing back an empty deck that would render as a blank file.
128
+ if (doc.readerOnly !== undefined) {
129
+ return { errors: ["the plan is reader-only, so there is nothing to hand over"], warnings, used: [] };
130
+ }
131
+ const errors = [];
132
+ const verified = [];
133
+ for (const artifact of doc.artifacts) {
134
+ const label = `${artifact.task}/${artifact.path}`;
135
+ const abs = join(input.artifactsRoot, artifact.task, ...artifact.path.split("/"));
136
+ // `insideResolved` resolves both sides through `realish`, so a `..` that climbs out and a symlink that points out are
137
+ // the same refusal; a name that merely looks harmless is not enough for a path built from a document.
138
+ if (!insideResolved(input.artifactsRoot, abs)) {
139
+ errors.push(`${label} resolves outside the artifacts root`);
140
+ continue;
141
+ }
142
+ let info;
143
+ try {
144
+ info = await stat(abs);
145
+ }
146
+ catch (err) {
147
+ errors.push(`${label}: cannot be read (${why(err)})`);
148
+ continue;
149
+ }
150
+ if (!info.isFile()) {
151
+ errors.push(`${label}: expected a file, not a directory`);
152
+ continue;
153
+ }
154
+ const sha256 = await sha256File(abs);
155
+ if (sha256 !== artifact.sha256) {
156
+ errors.push(`${label}: plan.md records sha256 ${artifact.sha256}, but the file hashes to ${sha256}`);
157
+ continue;
158
+ }
159
+ if (info.size !== artifact.bytes) {
160
+ errors.push(`${label}: plan.md records ${artifact.bytes} B, but the file is ${info.size} B`);
161
+ continue;
162
+ }
163
+ verified.push({ task: artifact.task, path: artifact.path, asset: label, abs, sha256 });
164
+ }
165
+ // The files this kind can use, and a word about every one it cannot. The order of `warnings` follows plan.md.
166
+ const usable = [];
167
+ for (const file of verified) {
168
+ if (EXTENSIONS[input.kind].includes(extname(file.path).toLowerCase()))
169
+ usable.push(file);
170
+ else
171
+ warnings.push(`${file.asset} is not used by a ${input.kind} spec`);
172
+ }
173
+ // A broken file is a broken handoff even when the rest would build: the plan is the only claim about which bytes are
174
+ // the job's, and a caller that shipped a deck from half of them would never learn the other half was wrong.
175
+ if (errors.length)
176
+ return { errors, warnings, used: [] };
177
+ if (!usable.length) {
178
+ errors.push(`the plan promotes no file a ${input.kind} spec can use`);
179
+ return { errors, warnings, used: [] };
180
+ }
181
+ const base = {
182
+ // The version belongs to the kind (spec.ts): a deck is 2 since B3-T1, a video is 2 since B2-T2 and an image set is 2
183
+ // since B5-T1, while a site is 1. This file asks, so a bump cannot leave a handoff writing yesterday's number.
184
+ version: specVersionOf(input.kind),
185
+ job: input.job,
186
+ brief: input.brief,
187
+ ...(input.checks !== undefined ? { checks: [...input.checks] } : {}),
188
+ assets: usable.map((file) => ({ path: file.asset, sha256: file.sha256 })),
189
+ };
190
+ const used = [];
191
+ const seen = new Set();
192
+ let built;
193
+ if (input.kind === "deck") {
194
+ const slides = [];
195
+ for (const file of usable) {
196
+ slides.push({ id: uniqueId(slugOf(file.asset), seen), title: await titleOf(file), asset: file.asset });
197
+ // The spec names the file by its asset path, so that is the path provenance records.
198
+ used.push({ task: file.task, path: file.asset, sha256: file.sha256 });
199
+ }
200
+ built = { kind: "deck", ...base, slides };
201
+ }
202
+ else if (input.kind === "video") {
203
+ warnings.push(`plan.md carries no fps, so the spec uses the default ${DEFAULT_FPS} fps`);
204
+ warnings.push(`plan.md carries no frame size, so the spec uses the default ${DEFAULT_SIZE.width}×${DEFAULT_SIZE.height}`);
205
+ // A video plan becomes a storyboard first (B2-T3): the plan's prose is the beat sheet, each promoted clip a beat, and
206
+ // the two things plan.md never carries — a duration and an acceptance line for the scene — are stated by the
207
+ // storyboard rather than invented by the adapter. The scenes are the beats read back in time order.
208
+ const drafts = usable.map((file) => ({
209
+ id: uniqueId(slugOf(file.asset), seen),
210
+ asset: file.asset,
211
+ }));
212
+ const board = storyboardFromPlan({
213
+ job: input.job,
214
+ goal: doc.goal,
215
+ findings: doc.findings,
216
+ decisions: doc.decisions,
217
+ scenes: drafts,
218
+ });
219
+ warnings.push(...board.notes);
220
+ if (board.storyboard === undefined) {
221
+ errors.push(...board.errors);
222
+ return { errors, warnings, used: [] };
223
+ }
224
+ const beats = board.storyboard.beats;
225
+ const scenes = beats.map((beat, index) => {
226
+ const end = index + 1 < beats.length ? beats[index + 1].at : board.storyboard.duration;
227
+ return {
228
+ id: beat.id,
229
+ duration: Math.round((end - beat.at) * 1000) / 1000,
230
+ asset: usable[index].asset,
231
+ acceptance: [...beat.acceptance],
232
+ };
233
+ });
234
+ for (const file of usable)
235
+ used.push({ task: file.task, path: file.asset, sha256: file.sha256 });
236
+ built = {
237
+ kind: "video",
238
+ ...base,
239
+ engine: "hyperframes",
240
+ fps: DEFAULT_FPS,
241
+ size: { width: DEFAULT_SIZE.width, height: DEFAULT_SIZE.height },
242
+ scenes,
243
+ };
244
+ }
245
+ else if (input.kind === "site") {
246
+ const pages = [];
247
+ // A site page is addressed by where it sits in the site, so the task directory the plan used for storage is not part
248
+ // of it — which is why two tasks promoting `sub/page.html` would write one page twice. That is a collision the spec
249
+ // cannot see (both pages are valid on their own), so it is refused here, naming both tasks.
250
+ const owners = new Map();
251
+ for (const file of usable) {
252
+ const owner = owners.get(file.path);
253
+ if (owner !== undefined) {
254
+ errors.push(`page ${file.path} is promoted by both ${owner} and ${file.task}`);
255
+ continue;
256
+ }
257
+ owners.set(file.path, file.task);
258
+ pages.push({ path: file.path, title: await titleOf(file) });
259
+ used.push({ task: file.task, path: file.path, sha256: file.sha256 });
260
+ }
261
+ if (errors.length)
262
+ return { errors, warnings, used: [] };
263
+ built = { kind: "site", ...base, pages };
264
+ }
265
+ else {
266
+ const slots = [];
267
+ for (const file of usable) {
268
+ slots.push({ id: uniqueId(slugOf(file.asset), seen), prompt: stemOf(file.path), size: { ...DEFAULT_IMAGE_SIZE } });
269
+ warnings.push(`${file.asset}: plan.md carries no prompt, so the slot's prompt is the file's name`);
270
+ warnings.push(`${file.asset}: plan.md carries no size, so the slot uses the default ${DEFAULT_IMAGE_SIZE.width}×${DEFAULT_IMAGE_SIZE.height}`);
271
+ used.push({ task: file.task, path: file.asset, sha256: file.sha256 });
272
+ }
273
+ built = { kind: "images", ...base, slots };
274
+ }
275
+ // The spec's own parser is the last word: a mapping this file got wrong (a task id that is not a path segment, an
276
+ // empty brief) fails here, where a caller can still say why, instead of inside the adapter.
277
+ const spec = parseSpec(input.kind, built);
278
+ if (!spec.spec)
279
+ return { errors: spec.errors, warnings, used: [] };
280
+ return { spec: spec.spec, errors: [], warnings, used };
281
+ }
package/dist/ask.js ADDED
@@ -0,0 +1,200 @@
1
+ // Asks: a worker's permission request that nobody could decide is paused and put to the micromanager, and through it
2
+ // to the user, instead of being refused.
3
+ //
4
+ // Background workers used to get "refused, not queued" for every request the decider was not sure about (live runs: 568
5
+ // times "decider unsure", 90 "the user must decide"), and a worker that cannot run its own verification cannot finish its task.
6
+ // OpenCode parks a request whose effect stays "ask" until someone replies (Permission.assert waits on a deferred,
7
+ // whatever the session), and the plugin can reply through ctx.permission.reply. So the request waits, the micromanager
8
+ // is woken with what is asked and why, and the answer comes from the one who can give it:
9
+ // - the micromanager, through answer_permission, for a request that clearly serves the task;
10
+ // - the user, in their own turn ("yes", "yes always", "no"), for anything else, and always for a hard rule: the
11
+ // micromanager is an LLM a worker's output can steer, so a hard rule never opens on its word;
12
+ // - nobody, after the timeout: then it is refused as before, and the worker carries on without it.
13
+ // "once" lets this call run; "job" also lets the exact same request run for the rest of the job; "refuse" fails it with
14
+ // the reason. OpenCode's own "always" is never used: it writes a rule into the project for good.
15
+ import { askForm, formInput } from "./forms.js";
16
+ export const ASK_TIMEOUT_MS = 10 * 60_000;
17
+ export function askKey(action, resources) {
18
+ return `${action}\0${resources.map((r) => r.trim().replace(/\s+/g, " ")).join("\0")}`;
19
+ }
20
+ export function commandPrefix(resources) {
21
+ const first = resources[0] ?? "";
22
+ const parts = first.trim().split(/\s+/).filter(Boolean);
23
+ return parts.slice(0, 3).join(" ");
24
+ }
25
+ // The user's answer, in English or German, as short as people answer. Anything else is not an answer.
26
+ export function askAnswer(text) {
27
+ const t = text.trim().toLowerCase().replace(/[.!?"']+$/g, "").replace(/^["']/, "").replace(/\s+/g, " ");
28
+ if (["yes always", "always", "allow always", "for the job", "yes for the job", "ja immer", "immer", "für den job"].includes(t))
29
+ return "job";
30
+ if (["yes", "y", "yeah", "yep", "sure", "ok", "okay", "allow", "allow it", "once", "allow once", "go ahead", "do it", "ja", "einmal", "ja einmal", "erlauben"].includes(t))
31
+ return "once";
32
+ if (["no", "n", "nope", "nah", "deny", "refuse", "no way", "nein", "ablehnen", "verweigern"].includes(t))
33
+ return "refuse";
34
+ return undefined;
35
+ }
36
+ export class Asks {
37
+ #pending = new Map();
38
+ #granted = new Map(); // micromanager session -> keys allowed for the job
39
+ #refused = new Map(); // micromanager session -> keys the user or micromanager refused
40
+ #journal;
41
+ #timeoutMs;
42
+ #n = 0;
43
+ #persistedGrants = new Map();
44
+ constructor(journal = () => { }, timeoutMs = ASK_TIMEOUT_MS) {
45
+ this.#journal = journal;
46
+ this.#timeoutMs = timeoutMs;
47
+ }
48
+ loadPersistedGrants(jobId, grants = []) {
49
+ this.#persistedGrants.set(jobId, grants);
50
+ const set = new Set(grants.map((g) => g.key));
51
+ if (set.size)
52
+ this.#granted.set(jobId, set);
53
+ }
54
+ persistedGrants(jobId) {
55
+ return this.#persistedGrants.get(jobId) ?? [];
56
+ }
57
+ persistGrant(jobId, action, resources, directory, taskSession) {
58
+ const key = askKey(action, resources);
59
+ const prefix = resources[0]?.split(/\s+/).slice(0, 3).join(" ") ?? action;
60
+ const list = this.#persistedGrants.get(jobId) ?? [];
61
+ if (list.some((g) => g.key === key))
62
+ return;
63
+ list.push({ key, action, prefix, directory, taskSession });
64
+ this.#persistedGrants.set(jobId, list);
65
+ }
66
+ // What was decided before about exactly this request in this micromanager's job: asked once, never asked again.
67
+ standing(parent, action, resources) {
68
+ const key = askKey(action, resources);
69
+ if (this.#refused.get(parent)?.has(key))
70
+ return "deny";
71
+ if (this.#granted.get(parent)?.has(key))
72
+ return "allow";
73
+ return undefined;
74
+ }
75
+ open(request, reply) {
76
+ let resolve;
77
+ const settled = new Promise((r) => (resolve = r));
78
+ const ask = { ...request, id: `A${++this.#n}`, at: Date.now(), reply, settled, resolve };
79
+ this.#pending.set(ask.id, ask);
80
+ ask.timer = setTimeout(() => void this.answer(ask.id, "refuse", "timeout"), this.#timeoutMs);
81
+ ask.timer.unref?.();
82
+ this.#journal({ kind: "ask", event: "opened", id: ask.id, sessionID: ask.sessionID, parent: ask.parent, agent: ask.agent, action: ask.action, resources: ask.resources, reason: ask.reason, hard: ask.hard });
83
+ return strip(ask);
84
+ }
85
+ get(id) {
86
+ const ask = this.#pending.get(id);
87
+ return ask && strip(ask);
88
+ }
89
+ // The paused request of a worker, by its id ("A1") or by a short label that is part of what was asked. A worker that
90
+ // waits for its own request finds it by its session: it does not know the A-number.
91
+ find(id, sessionID) {
92
+ const byId = this.#pending.get(id);
93
+ if (byId)
94
+ return strip(byId);
95
+ const wanted = id.trim().toLowerCase();
96
+ if (!wanted)
97
+ return undefined;
98
+ const mine = [...this.#pending.values()].filter((a) => !sessionID || a.sessionID === sessionID);
99
+ const labelled = mine.find((a) => `${a.action} ${a.resources.join(" ")}`.toLowerCase().includes(wanted));
100
+ return labelled && strip(labelled);
101
+ }
102
+ // The promise a worker waits on: it settles when the request is answered, refused or dropped.
103
+ settled(id, sessionID) {
104
+ const ask = this.find(id, sessionID);
105
+ if (!ask)
106
+ return undefined;
107
+ const pending = this.#pending.get(ask.id);
108
+ return pending?.settled;
109
+ }
110
+ // The requests of this worker that wait: what it can wait for.
111
+ mine(sessionID) {
112
+ return [...this.#pending.values()].filter((a) => a.sessionID === sessionID).sort((a, b) => a.at - b.at).map(strip);
113
+ }
114
+ // The oldest request still waiting for this micromanager's answer: the one the user's next "yes" or "no" is about.
115
+ oldest(parent) {
116
+ return [...this.#pending.values()].filter((a) => a.parent === parent).sort((a, b) => a.at - b.at)[0];
117
+ }
118
+ waiting(sessionID) {
119
+ return [...this.#pending.values()].some((a) => a.sessionID === sessionID);
120
+ }
121
+ async answer(id, decision, by, note = "") {
122
+ const ask = this.#pending.get(id);
123
+ if (!ask)
124
+ return { text: `There is no request ${id} waiting: it was answered already, or it timed out.` };
125
+ if (ask.hard && by === "micromanager" && decision !== "refuse") {
126
+ return { text: `${id} is a hard rule (${ask.reason}): only the user can allow it. Show them the request as it is and end your turn; their answer reaches the plugin by itself.`, ask: strip(ask) };
127
+ }
128
+ this.#pending.delete(id);
129
+ clearTimeout(ask.timer);
130
+ const key = askKey(ask.action, ask.resources);
131
+ const who = by === "timeout" ? "nobody answered in time" : `the ${by}`;
132
+ if (decision === "refuse") {
133
+ if (by !== "timeout")
134
+ this.#set(this.#refused, ask.parent, key);
135
+ // OpenCode fails every other paused request of the same session with a reject, so they leave the list too.
136
+ for (const [other, a] of this.#pending)
137
+ if (a.sessionID === ask.sessionID) {
138
+ clearTimeout(a.timer);
139
+ this.#pending.delete(other);
140
+ a.resolve?.({ id: other, decision: "refuse", by, note: `This request is void: ${id} was answered and OpenCode fails the other requests of a session with it.` });
141
+ }
142
+ const message = by === "timeout"
143
+ ? `This is refused, not queued: nobody answered in time (${ask.reason}). It does not stop your task: carry on without it, and say in your report what you wanted it for and what you did instead. Report STATUS: NEEDS_CONTEXT only if you genuinely cannot proceed without it.`
144
+ : `Refused by the ${by}${note ? `: ${note}` : ""}. Do not try it another way; carry on without it, and say in your report what you wanted it for. Report STATUS: NEEDS_CONTEXT only if you genuinely cannot proceed without it.`;
145
+ await ask.reply("reject", message).catch(() => undefined);
146
+ }
147
+ else {
148
+ if (decision === "job")
149
+ this.#set(this.#granted, ask.parent, key);
150
+ await ask.reply("once").catch(() => undefined);
151
+ }
152
+ this.#journal({ kind: "ask", event: "answered", id, sessionID: ask.sessionID, parent: ask.parent, action: ask.action, resources: ask.resources, decision, by, note: note.slice(0, 300), waitedMs: Date.now() - ask.at });
153
+ // A worker that waits for this request hears how it ended, whether the answer was the micromanager's or the user's.
154
+ ask.resolve?.({ id, decision, by, note });
155
+ const verdict = decision === "refuse" ? "refused" : decision === "job" ? "allowed for the rest of the job" : "allowed once";
156
+ return { text: `${id} ${verdict} (${who}); the worker ${decision === "refuse" ? "gets the refusal with the reason" : "goes on"}.`, ask: strip(ask) };
157
+ }
158
+ // The paused requests of sessions that ended or were stopped: nobody needs their answer any more, so they are failed
159
+ // quietly and leave the list, and the caller tells the micromanager they are void (src/plugin.ts release).
160
+ async drop(sessionIDs, why) {
161
+ const dropped = [];
162
+ for (const [id, ask] of this.#pending) {
163
+ if (!sessionIDs.includes(ask.sessionID))
164
+ continue;
165
+ this.#pending.delete(id);
166
+ clearTimeout(ask.timer);
167
+ await ask.reply("reject", `This request is void: ${why}.`).catch(() => undefined);
168
+ this.#journal({ kind: "ask", event: "dropped", id, sessionID: ask.sessionID, parent: ask.parent, why, waitedMs: Date.now() - ask.at });
169
+ // A worker that was waiting for this request hears that it is void, not that it was answered.
170
+ ask.resolve?.({ id, decision: "refuse", by: "timeout", note: `This request is void: ${why}.` });
171
+ dropped.push(strip(ask));
172
+ }
173
+ return dropped;
174
+ }
175
+ #set(map, parent, key) {
176
+ const set = map.get(parent) ?? new Set();
177
+ set.add(key);
178
+ map.set(parent, set);
179
+ }
180
+ grantKey(action, resources) {
181
+ return askKey(action, resources);
182
+ }
183
+ }
184
+ // The pending ask as the outside sees it: without the reply it carries and the promise it settles.
185
+ function strip(ask) {
186
+ const { reply: _reply, timer: _timer, settled: _settled, resolve: _resolve, ...shown } = ask;
187
+ return shown;
188
+ }
189
+ // The note that wakes the micromanager. Everything needed to decide is in it.
190
+ export function askNote(ask, timeoutMs = ASK_TIMEOUT_MS) {
191
+ const what = `${ask.action}: ${ask.resources.join(" | ").slice(0, 600)}`;
192
+ const minutes = Math.round(timeoutMs / 60_000);
193
+ const head = `[micromanager] ${ask.id}: worker ${ask.task} (${ask.agent}, session ${ask.sessionID}) is paused on a permission request until it is answered.\nRequest: ${what}\nWhy it was not decided automatically: ${ask.reason}`;
194
+ const end = `Without an answer it is refused in ${minutes} minutes and the worker carries on without it.`;
195
+ const form = formInput(askForm(ask.id, ask.task, what, ask.reason));
196
+ if (ask.hard) {
197
+ return `${head}\nThis is a hard rule: only the user can allow it. Ask them with the question tool, with exactly this input (a form that waits for their answer; it reaches the plugin by itself):\n${form} ${end}`;
198
+ }
199
+ return `${head}\nDecide it: if it clearly serves the worker's task and reaches nothing outside the project, call answer_permission with id ${ask.id} and decision once (this call) or job (this exact request for the rest of the job), inside the execute tool: await tools.answer_permission({ id: "${ask.id}", decision: "once", note: "" }). If it is risky, outside the task, or you are not sure, ask the user instead with the question tool, with exactly this input (their answer reaches the plugin by itself):\n${form}\nTo refuse it yourself, call answer_permission with decision refuse and a note why. ${end}`;
200
+ }