ultimate-pi 0.3.1 → 0.4.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 (114) hide show
  1. package/.agents/skills/harness-decisions/SKILL.md +37 -0
  2. package/.agents/skills/harness-governor/SKILL.md +1 -1
  3. package/.agents/skills/harness-orchestration/SKILL.md +54 -0
  4. package/.agents/skills/harness-plan/SKILL.md +4 -3
  5. package/.agents/skills/harness-sentrux-setup/SKILL.md +57 -0
  6. package/.agents/skills/scrapling-web/SKILL.md +93 -0
  7. package/.pi/PACKAGING.md +2 -2
  8. package/.pi/SYSTEM.md +13 -15
  9. package/.pi/agents/harness/adversary.md +3 -0
  10. package/.pi/agents/harness/evaluator.md +3 -0
  11. package/.pi/agents/harness/executor.md +4 -1
  12. package/.pi/agents/harness/meta-optimizer.md +2 -1
  13. package/.pi/agents/harness/planner.md +22 -1
  14. package/.pi/agents/harness/sentrux-bootstrap.md +42 -0
  15. package/.pi/agents/harness/tie-breaker.md +2 -0
  16. package/.pi/extensions/harness-ask-user.ts +74 -0
  17. package/.pi/extensions/harness-subagents.ts +9 -0
  18. package/.pi/extensions/lib/ask-user/dialog.ts +260 -0
  19. package/.pi/extensions/lib/ask-user/fallback.ts +78 -0
  20. package/.pi/extensions/lib/ask-user/render.ts +66 -0
  21. package/.pi/extensions/lib/ask-user/schema.ts +69 -0
  22. package/.pi/extensions/lib/ask-user/types.ts +41 -0
  23. package/.pi/extensions/lib/ask-user/validate-core.mjs +79 -0
  24. package/.pi/extensions/lib/ask-user/validate.ts +92 -0
  25. package/.pi/extensions/lib/harness-subagents/agent-loader.ts +126 -0
  26. package/.pi/extensions/lib/harness-subagents/agent-manifest.ts +119 -0
  27. package/.pi/extensions/lib/harness-subagents/agent-parser.ts +87 -0
  28. package/.pi/extensions/lib/harness-subagents/blackboard-tool.ts +118 -0
  29. package/.pi/extensions/lib/harness-subagents/blackboard.ts +175 -0
  30. package/.pi/extensions/lib/harness-subagents/spawn-policy.ts +27 -0
  31. package/.pi/extensions/lib/harness-subagents/types-blackboard.ts +27 -0
  32. package/.pi/extensions/lib/harness-subagents/vendored/agent-manager.ts +553 -0
  33. package/.pi/extensions/lib/harness-subagents/vendored/agent-runner.ts +637 -0
  34. package/.pi/extensions/lib/harness-subagents/vendored/agent-types.ts +175 -0
  35. package/.pi/extensions/lib/harness-subagents/vendored/context.ts +59 -0
  36. package/.pi/extensions/lib/harness-subagents/vendored/cross-extension-rpc.ts +134 -0
  37. package/.pi/extensions/lib/harness-subagents/vendored/custom-agents.ts +5 -0
  38. package/.pi/extensions/lib/harness-subagents/vendored/default-agents.ts +123 -0
  39. package/.pi/extensions/lib/harness-subagents/vendored/env.ts +43 -0
  40. package/.pi/extensions/lib/harness-subagents/vendored/group-join.ts +144 -0
  41. package/.pi/extensions/lib/harness-subagents/vendored/index.ts +2447 -0
  42. package/.pi/extensions/lib/harness-subagents/vendored/invocation-config.ts +52 -0
  43. package/.pi/extensions/lib/harness-subagents/vendored/memory.ts +182 -0
  44. package/.pi/extensions/lib/harness-subagents/vendored/model-resolver.ts +92 -0
  45. package/.pi/extensions/lib/harness-subagents/vendored/output-file.ts +115 -0
  46. package/.pi/extensions/lib/harness-subagents/vendored/prompts.ts +103 -0
  47. package/.pi/extensions/lib/harness-subagents/vendored/schedule-store.ts +177 -0
  48. package/.pi/extensions/lib/harness-subagents/vendored/schedule.ts +416 -0
  49. package/.pi/extensions/lib/harness-subagents/vendored/settings.ts +210 -0
  50. package/.pi/extensions/lib/harness-subagents/vendored/skill-loader.ts +108 -0
  51. package/.pi/extensions/lib/harness-subagents/vendored/types.ts +187 -0
  52. package/.pi/extensions/lib/harness-subagents/vendored/ui/agent-widget.ts +637 -0
  53. package/.pi/extensions/lib/harness-subagents/vendored/ui/conversation-viewer.ts +324 -0
  54. package/.pi/extensions/lib/harness-subagents/vendored/ui/schedule-menu.ts +110 -0
  55. package/.pi/extensions/lib/harness-subagents/vendored/usage.ts +71 -0
  56. package/.pi/extensions/lib/harness-subagents/vendored/worktree.ts +195 -0
  57. package/.pi/harness/README.md +2 -1
  58. package/.pi/harness/agents.manifest.json +80 -0
  59. package/.pi/harness/docs/adrs/0009-sentrux-rules-lifecycle.md +9 -5
  60. package/.pi/harness/env.harness.template +28 -0
  61. package/.pi/harness/sentrux/architecture.manifest.json +6 -1
  62. package/.pi/prompts/harness-auto.md +2 -2
  63. package/.pi/prompts/harness-plan.md +2 -2
  64. package/.pi/prompts/harness-router-tune.md +2 -2
  65. package/.pi/prompts/harness-run.md +1 -0
  66. package/.pi/prompts/harness-setup.md +178 -339
  67. package/.pi/scripts/README.md +6 -1
  68. package/.pi/scripts/harness-agents-manifest.mjs +123 -0
  69. package/.pi/scripts/harness-cli-verify.sh +60 -11
  70. package/.pi/scripts/harness-generate-model-router.mjs +242 -0
  71. package/.pi/scripts/harness-graphify-bootstrap.sh +1 -6
  72. package/.pi/scripts/harness-resolve-up-pkg.mjs +71 -0
  73. package/.pi/scripts/harness-seed-project-contracts.mjs +33 -1
  74. package/.pi/scripts/harness-sentrux-bootstrap.mjs +146 -0
  75. package/.pi/scripts/harness-sync-env.mjs +148 -0
  76. package/.pi/scripts/harness-verify.mjs +19 -0
  77. package/.pi/scripts/harness-web-search.md +33 -0
  78. package/.pi/scripts/harness-web.py +177 -0
  79. package/.pi/scripts/harness_web/__init__.py +1 -0
  80. package/.pi/scripts/harness_web/config.py +80 -0
  81. package/.pi/scripts/harness_web/output.py +55 -0
  82. package/.pi/scripts/harness_web/scrape.py +120 -0
  83. package/.pi/scripts/harness_web/search_ddg.py +106 -0
  84. package/.pi/scripts/release.sh +338 -0
  85. package/.pi/scripts/sentrux-rules-sync.mjs +29 -7
  86. package/.pi/settings.example.json +0 -1
  87. package/.sentrux/rules.toml +1 -1
  88. package/AGENTS.md +1 -1
  89. package/CHANGELOG.md +12 -0
  90. package/THIRD_PARTY_NOTICES.md +22 -0
  91. package/package.json +12 -9
  92. package/.agents/skills/firecrawl/SKILL.md +0 -150
  93. package/.agents/skills/firecrawl/rules/install.md +0 -82
  94. package/.agents/skills/firecrawl/rules/security.md +0 -26
  95. package/.agents/skills/firecrawl-agent/SKILL.md +0 -57
  96. package/.agents/skills/firecrawl-build-interact/SKILL.md +0 -67
  97. package/.agents/skills/firecrawl-build-onboarding/SKILL.md +0 -102
  98. package/.agents/skills/firecrawl-build-onboarding/references/auth-flow.md +0 -39
  99. package/.agents/skills/firecrawl-build-onboarding/references/project-setup.md +0 -20
  100. package/.agents/skills/firecrawl-build-onboarding/references/sdk-installation.md +0 -17
  101. package/.agents/skills/firecrawl-build-scrape/SKILL.md +0 -68
  102. package/.agents/skills/firecrawl-build-search/SKILL.md +0 -68
  103. package/.agents/skills/firecrawl-crawl/SKILL.md +0 -58
  104. package/.agents/skills/firecrawl-download/SKILL.md +0 -69
  105. package/.agents/skills/firecrawl-interact/SKILL.md +0 -83
  106. package/.agents/skills/firecrawl-map/SKILL.md +0 -50
  107. package/.agents/skills/firecrawl-parse/SKILL.md +0 -61
  108. package/.agents/skills/firecrawl-scrape/SKILL.md +0 -68
  109. package/.agents/skills/firecrawl-search/SKILL.md +0 -59
  110. package/firecrawl/.env.template +0 -62
  111. package/firecrawl/README.md +0 -49
  112. package/firecrawl/docker-compose.yaml +0 -201
  113. package/firecrawl/searxng/searxng.env +0 -3
  114. package/firecrawl/searxng/settings.yml +0 -85
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Recursive discovery: $UP_PKG/.pi/agents/** + project .pi/agents/** overrides.
3
+ */
4
+
5
+ import { createHash } from "node:crypto";
6
+ import { type Dirent, existsSync, readdirSync, readFileSync } from "node:fs";
7
+ import { join, relative } from "node:path";
8
+ import { getAgentDir } from "@mariozechner/pi-coding-agent";
9
+ import { parseAgentMarkdown } from "./agent-parser.js";
10
+ import type { AgentConfig } from "./vendored/types.js";
11
+
12
+ export type AgentSource = "package" | "project" | "global";
13
+
14
+ export interface DiscoveredAgentFile {
15
+ id: string;
16
+ path: string;
17
+ source: AgentSource;
18
+ content: string;
19
+ }
20
+
21
+ /** Reject path traversal and unsafe ids. */
22
+ export function isSafeAgentId(id: string): boolean {
23
+ if (!id || id.includes("..") || id.startsWith("/") || id.includes("\\")) {
24
+ return false;
25
+ }
26
+ return /^[a-zA-Z0-9][a-zA-Z0-9/_-]*$/.test(id);
27
+ }
28
+
29
+ function walkAgentsDir(
30
+ rootDir: string,
31
+ source: AgentSource,
32
+ out: Map<string, DiscoveredAgentFile>,
33
+ ): void {
34
+ if (!existsSync(rootDir)) return;
35
+
36
+ const stack: string[] = [rootDir];
37
+ while (stack.length > 0) {
38
+ const dir = stack.pop()!;
39
+ let entries: Dirent[];
40
+ try {
41
+ entries = readdirSync(dir, { withFileTypes: true });
42
+ } catch {
43
+ continue;
44
+ }
45
+
46
+ for (const entry of entries) {
47
+ const full = join(dir, entry.name);
48
+ if (entry.isDirectory()) {
49
+ stack.push(full);
50
+ continue;
51
+ }
52
+ if (!entry.name.endsWith(".md")) continue;
53
+
54
+ const rel = relative(rootDir, full).replace(/\\/g, "/");
55
+ const id = rel.replace(/\.md$/i, "");
56
+ if (!isSafeAgentId(id)) continue;
57
+
58
+ let content: string;
59
+ try {
60
+ content = readFileSync(full, "utf-8");
61
+ } catch {
62
+ continue;
63
+ }
64
+
65
+ out.set(id, { id, path: full, source, content });
66
+ }
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Discover agent files from package, global, and project (low → high priority).
72
+ */
73
+ export function discoverAgentFiles(
74
+ cwd: string,
75
+ packageRoot: string,
76
+ ): Map<string, DiscoveredAgentFile> {
77
+ const files = new Map<string, DiscoveredAgentFile>();
78
+
79
+ const packageAgents = join(packageRoot, ".pi", "agents");
80
+ const globalDir = join(getAgentDir(), "agents");
81
+ const projectDir = join(cwd, ".pi", "agents");
82
+
83
+ walkAgentsDir(packageAgents, "package", files);
84
+ walkAgentsDir(globalDir, "global", files);
85
+ walkAgentsDir(projectDir, "project", files);
86
+
87
+ return files;
88
+ }
89
+
90
+ /** Load merged AgentConfig map (project overrides package for same id). */
91
+ export function loadHarnessAgents(
92
+ cwd: string,
93
+ packageRoot: string,
94
+ ): Map<string, AgentConfig> {
95
+ const agents = new Map<string, AgentConfig>();
96
+ for (const file of discoverAgentFiles(cwd, packageRoot).values()) {
97
+ agents.set(file.id, parseAgentMarkdown(file.id, file.content, file.source));
98
+ }
99
+ return agents;
100
+ }
101
+
102
+ export function sha256Content(content: string): string {
103
+ return createHash("sha256").update(content, "utf8").digest("hex");
104
+ }
105
+
106
+ /** Package-only manifest entries (path → hash). */
107
+ export function loadPackageAgentHashes(
108
+ packageRoot: string,
109
+ ): Map<string, { path: string; sha256: string }> {
110
+ const packageAgents = join(packageRoot, ".pi", "agents");
111
+ const out = new Map<string, { path: string; sha256: string }>();
112
+ const files = new Map<string, DiscoveredAgentFile>();
113
+ walkAgentsDir(packageAgents, "package", files);
114
+ for (const f of files.values()) {
115
+ out.set(f.id, { path: f.path, sha256: sha256Content(f.content) });
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /** Legacy hook used by pi-subagents custom-agents.ts replacement. */
121
+ export function loadCustomAgents(
122
+ cwd: string,
123
+ packageRoot: string,
124
+ ): Map<string, AgentConfig> {
125
+ return loadHarnessAgents(cwd, packageRoot);
126
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * agents.manifest.json drift detection (package agents vs installed hashes).
3
+ */
4
+
5
+ import { readFileSync } from "node:fs";
6
+ import { join } from "node:path";
7
+ import {
8
+ type DiscoveredAgentFile,
9
+ loadPackageAgentHashes,
10
+ sha256Content,
11
+ } from "./agent-loader.js";
12
+
13
+ export interface ManifestEntry {
14
+ path: string;
15
+ sha256: string;
16
+ }
17
+
18
+ export interface AgentsManifest {
19
+ schema_version: string;
20
+ package: string;
21
+ package_version: string;
22
+ generated_at: string;
23
+ agents: Record<string, ManifestEntry>;
24
+ }
25
+
26
+ export interface DriftItem {
27
+ id: string;
28
+ kind: "missing_in_manifest" | "hash_mismatch" | "missing_on_disk";
29
+ expected?: string;
30
+ actual?: string;
31
+ }
32
+
33
+ export interface DriftReport {
34
+ ok: boolean;
35
+ packageVersion: string;
36
+ items: DriftItem[];
37
+ }
38
+
39
+ function readPackageVersion(packageRoot: string): string {
40
+ try {
41
+ const pkg = JSON.parse(
42
+ readFileSync(join(packageRoot, "package.json"), "utf-8"),
43
+ ) as { version?: string };
44
+ return pkg.version ?? "unknown";
45
+ } catch {
46
+ return "unknown";
47
+ }
48
+ }
49
+
50
+ export function readAgentsManifest(packageRoot: string): AgentsManifest | null {
51
+ const path = join(packageRoot, ".pi", "harness", "agents.manifest.json");
52
+ try {
53
+ return JSON.parse(readFileSync(path, "utf-8")) as AgentsManifest;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ export function getDriftReport(packageRoot: string): DriftReport {
60
+ const manifest = readAgentsManifest(packageRoot);
61
+ const onDisk = loadPackageAgentHashes(packageRoot);
62
+ const packageVersion = readPackageVersion(packageRoot);
63
+ const items: DriftItem[] = [];
64
+
65
+ if (!manifest) {
66
+ return {
67
+ ok: false,
68
+ packageVersion,
69
+ items: [{ id: "*", kind: "missing_on_disk" }],
70
+ };
71
+ }
72
+
73
+ for (const [id, entry] of onDisk) {
74
+ const expected = manifest.agents[id];
75
+ if (!expected) {
76
+ items.push({ id, kind: "missing_in_manifest" });
77
+ continue;
78
+ }
79
+ if (expected.sha256 !== entry.sha256) {
80
+ items.push({
81
+ id,
82
+ kind: "hash_mismatch",
83
+ expected: expected.sha256,
84
+ actual: entry.sha256,
85
+ });
86
+ }
87
+ }
88
+
89
+ for (const id of Object.keys(manifest.agents)) {
90
+ if (!onDisk.has(id)) {
91
+ items.push({ id, kind: "missing_on_disk" });
92
+ }
93
+ }
94
+
95
+ return { ok: items.length === 0, packageVersion, items };
96
+ }
97
+
98
+ export function buildManifestFromFiles(
99
+ files: Iterable<DiscoveredAgentFile>,
100
+ packageName: string,
101
+ packageVersion: string,
102
+ ): AgentsManifest {
103
+ const agents: Record<string, ManifestEntry> = {};
104
+ for (const f of files) {
105
+ if (f.source !== "package") continue;
106
+ const relPath = `.pi/agents/${f.id}.md`;
107
+ agents[f.id] = {
108
+ path: relPath,
109
+ sha256: sha256Content(f.content),
110
+ };
111
+ }
112
+ return {
113
+ schema_version: "1.0.0",
114
+ package: packageName,
115
+ package_version: packageVersion,
116
+ generated_at: new Date().toISOString(),
117
+ agents,
118
+ };
119
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Parse harness agent .md files into AgentConfig (path id = posix relative path).
3
+ */
4
+
5
+ import { parseFrontmatter } from "@mariozechner/pi-coding-agent";
6
+ import { BUILTIN_TOOL_NAMES } from "./vendored/agent-types.js";
7
+ import type {
8
+ AgentConfig,
9
+ MemoryScope,
10
+ ThinkingLevel,
11
+ } from "./vendored/types.js";
12
+
13
+ function str(val: unknown): string | undefined {
14
+ return typeof val === "string" ? val : undefined;
15
+ }
16
+
17
+ function nonNegativeInt(val: unknown): number | undefined {
18
+ return typeof val === "number" && val >= 0 ? val : undefined;
19
+ }
20
+
21
+ function parseCsvField(val: unknown): string[] | undefined {
22
+ if (val === undefined || val === null) return undefined;
23
+ const s = String(val).trim();
24
+ if (!s || s === "none") return undefined;
25
+ const items = s
26
+ .split(",")
27
+ .map((t) => t.trim())
28
+ .filter(Boolean);
29
+ return items.length > 0 ? items : undefined;
30
+ }
31
+
32
+ function csvList(val: unknown, defaults: string[]): string[] {
33
+ if (val === undefined || val === null) return defaults;
34
+ return parseCsvField(val) ?? [];
35
+ }
36
+
37
+ function csvListOptional(val: unknown): string[] | undefined {
38
+ return parseCsvField(val);
39
+ }
40
+
41
+ function parseMemory(val: unknown): MemoryScope | undefined {
42
+ if (val === "user" || val === "project" || val === "local") return val;
43
+ return undefined;
44
+ }
45
+
46
+ function inheritField(val: unknown): true | string[] | false {
47
+ if (val === undefined || val === null || val === true) return true;
48
+ if (val === false || val === "none") return false;
49
+ const items = csvList(val, []);
50
+ return items.length > 0 ? items : false;
51
+ }
52
+
53
+ export function parseAgentMarkdown(
54
+ agentId: string,
55
+ content: string,
56
+ source: "package" | "project" | "global",
57
+ ): AgentConfig {
58
+ const { frontmatter: fm, body } =
59
+ parseFrontmatter<Record<string, unknown>>(content);
60
+
61
+ const yamlName = str(fm.name);
62
+ const displayName = str(fm.display_name) ?? yamlName;
63
+
64
+ return {
65
+ name: agentId,
66
+ displayName,
67
+ description: str(fm.description) ?? agentId,
68
+ builtinToolNames: csvList(fm.tools, BUILTIN_TOOL_NAMES),
69
+ disallowedTools: csvListOptional(fm.disallowed_tools),
70
+ extensions: inheritField(fm.extensions ?? fm.inherit_extensions),
71
+ skills: inheritField(fm.skills ?? fm.inherit_skills),
72
+ model: str(fm.model),
73
+ thinking: str(fm.thinking) as ThinkingLevel | undefined,
74
+ maxTurns: nonNegativeInt(fm.max_turns),
75
+ systemPrompt: body.trim(),
76
+ promptMode: fm.prompt_mode === "append" ? "append" : "replace",
77
+ inheritContext:
78
+ fm.inherit_context != null ? fm.inherit_context === true : undefined,
79
+ runInBackground:
80
+ fm.run_in_background != null ? fm.run_in_background === true : undefined,
81
+ isolated: fm.isolated != null ? fm.isolated === true : undefined,
82
+ memory: parseMemory(fm.memory),
83
+ isolation: fm.isolation === "worktree" ? "worktree" : undefined,
84
+ enabled: fm.enabled !== false,
85
+ source: source === "package" ? "global" : source,
86
+ };
87
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Orchestrator blackboard tool (list/read/query/wait/delete).
3
+ */
4
+
5
+ import { defineTool, type ExtensionAPI } from "@mariozechner/pi-coding-agent";
6
+ import { Type } from "@sinclair/typebox";
7
+ import type { Blackboard } from "./blackboard.js";
8
+ import type { BlackboardQuery } from "./types-blackboard.js";
9
+
10
+ function textResult(text: string) {
11
+ return {
12
+ content: [{ type: "text" as const, text }],
13
+ details: {},
14
+ };
15
+ }
16
+
17
+ export function registerBlackboardTool(
18
+ pi: ExtensionAPI,
19
+ blackboard: Blackboard,
20
+ ): void {
21
+ pi.registerTool(
22
+ defineTool({
23
+ name: "blackboard",
24
+ label: "Blackboard",
25
+ description:
26
+ "Shared knowledge store for harness orchestration. Actions: list, read, query, wait, delete. " +
27
+ "Use namespaced keys (e.g. scout:findings). Spawn context injection is capped at ~8k chars.",
28
+ parameters: Type.Object({
29
+ action: Type.Union([
30
+ Type.Literal("list"),
31
+ Type.Literal("read"),
32
+ Type.Literal("query"),
33
+ Type.Literal("wait"),
34
+ Type.Literal("delete"),
35
+ ]),
36
+ key: Type.Optional(Type.String()),
37
+ pattern: Type.Optional(Type.String()),
38
+ agent_id: Type.Optional(Type.String()),
39
+ agent_name: Type.Optional(Type.String()),
40
+ category: Type.Optional(Type.String()),
41
+ timeout_ms: Type.Optional(
42
+ Type.Number({ description: "For wait action (default 30000)." }),
43
+ ),
44
+ }),
45
+ execute: async (_id, params) => {
46
+ const action = params.action as string;
47
+
48
+ if (action === "list") {
49
+ return textResult(blackboard.serialize());
50
+ }
51
+
52
+ if (action === "read") {
53
+ const key = params.key as string | undefined;
54
+ if (!key) return textResult("read requires key.");
55
+ const entry = blackboard.get(key);
56
+ if (!entry) {
57
+ return textResult(`No entry for key "${key}".`);
58
+ }
59
+ return textResult(JSON.stringify(entry, null, 2));
60
+ }
61
+
62
+ if (action === "query") {
63
+ const q: BlackboardQuery = {};
64
+ if (params.pattern) q.pattern = params.pattern as string;
65
+ if (params.agent_id) q.agentId = params.agent_id as string;
66
+ if (params.agent_name) q.agentName = params.agent_name as string;
67
+ if (params.category) q.category = params.category as string;
68
+ if (params.key) q.keys = [params.key as string];
69
+ return textResult(JSON.stringify(blackboard.toJSON(q), null, 2));
70
+ }
71
+
72
+ if (action === "delete") {
73
+ const key = params.key as string | undefined;
74
+ if (!key) return textResult("delete requires key.");
75
+ const removed = blackboard.delete(key);
76
+ return textResult(
77
+ removed ? `Deleted "${key}".` : `Key "${key}" not found.`,
78
+ );
79
+ }
80
+
81
+ if (action === "wait") {
82
+ const pattern = (params.pattern ?? params.key) as string | undefined;
83
+ if (!pattern) {
84
+ return textResult("wait requires pattern or key.");
85
+ }
86
+ const timeoutMs = (params.timeout_ms as number) ?? 30_000;
87
+ const start = Date.now();
88
+ while (Date.now() - start < timeoutMs) {
89
+ const matches = blackboard.query({ pattern });
90
+ if (matches.length > 0) {
91
+ return textResult(
92
+ JSON.stringify(blackboard.toJSON({ pattern }), null, 2),
93
+ );
94
+ }
95
+ await new Promise((r) => setTimeout(r, 200));
96
+ }
97
+ return textResult(`Timeout waiting for pattern "${pattern}".`);
98
+ }
99
+
100
+ return textResult("Unknown action.");
101
+ },
102
+ }),
103
+ );
104
+ }
105
+
106
+ export function buildBlackboardContextInjection(
107
+ blackboard: Blackboard,
108
+ spec?: { agentId?: string; keys?: string[]; agentName?: string },
109
+ ): string | undefined {
110
+ if (!spec) return undefined;
111
+ const q: BlackboardQuery = {};
112
+ if (spec.agentId) q.agentId = spec.agentId;
113
+ if (spec.agentName) q.agentName = spec.agentName;
114
+ if (spec.keys?.length) q.keys = spec.keys;
115
+ const serialized = blackboard.serialize(q);
116
+ if (serialized === "(blackboard is empty)") return undefined;
117
+ return serialized;
118
+ }
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Shared blackboard for orchestrator ↔ subagent handoffs (~8k injection cap).
3
+ */
4
+
5
+ import type {
6
+ BlackboardEntry,
7
+ BlackboardQuery,
8
+ PostMetadata,
9
+ } from "./types-blackboard.js";
10
+
11
+ const MAX_VALUE_DISPLAY_CHARS = 500;
12
+ export const MAX_SERIALIZE_TOTAL_CHARS = 8_000;
13
+
14
+ function truncateForDisplay(value: unknown): string {
15
+ const str =
16
+ typeof value === "string" ? value : JSON.stringify(value, null, 2);
17
+ if (str.length <= MAX_VALUE_DISPLAY_CHARS) return str;
18
+ return `${str.slice(0, MAX_VALUE_DISPLAY_CHARS)}...(truncated)`;
19
+ }
20
+
21
+ type PostHandler = (key: string, entry: BlackboardEntry) => void;
22
+
23
+ export class Blackboard {
24
+ private entries = new Map<string, BlackboardEntry>();
25
+ private postHandlers: PostHandler[] = [];
26
+
27
+ post(
28
+ namespacedKey: string,
29
+ value: unknown,
30
+ agentId: string,
31
+ agentName: string,
32
+ metadata?: PostMetadata,
33
+ ): void {
34
+ if (metadata?.supersedes) {
35
+ this.entries.delete(metadata.supersedes);
36
+ }
37
+
38
+ const entry: BlackboardEntry = {
39
+ key: namespacedKey,
40
+ value,
41
+ agentId,
42
+ agentName,
43
+ timestamp: Date.now(),
44
+ metadata,
45
+ };
46
+
47
+ this.entries.set(namespacedKey, entry);
48
+
49
+ for (const handler of this.postHandlers) {
50
+ try {
51
+ handler(namespacedKey, entry);
52
+ } catch {
53
+ /* ignore */
54
+ }
55
+ }
56
+ }
57
+
58
+ get(key: string): BlackboardEntry | undefined {
59
+ return this.entries.get(key);
60
+ }
61
+
62
+ getAll(): Map<string, BlackboardEntry> {
63
+ return new Map(this.entries);
64
+ }
65
+
66
+ query(query: BlackboardQuery): BlackboardEntry[] {
67
+ let results = [...this.entries.values()];
68
+
69
+ if (query.keys?.length) {
70
+ results = results.filter((e) => query.keys?.includes(e.key));
71
+ }
72
+
73
+ if (query.pattern) {
74
+ const pat = query.pattern;
75
+ if (pat instanceof RegExp) {
76
+ results = results.filter((e) => pat.test(e.key));
77
+ } else {
78
+ const escaped = pat.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
79
+ const re = new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);
80
+ results = results.filter((e) => re.test(e.key) || e.key.includes(pat));
81
+ }
82
+ }
83
+
84
+ if (query.agentId) {
85
+ results = results.filter((e) => e.agentId === query.agentId);
86
+ }
87
+ if (query.agentName) {
88
+ results = results.filter((e) => e.agentName === query.agentName);
89
+ }
90
+ if (query.category) {
91
+ results = results.filter((e) => e.metadata?.category === query.category);
92
+ }
93
+ if (query.after !== undefined) {
94
+ results = results.filter((e) => e.timestamp > query.after!);
95
+ }
96
+
97
+ return results;
98
+ }
99
+
100
+ serialize(query?: BlackboardQuery): string {
101
+ const entries = query ? this.query(query) : [...this.entries.values()];
102
+
103
+ if (entries.length === 0) return "(blackboard is empty)";
104
+
105
+ const lines: string[] = [`Blackboard (${entries.length} entries):`];
106
+ let totalChars = lines[0].length;
107
+
108
+ for (const entry of entries) {
109
+ const summary = entry.metadata?.summary
110
+ ? entry.metadata.summary
111
+ : truncateForDisplay(entry.value);
112
+ const category = entry.metadata?.category
113
+ ? ` [${entry.metadata.category}]`
114
+ : "";
115
+ const ts = new Date(entry.timestamp).toISOString().slice(11, 19);
116
+ const keyLine = ` ${entry.key}${category} (${entry.agentName} @ ${ts})`;
117
+ const valLine = ` ${summary}`;
118
+ const entryChars = keyLine.length + valLine.length + 2;
119
+
120
+ if (totalChars + entryChars > MAX_SERIALIZE_TOTAL_CHARS) {
121
+ lines.push(
122
+ " ... (more entries truncated — use blackboard query with specific keys)",
123
+ );
124
+ break;
125
+ }
126
+ lines.push(keyLine, valLine);
127
+ totalChars += entryChars;
128
+ }
129
+
130
+ return lines.join("\n");
131
+ }
132
+
133
+ toJSON(query?: BlackboardQuery): object {
134
+ const entries = query ? this.query(query) : [...this.entries.values()];
135
+ return {
136
+ count: entries.length,
137
+ entries: entries.map((e) => ({
138
+ key: e.key,
139
+ agentId: e.agentId,
140
+ agentName: e.agentName,
141
+ timestamp: e.timestamp,
142
+ summary: e.metadata?.summary ?? null,
143
+ category: e.metadata?.category ?? null,
144
+ value: e.value,
145
+ })),
146
+ };
147
+ }
148
+
149
+ clear(): void {
150
+ this.entries.clear();
151
+ }
152
+
153
+ restore(data: {
154
+ key: string;
155
+ value: unknown;
156
+ agentId: string;
157
+ agentName: string;
158
+ timestamp: number;
159
+ metadata?: PostMetadata;
160
+ }): void {
161
+ this.entries.set(data.key, { ...data });
162
+ }
163
+
164
+ delete(key: string): boolean {
165
+ return this.entries.delete(key);
166
+ }
167
+
168
+ get size(): number {
169
+ return this.entries.size;
170
+ }
171
+
172
+ on(event: "post", handler: PostHandler): void {
173
+ if (event === "post") this.postHandlers.push(handler);
174
+ }
175
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Subagent tool policy — block nested orchestration tools (defense in depth).
3
+ */
4
+
5
+ export const SUBAGENT_BLOCKED_TOOLS = new Set([
6
+ "Agent",
7
+ "get_subagent_result",
8
+ "steer_subagent",
9
+ "blackboard",
10
+ "ask_user",
11
+ ]);
12
+
13
+ export interface ToolCallDecision {
14
+ action: "allow" | "block" | "modify";
15
+ reason?: string;
16
+ newArgs?: Record<string, unknown>;
17
+ }
18
+
19
+ export function evaluateSubagentToolCall(toolName: string): ToolCallDecision {
20
+ if (SUBAGENT_BLOCKED_TOOLS.has(toolName)) {
21
+ return {
22
+ action: "block",
23
+ reason: `Tool "${toolName}" is not available in subagent sessions (single spawn depth).`,
24
+ };
25
+ }
26
+ return { action: "allow" };
27
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Blackboard types (ported from subagent-v2 reference; MIT design reference).
3
+ */
4
+
5
+ export interface PostMetadata {
6
+ summary?: string;
7
+ category?: string;
8
+ supersedes?: string;
9
+ }
10
+
11
+ export interface BlackboardEntry {
12
+ key: string;
13
+ value: unknown;
14
+ agentId: string;
15
+ agentName: string;
16
+ timestamp: number;
17
+ metadata?: PostMetadata;
18
+ }
19
+
20
+ export interface BlackboardQuery {
21
+ keys?: string[];
22
+ pattern?: string | RegExp;
23
+ agentId?: string;
24
+ agentName?: string;
25
+ category?: string;
26
+ after?: number;
27
+ }