@guilhermednobre/agent-kit 0.1.0 → 0.3.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 (57) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/README.md +102 -47
  3. package/bin/cli.js +79 -38
  4. package/package.json +12 -4
  5. package/src/cli/tools.js +51 -0
  6. package/src/cli/wf.js +400 -0
  7. package/src/core/briefing.js +188 -0
  8. package/src/core/config.js +321 -0
  9. package/src/core/dag.js +103 -0
  10. package/src/core/engine.js +505 -0
  11. package/src/core/policy.js +145 -0
  12. package/src/core/report.js +104 -0
  13. package/src/core/states.js +59 -0
  14. package/src/core/store.js +60 -0
  15. package/src/core/verify.js +54 -0
  16. package/src/detect.js +6 -0
  17. package/src/generate.js +55 -0
  18. package/src/install.js +22 -14
  19. package/src/render.js +5 -7
  20. package/src/runtimes/index.js +24 -0
  21. package/src/runtimes/orca.js +61 -0
  22. package/src/runtimes/t3.js +87 -0
  23. package/src/trackers/index.js +34 -0
  24. package/src/trackers/linear-t3.js +138 -0
  25. package/src/trackers/linear.js +209 -0
  26. package/templates/AGENTS.md +111 -110
  27. package/templates/CLAUDE.md +185 -306
  28. package/templates/agent-kit/hooks/pretooluse.mjs +53 -0
  29. package/templates/agent-kit/hooks/session-context.mjs +41 -0
  30. package/templates/agent-kit/runtime/orca.md +68 -0
  31. package/templates/agent-kit/runtime/t3.md +109 -0
  32. package/templates/claude/commands/analisar-consistencia.md +111 -0
  33. package/templates/claude/commands/avaliar-ideia.md +63 -0
  34. package/templates/claude/commands/configurar-worker.md +116 -0
  35. package/templates/claude/commands/criar-prd.md +16 -1
  36. package/templates/claude/commands/criar-tasks.md +40 -3
  37. package/templates/claude/commands/criar-techspec.md +12 -1
  38. package/templates/claude/commands/executar-bugfix.md +11 -11
  39. package/templates/claude/commands/executar-qa.md +14 -15
  40. package/templates/claude/commands/executar-release.md +20 -0
  41. package/templates/claude/commands/executar-review.md +51 -31
  42. package/templates/claude/commands/executar-task.md +14 -23
  43. package/templates/claude/commands/executar-workflow.md +101 -0
  44. package/templates/claude/commands/fechar-ciclo.md +88 -0
  45. package/templates/claude/commands/replanejar-workflow.md +32 -0
  46. package/templates/claude/commands/retomar-workflow.md +30 -0
  47. package/templates/claude/commands/status-workflow.md +19 -0
  48. package/templates/claude/rules/README.md +2 -2
  49. package/templates/claude/settings.json +25 -0
  50. package/templates/claude/templates/bugs-template.md +2 -2
  51. package/templates/claude/templates/plan-template.json +33 -0
  52. package/templates/claude/templates/prd-template.md +65 -61
  53. package/templates/claude/templates/task-template.md +8 -8
  54. package/templates/claude/templates/tasks-template.md +1 -1
  55. package/templates/claude/templates/techspec-template.md +129 -129
  56. package/templates/claude/templates/worker-brief-template.md +11 -7
  57. package/templates/docs/agents/worker.md +94 -0
