@kkelly-offical/kkcode 0.1.3 → 0.1.6

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 (58) hide show
  1. package/README.md +110 -172
  2. package/package.json +46 -46
  3. package/src/agent/agent.mjs +41 -0
  4. package/src/agent/prompt/frontend-designer.txt +58 -0
  5. package/src/agent/prompt/longagent-blueprint-agent.txt +83 -0
  6. package/src/agent/prompt/longagent-coding-agent.txt +37 -0
  7. package/src/agent/prompt/longagent-debugging-agent.txt +46 -0
  8. package/src/agent/prompt/longagent-preview-agent.txt +63 -0
  9. package/src/config/defaults.mjs +260 -195
  10. package/src/config/schema.mjs +71 -6
  11. package/src/core/constants.mjs +91 -46
  12. package/src/index.mjs +1 -1
  13. package/src/knowledge/frontend-aesthetics.txt +39 -0
  14. package/src/knowledge/loader.mjs +2 -1
  15. package/src/knowledge/tailwind.txt +12 -3
  16. package/src/mcp/client-http.mjs +141 -157
  17. package/src/mcp/client-sse.mjs +288 -286
  18. package/src/mcp/client-stdio.mjs +533 -451
  19. package/src/mcp/constants.mjs +2 -0
  20. package/src/mcp/registry.mjs +479 -394
  21. package/src/mcp/stdio-framing.mjs +133 -127
  22. package/src/mcp/tool-result.mjs +24 -0
  23. package/src/observability/index.mjs +42 -0
  24. package/src/observability/metrics.mjs +137 -0
  25. package/src/observability/tracer.mjs +137 -0
  26. package/src/orchestration/background-manager.mjs +372 -358
  27. package/src/orchestration/background-worker.mjs +305 -245
  28. package/src/orchestration/longagent-manager.mjs +171 -116
  29. package/src/orchestration/stage-scheduler.mjs +728 -489
  30. package/src/permission/exec-policy.mjs +9 -11
  31. package/src/provider/anthropic.mjs +1 -0
  32. package/src/provider/openai.mjs +340 -339
  33. package/src/provider/retry-policy.mjs +68 -68
  34. package/src/provider/router.mjs +241 -228
  35. package/src/provider/sse.mjs +104 -91
  36. package/src/repl.mjs +1 -1
  37. package/src/session/checkpoint.mjs +66 -3
  38. package/src/session/engine.mjs +227 -225
  39. package/src/session/longagent-4stage.mjs +460 -0
  40. package/src/session/longagent-hybrid.mjs +1081 -0
  41. package/src/session/longagent-plan.mjs +365 -329
  42. package/src/session/longagent-project-memory.mjs +53 -0
  43. package/src/session/longagent-scaffold.mjs +291 -100
  44. package/src/session/longagent-task-bus.mjs +54 -0
  45. package/src/session/longagent-utils.mjs +472 -0
  46. package/src/session/longagent.mjs +884 -1462
  47. package/src/session/project-context.mjs +30 -0
  48. package/src/session/store.mjs +510 -503
  49. package/src/session/task-validator.mjs +4 -3
  50. package/src/skill/builtin/design.mjs +76 -0
  51. package/src/skill/builtin/frontend.mjs +8 -0
  52. package/src/skill/registry.mjs +390 -336
  53. package/src/storage/ghost-commit-store.mjs +18 -8
  54. package/src/tool/executor.mjs +11 -0
  55. package/src/tool/git-auto.mjs +0 -19
  56. package/src/tool/registry.mjs +71 -37
  57. package/src/ui/activity-renderer.mjs +664 -410
  58. package/src/util/git.mjs +23 -0
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Project Memory — 跨会话项目级知识持久化
3
+ * 存储在 .kkcode/project-memory.json,记住技术栈、惯用模式等
4
+ */
5
+ import { readFile, writeFile, mkdir } from "node:fs/promises"
6
+ import path from "node:path"
7
+
8
+ const MEMORY_FILE = ".kkcode/project-memory.json"
9
+
10
+ export async function loadProjectMemory(cwd) {
11
+ try {
12
+ const raw = await readFile(path.join(cwd, MEMORY_FILE), "utf-8")
13
+ return JSON.parse(raw)
14
+ } catch {
15
+ return { techStack: [], patterns: [], conventions: [], lastUpdated: null }
16
+ }
17
+ }
18
+
19
+ export async function saveProjectMemory(cwd, memory) {
20
+ const filePath = path.join(cwd, MEMORY_FILE)
21
+ await mkdir(path.dirname(filePath), { recursive: true })
22
+ memory.lastUpdated = new Date().toISOString()
23
+ await writeFile(filePath, JSON.stringify(memory, null, 2), "utf-8")
24
+ }
25
+
26
+ export function memoryToContext(memory) {
27
+ const ts = Array.isArray(memory?.techStack) ? memory.techStack : []
28
+ const pt = Array.isArray(memory?.patterns) ? memory.patterns : []
29
+ const cv = Array.isArray(memory?.conventions) ? memory.conventions : []
30
+ if (!ts.length && !pt.length) return ""
31
+ const lines = ["### Project Memory (from previous sessions)"]
32
+ if (ts.length) lines.push(`Tech stack: ${ts.join(", ")}`)
33
+ if (pt.length) lines.push(`Patterns: ${pt.join(", ")}`)
34
+ if (cv.length) lines.push(`Conventions: ${cv.join(", ")}`)
35
+ return lines.join("\n")
36
+ }
37
+
38
+ export function parseMemoryFromPreview(text) {
39
+ const memory = { techStack: [], patterns: [], conventions: [] }
40
+ // Only match lines that clearly declare tech stack (require colon separator)
41
+ const techMatch = text.match(/(?:tech\s*stack|技术栈|frameworks?|主要语言|dependencies)\s*[::]\s*([^\n]+)/gi)
42
+ if (techMatch) {
43
+ for (const m of techMatch) {
44
+ const items = m.replace(/^[^::]+[::]/, "").split(/[,,、;;]/).map(s => s.trim()).filter(s => {
45
+ // Filter out overly generic or long items (likely false positives)
46
+ return s.length >= 2 && s.length <= 40 && !/^\d+$/.test(s)
47
+ })
48
+ memory.techStack.push(...items)
49
+ }
50
+ }
51
+ memory.techStack = [...new Set(memory.techStack)].slice(0, 20)
52
+ return memory
53
+ }
@@ -1,100 +1,291 @@
1
- import { processTurnLoop } from "./loop.mjs"
2
- import { EventBus } from "../core/events.mjs"
3
- import { EVENT_TYPES } from "../core/constants.mjs"
4
-
5
- function buildScaffoldPrompt(objective, stagePlan) {
6
- const allFiles = new Set()
7
- const taskSpecs = []
8
-
9
- for (const stage of stagePlan.stages || []) {
10
- for (const task of stage.tasks || []) {
11
- for (const file of task.plannedFiles || []) {
12
- allFiles.add(file)
13
- }
14
- taskSpecs.push({
15
- taskId: task.taskId,
16
- prompt: task.prompt,
17
- plannedFiles: task.plannedFiles,
18
- acceptance: task.acceptance
19
- })
20
- }
21
- }
22
-
23
- const fileList = [...allFiles].sort()
24
- if (!fileList.length) return null
25
-
26
- return [
27
- "You are in SCAFFOLDING mode. Your job is to create stub files that define contracts for parallel implementation agents.",
28
- "",
29
- `## Objective: ${objective}`,
30
- "",
31
- "## Files to scaffold:",
32
- ...fileList.map((f) => `- ${f}`),
33
- "",
34
- "## Task specifications (for context):",
35
- JSON.stringify(taskSpecs, null, 2),
36
- "",
37
- "## Scaffolding rules:",
38
- "1. Create EVERY file listed above using the `write` tool.",
39
- "2. For Python files: write function/class signatures with docstrings describing inputs, outputs, and behavior. Use `pass` or `...` as body.",
40
- "3. For Vue/React components: write component stubs with props/events/slots documented in comments. Include the component shell structure.",
41
- "4. For TypeScript/JavaScript: write export signatures with JSDoc or TSDoc describing the interface contract.",
42
- "5. For config/data files: write the expected schema structure with placeholder values and comments.",
43
- "6. For test files: write test suite structure with describe/it blocks and comments describing what each test should verify.",
44
- "7. Each file MUST have a header comment explaining: purpose, dependencies, interfaces it implements/exports.",
45
- "8. Do NOT implement business logic. Only define the contract (signatures, types, interfaces).",
46
- "9. Include import statements that reference other scaffolded files so the dependency graph is explicit.",
47
- "10. When done with ALL files, say [SCAFFOLD_COMPLETE].",
48
- "",
49
- "Start creating all stub files now."
50
- ].join("\n")
51
- }
52
-
53
- export async function runScaffoldPhase({
54
- objective,
55
- stagePlan,
56
- model,
57
- providerType,
58
- sessionId,
59
- configState,
60
- baseUrl = null,
61
- apiKeyEnv = null,
62
- agent = null,
63
- signal = null,
64
- toolContext = {}
65
- }) {
66
- const prompt = buildScaffoldPrompt(objective, stagePlan)
67
- if (!prompt) {
68
- return { scaffolded: false, fileCount: 0, files: [], errors: [] }
69
- }
70
-
71
- const out = await processTurnLoop({
72
- prompt,
73
- mode: "agent",
74
- model,
75
- providerType,
76
- sessionId,
77
- configState,
78
- baseUrl,
79
- apiKeyEnv,
80
- agent,
81
- signal,
82
- allowQuestion: false,
83
- toolContext
84
- })
85
-
86
- // Extract files created from tool events
87
- const createdFiles = (out.toolEvents || [])
88
- .filter((e) => e.name === "write" && e.status === "completed")
89
- .map((e) => e.args?.path)
90
- .filter(Boolean)
91
-
92
- return {
93
- scaffolded: true,
94
- fileCount: createdFiles.length,
95
- files: createdFiles,
96
- usage: out.usage,
97
- toolEvents: out.toolEvents,
98
- errors: []
99
- }
100
- }
1
+ import { processTurnLoop } from "./loop.mjs"
2
+ import { EventBus } from "../core/events.mjs"
3
+ import { EVENT_TYPES } from "../core/constants.mjs"
4
+ import { stat } from "node:fs/promises"
5
+ import path from "node:path"
6
+
7
+ function buildScaffoldPrompt(objective, stagePlan) {
8
+ const tasksByFile = new Map()
9
+ const taskSpecs = []
10
+
11
+ for (const stage of stagePlan.stages || []) {
12
+ for (const task of stage.tasks || []) {
13
+ for (const file of task.plannedFiles || []) {
14
+ tasksByFile.set(file, { taskId: task.taskId, stageId: stage.stageId, prompt: task.prompt, acceptance: task.acceptance })
15
+ }
16
+ taskSpecs.push({ taskId: task.taskId, stageId: stage.stageId, prompt: task.prompt, plannedFiles: task.plannedFiles, acceptance: task.acceptance })
17
+ }
18
+ }
19
+
20
+ const fileList = [...tasksByFile.keys()].sort()
21
+ if (!fileList.length) return null
22
+
23
+ const fileContext = fileList.map((f) => {
24
+ const t = tasksByFile.get(f)
25
+ return `- ${f} (task: ${t.taskId}, stage: ${t.stageId})`
26
+ })
27
+
28
+ return [
29
+ "You are the ARCHITECT agent for a production-grade parallel coding pipeline.",
30
+ "Your job: create ALL project files as detailed scaffolds that guide independent sub-agents to produce compatible, integrable code.",
31
+ "",
32
+ "CRITICAL CONTEXT: Each sub-agent works in ISOLATION. It can only see:",
33
+ "- The scaffold file you create (with your inline comments)",
34
+ "- Its task prompt and file ownership list",
35
+ "- Files created by PREVIOUS stages (not the current stage)",
36
+ "Your scaffold is the sub-agent's PRIMARY source of truth. Ambiguous or incomplete scaffolds cause integration failures.",
37
+ "",
38
+ "## Objective",
39
+ objective,
40
+ "",
41
+ "## Files to create:",
42
+ ...fileContext,
43
+ "",
44
+ "## Task plan (each task assigned to an independent sub-agent):",
45
+ JSON.stringify(taskSpecs, null, 2),
46
+ "",
47
+ "## Scaffold Specification (follow EXACTLY)",
48
+ "",
49
+ "Create EVERY file listed above using the `write` tool. Each file MUST contain:",
50
+ "",
51
+ "### 1. File Header Block",
52
+ "```",
53
+ "// FILE: <relative path>",
54
+ "// PURPOSE: <one-sentence description of this file's responsibility>",
55
+ "// DEPENDS ON: <list of files this imports from, with what symbols>",
56
+ "// USED BY: <list of files that import from this>",
57
+ "// OWNER: task <taskId> | stage <stageId>",
58
+ "```",
59
+ "",
60
+ "### 2. Complete Import Statements",
61
+ "- Write ALL import/require statements with CORRECT relative paths",
62
+ "- Include the exact symbol names being imported: `import { foo, bar } from './module.mjs'`",
63
+ "- This is the dependency contract — sub-agents rely on these paths being accurate",
64
+ "- If importing from a file owned by a DIFFERENT task in the same stage, add a comment: `// CROSS-TASK: implemented by <taskId>`",
65
+ "",
66
+ "### 3. Exported API Surface",
67
+ "- Declare ALL exports with full signatures (function name, parameters with types, return type)",
68
+ "- For each export, add a one-line JSDoc/docstring describing its contract",
69
+ "- This is the integration contract — other files depend on these exact signatures",
70
+ "",
71
+ "### 4. Implementation Blueprint (THE CORE)",
72
+ "For every function, class, method, handler, route:",
73
+ "- Write the complete signature/declaration",
74
+ "- Inside the body, write NUMBERED STEP comments describing:",
75
+ " 1. Input validation: what to check, what errors to throw for invalid input",
76
+ " 2. Core algorithm: step-by-step logic flow with concrete details",
77
+ " 3. Data transformations: input shape → processing → output shape",
78
+ " 4. Error handling: what to catch, what to throw, what to log",
79
+ " 5. Side effects: DB writes, API calls, event emissions, file I/O",
80
+ " 6. Return value: exact shape and type of the return value",
81
+ "",
82
+ "### 5. Strict Prohibitions",
83
+ "- Do NOT write actual implementation code — only signatures + comment blueprints",
84
+ "- Do NOT write vague placeholders like `// TODO` or `pass` without detailed steps",
85
+ "- Do NOT skip any file — every file in the list MUST be created",
86
+ "- Do NOT invent files not in the plan — only create files listed above",
87
+ "- Do NOT use generic comments like 'handle errors' — specify WHICH errors and HOW",
88
+ "",
89
+ "### Language-specific patterns",
90
+ "",
91
+ "**JavaScript/TypeScript:**",
92
+ "```js",
93
+ "// FILE: src/auth/jwt.mjs",
94
+ "// PURPOSE: JWT token generation and verification",
95
+ "// DEPENDS ON: src/config/env.mjs (reads JWT_SECRET)",
96
+ "// USED BY: src/middleware/auth.mjs, src/routes/login.mjs",
97
+ "// TASK: s1_auth | STAGE: s1",
98
+ "",
99
+ "import { getEnv } from '../config/env.mjs'",
100
+ "",
101
+ "export function generateToken(userId, role) {",
102
+ " // 1. Read JWT_SECRET from getEnv('JWT_SECRET')",
103
+ " // 2. Build payload: { sub: userId, role, iat: now, exp: now + 24h }",
104
+ " // 3. Sign with HS256 algorithm using jsonwebtoken.sign()",
105
+ " // 4. Return the signed token string",
106
+ " // ERROR: throw if JWT_SECRET is missing",
107
+ "}",
108
+ "```",
109
+ "",
110
+ "**Python:**",
111
+ "```python",
112
+ "# FILE: app/services/user_service.py",
113
+ "# PURPOSE: User CRUD operations",
114
+ "# DEPENDS ON: app/models/user.py, app/db/session.py",
115
+ "# USED BY: app/routes/users.py",
116
+ "# TASK: s1_users | STAGE: s1",
117
+ "",
118
+ "from app.models.user import User",
119
+ "from app.db.session import get_db",
120
+ "",
121
+ "async def create_user(email: str, password: str) -> User:",
122
+ " # 1. Validate email format with regex",
123
+ " # 2. Check if email already exists in DB → raise DuplicateError",
124
+ " # 3. Hash password with bcrypt (12 rounds)",
125
+ " # 4. Insert new User record into DB",
126
+ " # 5. Return the created User object (without password hash)",
127
+ " pass",
128
+ "```",
129
+ "",
130
+ "**React/Vue components:**",
131
+ "```jsx",
132
+ "// FILE: src/components/UserList.tsx",
133
+ "// PURPOSE: Paginated user list with search and sort",
134
+ "// DEPENDS ON: src/api/users.ts, src/components/Pagination.tsx",
135
+ "// USED BY: src/pages/AdminDashboard.tsx",
136
+ "// TASK: s2_ui | STAGE: s2",
137
+ "",
138
+ "// PROPS: { pageSize?: number, onSelect: (user) => void }",
139
+ "// STATE: users[], loading, error, searchQuery, sortField, currentPage",
140
+ "// EFFECTS:",
141
+ "// - On mount + searchQuery/sortField/page change → fetch users from API",
142
+ "// - Debounce search input by 300ms",
143
+ "// RENDER:",
144
+ "// - Search input at top",
145
+ "// - Table with columns: name, email, role, created_at (all sortable)",
146
+ "// - Loading skeleton while fetching",
147
+ "// - Error banner with retry button",
148
+ "// - Pagination component at bottom",
149
+ "// STYLE:",
150
+ "// - Use project's CSS framework (Tailwind/CSS vars) — read config first",
151
+ "// - Hover states on table rows, focus ring on search input",
152
+ "// - Consistent spacing from project's design tokens",
153
+ "```",
154
+ "",
155
+ "## Tool Usage Rules",
156
+ "- USE `write` to create each file — this is your PRIMARY and MAIN tool",
157
+ "- USE `read` ONLY to check existing project files (package.json, tsconfig.json, existing modules) for conventions and patterns",
158
+ "- Do NOT use `edit`, `bash`, `grep`, or `glob` — you are creating new scaffolds, not modifying existing code",
159
+ "- Create files in dependency order: shared types/interfaces first, then modules that import them",
160
+ "",
161
+ "## Quality Checklist (verify before completing)",
162
+ "- [ ] Every file in the list has been created",
163
+ "- [ ] All import paths are correct relative paths",
164
+ "- [ ] All exported function signatures include parameter names and types",
165
+ "- [ ] Every function body has numbered step comments (not just '// implement')",
166
+ "- [ ] Cross-task dependencies are marked with `// CROSS-TASK: implemented by <taskId>`",
167
+ "- [ ] File headers include DEPENDS ON and USED BY sections",
168
+ "",
169
+ "## Completion",
170
+ "When ALL files are created and the checklist is satisfied, say [SCAFFOLD_COMPLETE].",
171
+ "",
172
+ "Start now. Create files in dependency order (shared types first, then consumers)."
173
+ ].join("\n")
174
+ }
175
+
176
+ function buildTddScaffoldPrompt(objective, stagePlan) {
177
+ const taskSpecs = []
178
+ const allFiles = new Set()
179
+ for (const stage of stagePlan.stages || []) {
180
+ for (const task of stage.tasks || []) {
181
+ taskSpecs.push({ taskId: task.taskId, stageId: stage.stageId, prompt: task.prompt, plannedFiles: task.plannedFiles, acceptance: task.acceptance })
182
+ for (const f of task.plannedFiles || []) allFiles.add(f)
183
+ }
184
+ }
185
+ if (!allFiles.size) return null
186
+
187
+ return [
188
+ "You are the TDD ARCHITECT agent for a production-grade parallel coding pipeline.",
189
+ "Your job: create TEST FILES FIRST to define the contract, then implementation scaffolds with inline blueprints.",
190
+ "",
191
+ "## Objective",
192
+ objective,
193
+ "",
194
+ "## Task plan:",
195
+ JSON.stringify(taskSpecs, null, 2),
196
+ "",
197
+ "## TDD Workflow (strict order)",
198
+ "",
199
+ "For EACH planned source file, create TWO files in this order:",
200
+ "",
201
+ "### Step 1: Test File",
202
+ "- Create the test file BEFORE the implementation file",
203
+ "- Write concrete test cases derived from the task's acceptance criteria",
204
+ "- Each test must have: descriptive name, setup, action, assertion",
205
+ "- Cover: happy path, error cases, edge cases (null/empty/invalid input), boundary conditions",
206
+ "- Tests should be runnable but FAIL (because implementation is a stub)",
207
+ "- Import the source module using the correct relative path",
208
+ "",
209
+ "### Step 2: Implementation Scaffold",
210
+ "- Create the source file with full signatures + numbered step comments (same as normal scaffold)",
211
+ "- Functions should have minimal stub bodies (throw or return placeholder) so tests can import them",
212
+ "",
213
+ "## Test File Naming Convention",
214
+ "- JS/TS: `<name>.test.mjs` or `<name>.spec.ts` (match project convention)",
215
+ "- Python: `test_<name>.py` in same directory or `tests/` directory",
216
+ "- Check existing test files in the project to match the convention",
217
+ "",
218
+ "## Completion",
219
+ "When ALL files (tests + stubs) are created, say [SCAFFOLD_COMPLETE].",
220
+ "",
221
+ "Start now. Create test files first, then implementation stubs."
222
+ ].join("\n")
223
+ }
224
+
225
+ export async function runScaffoldPhase({
226
+ objective,
227
+ stagePlan,
228
+ model,
229
+ providerType,
230
+ sessionId,
231
+ configState,
232
+ baseUrl = null,
233
+ apiKeyEnv = null,
234
+ agent = null,
235
+ signal = null,
236
+ toolContext = {},
237
+ tddMode = false
238
+ }) {
239
+ const prompt = tddMode
240
+ ? buildTddScaffoldPrompt(objective, stagePlan)
241
+ : buildScaffoldPrompt(objective, stagePlan)
242
+ if (!prompt) {
243
+ return { scaffolded: false, fileCount: 0, files: [], errors: [] }
244
+ }
245
+
246
+ const out = await processTurnLoop({
247
+ prompt,
248
+ mode: "agent",
249
+ model,
250
+ providerType,
251
+ sessionId,
252
+ configState,
253
+ baseUrl,
254
+ apiKeyEnv,
255
+ agent,
256
+ signal,
257
+ allowQuestion: false,
258
+ toolContext
259
+ })
260
+
261
+ // Extract files created from tool events
262
+ const createdFiles = (out.toolEvents || [])
263
+ .filter((e) => e.name === "write" && e.status === "completed")
264
+ .map((e) => e.args?.path)
265
+ .filter(Boolean)
266
+
267
+ // Verify files actually exist on disk
268
+ const verified = []
269
+ const missing = []
270
+ for (const file of createdFiles) {
271
+ const abs = path.isAbsolute(file) ? file : path.join(process.cwd(), file)
272
+ try {
273
+ await stat(abs)
274
+ verified.push(file)
275
+ } catch {
276
+ missing.push(file)
277
+ }
278
+ }
279
+
280
+ return {
281
+ scaffolded: true,
282
+ fileCount: verified.length,
283
+ files: verified,
284
+ missingFiles: missing,
285
+ usage: out.usage,
286
+ toolEvents: out.toolEvents,
287
+ errors: missing.length > 0
288
+ ? [`${missing.length} file(s) reported created but not found on disk: ${missing.slice(0, 5).join(", ")}`]
289
+ : []
290
+ }
291
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Task Bus — 并行 task 间的轻量通信机制
3
+ * task 可以发布消息(接口变更、共享数据),其他 task 通过 priorContext 读取
4
+ */
5
+
6
+ export class TaskBus {
7
+ constructor({ maxMessages = 500 } = {}) {
8
+ this._messages = []
9
+ this._shared = {}
10
+ this._maxMessages = maxMessages
11
+ }
12
+
13
+ publish(taskId, key, value) {
14
+ this._messages.push({ taskId, key, value, ts: Date.now() })
15
+ // Evict oldest messages when exceeding capacity
16
+ if (this._messages.length > this._maxMessages) {
17
+ this._messages = this._messages.slice(-Math.round(this._maxMessages * 0.8))
18
+ }
19
+ this._shared[key] = { value, from: taskId, ts: Date.now() }
20
+ }
21
+
22
+ get(key) {
23
+ return this._shared[key]?.value ?? null
24
+ }
25
+
26
+ snapshot() {
27
+ return { ...this._shared }
28
+ }
29
+
30
+ toContextString(maxLen = 2000) {
31
+ const entries = Object.entries(this._shared)
32
+ if (!entries.length) return ""
33
+ const lines = ["### Task Bus (shared context)"]
34
+ for (const [key, { value, from }] of entries) {
35
+ const val = typeof value === "string" ? value : JSON.stringify(value)
36
+ lines.push(`- [${from}] ${key}: ${val.slice(0, 200)}`)
37
+ }
38
+ const result = lines.join("\n")
39
+ return result.length > maxLen ? result.slice(0, maxLen) + "\n..." : result
40
+ }
41
+
42
+ parseTaskOutput(taskId, text) {
43
+ const pattern = /\[TASK_BROADCAST:\s*(\w+)\s*=\s*(.*?)\]/g
44
+ let match
45
+ while ((match = pattern.exec(text)) !== null) {
46
+ this.publish(taskId, match[1], match[2].trim())
47
+ }
48
+ }
49
+
50
+ clear() {
51
+ this._messages = []
52
+ this._shared = {}
53
+ }
54
+ }