@@ -0,0 +1,104 @@
1
+ export const REPORT_FENCE = "agent-kit-report";
2
+ export const OUTCOMES = ["succeeded", "failed", "blocked"];
3
+
4
+ const BLOCK = new RegExp("```" + REPORT_FENCE + "\\s*\\n([\\s\\S]*?)\\n```", "g");
5
+
6
+ export function reportExample() {
7
+ return [
8
+ "```" + REPORT_FENCE,
9
+ JSON.stringify(
10
+ {
11
+ outcome: "succeeded",
12
+ summary: "What was done, in two or three sentences",
13
+ filesChanged: ["path/a", "path/b"],
14
+ checks: [{ command: "the exact command", exitCode: 0, observed: "last relevant output lines" }],
15
+ blockers: [],
16
+ notes: "Anything partial or skipped, and why",
17
+ },
18
+ null,
19
+ 2
20
+ ),
21
+ "```",
22
+ ].join("\n");
23
+ }
24
+
25
+ export function parseReport(text) {
26
+ const blocks = [...String(text || "").matchAll(BLOCK)];
27
+ if (blocks.length === 0) {
28
+ return { valid: false, errors: [`no \`\`\`${REPORT_FENCE} block found`], report: null };
29
+ }
30
+ let data;
31
+ try {
32
+ data = JSON.parse(blocks[blocks.length - 1][1]);
33
+ } catch (error) {
34
+ return { valid: false, errors: [`report block is not valid JSON: ${error.message}`], report: null };
35
+ }
36
+ const errors = validateReport(data);
37
+ return { valid: errors.length === 0, errors, report: errors.length === 0 ? normalize(data) : null };
38
+ }
39
+
40
+ function validateReport(data) {
41
+ const errors = [];
42
+ if (!data || typeof data !== "object") return ["report must be a JSON object"];
43
+ if (!OUTCOMES.includes(data.outcome)) errors.push(`outcome must be one of ${OUTCOMES.join(", ")}`);
44
+ if (typeof data.summary !== "string" || !data.summary.trim()) errors.push("summary is required");
45
+ if (data.filesChanged !== undefined && !Array.isArray(data.filesChanged)) errors.push("filesChanged must be an array");
46
+ if (data.checks !== undefined && !Array.isArray(data.checks)) errors.push("checks must be an array");
47
+ if (data.blockers !== undefined && !Array.isArray(data.blockers)) errors.push("blockers must be an array");
48
+ if (data.outcome === "blocked" && !(data.blockers || []).length) errors.push("a blocked report must list blockers");
49
+ return errors;
50
+ }
51
+
52
+ function normalize(data) {
53
+ return {
54
+ outcome: data.outcome,
55
+ summary: data.summary.trim(),
56
+ filesChanged: (data.filesChanged || []).map(String),
57
+ checks: data.checks || [],
58
+ blockers: (data.blockers || []).map(String),
59
+ notes: data.notes ? String(data.notes) : "",
60
+ };
61
+ }
62
+
63
+ export const REVIEW_FENCE = "agent-kit-review";
64
+ const REVIEW_BLOCK = new RegExp("```" + REVIEW_FENCE + "\\s*\\n([\\s\\S]*?)\\n```", "g");
65
+ const SEVERITIES = ["blocker", "high", "medium", "low"];
66
+
67
+ export function reviewExample() {
68
+ return [
69
+ "```" + REVIEW_FENCE,
70
+ JSON.stringify(
71
+ {
72
+ verdict: "rejected",
73
+ findings: [{ severity: "high", title: "Short title", detail: "What is wrong, where, and why it matters", file: "path/a:42" }],
74
+ criteria: [{ criterion: "Acceptance criterion text", met: false, evidence: "What you ran or read" }],
75
+ summary: "One or two sentences",
76
+ },
77
+ null,
78
+ 2
79
+ ),
80
+ "```",
81
+ ].join("\n");
82
+ }
83
+
84
+ export function parseReview(text) {
85
+ const blocks = [...String(text || "").matchAll(REVIEW_BLOCK)];
86
+ if (blocks.length === 0) return { valid: false, errors: [`no \`\`\`${REVIEW_FENCE} block found`], review: null };
87
+ let data;
88
+ try {
89
+ data = JSON.parse(blocks[blocks.length - 1][1]);
90
+ } catch (error) {
91
+ return { valid: false, errors: [`review block is not valid JSON: ${error.message}`], review: null };
92
+ }
93
+ const errors = [];
94
+ if (!["approved", "rejected"].includes(data?.verdict)) errors.push('verdict must be "approved" or "rejected"');
95
+ if (data?.findings !== undefined && !Array.isArray(data.findings)) errors.push("findings must be an array");
96
+ const findings = (data?.findings || []).map((finding) =>
97
+ typeof finding === "string" ? finding : `${SEVERITIES.includes(finding.severity) ? finding.severity.toUpperCase() : "NOTE"}: ${finding.title || ""}${finding.file ? ` (${finding.file})` : ""}${finding.detail ? ` — ${finding.detail}` : ""}`
98
+ );
99
+ const blocking = (data?.findings || []).filter((finding) => ["blocker", "high"].includes(finding?.severity));
100
+ if (data?.verdict === "approved" && blocking.length) errors.push("an approved review cannot carry blocker or high findings");
101
+ if (data?.verdict === "rejected" && findings.length === 0) errors.push("a rejected review must list findings");
102
+ if (errors.length) return { valid: false, errors, review: null };
103
+ return { valid: true, errors: [], review: { verdict: data.verdict, findings, criteria: data.criteria || [], summary: data.summary || "" } };
104
+ }
@@ -0,0 +1,59 @@
1
+ export const TASK_STATES = Object.freeze([
2
+ "pending",
3
+ "ready",
4
+ "running",
5
+ "testing",
6
+ "review",
7
+ "blocked",
8
+ "failed",
9
+ "completed",
10
+ "cancelled",
11
+ ]);
12
+
13
+ export const WORKFLOW_STATES = Object.freeze([
14
+ "planning",
15
+ "running",
16
+ "blocked",
17
+ "failed",
18
+ "completed",
19
+ "cancelled",
20
+ ]);
21
+
22
+ const TASK_TRANSITIONS = {
23
+ pending: ["ready", "blocked", "cancelled"],
24
+ ready: ["running", "pending", "blocked", "cancelled"],
25
+ running: ["testing", "ready", "failed", "blocked", "cancelled"],
26
+ testing: ["review", "ready", "failed", "blocked", "cancelled"],
27
+ review: ["completed", "ready", "failed", "blocked", "cancelled"],
28
+ blocked: ["pending", "ready", "failed", "cancelled"],
29
+ failed: ["pending", "ready", "cancelled"],
30
+ completed: [],
31
+ cancelled: [],
32
+ };
33
+
34
+ const WORKFLOW_TRANSITIONS = {
35
+ planning: ["running", "cancelled"],
36
+ running: ["blocked", "failed", "completed", "cancelled", "planning"],
37
+ blocked: ["running", "planning", "failed", "cancelled"],
38
+ failed: ["planning", "cancelled"],
39
+ completed: [],
40
+ cancelled: [],
41
+ };
42
+
43
+ export const TERMINAL_TASK_STATES = Object.freeze(["completed", "cancelled"]);
44
+ export const ACTIVE_TASK_STATES = Object.freeze(["running", "testing", "review"]);
45
+
46
+ export function canTransitionTask(from, to) {
47
+ return (TASK_TRANSITIONS[from] || []).includes(to);
48
+ }
49
+
50
+ export function canTransitionWorkflow(from, to) {
51
+ return (WORKFLOW_TRANSITIONS[from] || []).includes(to);
52
+ }
53
+
54
+ export class TransitionError extends Error {
55
+ constructor(scope, id, from, to) {
56
+ super(`Invalid ${scope} transition for ${id}: ${from} -> ${to}`);
57
+ this.name = "TransitionError";
58
+ }
59
+ }
@@ -0,0 +1,60 @@
1
+ import { mkdir, readFile, readdir, rename, writeFile } from "node:fs/promises";
2
+ import { existsSync } from "node:fs";
3
+ import { dirname, join, relative } from "node:path";
4
+ import { CONFIG_DIR } from "./config.js";
5
+
6
+ const RUN_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
7
+
8
+ export function runsDir(root) {
9
+ return join(root, CONFIG_DIR, "runs");
10
+ }
11
+
12
+ export function runDir(root, runId) {
13
+ assertRunId(runId);
14
+ return join(runsDir(root), runId);
15
+ }
16
+
17
+ export function assertRunId(runId) {
18
+ if (!RUN_ID.test(String(runId || ""))) {
19
+ throw new Error(`Invalid run id "${runId}": use letters, digits, ".", "_" or "-" (max 64)`);
20
+ }
21
+ }
22
+
23
+ export async function writeAtomic(path, content) {
24
+ await mkdir(dirname(path), { recursive: true });
25
+ const temp = `${path}.${process.pid}.tmp`;
26
+ await writeFile(temp, content, "utf8");
27
+ await rename(temp, path);
28
+ }
29
+
30
+ export async function saveRun(root, run) {
31
+ await writeAtomic(join(runDir(root, run.id), "run.json"), `${JSON.stringify(run, null, 2)}\n`);
32
+ }
33
+
34
+ export async function loadRun(root, runId) {
35
+ const path = join(runDir(root, runId), "run.json");
36
+ if (!existsSync(path)) throw new Error(`Run "${runId}" not found at ${relative(root, path)}`);
37
+ return JSON.parse(await readFile(path, "utf8"));
38
+ }
39
+
40
+ export function runExists(root, runId) {
41
+ return existsSync(join(runDir(root, runId), "run.json"));
42
+ }
43
+
44
+ export async function listRuns(root) {
45
+ if (!existsSync(runsDir(root))) return [];
46
+ const entries = await readdir(runsDir(root), { withFileTypes: true });
47
+ const runs = [];
48
+ for (const entry of entries.filter((item) => item.isDirectory())) {
49
+ if (!runExists(root, entry.name)) continue;
50
+ const run = await loadRun(root, entry.name);
51
+ runs.push({ id: run.id, state: run.state, objective: run.objective, updatedAt: run.updatedAt });
52
+ }
53
+ return runs.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : -1));
54
+ }
55
+
56
+ export async function saveArtifact(root, runId, name, content) {
57
+ const path = join(runDir(root, runId), name);
58
+ await writeAtomic(path, content);
59
+ return relative(root, path).replace(/\\/g, "/");
60
+ }
@@ -0,0 +1,54 @@
1
+ import { spawn } from "node:child_process";
2
+
3
+ const OUTPUT_TAIL = 4000;
4
+
5
+ export function runCommand(command, { cwd, timeoutSeconds = 900, env } = {}) {
6
+ return new Promise((resolve) => {
7
+ const started = Date.now();
8
+ const child = spawn(command, { cwd, shell: true, env: env || process.env, windowsHide: true });
9
+ let output = "";
10
+ let timedOut = false;
11
+ const keep = (chunk) => {
12
+ output = (output + chunk.toString()).slice(-OUTPUT_TAIL * 2);
13
+ };
14
+ child.stdout.on("data", keep);
15
+ child.stderr.on("data", keep);
16
+ const timer = setTimeout(() => {
17
+ timedOut = true;
18
+ child.kill();
19
+ }, timeoutSeconds * 1000);
20
+ const finish = (exitCode, error) => {
21
+ clearTimeout(timer);
22
+ resolve({
23
+ command,
24
+ exitCode: timedOut ? null : exitCode,
25
+ passed: !timedOut && exitCode === 0,
26
+ timedOut,
27
+ durationMs: Date.now() - started,
28
+ output: (error ? `${error.message}\n` : "") + output.slice(-OUTPUT_TAIL),
29
+ });
30
+ };
31
+ child.on("error", (error) => finish(null, error));
32
+ child.on("close", (code) => finish(code));
33
+ });
34
+ }
35
+
36
+ export async function runChecks(checks, options = {}) {
37
+ const results = [];
38
+ for (const check of checks) {
39
+ const result = await runCommand(check.command, {
40
+ ...options,
41
+ timeoutSeconds: check.timeoutSeconds || options.timeoutSeconds,
42
+ });
43
+ results.push({ name: check.name || check.command, required: check.required !== false, ...result });
44
+ }
45
+ const passed = results.every((result) => result.passed || !result.required);
46
+ return { passed, skipped: results.length === 0, results };
47
+ }
48
+
49
+ export function taskChecks(task, config) {
50
+ if (task.validation?.length) {
51
+ return task.validation.map((command) => ({ name: command, command, required: true }));
52
+ }
53
+ return (config.checks || []).filter((check) => check.perTask);
54
+ }
package/src/detect.js CHANGED
@@ -52,6 +52,7 @@ function blankCommands() {
52
52
  build: UNKNOWN,
53
53
  test: UNKNOWN,
54
54
  lint: UNKNOWN,
55
+ typecheck: UNKNOWN,
55
56
  testOne: UNKNOWN,
56
57
  };
57
58
  }
@@ -84,10 +85,15 @@ function nodeCommands(dir, scripts) {
84
85
  build: scripts.build ? `${runner} build` : UNKNOWN,
85
86
  test: scripts.test ? `${manager.name} test` : UNKNOWN,
86
87
  lint: scripts.lint ? `${runner} lint` : UNKNOWN,
88
+ typecheck: typecheckScript(scripts) ? `${runner} ${typecheckScript(scripts)}` : UNKNOWN,
87
89
  testOne: UNKNOWN,
88
90
  };
89
91
  }
90
92
 
93
+ function typecheckScript(scripts) {
94
+ return ["typecheck", "type-check", "check-types", "tsc"].find((name) => scripts[name]);
95
+ }
96
+
91
97
  function detectPackageManager(dir) {
92
98
  const found = PACKAGE_MANAGERS.find((entry) => existsSync(join(dir, entry.lockfile)));
93
99
  return found || { name: "npm", install: "npm install" };
@@ -0,0 +1,55 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { fileURLToPath } from "node:url";
3
+ import { join } from "node:path";
4
+ import { RUNTIMES, TRACKERS, defaultAutonomy, defaultConfig, defaultWorkflow } from "./core/config.js";
5
+
6
+ const POLICY_SOURCE = fileURLToPath(new URL("./core/policy.js", import.meta.url));
7
+ const UNKNOWN = "TBD";
8
+
9
+ export function normalizeInitChoices(flags = {}) {
10
+ const runtime = flags.runtime || "t3";
11
+ const tracker = flags.tracker || "local";
12
+ if (!RUNTIMES.includes(runtime)) throw new Error(`Invalid --runtime: ${runtime}. Use ${RUNTIMES.join(" or ")}.`);
13
+ if (!TRACKERS.includes(tracker)) throw new Error(`Invalid --tracker: ${tracker}. Use ${TRACKERS.join(" or ")}.`);
14
+ if (flags["linear-team"] && tracker !== "linear") throw new Error("--linear-team requires --tracker linear");
15
+ return { runtime, tracker, linearTeam: flags["linear-team"] || null };
16
+ }
17
+
18
+ export function checksFromCommands(commands = {}) {
19
+ const order = [
20
+ ["lint", commands.lint],
21
+ ["typecheck", commands.typecheck],
22
+ ["test", commands.test],
23
+ ["build", commands.build],
24
+ ];
25
+ return order
26
+ .filter(([, command]) => command && command !== UNKNOWN)
27
+ .map(([name, command]) => ({ name, command, required: true }));
28
+ }
29
+
30
+ export function buildConfig({ detected, answers, choices }) {
31
+ const config = defaultConfig({ runtime: choices.runtime, checks: checksFromCommands(detected.commands) });
32
+ config.project = {
33
+ name: answers.name,
34
+ description: answers.description || "",
35
+ stack: detected.stack || null,
36
+ manifest: detected.manifest || null,
37
+ };
38
+ config.tracker.kind = choices.tracker;
39
+ if (choices.linearTeam) config.tracker.linear.teamKey = choices.linearTeam;
40
+ return config;
41
+ }
42
+
43
+ function json(value) {
44
+ return `${JSON.stringify(value, null, 2)}\n`;
45
+ }
46
+
47
+ export async function generatedFiles({ detected, answers, choices }) {
48
+ const policy = await readFile(POLICY_SOURCE, "utf8");
49
+ return [
50
+ { target: join(".agent-kit", "config.json"), content: json(buildConfig({ detected, answers, choices })) },
51
+ { target: join(".agent-kit", "autonomy.json"), content: json(defaultAutonomy()) },
52
+ { target: join(".agent-kit", "workflow.json"), content: json(defaultWorkflow()) },
53
+ { target: join(".agent-kit", "hooks", "policy.mjs"), content: policy },
54
+ ];
55
+ }
package/src/install.js CHANGED
@@ -3,12 +3,18 @@ import { existsSync } from "node:fs";
3
3
  import { dirname, join, relative, sep } from "node:path";
4
4
  import { render } from "./render.js";
5
5
 
6
- export async function planFiles(templatesDir) {
6
+ const DOTTED = { claude: ".claude", "agent-kit": ".agent-kit" };
7
+ const RUNTIME_GUIDE = /^agent-kit[\\/]runtime[\\/]([a-z0-9-]+)\.md$/;
8
+
9
+ export async function planFiles(templatesDir, { runtime } = {}) {
7
10
  const sources = await listFiles(templatesDir);
8
- return sources.map((source) => ({
9
- source,
10
- target: toTargetPath(relative(templatesDir, source)),
11
- }));
11
+ return sources
12
+ .map((source) => ({ source, relativePath: relative(templatesDir, source) }))
13
+ .filter(({ relativePath }) => {
14
+ const guide = RUNTIME_GUIDE.exec(relativePath);
15
+ return !guide || !runtime || guide[1] === runtime;
16
+ })
17
+ .map(({ source, relativePath }) => ({ source, target: toTargetPath(relativePath) }));
12
18
  }
13
19
 
14
20
  async function listFiles(dir) {
@@ -19,30 +25,32 @@ async function listFiles(dir) {
19
25
  return entry.isDirectory() ? listFiles(full) : Promise.resolve([full]);
20
26
  })
21
27
  );
22
- return nested.flat();
28
+ return nested.flat().sort();
23
29
  }
24
30
 
25
31
  function toTargetPath(relativePath) {
26
32
  const segments = relativePath.split(sep);
27
- if (segments[0] === "claude") {
28
- return [".claude", ...segments.slice(1)].join(sep);
29
- }
33
+ if (DOTTED[segments[0]]) return [DOTTED[segments[0]], ...segments.slice(1)].join(sep);
30
34
  return relativePath;
31
35
  }
32
36
 
33
37
  export async function installFiles(options) {
34
- const { files, targetDir, mode, vars, resolveConflict, dryRun } = options;
38
+ const { files, targetDir, mode, vars, flags, resolveConflict, dryRun } = options;
35
39
  const results = [];
36
40
  for (const file of files) {
37
- results.push(await installOne(file, { targetDir, mode, vars, resolveConflict, dryRun }));
41
+ results.push(await installOne(file, { targetDir, mode, vars, flags, resolveConflict, dryRun }));
38
42
  }
39
43
  return results;
40
44
  }
41
45
 
42
- async function installOne(file, { targetDir, mode, vars, resolveConflict, dryRun }) {
46
+ async function contentOf(file, mode, vars, flags) {
47
+ if (file.content !== undefined) return file.content;
48
+ return render(await readFile(file.source, "utf8"), mode, vars, flags);
49
+ }
50
+
51
+ async function installOne(file, { targetDir, mode, vars, flags, resolveConflict, dryRun }) {
43
52
  const absoluteTarget = join(targetDir, file.target);
44
- const template = await readFile(file.source, "utf8");
45
- const content = render(template, mode, vars);
53
+ const content = await contentOf(file, mode, vars, flags);
46
54
  if (!existsSync(absoluteTarget)) {
47
55
  await writeIfWanted(absoluteTarget, content, dryRun);
48
56
  return { target: file.target, action: "created" };
package/src/render.js CHANGED
@@ -1,15 +1,13 @@
1
- const CONDITIONAL_BLOCK = /<!--IF:([a-z-]+)-->\r?\n?([\s\S]*?)<!--END-->\r?\n?/g;
1
+ const CONDITIONAL_BLOCK = /<!--IF:([a-z0-9=-]+)-->\r?\n?([\s\S]*?)<!--END-->\r?\n?/g;
2
2
  const PLACEHOLDER = /\{\{([A-Z_]+)\}\}/g;
3
3
 
4
- export function render(text, mode, vars) {
5
- const selected = selectBlocks(text, mode);
4
+ export function render(text, mode, vars, flags = []) {
5
+ const selected = selectBlocks(text, new Set([mode, ...flags]));
6
6
  return fillPlaceholders(selected, vars);
7
7
  }
8
8
 
9
- function selectBlocks(text, mode) {
10
- return text.replace(CONDITIONAL_BLOCK, (_, blockMode, body) =>
11
- blockMode === mode ? body : ""
12
- );
9
+ function selectBlocks(text, active) {
10
+ return text.replace(CONDITIONAL_BLOCK, (_, condition, body) => (active.has(condition) ? body : ""));
13
11
  }
14
12
 
15
13
  function fillPlaceholders(text, vars) {
@@ -0,0 +1,24 @@
1
+ import { t3 } from "./t3.js";
2
+ import { orca } from "./orca.js";
3
+
4
+ const REQUIRED = ["name", "completionNote", "validateProfile", "dispatch", "status", "cancel", "interpretStatus"];
5
+ const adapters = new Map();
6
+
7
+ export function registerAdapter(adapter) {
8
+ const missing = REQUIRED.filter((key) => adapter?.[key] === undefined);
9
+ if (missing.length) throw new Error(`Runtime adapter is missing: ${missing.join(", ")}`);
10
+ adapters.set(adapter.name, adapter);
11
+ }
12
+
13
+ export function getAdapter(name) {
14
+ const adapter = adapters.get(name);
15
+ if (!adapter) throw new Error(`Unknown runtime "${name}". Known: ${[...adapters.keys()].join(", ")}`);
16
+ return adapter;
17
+ }
18
+
19
+ export function listAdapters() {
20
+ return [...adapters.values()].map((adapter) => ({ name: adapter.name, description: adapter.description }));
21
+ }
22
+
23
+ registerAdapter(t3);
24
+ registerAdapter(orca);
@@ -0,0 +1,61 @@
1
+ // Legacy Orca adapter: the recipe that used to live in CLAUDE.md section 2, generated per task.
2
+
3
+ function quote(value) {
4
+ return `"${String(value).replace(/(["\\$`])/g, "\\$1")}"`;
5
+ }
6
+
7
+ export const orca = {
8
+ name: "orca",
9
+ description: "Orca orchestration: worker TUI in an Orca terminal, worker_done messages",
10
+
11
+ completionNote:
12
+ "Envie também `orca orchestration send --type worker_done ... --outcome <succeeded|failed>` uma única vez, com o bloco `agent-kit-report` no `--body`.",
13
+
14
+ validateProfile(profile, config) {
15
+ const errors = [];
16
+ if (profile.provider !== "coordinator" && !config.runtimes?.orca?.launchCommand) {
17
+ errors.push("runtimes.orca.launchCommand is not set; run /configurar-worker");
18
+ }
19
+ return errors;
20
+ },
21
+
22
+ dispatch({ run, task, attempt, profile, config }) {
23
+ if (profile.provider === "coordinator") {
24
+ return { runtime: "orca", kind: "coordinator", instruction: `Do task ${task.id} yourself using ${attempt.briefPath}.` };
25
+ }
26
+ const orcaConfig = config.runtimes.orca;
27
+ const launch = orcaConfig.launchCommand.replace("{model}", profile.model || "");
28
+ const slug = `${run.id}-${task.id}`.replace(/[^a-z0-9-]/gi, "-").toLowerCase();
29
+ const linear = task.tracker?.identifier ? ` --linear-issue ${task.tracker.identifier}` : "";
30
+ return {
31
+ runtime: "orca",
32
+ kind: "shell",
33
+ commands: [
34
+ `orca orchestration run-create --objective ${quote(run.objective || run.id)} --json # once per run`,
35
+ `orca worktree create --name ${slug} --no-parent${linear} --json # only when running in parallel; else use the current worktree`,
36
+ `orca terminal create --worktree <selector> --title ${slug} --command ${quote(launch)} --json`,
37
+ `orca terminal read --terminal <handle> --json # repeat until: ${orcaConfig.readiness || "the TUI is ready"}`,
38
+ `orca orchestration task-create --spec "$(cat ${attempt.briefPath})" --json`,
39
+ "orca orchestration dispatch --task <task_id> --to <handle> --return-preamble --json",
40
+ `orca terminal send --terminal <handle> --text "Read the file <abs-path-to-preamble> in full, then follow it exactly." --enter --json`,
41
+ ],
42
+ then: `agent-kit wf started ${run.id} ${task.id} --ref <handle>|<task_id>`,
43
+ notes: ["Never pass --inject. Arm the Monitor described in .agent-kit/runtime/orca.md after dispatch."],
44
+ };
45
+ },
46
+
47
+ status() {
48
+ return { runtime: "orca", kind: "shell", commands: ["orca orchestration check --run <run> --json"] };
49
+ },
50
+
51
+ cancel({ attempt }) {
52
+ const handle = String(attempt.runtimeRef || "<handle>").split("|")[0];
53
+ return { runtime: "orca", kind: "shell", commands: [`orca terminal close --terminal ${handle} --tab --json`] };
54
+ },
55
+
56
+ interpretStatus(message) {
57
+ if (message?.type === "worker_done") return { finished: true, summary: message.body || "" };
58
+ if (message?.type === "escalation") return { finished: true, summary: message.body || "", escalation: true };
59
+ return { finished: false };
60
+ },
61
+ };
@@ -0,0 +1,87 @@
1
+ // T3 Code orchestrator adapter. The Node side cannot call T3 tools (they are MCP tools of the
2
+ // coordinator session); it produces the exact call the coordinator makes and interprets results.
3
+
4
+ const T3_ROLES = {
5
+ implementation: "implementation",
6
+ debug: "implementation",
7
+ docs: "general",
8
+ test: "test",
9
+ review: "review",
10
+ research: "research",
11
+ design: "design",
12
+ qa: "test",
13
+ system: "review",
14
+ uiux: "review",
15
+ security: "review",
16
+ "product-owner": "review",
17
+ pm: "design",
18
+ architect: "design",
19
+ release: "general",
20
+ };
21
+
22
+ export const t3 = {
23
+ name: "t3",
24
+ description: "T3 Code orchestrator: delegate_task child threads, completion delivered to the parent",
25
+
26
+ completionNote: "Sua resposta final é o resultado que o coordenador lê; o bloco `agent-kit-report` precisa estar nela.",
27
+
28
+ validateProfile(profile) {
29
+ const errors = [];
30
+ if (profile.provider !== "coordinator" && !profile.model) {
31
+ errors.push(`profile "${profile.name}" has no model; run /configurar-worker (uses orchestrator_capabilities)`);
32
+ }
33
+ return errors;
34
+ },
35
+
36
+ dispatch({ run, task, attempt, brief, profile, config }) {
37
+ if (profile.provider === "coordinator") {
38
+ return {
39
+ runtime: "t3",
40
+ kind: "coordinator",
41
+ instruction: `Profile "${profile.name}" runs on the coordinator: do task ${task.id} yourself using the brief at ${attempt.briefPath}, then record the report with agent-kit wf report.`,
42
+ };
43
+ }
44
+ const target = { providerInstanceId: profile.provider, model: profile.model };
45
+ if (profile.options && Object.keys(profile.options).length) target.options = profile.options;
46
+ return {
47
+ runtime: "t3",
48
+ kind: "tool-call",
49
+ tool: "delegate_task",
50
+ args: {
51
+ task: brief,
52
+ title: `${task.id} ${task.title}`.slice(0, 120),
53
+ role: T3_ROLES[task.role] || "general",
54
+ mode: "async",
55
+ isolation: config.runtimes?.t3?.isolation || "shared",
56
+ clientRequestId: attempt.clientRequestId,
57
+ target,
58
+ },
59
+ then: `agent-kit wf started ${run.id} ${task.id} --ref <taskId returned by delegate_task>`,
60
+ notes: [
61
+ "Do not poll task_status; the child's completion wakes the coordinator.",
62
+ "If the dispatch call fails or times out, call it again with the same clientRequestId — it is the retry key.",
63
+ ],
64
+ };
65
+ },
66
+
67
+ status({ attempt }) {
68
+ return {
69
+ runtime: "t3",
70
+ kind: "tool-call",
71
+ tool: "task_status",
72
+ args: { taskId: attempt.runtimeRef },
73
+ notes: ["Only on resume or for an overdue task; reading the summary marks it delivered."],
74
+ };
75
+ },
76
+
77
+ cancel({ attempt, reason }) {
78
+ return { runtime: "t3", kind: "tool-call", tool: "task_cancel", args: { taskId: attempt.runtimeRef, reason } };
79
+ },
80
+
81
+ interpretStatus(status) {
82
+ const state = status?.workState;
83
+ if (state === "result_available") return { finished: true, summary: status.summary || "" };
84
+ if (state === "working" || state === "waiting_for_children") return { finished: false };
85
+ return { finished: false, unknown: true };
86
+ },
87
+ };
@@ -0,0 +1,34 @@
1
+ import { createLinearClient, linearTracker } from "./linear.js";
2
+ import { linearT3Tracker } from "./linear-t3.js";
3
+
4
+ const localTracker = {
5
+ kind: "local",
6
+ async publishPlan() {
7
+ return { created: [], parent: null };
8
+ },
9
+ async sync(run) {
10
+ let synced = 0;
11
+ for (const event of run.events) {
12
+ if (!event.synced) {
13
+ event.synced = true;
14
+ synced += 1;
15
+ }
16
+ }
17
+ return { synced, pending: 0 };
18
+ },
19
+ async importPlan() {
20
+ throw new Error("The local tracker cannot import plans; use --plan <file>");
21
+ },
22
+ };
23
+
24
+ export function createTracker(config, { env = process.env, fetchImpl } = {}) {
25
+ const kind = config.tracker?.kind || "local";
26
+ if (kind === "local") return localTracker;
27
+ if (kind === "linear") {
28
+ const settings = config.tracker.linear || {};
29
+ if (settings.via === "t3") return linearT3Tracker({ settings });
30
+ const gql = createLinearClient({ apiKey: env[settings.apiKeyEnv || "LINEAR_API_KEY"], fetchImpl });
31
+ return linearTracker({ settings, gql });
32
+ }
33
+ throw new Error(`Unknown tracker "${kind}"`);
34
+ }