Merge remote-tracking branch 'origin/dev' into fix/cli-run-premature-exit-with-background-tasks
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
# src/features/ — 19 Feature Modules
|
||||
|
||||
**Generated:** 2026-04-11
|
||||
**Generated:** 2026-04-18
|
||||
|
||||
## OVERVIEW
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ Both must agree before marking a task complete. Prevents premature completion on
|
||||
|
||||
## CONCURRENCY MODEL
|
||||
|
||||
- Key format: `{providerID}/{modelID}` (e.g., `anthropic/claude-opus-4-6`)
|
||||
- Key format: `{providerID}/{modelID}` (e.g., `anthropic/claude-opus-4-7`)
|
||||
- Default limit: 5 concurrent per key (configurable via `background_task` config)
|
||||
- FIFO queue: tasks wait in order when slots full
|
||||
- Slot released on: completion, error, cancellation
|
||||
|
||||
@@ -83,7 +83,7 @@ describe("findNearestMessageExcludingCompaction", () => {
|
||||
// given
|
||||
const message = {
|
||||
agent: "sisyphus",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-7" },
|
||||
}
|
||||
writeFileSync(join(tempDir, "001.json"), JSON.stringify(message))
|
||||
|
||||
@@ -94,18 +94,18 @@ describe("findNearestMessageExcludingCompaction", () => {
|
||||
expect(result).not.toBeNull()
|
||||
expect(result?.agent).toBe("sisyphus")
|
||||
expect(result?.model?.providerID).toBe("anthropic")
|
||||
expect(result?.model?.modelID).toBe("claude-opus-4-6")
|
||||
expect(result?.model?.modelID).toBe("claude-opus-4-7")
|
||||
})
|
||||
|
||||
test("skips compaction agent messages", () => {
|
||||
// given
|
||||
const compactionMessage = {
|
||||
agent: "compaction",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-7" },
|
||||
}
|
||||
const validMessage = {
|
||||
agent: "sisyphus",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-7" },
|
||||
}
|
||||
writeFileSync(join(tempDir, "002.json"), JSON.stringify(compactionMessage))
|
||||
writeFileSync(join(tempDir, "001.json"), JSON.stringify(validMessage))
|
||||
@@ -125,12 +125,12 @@ describe("findNearestMessageExcludingCompaction", () => {
|
||||
writeFileSync(join(tempDir, "002.json"), JSON.stringify({
|
||||
id: compactionMessageID,
|
||||
agent: "atlas",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-7" },
|
||||
}))
|
||||
writeFileSync(join(tempDir, "001.json"), JSON.stringify({
|
||||
id: "msg_001",
|
||||
agent: "sisyphus",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4-7" },
|
||||
}))
|
||||
mkdirSync(partDir, { recursive: true })
|
||||
writeFileSync(join(partDir, "prt_0001.json"), JSON.stringify({ type: "compaction" }))
|
||||
|
||||
@@ -94,7 +94,7 @@ describe("ConcurrencyManager.getConcurrencyLimit", () => {
|
||||
|
||||
// when
|
||||
const modelLimit = manager.getConcurrencyLimit("anthropic/claude-sonnet-4-6")
|
||||
const providerLimit = manager.getConcurrencyLimit("anthropic/claude-opus-4-6")
|
||||
const providerLimit = manager.getConcurrencyLimit("anthropic/claude-opus-4-7")
|
||||
const defaultLimit = manager.getConcurrencyLimit("google/gemini-3.1-pro")
|
||||
|
||||
// then
|
||||
|
||||
@@ -1,2 +1,4 @@
|
||||
export * from "./types"
|
||||
export { BackgroundManager, type SubagentSessionCreatedEvent, type OnSubagentSessionCreated } from "./manager"
|
||||
export { waitForTaskSessionID } from "./wait-for-task-session"
|
||||
export type { WaitForTaskSessionIDOptions } from "./wait-for-task-session"
|
||||
|
||||
@@ -855,7 +855,7 @@ describe("BackgroundManager.notifyParentSession - dynamic message lookup", () =>
|
||||
{
|
||||
info: {
|
||||
agent: "sisyphus",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -890,7 +890,7 @@ describe("BackgroundManager.notifyParentSession - dynamic message lookup", () =>
|
||||
|
||||
//#then
|
||||
expect(capturedBody?.agent).toBe("sisyphus")
|
||||
expect(capturedBody?.model).toEqual({ providerID: "anthropic", modelID: "claude-opus-4.6" })
|
||||
expect(capturedBody?.model).toEqual({ providerID: "anthropic", modelID: "claude-opus-4.7" })
|
||||
|
||||
manager.shutdown()
|
||||
})
|
||||
@@ -913,7 +913,7 @@ describe("BackgroundManager.notifyParentSession - dynamic message lookup", () =>
|
||||
}
|
||||
const currentMessage: CurrentMessage = {
|
||||
agent: "sisyphus",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
}
|
||||
|
||||
// when
|
||||
@@ -921,7 +921,7 @@ describe("BackgroundManager.notifyParentSession - dynamic message lookup", () =>
|
||||
|
||||
// then - uses currentMessage values, not task.parentModel/parentAgent
|
||||
expect(promptBody.agent).toBe("sisyphus")
|
||||
expect(promptBody.model).toEqual({ providerID: "anthropic", modelID: "claude-opus-4.6" })
|
||||
expect(promptBody.model).toEqual({ providerID: "anthropic", modelID: "claude-opus-4.7" })
|
||||
})
|
||||
|
||||
test("should fallback to parentAgent when currentMessage.agent is undefined", async () => {
|
||||
@@ -1155,7 +1155,7 @@ describe("BackgroundManager.notifyParentSession - notifications toggle", () => {
|
||||
agent: "explore",
|
||||
model: {
|
||||
providerID: "anthropic",
|
||||
modelID: "claude-opus-4.6",
|
||||
modelID: "claude-opus-4.7",
|
||||
variant: "high",
|
||||
},
|
||||
},
|
||||
@@ -1211,7 +1211,7 @@ describe("BackgroundManager.notifyParentSession - variant propagation", () => {
|
||||
agent: "explore",
|
||||
model: {
|
||||
providerID: "anthropic",
|
||||
modelID: "claude-opus-4.6",
|
||||
modelID: "claude-opus-4.7",
|
||||
variant: "max",
|
||||
},
|
||||
},
|
||||
@@ -1231,7 +1231,7 @@ describe("BackgroundManager.notifyParentSession - variant propagation", () => {
|
||||
status: "completed",
|
||||
startedAt: new Date(),
|
||||
completedAt: new Date(),
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6", variant: "high" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7", variant: "high" },
|
||||
}
|
||||
getPendingByParent(manager).set("session-parent", new Set([task.id]))
|
||||
|
||||
@@ -1272,7 +1272,7 @@ describe("BackgroundManager.notifyParentSession - variant propagation", () => {
|
||||
status: "completed",
|
||||
startedAt: new Date(),
|
||||
completedAt: new Date(),
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
}
|
||||
getPendingByParent(manager).set("session-parent", new Set([task.id]))
|
||||
|
||||
@@ -1349,7 +1349,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
|
||||
test("should release concurrency and clear key on completion", async () => {
|
||||
// given
|
||||
const concurrencyKey = "anthropic/claude-opus-4.6"
|
||||
const concurrencyKey = "anthropic/claude-opus-4.7"
|
||||
const concurrencyManager = getConcurrencyManager(manager)
|
||||
await concurrencyManager.acquire(concurrencyKey)
|
||||
|
||||
@@ -1378,7 +1378,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
|
||||
test("should prevent double completion and double release", async () => {
|
||||
// given
|
||||
const concurrencyKey = "anthropic/claude-opus-4.6"
|
||||
const concurrencyKey = "anthropic/claude-opus-4.7"
|
||||
const concurrencyManager = getConcurrencyManager(manager)
|
||||
await concurrencyManager.acquire(concurrencyKey)
|
||||
|
||||
@@ -1508,7 +1508,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
|
||||
test("should release task concurrencyKey when startTask throws after assigning it", async () => {
|
||||
// given
|
||||
const concurrencyKey = "anthropic/claude-opus-4.6"
|
||||
const concurrencyKey = "anthropic/claude-opus-4.7"
|
||||
const concurrencyManager = getConcurrencyManager(manager)
|
||||
|
||||
const task = createMockTask({
|
||||
@@ -1524,7 +1524,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
agent: task.agent,
|
||||
parentSessionID: task.parentSessionID,
|
||||
parentMessageID: task.parentMessageID,
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
}
|
||||
getTaskMap(manager).set(task.id, task)
|
||||
getQueuesByKey(manager).set(concurrencyKey, [{ task, input }])
|
||||
@@ -1544,7 +1544,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
|
||||
test("should mark task as error when startTask throws after session creation", async () => {
|
||||
//#given - startTask creates session but fails before sending prompt
|
||||
const concurrencyKey = "anthropic/claude-opus-4.6"
|
||||
const concurrencyKey = "anthropic/claude-opus-4.7"
|
||||
|
||||
const task = createMockTask({
|
||||
id: "task-zombie-session",
|
||||
@@ -1561,7 +1561,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
agent: task.agent,
|
||||
parentSessionID: task.parentSessionID,
|
||||
parentMessageID: task.parentMessageID,
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
}
|
||||
getTaskMap(manager).set(task.id, task)
|
||||
getQueuesByKey(manager).set(concurrencyKey, [{ task, input }])
|
||||
@@ -1585,7 +1585,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
|
||||
test("should release queue slot when queued task is already interrupt", async () => {
|
||||
// given
|
||||
const concurrencyKey = "anthropic/claude-opus-4.6"
|
||||
const concurrencyKey = "anthropic/claude-opus-4.7"
|
||||
const concurrencyManager = getConcurrencyManager(manager)
|
||||
|
||||
const task = createMockTask({
|
||||
@@ -1601,7 +1601,7 @@ describe("BackgroundManager.tryCompleteTask", () => {
|
||||
agent: task.agent,
|
||||
parentSessionID: task.parentSessionID,
|
||||
parentMessageID: task.parentMessageID,
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
}
|
||||
getTaskMap(manager).set(task.id, task)
|
||||
getQueuesByKey(manager).set(concurrencyKey, [{ task, input }])
|
||||
@@ -2104,7 +2104,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
agent: "test-agent",
|
||||
parentSessionID: "parent-session",
|
||||
parentMessageID: "parent-message",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
}
|
||||
const launchInputWithoutModel = {
|
||||
description: "Test task without model",
|
||||
@@ -2124,7 +2124,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
expect(taskWithModel.status).toBe("pending")
|
||||
expect(taskWithoutModel.status).toBe("pending")
|
||||
expect(promptBodies).toHaveLength(2)
|
||||
expect(promptBodies[0].model).toEqual({ providerID: "anthropic", modelID: "claude-opus-4.6" })
|
||||
expect(promptBodies[0].model).toEqual({ providerID: "anthropic", modelID: "claude-opus-4.7" })
|
||||
expect(promptBodies[0].agent).toBe("test-agent")
|
||||
expect(promptBodies[1].agent).toBe("test-agent")
|
||||
expect("model" in promptBodies[1]).toBe(false)
|
||||
@@ -2327,7 +2327,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
await expect(result).rejects.toThrow("background_task.maxDepth=3")
|
||||
})
|
||||
|
||||
test("should block launches when maxDescendants is reached", async () => {
|
||||
test("allows multiple descendants without a root spawn cap", async () => {
|
||||
// given
|
||||
manager.shutdown()
|
||||
manager = new BackgroundManager(
|
||||
@@ -2337,7 +2337,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 1 },
|
||||
)
|
||||
|
||||
const input = {
|
||||
@@ -2354,10 +2353,10 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
const result = manager.launch(input)
|
||||
|
||||
// then
|
||||
await expect(result).rejects.toThrow("background_task.maxDescendants=1")
|
||||
await expect(result).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
test("should consume descendant quota for reserved sync spawns", async () => {
|
||||
test("allows spawn assertions after reserveSubagentSpawn without a root spawn cap", async () => {
|
||||
// given
|
||||
manager.shutdown()
|
||||
manager = new BackgroundManager(
|
||||
@@ -2367,7 +2366,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 1 },
|
||||
)
|
||||
|
||||
await manager.reserveSubagentSpawn("session-root")
|
||||
@@ -2376,7 +2374,10 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
const result = manager.assertCanSpawn("session-root")
|
||||
|
||||
// then
|
||||
await expect(result).rejects.toThrow("background_task.maxDescendants=1")
|
||||
await expect(result).resolves.toMatchObject({
|
||||
rootSessionID: "session-root",
|
||||
childDepth: 1,
|
||||
})
|
||||
})
|
||||
|
||||
test("should fail closed when session lineage lookup fails", async () => {
|
||||
@@ -2392,7 +2393,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 1 },
|
||||
)
|
||||
|
||||
const input = {
|
||||
@@ -2407,10 +2407,10 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
const result = manager.launch(input)
|
||||
|
||||
// then
|
||||
await expect(result).rejects.toThrow("background_task.maxDescendants cannot be enforced safely")
|
||||
await expect(result).rejects.toThrow("background_task.maxDepth cannot be enforced safely")
|
||||
})
|
||||
|
||||
test("should release descendant quota when queued task is cancelled before session starts", async () => {
|
||||
test("allows replacement launch when a queued task is cancelled before session starts", async () => {
|
||||
// given
|
||||
manager.shutdown()
|
||||
manager = new BackgroundManager(
|
||||
@@ -2420,7 +2420,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ defaultConcurrency: 1, maxDescendants: 2 },
|
||||
{ defaultConcurrency: 1 },
|
||||
)
|
||||
|
||||
const input = {
|
||||
@@ -2445,7 +2445,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
expect(replacementTask.status).toBe("pending")
|
||||
})
|
||||
|
||||
test("should release descendant quota when session creation fails before session starts", async () => {
|
||||
test("allows retry after session creation fails before session starts", async () => {
|
||||
// given
|
||||
let createAttempts = 0
|
||||
manager.shutdown()
|
||||
@@ -2472,7 +2472,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
},
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 1 },
|
||||
)
|
||||
|
||||
const input = {
|
||||
@@ -2887,7 +2886,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}
|
||||
})
|
||||
|
||||
test("should release descendant quota when task completes", async () => {
|
||||
test("allows relaunch after task completes", async () => {
|
||||
manager.shutdown()
|
||||
manager = new BackgroundManager(
|
||||
{
|
||||
@@ -2896,7 +2895,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 1 },
|
||||
)
|
||||
stubNotifyParentSession(manager)
|
||||
|
||||
@@ -2920,7 +2918,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
await expect(manager.launch(input)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
test("should release descendant quota when running task is cancelled", async () => {
|
||||
test("allows relaunch after running task is cancelled", async () => {
|
||||
manager.shutdown()
|
||||
manager = new BackgroundManager(
|
||||
{
|
||||
@@ -2929,7 +2927,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 1 },
|
||||
)
|
||||
|
||||
const input = {
|
||||
@@ -2950,7 +2947,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
await expect(manager.launch(input)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
test("should release descendant quota when task errors", async () => {
|
||||
test("allows relaunch after task errors", async () => {
|
||||
manager.shutdown()
|
||||
manager = new BackgroundManager(
|
||||
{
|
||||
@@ -2959,7 +2956,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 1 },
|
||||
)
|
||||
|
||||
const input = {
|
||||
@@ -2984,7 +2980,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
await expect(manager.launch(input)).resolves.toBeDefined()
|
||||
})
|
||||
|
||||
test("should not double-decrement quota when pending task is cancelled", async () => {
|
||||
test("allows repeated relaunch after pending tasks are cancelled", async () => {
|
||||
manager.shutdown()
|
||||
manager = new BackgroundManager(
|
||||
{
|
||||
@@ -2993,7 +2989,6 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
}),
|
||||
directory: tmpdir(),
|
||||
} as unknown as PluginInput,
|
||||
{ maxDescendants: 2 },
|
||||
)
|
||||
|
||||
const input = {
|
||||
@@ -3250,7 +3245,7 @@ describe("BackgroundManager - Non-blocking Queue Integration", () => {
|
||||
description: "Task 1",
|
||||
prompt: "Do something",
|
||||
agent: "test-agent",
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7" },
|
||||
parentSessionID: "parent-session",
|
||||
parentMessageID: "parent-message",
|
||||
}
|
||||
@@ -4230,7 +4225,7 @@ describe("BackgroundManager.handleEvent - session.deleted cascade", () => {
|
||||
|
||||
describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
const defaultRetryFallbackChain = [
|
||||
{ providers: ["anthropic"], model: "claude-opus-4-6", variant: "max" },
|
||||
{ providers: ["anthropic"], model: "claude-opus-4-7", variant: "max" },
|
||||
{ providers: ["anthropic"], model: "gpt-5.3-codex", variant: "high" },
|
||||
]
|
||||
|
||||
@@ -4254,7 +4249,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
agent: "sisyphus",
|
||||
status: "running",
|
||||
concurrencyKey: input.concurrencyKey,
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.6-thinking" },
|
||||
model: { providerID: "anthropic", modelID: "claude-opus-4.7-thinking" },
|
||||
fallbackChain: input.fallbackChain ?? defaultRetryFallbackChain,
|
||||
attemptCount: 0,
|
||||
})
|
||||
@@ -4399,7 +4394,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
//#given
|
||||
const manager = createBackgroundManager()
|
||||
const concurrencyManager = getConcurrencyManager(manager)
|
||||
const concurrencyKey = "anthropic/claude-opus-4.6-thinking"
|
||||
const concurrencyKey = "anthropic/claude-opus-4.7-thinking"
|
||||
await concurrencyManager.acquire(concurrencyKey)
|
||||
|
||||
stubProcessKey(manager)
|
||||
@@ -4411,7 +4406,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
description: "task that should retry",
|
||||
concurrencyKey,
|
||||
fallbackChain: [
|
||||
{ providers: ["anthropic"], model: "claude-opus-4-6", variant: "max" },
|
||||
{ providers: ["anthropic"], model: "claude-opus-4-7", variant: "max" },
|
||||
{ providers: ["anthropic"], model: "claude-opus-4-5", variant: "max" },
|
||||
],
|
||||
})
|
||||
@@ -4425,7 +4420,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
name: "UnknownError",
|
||||
data: {
|
||||
message:
|
||||
"Bad Gateway: {\"error\":{\"message\":\"unknown provider for model claude-opus-4.6-thinking\"}}",
|
||||
"Bad Gateway: {\"error\":{\"message\":\"unknown provider for model claude-opus-4.7-thinking\"}}",
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -4436,7 +4431,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
expect(task.attemptCount).toBe(1)
|
||||
expect(task.model).toEqual({
|
||||
providerID: "anthropic",
|
||||
modelID: "claude-opus-4.6",
|
||||
modelID: "claude-opus-4.7",
|
||||
variant: "max",
|
||||
})
|
||||
expect(task.concurrencyKey).toBeUndefined()
|
||||
@@ -4474,7 +4469,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
expect(task.attemptCount).toBe(1)
|
||||
expect(task.model).toEqual({
|
||||
providerID: "anthropic",
|
||||
modelID: "claude-opus-4.6",
|
||||
modelID: "claude-opus-4.7",
|
||||
variant: "max",
|
||||
})
|
||||
|
||||
@@ -4502,7 +4497,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
name: "UnknownError",
|
||||
data: {
|
||||
message:
|
||||
"Bad Gateway: {\"error\":{\"message\":\"unknown provider for model claude-opus-4.6-thinking\"}}",
|
||||
"Bad Gateway: {\"error\":{\"message\":\"unknown provider for model claude-opus-4.7-thinking\"}}",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -4519,7 +4514,7 @@ describe("BackgroundManager.handleEvent - session.error", () => {
|
||||
expect(task.attemptCount).toBe(1)
|
||||
expect(task.model).toEqual({
|
||||
providerID: "anthropic",
|
||||
modelID: "claude-opus-4.6",
|
||||
modelID: "claude-opus-4.7",
|
||||
variant: "max",
|
||||
})
|
||||
|
||||
|
||||
@@ -73,8 +73,6 @@ import {
|
||||
} from "./loop-detector"
|
||||
import {
|
||||
createSubagentDepthLimitError,
|
||||
createSubagentDescendantLimitError,
|
||||
getMaxRootSessionSpawnBudget,
|
||||
getMaxSubagentDepth,
|
||||
resolveSubagentSpawnContext,
|
||||
type SubagentSpawnContext,
|
||||
@@ -219,16 +217,6 @@ export class BackgroundManager {
|
||||
})
|
||||
}
|
||||
|
||||
const maxRootSessionSpawnBudget = getMaxRootSessionSpawnBudget(this.config)
|
||||
const descendantCount = this.rootDescendantCounts.get(spawnContext.rootSessionID) ?? 0
|
||||
if (descendantCount >= maxRootSessionSpawnBudget) {
|
||||
throw createSubagentDescendantLimitError({
|
||||
rootSessionID: spawnContext.rootSessionID,
|
||||
descendantCount,
|
||||
maxDescendants: maxRootSessionSpawnBudget,
|
||||
})
|
||||
}
|
||||
|
||||
return spawnContext
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
type ProcessCleanupEvent =
|
||||
| NodeJS.Signals
|
||||
| "beforeExit"
|
||||
| "exit"
|
||||
| "uncaughtException"
|
||||
| "unhandledRejection"
|
||||
|
||||
export function getNewListener(
|
||||
signal: ProcessCleanupEvent,
|
||||
existingListeners: Function[],
|
||||
): () => void {
|
||||
const listener = process
|
||||
.listeners(signal)
|
||||
.find((registeredListener) => !existingListeners.includes(registeredListener))
|
||||
|
||||
if (typeof listener !== "function") {
|
||||
throw new Error(`Expected a ${signal} listener to be registered`)
|
||||
}
|
||||
|
||||
return listener
|
||||
}
|
||||
|
||||
export async function flushMicrotasks(): Promise<void> {
|
||||
for (let iteration = 0; iteration < 10; iteration += 1) {
|
||||
await Promise.resolve()
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
/// <reference types="bun-types" />
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"
|
||||
|
||||
import {
|
||||
@@ -5,42 +7,17 @@ import {
|
||||
registerManagerForCleanup,
|
||||
unregisterManagerForCleanup,
|
||||
} from "./process-cleanup"
|
||||
import { flushMicrotasks, getNewListener } from "./process-cleanup.test-helpers"
|
||||
|
||||
type CleanupManager = {
|
||||
shutdown: () => void | Promise<void>
|
||||
}
|
||||
|
||||
type ProcessCleanupEvent = NodeJS.Signals | "beforeExit" | "exit"
|
||||
|
||||
function getNewListener(
|
||||
signal: ProcessCleanupEvent,
|
||||
existingListeners: Function[],
|
||||
): () => void {
|
||||
const listener = process
|
||||
.listeners(signal)
|
||||
.find((registeredListener) => !existingListeners.includes(registeredListener))
|
||||
|
||||
expect(listener).toBeDefined()
|
||||
|
||||
if (typeof listener !== "function") {
|
||||
throw new Error(`Expected a ${signal} listener to be registered`)
|
||||
}
|
||||
|
||||
return listener
|
||||
}
|
||||
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
for (let iteration = 0; iteration < 10; iteration += 1) {
|
||||
await Promise.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
describe("#given process cleanup registration", () => {
|
||||
const registeredManagers: CleanupManager[] = []
|
||||
const originalExitCode = process.exitCode
|
||||
|
||||
beforeEach(() => {
|
||||
process.exitCode = originalExitCode
|
||||
process.exitCode = 0
|
||||
registeredManagers.length = 0
|
||||
_resetForTesting()
|
||||
})
|
||||
@@ -50,7 +27,7 @@ describe("#given process cleanup registration", () => {
|
||||
unregisterManagerForCleanup(manager)
|
||||
}
|
||||
|
||||
process.exitCode = originalExitCode
|
||||
process.exitCode = 0
|
||||
_resetForTesting()
|
||||
})
|
||||
|
||||
@@ -92,13 +69,7 @@ describe("#given process cleanup registration", () => {
|
||||
|
||||
test("#when cleanup finishes after SIGINT #then the fallback exit timer is cleared", async () => {
|
||||
const sigintListenersBefore = process.listeners("SIGINT")
|
||||
const timeoutHandle = setTimeout(() => undefined, 0)
|
||||
clearTimeout(timeoutHandle)
|
||||
|
||||
const setTimeoutImplementation: typeof setTimeout = () => timeoutHandle
|
||||
const setTimeoutSpy = spyOn(globalThis, "setTimeout").mockImplementation(
|
||||
setTimeoutImplementation,
|
||||
)
|
||||
const setTimeoutSpy = spyOn(globalThis, "setTimeout")
|
||||
const clearTimeoutSpy = spyOn(globalThis, "clearTimeout")
|
||||
|
||||
try {
|
||||
@@ -117,11 +88,10 @@ describe("#given process cleanup registration", () => {
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(setTimeoutSpy).toHaveBeenCalledTimes(1)
|
||||
expect(clearTimeoutSpy).toHaveBeenCalledWith(timeoutHandle)
|
||||
expect(clearTimeoutSpy).toHaveBeenCalledTimes(1)
|
||||
} finally {
|
||||
setTimeoutSpy.mockRestore()
|
||||
clearTimeoutSpy.mockRestore()
|
||||
clearTimeout(timeoutHandle)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -163,6 +133,32 @@ describe("#given process cleanup registration", () => {
|
||||
|
||||
expect(process.listeners("SIGINT")).toHaveLength(sigintListenersAfterFirstRegistration)
|
||||
})
|
||||
|
||||
test("#given two managers registered #when uncaughtException fires #then both shutdowns called", async () => {
|
||||
const exitSpy = spyOn(process, "exit").mockImplementation((code?: number): never => {
|
||||
throw new Error(`Unexpected process.exit(${String(code)})`)
|
||||
})
|
||||
const shutdownOne = mock(() => {})
|
||||
const shutdownTwo = mock(() => {})
|
||||
const managerOne = { shutdown: shutdownOne }
|
||||
const managerTwo = { shutdown: shutdownTwo }
|
||||
registeredManagers.push(managerOne, managerTwo)
|
||||
|
||||
try {
|
||||
registerManagerForCleanup(managerOne)
|
||||
registerManagerForCleanup(managerTwo)
|
||||
|
||||
process.emit("uncaughtException", new Error("boom"))
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(shutdownOne).toHaveBeenCalledTimes(1)
|
||||
expect(shutdownTwo).toHaveBeenCalledTimes(1)
|
||||
expect(process.exitCode).toBe(1)
|
||||
expect(exitSpy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
exitSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("#given cleanup managers are unregistered", () => {
|
||||
@@ -202,5 +198,88 @@ describe("#given process cleanup registration", () => {
|
||||
expect(remainingManagerShutdown).toHaveBeenCalledTimes(1)
|
||||
expect(removedManagerShutdown).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test("#given uncaughtException handler registered #when manager is unregistered via unregisterManagerForCleanup #then subsequent events do not invoke that manager", () => {
|
||||
const uncaughtExceptionListenersBefore = process.listeners("uncaughtException")
|
||||
const shutdown = mock(() => {})
|
||||
const manager = { shutdown }
|
||||
registeredManagers.push(manager)
|
||||
|
||||
registerManagerForCleanup(manager)
|
||||
expect(process.listeners("uncaughtException")).toHaveLength(
|
||||
uncaughtExceptionListenersBefore.length + 1,
|
||||
)
|
||||
|
||||
unregisterManagerForCleanup(manager)
|
||||
registeredManagers.length = 0
|
||||
process.emit("uncaughtException", new Error("boom"))
|
||||
|
||||
expect(shutdown).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe("#given uncaught exception and rejection cleanup", () => {
|
||||
test("#given manager registered AND process emits uncaughtException #when event fires #then manager.shutdown() called AND process.exitCode set to 1", async () => {
|
||||
const exitSpy = spyOn(process, "exit").mockImplementation((code?: number): never => {
|
||||
throw new Error(`Unexpected process.exit(${String(code)})`)
|
||||
})
|
||||
const shutdown = mock(() => {})
|
||||
const manager = { shutdown }
|
||||
registeredManagers.push(manager)
|
||||
|
||||
try {
|
||||
registerManagerForCleanup(manager)
|
||||
|
||||
process.emit("uncaughtException", new Error("boom"))
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(shutdown).toHaveBeenCalledTimes(1)
|
||||
expect(process.exitCode).toBe(1)
|
||||
expect(exitSpy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
exitSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("#given manager registered AND process emits unhandledRejection #when event fires #then manager.shutdown() called AND process.exitCode set to 1", async () => {
|
||||
const exitSpy = spyOn(process, "exit").mockImplementation((code?: number): never => {
|
||||
throw new Error(`Unexpected process.exit(${String(code)})`)
|
||||
})
|
||||
const shutdown = mock(() => {})
|
||||
const manager = { shutdown }
|
||||
registeredManagers.push(manager)
|
||||
|
||||
try {
|
||||
registerManagerForCleanup(manager)
|
||||
|
||||
process.emit("unhandledRejection", new Error("boom"), Promise.resolve())
|
||||
await flushMicrotasks()
|
||||
|
||||
expect(shutdown).toHaveBeenCalledTimes(1)
|
||||
expect(process.exitCode).toBe(1)
|
||||
expect(exitSpy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
exitSpy.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
test("#given _resetForTesting() called #when event fires #then no cleanup runs", () => {
|
||||
const uncaughtExceptionListenersBefore = process.listeners("uncaughtException")
|
||||
const shutdown = mock(() => {})
|
||||
const manager = { shutdown }
|
||||
|
||||
registerManagerForCleanup(manager)
|
||||
expect(process.listeners("uncaughtException")).toHaveLength(
|
||||
uncaughtExceptionListenersBefore.length + 1,
|
||||
)
|
||||
|
||||
_resetForTesting()
|
||||
process.emit("uncaughtException", new Error("boom"))
|
||||
|
||||
expect(shutdown).not.toHaveBeenCalled()
|
||||
expect(process.listeners("uncaughtException")).toHaveLength(
|
||||
uncaughtExceptionListenersBefore.length,
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,33 +1,51 @@
|
||||
import { log } from "../../shared"
|
||||
|
||||
type ProcessCleanupEvent = NodeJS.Signals | "beforeExit" | "exit"
|
||||
type ProcessCleanupSignal = NodeJS.Signals | "beforeExit" | "exit"
|
||||
type ProcessCleanupErrorEvent = "uncaughtException" | "unhandledRejection"
|
||||
|
||||
function scheduleForcedExit(cleanupResult: void | Promise<void>, exitCode: number): void {
|
||||
process.exitCode = exitCode
|
||||
const exitTimeout = setTimeout(() => process.exit(), 6000)
|
||||
void Promise.resolve(cleanupResult).finally(() => {
|
||||
clearTimeout(exitTimeout)
|
||||
})
|
||||
}
|
||||
|
||||
function registerProcessSignal(
|
||||
signal: ProcessCleanupEvent,
|
||||
signal: ProcessCleanupSignal,
|
||||
handler: () => void | Promise<void>,
|
||||
exitAfter: boolean
|
||||
): () => void {
|
||||
const listener = () => {
|
||||
const cleanupResult = handler()
|
||||
if (exitAfter) {
|
||||
process.exitCode = 0
|
||||
const exitTimeout = setTimeout(() => process.exit(), 6000)
|
||||
void Promise.resolve(cleanupResult).finally(() => {
|
||||
clearTimeout(exitTimeout)
|
||||
})
|
||||
scheduleForcedExit(cleanupResult, 0)
|
||||
}
|
||||
}
|
||||
process.on(signal, listener)
|
||||
return listener
|
||||
}
|
||||
|
||||
function registerErrorEvent(
|
||||
signal: ProcessCleanupErrorEvent,
|
||||
handler: (error: unknown) => void | Promise<void>
|
||||
): (error: unknown) => void {
|
||||
const listener = (error: unknown) => {
|
||||
log(`[background-agent] ${signal} received during shutdown cleanup:`, error)
|
||||
scheduleForcedExit(handler(error), 1)
|
||||
}
|
||||
process.on(signal, listener)
|
||||
return listener
|
||||
}
|
||||
|
||||
interface CleanupTarget {
|
||||
shutdown(): void | Promise<void>
|
||||
}
|
||||
|
||||
const cleanupManagers = new Set<CleanupTarget>()
|
||||
let cleanupRegistered = false
|
||||
const cleanupHandlers = new Map<ProcessCleanupEvent, () => void>()
|
||||
const cleanupSignalHandlers = new Map<ProcessCleanupSignal, () => void>()
|
||||
const cleanupErrorHandlers = new Map<ProcessCleanupErrorEvent, (error: unknown) => void>()
|
||||
|
||||
export function registerManagerForCleanup(manager: CleanupTarget): void {
|
||||
cleanupManagers.add(manager)
|
||||
@@ -59,9 +77,9 @@ export function registerManagerForCleanup(manager: CleanupTarget): void {
|
||||
return cleanupPromise
|
||||
}
|
||||
|
||||
const registerSignal = (signal: ProcessCleanupEvent, exitAfter: boolean): void => {
|
||||
const registerSignal = (signal: ProcessCleanupSignal, exitAfter: boolean): void => {
|
||||
const listener = registerProcessSignal(signal, cleanupAll, exitAfter)
|
||||
cleanupHandlers.set(signal, listener)
|
||||
cleanupSignalHandlers.set(signal, listener)
|
||||
}
|
||||
|
||||
registerSignal("SIGINT", true)
|
||||
@@ -71,6 +89,8 @@ export function registerManagerForCleanup(manager: CleanupTarget): void {
|
||||
}
|
||||
registerSignal("beforeExit", false)
|
||||
registerSignal("exit", false)
|
||||
cleanupErrorHandlers.set("uncaughtException", registerErrorEvent("uncaughtException", cleanupAll))
|
||||
cleanupErrorHandlers.set("unhandledRejection", registerErrorEvent("unhandledRejection", cleanupAll))
|
||||
}
|
||||
|
||||
export function unregisterManagerForCleanup(manager: CleanupTarget): void {
|
||||
@@ -78,10 +98,14 @@ export function unregisterManagerForCleanup(manager: CleanupTarget): void {
|
||||
|
||||
if (cleanupManagers.size > 0) return
|
||||
|
||||
for (const [signal, listener] of cleanupHandlers.entries()) {
|
||||
for (const [signal, listener] of cleanupSignalHandlers.entries()) {
|
||||
process.off(signal, listener)
|
||||
}
|
||||
cleanupHandlers.clear()
|
||||
for (const [signal, listener] of cleanupErrorHandlers.entries()) {
|
||||
process.off(signal, listener)
|
||||
}
|
||||
cleanupSignalHandlers.clear()
|
||||
cleanupErrorHandlers.clear()
|
||||
cleanupRegistered = false
|
||||
}
|
||||
|
||||
@@ -90,9 +114,13 @@ export function _resetForTesting(): void {
|
||||
for (const manager of [...cleanupManagers]) {
|
||||
cleanupManagers.delete(manager)
|
||||
}
|
||||
for (const [signal, listener] of cleanupHandlers.entries()) {
|
||||
for (const [signal, listener] of cleanupSignalHandlers.entries()) {
|
||||
process.off(signal, listener)
|
||||
}
|
||||
cleanupHandlers.clear()
|
||||
for (const [signal, listener] of cleanupErrorHandlers.entries()) {
|
||||
process.off(signal, listener)
|
||||
}
|
||||
cleanupSignalHandlers.clear()
|
||||
cleanupErrorHandlers.clear()
|
||||
cleanupRegistered = false
|
||||
}
|
||||
|
||||
@@ -577,3 +577,84 @@ describe("background-agent spawner fallback model promotion", () => {
|
||||
expect(promptCalls[0]?.body?.agent).toBe("sisyphus-junior")
|
||||
})
|
||||
})
|
||||
|
||||
describe("background-agent spawner tmux callback ordering", () => {
|
||||
test("fires promptAsync before tmux callback resolves (no blocking)", async () => {
|
||||
//#given
|
||||
const events: string[] = []
|
||||
let resolveTmuxCallback: () => void = () => {}
|
||||
const tmuxCallbackPromise = new Promise<void>((resolve) => {
|
||||
resolveTmuxCallback = resolve
|
||||
})
|
||||
|
||||
const client = {
|
||||
session: {
|
||||
get: async () => ({ data: { directory: "/tmp/test" } }),
|
||||
create: async () => {
|
||||
events.push("session.create")
|
||||
return { data: { id: "ses_blocking_tmux" } }
|
||||
},
|
||||
promptAsync: async () => {
|
||||
events.push("promptAsync")
|
||||
return { data: {} }
|
||||
},
|
||||
},
|
||||
} as any
|
||||
|
||||
const onSubagentSessionCreated = mock(async () => {
|
||||
events.push("tmux.callback.start")
|
||||
await tmuxCallbackPromise
|
||||
events.push("tmux.callback.end")
|
||||
})
|
||||
|
||||
const task = createTask({
|
||||
description: "Blocking tmux test",
|
||||
prompt: "Do work",
|
||||
agent: "general",
|
||||
parentSessionID: "ses_parent",
|
||||
parentMessageID: "msg_parent",
|
||||
})
|
||||
|
||||
const item = {
|
||||
task,
|
||||
input: {
|
||||
description: task.description,
|
||||
prompt: task.prompt,
|
||||
agent: task.agent,
|
||||
parentSessionID: task.parentSessionID,
|
||||
parentMessageID: task.parentMessageID,
|
||||
},
|
||||
}
|
||||
|
||||
const ctx = {
|
||||
client,
|
||||
directory: "/tmp/test",
|
||||
concurrencyManager: { release: () => {} },
|
||||
tmuxEnabled: true,
|
||||
onSubagentSessionCreated,
|
||||
onTaskError: () => {},
|
||||
}
|
||||
|
||||
const originalTmux = process.env.TMUX
|
||||
process.env.TMUX = "/tmp/fake-tmux-socket"
|
||||
|
||||
try {
|
||||
//#when
|
||||
await startTask(item as any, ctx as any)
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
|
||||
//#then
|
||||
expect(events).toContain("session.create")
|
||||
expect(events).toContain("promptAsync")
|
||||
expect(events).toContain("tmux.callback.start")
|
||||
const promptIdx = events.indexOf("promptAsync")
|
||||
const tmuxStartIdx = events.indexOf("tmux.callback.start")
|
||||
expect(promptIdx < tmuxStartIdx).toBe(true)
|
||||
expect(events).not.toContain("tmux.callback.end")
|
||||
} finally {
|
||||
resolveTmuxCallback()
|
||||
if (originalTmux === undefined) delete process.env.TMUX
|
||||
else process.env.TMUX = originalTmux
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { BackgroundTask, LaunchInput, ResumeInput } from "./types"
|
||||
import type { OpencodeClient, OnSubagentSessionCreated, QueueItem } from "./constants"
|
||||
import { TMUX_CALLBACK_DELAY_MS } from "./constants"
|
||||
import { log, getAgentToolRestrictions, promptWithModelSuggestionRetry, createInternalAgentTextPart } from "../../shared"
|
||||
import { applySessionPromptParams } from "../../shared/session-prompt-params-helpers"
|
||||
import { subagentSessions } from "../claude-code-session-state"
|
||||
@@ -115,29 +114,6 @@ export async function startTask(
|
||||
const sessionID = createResult.data.id
|
||||
subagentSessions.add(sessionID)
|
||||
|
||||
log("[background-agent] tmux callback check", {
|
||||
hasCallback: !!onSubagentSessionCreated,
|
||||
tmuxEnabled,
|
||||
isInsideTmux: isInsideTmux(),
|
||||
sessionID,
|
||||
parentID: input.parentSessionID,
|
||||
})
|
||||
|
||||
if (onSubagentSessionCreated && tmuxEnabled && isInsideTmux()) {
|
||||
log("[background-agent] Invoking tmux callback NOW", { sessionID })
|
||||
await onSubagentSessionCreated({
|
||||
sessionID,
|
||||
parentID: input.parentSessionID,
|
||||
title: input.description,
|
||||
}).catch((err) => {
|
||||
log("[background-agent] Failed to spawn tmux pane:", err)
|
||||
})
|
||||
log("[background-agent] tmux callback completed, waiting")
|
||||
await new Promise(r => setTimeout(r, TMUX_CALLBACK_DELAY_MS))
|
||||
} else {
|
||||
log("[background-agent] SKIP tmux callback - conditions not met")
|
||||
}
|
||||
|
||||
task.status = "running"
|
||||
task.startedAt = new Date()
|
||||
task.sessionID = sessionID
|
||||
@@ -188,7 +164,8 @@ export async function startTask(
|
||||
parts: [createInternalAgentTextPart(input.prompt)],
|
||||
}
|
||||
|
||||
promptWithModelSuggestionRetry(client, {
|
||||
// Must fire BEFORE tmux callback: attach client needs session activity to render TUI.
|
||||
const promptChain = promptWithModelSuggestionRetry(client, {
|
||||
path: { id: sessionID },
|
||||
body: promptBody,
|
||||
}).catch(async (error) => {
|
||||
@@ -214,6 +191,29 @@ export async function startTask(
|
||||
log("[background-agent] promptAsync error:", error)
|
||||
onTaskError(task, error instanceof Error ? error : new Error(String(error)))
|
||||
})
|
||||
|
||||
void promptChain
|
||||
|
||||
log("[background-agent] tmux callback check", {
|
||||
hasCallback: !!onSubagentSessionCreated,
|
||||
tmuxEnabled,
|
||||
isInsideTmux: isInsideTmux(),
|
||||
sessionID,
|
||||
parentID: input.parentSessionID,
|
||||
})
|
||||
|
||||
if (onSubagentSessionCreated && tmuxEnabled && isInsideTmux()) {
|
||||
log("[background-agent] Invoking tmux callback (fire-and-forget)", { sessionID })
|
||||
void onSubagentSessionCreated({
|
||||
sessionID,
|
||||
parentID: input.parentSessionID,
|
||||
title: input.description,
|
||||
}).catch((err) => {
|
||||
log("[background-agent] Failed to spawn tmux pane:", err)
|
||||
})
|
||||
} else {
|
||||
log("[background-agent] SKIP tmux callback - conditions not met")
|
||||
}
|
||||
}
|
||||
|
||||
export async function resumeTask(
|
||||
|
||||
@@ -5,9 +5,6 @@ import {
|
||||
getMaxSubagentDepth,
|
||||
DEFAULT_MAX_SUBAGENT_DEPTH,
|
||||
createSubagentDepthLimitError,
|
||||
createSubagentDescendantLimitError,
|
||||
getMaxRootSessionSpawnBudget,
|
||||
DEFAULT_MAX_ROOT_SESSION_SPAWN_BUDGET,
|
||||
} from "./subagent-spawn-limits"
|
||||
|
||||
function createMockClient(sessionGet: OpencodeClient["session"]["get"]): OpencodeClient {
|
||||
@@ -62,7 +59,7 @@ describe("resolveSubagentSpawnContext", () => {
|
||||
const result = resolveSubagentSpawnContext(client, "parent-session")
|
||||
|
||||
// then
|
||||
await expect(result).rejects.toThrow(/background_task\.maxDescendants cannot be enforced safely.*lookup failed/)
|
||||
await expect(result).rejects.toThrow(/background_task\.maxDepth cannot be enforced safely.*lookup failed/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -77,7 +74,7 @@ describe("resolveSubagentSpawnContext", () => {
|
||||
const result = resolveSubagentSpawnContext(client, "parent-session")
|
||||
|
||||
// then
|
||||
await expect(result).rejects.toThrow(/background_task\.maxDescendants cannot be enforced safely.*No session data returned/)
|
||||
await expect(result).rejects.toThrow(/background_task\.maxDepth cannot be enforced safely.*No session data returned/)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -209,20 +206,6 @@ describe("getMaxSubagentDepth", () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe("getMaxRootSessionSpawnBudget", () => {
|
||||
test("returns DEFAULT_MAX_ROOT_SESSION_SPAWN_BUDGET when no config", () => {
|
||||
expect(getMaxRootSessionSpawnBudget()).toBe(DEFAULT_MAX_ROOT_SESSION_SPAWN_BUDGET)
|
||||
})
|
||||
|
||||
test("returns config.maxDescendants when provided", () => {
|
||||
expect(getMaxRootSessionSpawnBudget({ maxDescendants: 10 })).toBe(10)
|
||||
})
|
||||
|
||||
test("default is 50", () => {
|
||||
expect(DEFAULT_MAX_ROOT_SESSION_SPAWN_BUDGET).toBe(50)
|
||||
})
|
||||
})
|
||||
|
||||
describe("createSubagentDepthLimitError", () => {
|
||||
test("includes childDepth, maxDepth, and session IDs in message", () => {
|
||||
const error = createSubagentDepthLimitError({
|
||||
@@ -239,18 +222,3 @@ describe("createSubagentDepthLimitError", () => {
|
||||
expect(error.message).toContain("spawn blocked")
|
||||
})
|
||||
})
|
||||
|
||||
describe("createSubagentDescendantLimitError", () => {
|
||||
test("includes descendant count, max, and root session ID", () => {
|
||||
const error = createSubagentDescendantLimitError({
|
||||
rootSessionID: "root-789",
|
||||
descendantCount: 50,
|
||||
maxDescendants: 50,
|
||||
})
|
||||
|
||||
expect(error.message).toContain("root-789")
|
||||
expect(error.message).toContain("50")
|
||||
expect(error.message).toContain("maxDescendants=50")
|
||||
expect(error.message).toContain("spawn blocked")
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { BackgroundTaskConfig } from "../../config/schema"
|
||||
import type { OpencodeClient } from "./constants"
|
||||
|
||||
export const DEFAULT_MAX_SUBAGENT_DEPTH = 3
|
||||
export const DEFAULT_MAX_ROOT_SESSION_SPAWN_BUDGET = 50
|
||||
|
||||
export interface SubagentSpawnContext {
|
||||
rootSessionID: string
|
||||
@@ -14,10 +13,6 @@ export function getMaxSubagentDepth(config?: BackgroundTaskConfig): number {
|
||||
return config?.maxDepth ?? DEFAULT_MAX_SUBAGENT_DEPTH
|
||||
}
|
||||
|
||||
export function getMaxRootSessionSpawnBudget(config?: BackgroundTaskConfig): number {
|
||||
return config?.maxDescendants ?? DEFAULT_MAX_ROOT_SESSION_SPAWN_BUDGET
|
||||
}
|
||||
|
||||
export async function resolveSubagentSpawnContext(
|
||||
client: OpencodeClient,
|
||||
parentSessionID: string,
|
||||
@@ -53,7 +48,7 @@ export async function resolveSubagentSpawnContext(
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error)
|
||||
throw new Error(
|
||||
`Subagent spawn blocked: failed to resolve session lineage for ${parentSessionID}, so background_task.maxDescendants cannot be enforced safely. ${reason}`
|
||||
`Subagent spawn blocked: failed to resolve session lineage for ${parentSessionID}, so background_task.maxDepth cannot be enforced safely. ${reason}`
|
||||
)
|
||||
}
|
||||
|
||||
@@ -84,14 +79,3 @@ export function createSubagentDepthLimitError(input: {
|
||||
`Subagent spawn blocked: child depth ${childDepth} exceeds background_task.maxDepth=${maxDepth}. Parent session: ${parentSessionID}. Root session: ${rootSessionID}. Continue in an existing subagent session instead of spawning another.`
|
||||
)
|
||||
}
|
||||
|
||||
export function createSubagentDescendantLimitError(input: {
|
||||
rootSessionID: string
|
||||
descendantCount: number
|
||||
maxDescendants: number
|
||||
}): Error {
|
||||
const { rootSessionID, descendantCount, maxDescendants } = input
|
||||
return new Error(
|
||||
`Subagent spawn blocked: root session ${rootSessionID} already has ${descendantCount} descendants, which meets background_task.maxDescendants=${maxDescendants}. Reuse an existing session instead of spawning another.`
|
||||
)
|
||||
}
|
||||
|
||||
@@ -648,7 +648,7 @@ describe("checkAndInterruptStaleTasks", () => {
|
||||
const task = createRunningTask({
|
||||
startedAt: new Date(Date.now() - 15 * 60 * 1000),
|
||||
progress: undefined,
|
||||
concurrencyKey: "anthropic/claude-opus-4-6",
|
||||
concurrencyKey: "anthropic/claude-opus-4-7",
|
||||
})
|
||||
|
||||
//#when
|
||||
@@ -661,7 +661,7 @@ describe("checkAndInterruptStaleTasks", () => {
|
||||
})
|
||||
|
||||
//#then
|
||||
expect(releaseMock).toHaveBeenCalledWith("anthropic/claude-opus-4-6")
|
||||
expect(releaseMock).toHaveBeenCalledWith("anthropic/claude-opus-4-7")
|
||||
expect(task.concurrencyKey).toBeUndefined()
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import type { BackgroundTaskStatus } from "./types"
|
||||
import { waitForTaskSessionID } from "./wait-for-task-session"
|
||||
|
||||
interface TaskSnapshot {
|
||||
sessionID?: string
|
||||
status?: BackgroundTaskStatus
|
||||
}
|
||||
|
||||
function createManager(responses: TaskSnapshot[]) {
|
||||
let index = 0
|
||||
|
||||
return {
|
||||
getTask(_taskID: string): TaskSnapshot {
|
||||
const response = responses[Math.min(index, responses.length - 1)]
|
||||
index += 1
|
||||
return response
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe("waitForTaskSessionID", () => {
|
||||
test("#given task already has a session id #when waiting #then it returns immediately", async () => {
|
||||
// given
|
||||
const manager = createManager([{ sessionID: "ses_ready_123", status: "running" }])
|
||||
|
||||
// when
|
||||
const sessionID = await waitForTaskSessionID(manager, "bg_ready")
|
||||
|
||||
// then
|
||||
expect(sessionID).toBe("ses_ready_123")
|
||||
})
|
||||
|
||||
test("#given session appears later #when waiting #then it polls until resolved", async () => {
|
||||
// given
|
||||
const manager = createManager([
|
||||
{ status: "running" },
|
||||
{ status: "running" },
|
||||
{ sessionID: "ses_late_123", status: "running" },
|
||||
])
|
||||
|
||||
// when
|
||||
const sessionID = await waitForTaskSessionID(manager, "bg_late", {
|
||||
intervalMs: 1,
|
||||
timeoutMs: 20,
|
||||
})
|
||||
|
||||
// then
|
||||
expect(sessionID).toBe("ses_late_123")
|
||||
})
|
||||
|
||||
test("#given aborted signal #when waiting #then it returns undefined", async () => {
|
||||
// given
|
||||
const controller = new AbortController()
|
||||
controller.abort()
|
||||
const manager = createManager([{ status: "running" }])
|
||||
|
||||
// when
|
||||
const sessionID = await waitForTaskSessionID(manager, "bg_abort", {
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
// then
|
||||
expect(sessionID).toBeUndefined()
|
||||
})
|
||||
|
||||
test("#given task never resolves #when waiting past timeout #then it returns undefined", async () => {
|
||||
// given
|
||||
const manager = createManager([{ status: "running" }, { status: "running" }, { status: "running" }])
|
||||
|
||||
// when
|
||||
const sessionID = await waitForTaskSessionID(manager, "bg_timeout", {
|
||||
intervalMs: 1,
|
||||
timeoutMs: 3,
|
||||
})
|
||||
|
||||
// then
|
||||
expect(sessionID).toBeUndefined()
|
||||
})
|
||||
|
||||
test.each(["error", "cancelled", "interrupt"] satisfies BackgroundTaskStatus[])(
|
||||
"#given %s task state #when waiting #then it returns undefined",
|
||||
async (status: BackgroundTaskStatus) => {
|
||||
// given
|
||||
const manager = createManager([{ status }])
|
||||
|
||||
// when
|
||||
const sessionID = await waitForTaskSessionID(manager, `bg_${status}`)
|
||||
|
||||
// then
|
||||
expect(sessionID).toBeUndefined()
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,68 @@
|
||||
import { getTimingConfig } from "../../tools/delegate-task/timing"
|
||||
import type { BackgroundTaskStatus } from "./types"
|
||||
|
||||
type SessionWaitTerminalStatus = Extract<BackgroundTaskStatus, "error" | "cancelled" | "interrupt">
|
||||
type AbortSignalLike = { aborted: boolean }
|
||||
|
||||
interface TaskReader {
|
||||
getTask(taskID: string): { sessionID?: string; status?: BackgroundTaskStatus } | undefined
|
||||
}
|
||||
|
||||
export interface WaitForTaskSessionIDOptions {
|
||||
timeoutMs?: number
|
||||
intervalMs?: number
|
||||
signal?: AbortSignalLike
|
||||
}
|
||||
|
||||
function isTerminalStatus(status: BackgroundTaskStatus | undefined): status is SessionWaitTerminalStatus {
|
||||
return status === "error" || status === "cancelled" || status === "interrupt"
|
||||
}
|
||||
|
||||
function waitForInterval(intervalMs: number): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
const scheduler = globalThis as { setTimeout: (handler: () => void, timeout?: number) => unknown }
|
||||
scheduler.setTimeout(resolve, intervalMs)
|
||||
})
|
||||
}
|
||||
|
||||
export async function waitForTaskSessionID(
|
||||
manager: TaskReader,
|
||||
taskID: string,
|
||||
options: WaitForTaskSessionIDOptions = {}
|
||||
): Promise<string | undefined> {
|
||||
const timing = getTimingConfig()
|
||||
const timeoutMs = options.timeoutMs ?? timing.WAIT_FOR_SESSION_TIMEOUT_MS
|
||||
const intervalMs = options.intervalMs ?? timing.WAIT_FOR_SESSION_INTERVAL_MS
|
||||
|
||||
if (options.signal?.aborted) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const initialTask = manager.getTask(taskID)
|
||||
if (initialTask?.sessionID) {
|
||||
return initialTask.sessionID
|
||||
}
|
||||
if (isTerminalStatus(initialTask?.status)) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const deadline = Date.now() + timeoutMs
|
||||
|
||||
while (Date.now() < deadline) {
|
||||
if (options.signal?.aborted) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
await waitForInterval(intervalMs)
|
||||
|
||||
const task = manager.getTask(taskID)
|
||||
if (task?.sessionID) {
|
||||
return task.sessionID
|
||||
}
|
||||
if (isTerminalStatus(task?.status)) {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
@@ -23,8 +23,8 @@ describe("mapClaudeModelToOpenCode", () => {
|
||||
expect(mapClaudeModelToOpenCode("sonnet")).toEqual({ providerID: "anthropic", modelID: "claude-sonnet-4-6" })
|
||||
})
|
||||
|
||||
it("#when called with opus #then maps to anthropic claude-opus-4-6 object", () => {
|
||||
expect(mapClaudeModelToOpenCode("opus")).toEqual({ providerID: "anthropic", modelID: "claude-opus-4-6" })
|
||||
it("#when called with opus #then maps to anthropic claude-opus-4-7 object", () => {
|
||||
expect(mapClaudeModelToOpenCode("opus")).toEqual({ providerID: "anthropic", modelID: "claude-opus-4-7" })
|
||||
})
|
||||
|
||||
it("#when called with haiku #then maps to anthropic claude-haiku-4-5 object", () => {
|
||||
@@ -47,8 +47,8 @@ describe("mapClaudeModelToOpenCode", () => {
|
||||
expect(mapClaudeModelToOpenCode("claude-sonnet-4-5-20250514")).toEqual({ providerID: "anthropic", modelID: "claude-sonnet-4-5-20250514" })
|
||||
})
|
||||
|
||||
it("#when called with claude-opus-4-6 #then adds anthropic object format", () => {
|
||||
expect(mapClaudeModelToOpenCode("claude-opus-4-6")).toEqual({ providerID: "anthropic", modelID: "claude-opus-4-6" })
|
||||
it("#when called with claude-opus-4-7 #then adds anthropic object format", () => {
|
||||
expect(mapClaudeModelToOpenCode("claude-opus-4-7")).toEqual({ providerID: "anthropic", modelID: "claude-opus-4-7" })
|
||||
})
|
||||
|
||||
it("#when called with claude-haiku-4-5-20251001 #then adds anthropic object format", () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ const ANTHROPIC_PREFIX = "anthropic/"
|
||||
|
||||
const CLAUDE_CODE_ALIAS_MAP = new Map<string, string>([
|
||||
["sonnet", `${ANTHROPIC_PREFIX}claude-sonnet-4-6`],
|
||||
["opus", `${ANTHROPIC_PREFIX}claude-opus-4-6`],
|
||||
["opus", `${ANTHROPIC_PREFIX}claude-opus-4-7`],
|
||||
["haiku", `${ANTHROPIC_PREFIX}claude-haiku-4-5`],
|
||||
])
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ describe("readOpencodeConfigAgents", () => {
|
||||
agents: {
|
||||
"my-agent": {
|
||||
description: "Custom agent",
|
||||
model: "claude-opus-4-6",
|
||||
model: "claude-opus-4-7",
|
||||
mode: "subagent",
|
||||
prompt: "You are a helpful assistant",
|
||||
},
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { promises as fs } from "fs"
|
||||
import { resolve } from "path"
|
||||
|
||||
import type { CommandDefinition } from "./types"
|
||||
|
||||
const commandLoaderCache = new Map<string, Promise<Record<string, CommandDefinition>>>()
|
||||
|
||||
export async function getCommandLoaderCacheKey(directory?: string): Promise<string> {
|
||||
const resolvedDirectory = resolve(directory ?? process.cwd())
|
||||
|
||||
try {
|
||||
return await fs.realpath(resolvedDirectory)
|
||||
} catch {
|
||||
return resolvedDirectory
|
||||
}
|
||||
}
|
||||
|
||||
export function getCachedCommands(
|
||||
cacheKey: string,
|
||||
): Promise<Record<string, CommandDefinition>> | undefined {
|
||||
return commandLoaderCache.get(cacheKey)
|
||||
}
|
||||
|
||||
export function setCachedCommands(
|
||||
cacheKey: string,
|
||||
commands: Promise<Record<string, CommandDefinition>>,
|
||||
): void {
|
||||
commandLoaderCache.set(cacheKey, commands)
|
||||
}
|
||||
|
||||
export function deleteCachedCommands(cacheKey: string): void {
|
||||
commandLoaderCache.delete(cacheKey)
|
||||
}
|
||||
|
||||
export function clearCommandLoaderCache(): void {
|
||||
commandLoaderCache.clear()
|
||||
}
|
||||
@@ -1,9 +1,10 @@
|
||||
import { execFileSync } from "node:child_process"
|
||||
import { afterEach, beforeEach, describe, expect, it } from "bun:test"
|
||||
import { promises as fs } from "node:fs"
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from "bun:test"
|
||||
import { mkdirSync, rmSync, writeFileSync } from "node:fs"
|
||||
import { tmpdir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
import { loadOpencodeGlobalCommands, loadOpencodeProjectCommands } from "./loader"
|
||||
import * as loader from "./loader"
|
||||
|
||||
const TEST_DIR = join(tmpdir(), `claude-code-command-loader-${Date.now()}`)
|
||||
|
||||
@@ -16,19 +17,41 @@ function writeCommand(directory: string, name: string, description: string): voi
|
||||
}
|
||||
|
||||
describe("claude-code command loader", () => {
|
||||
let originalClaudeConfigDir: string | undefined
|
||||
let originalOpencodeConfigDir: string | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
mkdirSync(TEST_DIR, { recursive: true })
|
||||
originalClaudeConfigDir = process.env.CLAUDE_CONFIG_DIR
|
||||
originalOpencodeConfigDir = process.env.OPENCODE_CONFIG_DIR
|
||||
|
||||
const claudeConfigDir = join(TEST_DIR, "claude-config")
|
||||
const opencodeConfigDir = join(TEST_DIR, "opencode-config")
|
||||
process.env.CLAUDE_CONFIG_DIR = claudeConfigDir
|
||||
process.env.OPENCODE_CONFIG_DIR = opencodeConfigDir
|
||||
|
||||
if ("clearCommandLoaderCache" in loader && typeof loader.clearCommandLoaderCache === "function") {
|
||||
loader.clearCommandLoaderCache()
|
||||
}
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (originalClaudeConfigDir === undefined) {
|
||||
delete process.env.CLAUDE_CONFIG_DIR
|
||||
} else {
|
||||
process.env.CLAUDE_CONFIG_DIR = originalClaudeConfigDir
|
||||
}
|
||||
|
||||
if (originalOpencodeConfigDir === undefined) {
|
||||
delete process.env.OPENCODE_CONFIG_DIR
|
||||
} else {
|
||||
process.env.OPENCODE_CONFIG_DIR = originalOpencodeConfigDir
|
||||
}
|
||||
|
||||
if ("clearCommandLoaderCache" in loader && typeof loader.clearCommandLoaderCache === "function") {
|
||||
loader.clearCommandLoaderCache()
|
||||
}
|
||||
|
||||
rmSync(TEST_DIR, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
@@ -39,7 +62,7 @@ describe("claude-code command loader", () => {
|
||||
writeCommand(join(projectDir, ".opencode", "commands"), "ancestor", "Ancestor command")
|
||||
|
||||
// when
|
||||
const commands = await loadOpencodeProjectCommands(childDir)
|
||||
const commands = await loader.loadOpencodeProjectCommands(childDir)
|
||||
|
||||
// then
|
||||
expect(commands.ancestor?.description).toBe("(opencode-project) Ancestor command")
|
||||
@@ -50,7 +73,7 @@ describe("claude-code command loader", () => {
|
||||
writeCommand(join(TEST_DIR, ".opencode", "command"), "singular", "Singular command")
|
||||
|
||||
// when
|
||||
const commands = await loadOpencodeProjectCommands(TEST_DIR)
|
||||
const commands = await loader.loadOpencodeProjectCommands(TEST_DIR)
|
||||
|
||||
// then
|
||||
expect(commands.singular?.description).toBe("(opencode-project) Singular command")
|
||||
@@ -66,7 +89,7 @@ describe("claude-code command loader", () => {
|
||||
writeCommand(projectDir, "duplicate", "Nearest command")
|
||||
|
||||
// when
|
||||
const commands = await loadOpencodeProjectCommands(childDir)
|
||||
const commands = await loader.loadOpencodeProjectCommands(childDir)
|
||||
|
||||
// then
|
||||
expect(commands.duplicate?.description).toBe("(opencode-project) Nearest command")
|
||||
@@ -79,7 +102,7 @@ describe("claude-code command loader", () => {
|
||||
writeCommand(join(opencodeConfigDir, "commands"), "global-plural", "Global plural command")
|
||||
|
||||
// when
|
||||
const commands = await loadOpencodeGlobalCommands()
|
||||
const commands = await loader.loadOpencodeGlobalCommands()
|
||||
|
||||
// then
|
||||
expect(commands["global-plural"]?.description).toBe("(opencode) Global plural command")
|
||||
@@ -94,7 +117,7 @@ describe("claude-code command loader", () => {
|
||||
writeCommand(join(profileConfigDir, "commands"), "duplicate-global", "Profile global command")
|
||||
|
||||
// when
|
||||
const commands = await loadOpencodeGlobalCommands()
|
||||
const commands = await loader.loadOpencodeGlobalCommands()
|
||||
|
||||
// then
|
||||
expect(commands["duplicate-global"]?.description).toBe("(opencode) Profile global command")
|
||||
@@ -114,7 +137,7 @@ describe("claude-code command loader", () => {
|
||||
writeCommand(join(TEST_DIR, ".opencode", "commands"), "outside", "Outside command")
|
||||
|
||||
// when
|
||||
const commands = await loadOpencodeProjectCommands(nestedDirectory)
|
||||
const commands = await loader.loadOpencodeProjectCommands(nestedDirectory)
|
||||
|
||||
// then
|
||||
expect(commands["deploy/staging"]?.description).toBe("(opencode-project) Deploy staging")
|
||||
@@ -122,4 +145,38 @@ describe("claude-code command loader", () => {
|
||||
expect(commands.outside).toBeUndefined()
|
||||
expect(commands["deploy:staging"]).toBeUndefined()
|
||||
})
|
||||
|
||||
it("#given commands nested under an excluded basename #when loadProjectCommands is called #then it skips the excluded directory contents", async () => {
|
||||
// given
|
||||
writeCommand(join(TEST_DIR, ".claude", "commands"), "real", "Real command")
|
||||
writeCommand(
|
||||
join(TEST_DIR, ".claude", "commands", "node_modules"),
|
||||
"fake",
|
||||
"Fake command",
|
||||
)
|
||||
|
||||
// when
|
||||
const commands = await loader.loadProjectCommands(TEST_DIR)
|
||||
|
||||
// then
|
||||
expect(commands.real?.description).toBe("(project) Real command")
|
||||
expect(commands.fake).toBeUndefined()
|
||||
})
|
||||
|
||||
it("#given a previously loaded directory #when loadAllCommands is called twice #then the second call reuses the cached result without readdir calls", async () => {
|
||||
// given
|
||||
writeCommand(join(TEST_DIR, ".claude", "commands"), "cached", "Cached command")
|
||||
const readdirSpy = spyOn(fs, "readdir")
|
||||
|
||||
// when
|
||||
const firstCommands = await loader.loadAllCommands(TEST_DIR)
|
||||
const firstReaddirCount = readdirSpy.mock.calls.length
|
||||
const secondCommands = await loader.loadAllCommands(TEST_DIR)
|
||||
|
||||
// then
|
||||
expect(firstCommands.cached?.description).toBe("(project) Cached command")
|
||||
expect(secondCommands).toEqual(firstCommands)
|
||||
expect(firstReaddirCount).toBeGreaterThan(0)
|
||||
expect(readdirSpy.mock.calls.length).toBe(firstReaddirCount)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,13 +4,23 @@ import { parseFrontmatter } from "../../shared/frontmatter"
|
||||
import { sanitizeModelField } from "../../shared/model-sanitizer"
|
||||
import { isMarkdownFile } from "../../shared/file-utils"
|
||||
import {
|
||||
EXCLUDED_DIRS,
|
||||
findProjectOpencodeCommandDirs,
|
||||
getClaudeConfigDir,
|
||||
getOpenCodeCommandDirs,
|
||||
} from "../../shared"
|
||||
import { log } from "../../shared/logger"
|
||||
import {
|
||||
clearCommandLoaderCache,
|
||||
deleteCachedCommands,
|
||||
getCachedCommands,
|
||||
getCommandLoaderCacheKey,
|
||||
setCachedCommands,
|
||||
} from "./loader-cache"
|
||||
import type { CommandScope, CommandDefinition, CommandFrontmatter, LoadedCommand } from "./types"
|
||||
|
||||
export { clearCommandLoaderCache }
|
||||
|
||||
async function loadCommandsFromDir(
|
||||
commandsDir: string,
|
||||
scope: CommandScope,
|
||||
@@ -48,6 +58,7 @@ async function loadCommandsFromDir(
|
||||
|
||||
for (const entry of entries) {
|
||||
if (entry.isDirectory()) {
|
||||
if (EXCLUDED_DIRS.has(entry.name)) continue
|
||||
if (entry.name.startsWith(".")) continue
|
||||
const subDirPath = join(commandsDir, entry.name)
|
||||
const subPrefix = prefix ? `${prefix}/${entry.name}` : entry.name
|
||||
@@ -159,11 +170,26 @@ export async function loadOpencodeProjectCommands(directory?: string): Promise<R
|
||||
}
|
||||
|
||||
export async function loadAllCommands(directory?: string): Promise<Record<string, CommandDefinition>> {
|
||||
const [user, project, global, projectOpencode] = await Promise.all([
|
||||
const cacheKey = await getCommandLoaderCacheKey(directory)
|
||||
const cachedCommands = getCachedCommands(cacheKey)
|
||||
if (cachedCommands) {
|
||||
return cachedCommands
|
||||
}
|
||||
|
||||
const loadCommandsPromise = Promise.all([
|
||||
loadUserCommands(),
|
||||
loadProjectCommands(directory),
|
||||
loadOpencodeGlobalCommands(),
|
||||
loadOpencodeProjectCommands(directory),
|
||||
])
|
||||
return { ...projectOpencode, ...global, ...project, ...user }
|
||||
.then(([user, project, global, projectOpencode]) => {
|
||||
return { ...projectOpencode, ...global, ...project, ...user }
|
||||
})
|
||||
.catch((error) => {
|
||||
deleteCachedCommands(cacheKey)
|
||||
throw error
|
||||
})
|
||||
|
||||
setCachedCommands(cacheKey, loadCommandsPromise)
|
||||
return loadCommandsPromise
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
# src/features/claude-code-mcp-loader/ — Tier 2 MCP Loader (.mcp.json)
|
||||
|
||||
**Generated:** 2026-04-18
|
||||
|
||||
## OVERVIEW
|
||||
|
||||
11 files. Loads `.mcp.json` files from project/user scopes and expands `${VAR}` env vars. Feeds Tier 2 of the 3-tier MCP system into `mcp-config-handler.ts` during Phase 5 of config loading.
|
||||
|
||||
## WHY IT EXISTS
|
||||
|
||||
Claude Code ecosystem ships MCPs via `.mcp.json` files with `${VAR}` env var placeholders. OmO consumes these unchanged so existing Claude Code MCP configs work.
|
||||
|
||||
## LOAD PIPELINE
|
||||
|
||||
```
|
||||
loadMcpConfigs(ctx)
|
||||
→ scope-filter.ts: discover .mcp.json at project + user scopes
|
||||
→ loader.ts: parse JSON
|
||||
→ env-expander.ts: replace ${VAR} with process.env[VAR]
|
||||
→ transformer.ts: map Claude Code format → OpenCode McpLocal / McpRemote shape
|
||||
→ return LoadedMcpServer[]
|
||||
```
|
||||
|
||||
## MCP FORMAT
|
||||
|
||||
```jsonc
|
||||
// .mcp.json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-stdio": {
|
||||
"type": "stdio",
|
||||
"command": "node",
|
||||
"args": ["server.js"],
|
||||
"env": {
|
||||
"API_KEY": "${MY_API_KEY}"
|
||||
}
|
||||
},
|
||||
"my-http": {
|
||||
"type": "http", // "sse" legacy → mapped to http
|
||||
"url": "https://example.com/mcp",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${MY_TOKEN}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## KEY FILES
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `index.ts` | Barrel: `loadMcpConfigs`, types |
|
||||
| `loader.ts` | `loadMcpConfigs()` main entry |
|
||||
| `types.ts` | `ClaudeCodeMcpServer`, `LoadedMcpServer`, `McpScope` |
|
||||
| `env-expander.ts` | `expandEnvVarsInObject()` — recursive `${VAR}` substitution |
|
||||
| `transformer.ts` | Claude Code format → OpenCode `Mcp` shape |
|
||||
| `scope-filter.ts` | Project vs user scope precedence |
|
||||
|
||||
## THREE-TIER MCP CONTEXT
|
||||
|
||||
| Tier | Loader | Scope |
|
||||
|------|--------|-------|
|
||||
| 1. Built-in | `src/mcp/` `createBuiltinMcps()` | Global, 3 remote HTTP MCPs |
|
||||
| 2. **Claude Code** | **This module** | **From `.mcp.json`, project + user** |
|
||||
| 3. Skill-embedded | `src/features/skill-mcp-manager/` | Per-session, from SKILL.md YAML |
|
||||
|
||||
## SECURITY
|
||||
|
||||
- **Env var allowlist**: `mcp_env_allowlist` config restricts which env vars can be expanded
|
||||
- **No shell execution**: `${VAR}` is string replacement only, not shell `$()`
|
||||
- **Secrets redaction**: `env-cleaner.ts` (in skill-mcp-manager) filters known secret patterns from logs
|
||||
|
||||
## RELATED
|
||||
|
||||
- Phase 5 integration: `src/plugin-handlers/mcp-config-handler.ts`
|
||||
- Skill-embedded MCPs (Tier 3): `src/features/skill-mcp-manager/`
|
||||
- Built-in MCPs (Tier 1): `src/mcp/`
|
||||
@@ -0,0 +1,78 @@
|
||||
# src/features/claude-code-plugin-loader/ — Unified Claude Code Plugin Loader
|
||||
|
||||
**Generated:** 2026-04-18
|
||||
|
||||
## OVERVIEW
|
||||
|
||||
16 files. Full Claude Code plugin compatibility layer. Discovers and loads ALL plugin components (commands, agents, skills, hooks, MCP servers, LSP servers) from `.opencode/plugins/` and `~/.claude/plugins/`.
|
||||
|
||||
## WHY IT EXISTS
|
||||
|
||||
Claude Code plugins ship commands/agents/skills as separate files with `plugin.json` manifest. OmO uses this loader to ingest them into its own registry so existing Claude Code plugins work unchanged under OmO.
|
||||
|
||||
## LOAD PIPELINE
|
||||
|
||||
```
|
||||
loadAllPluginComponents(ctx)
|
||||
→ discoverPlugins() # scan .opencode/plugins + ~/.claude/plugins
|
||||
→ readPluginManifest(plugin.json) # parse name/version/commands/agents/skills/hooks/mcpServers
|
||||
→ loadPluginCommands()
|
||||
→ loadPluginAgents()
|
||||
→ loadPluginSkills()
|
||||
→ loadPluginHooks() # register hook handlers
|
||||
→ loadPluginMcpServers() # feed into mcp-config-handler (tier 2)
|
||||
→ loadPluginLspServers()
|
||||
→ return LoadedPluginBundle
|
||||
```
|
||||
|
||||
Called from `src/plugin-handlers/plugin-components-loader.ts` during Phase 2 of config handler (10s timeout with error isolation — one broken plugin does not sink the plugin load).
|
||||
|
||||
## KEY FILES
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `index.ts` | Barrel: `loadAllPluginComponents`, `PluginManifest`, `ClaudeSettings` types |
|
||||
| `plugin-discovery.ts` | Find plugin directories across scopes |
|
||||
| `plugin-manifest-parser.ts` | Parse `plugin.json` with Zod validation |
|
||||
| `command-loader.ts` | Load commands from `commands/` or `COMMANDS.md` |
|
||||
| `agent-loader.ts` | Load agents from `agents/` or `AGENTS.md` frontmatter |
|
||||
| `skill-loader.ts` | Load skills from `skills/` or `SKILL.md` |
|
||||
| `hook-loader.ts` | Load hooks config from `hooks/` or manifest |
|
||||
| `mcp-loader.ts` | Extract MCP server configs |
|
||||
| `lsp-loader.ts` | Extract LSP server configs |
|
||||
| `settings-loader.ts` | Parse Claude Code `settings.json` |
|
||||
|
||||
## PLUGIN MANIFEST (plugin.json)
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"name": "my-plugin",
|
||||
"version": "1.0.0",
|
||||
"description": "...",
|
||||
"commands": ["./commands"], // or string[] of paths
|
||||
"agents": ["./agents"],
|
||||
"skills": ["./skills"],
|
||||
"hooks": "./hooks/config.json",
|
||||
"mcpServers": "./.mcp.json",
|
||||
"lspServers": "./lsp"
|
||||
}
|
||||
```
|
||||
|
||||
## SCOPES
|
||||
|
||||
| Scope | Path | Priority |
|
||||
|-------|------|----------|
|
||||
| `project` | `.opencode/plugins/` | Highest |
|
||||
| `local` | `~/.opencode/plugins/` | Medium |
|
||||
| `user` | `~/.claude/plugins/` | Medium |
|
||||
| `managed` | Built-in | Lowest |
|
||||
|
||||
## ERROR ISOLATION
|
||||
|
||||
Each plugin loads in isolation — if one fails (bad manifest, missing file, syntax error), others still load. Errors surface as warnings in `bunx oh-my-opencode doctor`.
|
||||
|
||||
## RELATED
|
||||
|
||||
- Phase 2 loader: `src/plugin-handlers/plugin-components-loader.ts`
|
||||
- Tier 2 MCP integration: `src/features/claude-code-mcp-loader/`
|
||||
- Claude Code compat hooks: `src/hooks/claude-code-hooks/`
|
||||
@@ -3,12 +3,19 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from "bun:test"
|
||||
import { join } from "node:path"
|
||||
import { tmpdir } from "node:os"
|
||||
import { resolveSkillContent, resolveMultipleSkills, resolveSkillContentAsync, resolveMultipleSkillsAsync } from "./skill-content"
|
||||
import {
|
||||
clearSkillCache,
|
||||
resolveSkillContent,
|
||||
resolveMultipleSkills,
|
||||
resolveSkillContentAsync,
|
||||
resolveMultipleSkillsAsync,
|
||||
} from "./skill-content"
|
||||
|
||||
let originalEnv: Record<string, string | undefined>
|
||||
let testConfigDir: string
|
||||
|
||||
beforeEach(() => {
|
||||
clearSkillCache()
|
||||
originalEnv = {
|
||||
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR,
|
||||
OPENCODE_CONFIG_DIR: process.env.OPENCODE_CONFIG_DIR,
|
||||
@@ -20,6 +27,7 @@ beforeEach(() => {
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearSkillCache()
|
||||
for (const [key, value] of Object.entries(originalEnv)) {
|
||||
if (value !== undefined) {
|
||||
process.env[key] = value
|
||||
|
||||
@@ -203,7 +203,7 @@ describe("TaskToastManager", () => {
|
||||
description: "Task with inherited model",
|
||||
agent: "sisyphus-junior",
|
||||
isBackground: false,
|
||||
modelInfo: { model: "cliproxy/claude-opus-4-6", type: "inherited" as const },
|
||||
modelInfo: { model: "cliproxy/claude-opus-4-7", type: "inherited" as const },
|
||||
}
|
||||
|
||||
// when - addTask is called
|
||||
@@ -213,7 +213,7 @@ describe("TaskToastManager", () => {
|
||||
expect(mockClient.tui.showToast).toHaveBeenCalled()
|
||||
const call = mockClient.tui.showToast.mock.calls[0][0]
|
||||
expect(call.body.message).toContain("[FALLBACK]")
|
||||
expect(call.body.message).toContain("cliproxy/claude-opus-4-6")
|
||||
expect(call.body.message).toContain("cliproxy/claude-opus-4-7")
|
||||
expect(call.body.message).toContain("(inherited from parent)")
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./types"
|
||||
export * from "./team-worktree"
|
||||
@@ -0,0 +1 @@
|
||||
export { canVisualize, createTeamLayout, removeTeamLayout } from "./layout"
|
||||
@@ -0,0 +1,94 @@
|
||||
import { beforeEach, describe, expect, mock, test } from "bun:test"
|
||||
|
||||
type LayoutModule = typeof import("./layout")
|
||||
|
||||
const spawnMock = mock(() => ({
|
||||
exited: Promise.resolve(0),
|
||||
stdout: new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("%1\n")); controller.close() } }),
|
||||
stderr: new ReadableStream({ start(controller) { controller.close() } }),
|
||||
}))
|
||||
|
||||
const layoutSpecifier = import.meta.resolve("./layout")
|
||||
const spawnProcessSpecifier = import.meta.resolve("../../../shared/tmux/tmux-utils/spawn-process")
|
||||
const tmuxPathResolverSpecifier = import.meta.resolve("../../../tools/interactive-bash/tmux-path-resolver")
|
||||
const sharedSpecifier = import.meta.resolve("../../../shared")
|
||||
|
||||
function registerModuleMocks(): void {
|
||||
mock.module(spawnProcessSpecifier, () => ({ spawn: spawnMock }))
|
||||
mock.module(tmuxPathResolverSpecifier, () => ({ getTmuxPath: mock(() => Promise.resolve("tmux")) }))
|
||||
mock.module(sharedSpecifier, () => ({ log: mock(() => undefined) }))
|
||||
}
|
||||
|
||||
async function loadLayoutModule(): Promise<LayoutModule> {
|
||||
const module = await import(`${layoutSpecifier}?test=${crypto.randomUUID()}`)
|
||||
return module as LayoutModule
|
||||
}
|
||||
|
||||
describe("team-layout-tmux", () => {
|
||||
beforeEach(() => {
|
||||
registerModuleMocks()
|
||||
spawnMock.mockClear()
|
||||
process.env.TMUX = "/tmp/tmux-1"
|
||||
})
|
||||
|
||||
test("returns null and makes no tmux calls when visualization unavailable", async () => {
|
||||
// given
|
||||
delete process.env.TMUX
|
||||
const { createTeamLayout, canVisualize } = await loadLayoutModule()
|
||||
|
||||
// when
|
||||
const result = await createTeamLayout("run-1", [], {} as never)
|
||||
|
||||
// then
|
||||
expect(canVisualize()).toBe(false)
|
||||
expect(result).toBeNull()
|
||||
expect(spawnMock).toHaveBeenCalledTimes(0)
|
||||
})
|
||||
|
||||
test("creates focus and grid windows", async () => {
|
||||
// given
|
||||
const { createTeamLayout } = await loadLayoutModule()
|
||||
const members = [
|
||||
{ name: "lead", sessionId: "s1", color: "red" },
|
||||
{ name: "m2", sessionId: "s2" },
|
||||
{ name: "m3", sessionId: "s3" },
|
||||
]
|
||||
|
||||
// when
|
||||
await createTeamLayout("run-2", members, {} as never)
|
||||
|
||||
// then
|
||||
expect(spawnMock.mock.calls.flatMap((call) => call[0] as Array<string>)).toContain("new-session")
|
||||
expect(spawnMock.mock.calls.flatMap((call) => call[0] as Array<string>)).toContain("new-window")
|
||||
expect(spawnMock.mock.calls.flatMap((call) => call[0] as Array<string>)).toContain("split-window")
|
||||
expect(spawnMock.mock.calls.flatMap((call) => call[0] as Array<string>)).toContain("select-layout")
|
||||
expect(spawnMock.mock.calls.flatMap((call) => call[0] as Array<string>)).toContain("select-pane")
|
||||
})
|
||||
|
||||
test("returns null when tmux command fails", async () => {
|
||||
// given
|
||||
const { createTeamLayout } = await loadLayoutModule()
|
||||
spawnMock.mockImplementationOnce(() => ({
|
||||
exited: Promise.resolve(1),
|
||||
stdout: new ReadableStream({ start(controller) { controller.close() } }),
|
||||
stderr: new ReadableStream({ start(controller) { controller.close() } }),
|
||||
}))
|
||||
|
||||
// when
|
||||
const result = await createTeamLayout("run-3", [{ name: "lead", sessionId: "s1" }], {} as never)
|
||||
|
||||
// then
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
|
||||
test("cleans up the tmux session", async () => {
|
||||
// given
|
||||
const { removeTeamLayout } = await loadLayoutModule()
|
||||
|
||||
// when
|
||||
await removeTeamLayout("run-4", {} as never)
|
||||
|
||||
// then
|
||||
expect(spawnMock.mock.calls.some((call) => (call[0] as Array<string>).includes("kill-session"))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,120 @@
|
||||
import { spawn } from "../../../shared/tmux/tmux-utils/spawn-process"
|
||||
import { log } from "../../../shared"
|
||||
import { getTmuxPath } from "../../../tools/interactive-bash/tmux-path-resolver"
|
||||
import type { TmuxSessionManager } from "../../tmux-subagent/manager"
|
||||
|
||||
type TeamLayoutMember = { name: string; sessionId: string; color?: string }
|
||||
|
||||
type TeamLayoutResult = {
|
||||
focusWindowId: string
|
||||
gridWindowId: string
|
||||
panesByMember: Record<string, string>
|
||||
}
|
||||
|
||||
export function canVisualize(): boolean {
|
||||
return process.env.TMUX !== undefined
|
||||
}
|
||||
|
||||
async function runTmux(tmuxPath: string, args: Array<string>): Promise<{ success: boolean; output: string }> {
|
||||
const proc = spawn([tmuxPath, ...args], { stdout: "pipe", stderr: "pipe" })
|
||||
const outputPromise = new Response(proc.stdout).text()
|
||||
const exitCode = await proc.exited
|
||||
const output = await outputPromise
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return { success: false, output: output.trim() }
|
||||
}
|
||||
|
||||
return { success: true, output: output.trim() }
|
||||
}
|
||||
|
||||
async function createWindow(
|
||||
tmuxPath: string,
|
||||
sessionName: string,
|
||||
windowName: string,
|
||||
layout: "main-vertical" | "tiled",
|
||||
members: Array<TeamLayoutMember>,
|
||||
): Promise<{ windowId: string; panesByMember: Record<string, string> } | null> {
|
||||
const base = await runTmux(tmuxPath, ["new-window", "-d", "-P", "-F", "#{window_id}", "-t", sessionName, "-n", windowName])
|
||||
if (!base.success || !base.output) return null
|
||||
|
||||
const panesByMember: Record<string, string> = {}
|
||||
const [lead, ...rest] = members
|
||||
if (!lead) return null
|
||||
|
||||
const leadPane = await runTmux(tmuxPath, ["list-panes", "-t", `${sessionName}:${base.output}`, "-F", "#{pane_id}"])
|
||||
if (!leadPane.success || !leadPane.output) return null
|
||||
panesByMember[lead.name] = leadPane.output.split("\n")[0] ?? ""
|
||||
|
||||
for (const member of rest) {
|
||||
const split = await runTmux(tmuxPath, ["split-window", "-d", "-P", "-F", "#{pane_id}", "-t", panesByMember[lead.name] ?? base.output, "sh", "-c", "cat >/dev/null"])
|
||||
if (!split.success || !split.output) return null
|
||||
panesByMember[member.name] = split.output
|
||||
}
|
||||
|
||||
const layoutResult = await runTmux(tmuxPath, ["select-layout", "-t", `${sessionName}:${base.output}`, layout])
|
||||
if (!layoutResult.success) return null
|
||||
|
||||
for (const member of members) {
|
||||
const paneId = panesByMember[member.name]
|
||||
if (!paneId) return null
|
||||
const label = member.color ? `${member.name} ${member.color}` : member.name
|
||||
const titleResult = await runTmux(tmuxPath, ["select-pane", "-t", paneId, "-T", label])
|
||||
if (!titleResult.success) return null
|
||||
await runTmux(tmuxPath, ["set-option", "-t", paneId, "pane-border-status", "top"])
|
||||
await runTmux(tmuxPath, ["set-option", "-t", paneId, "pane-border-format", `#{pane_title} ${label}`])
|
||||
await runTmux(tmuxPath, ["pipe-pane", "-I", "-t", paneId, "cat >/dev/null"])
|
||||
}
|
||||
|
||||
return { windowId: base.output, panesByMember }
|
||||
}
|
||||
|
||||
export async function createTeamLayout(
|
||||
teamRunId: string,
|
||||
members: Array<TeamLayoutMember>,
|
||||
tmuxMgr: TmuxSessionManager,
|
||||
): Promise<TeamLayoutResult | null> {
|
||||
if (!canVisualize()) {
|
||||
log("tmux visualization unavailable, skipping")
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
void tmuxMgr
|
||||
const tmuxPath = await getTmuxPath()
|
||||
if (!tmuxPath) {
|
||||
log("tmux visualization unavailable, skipping")
|
||||
return null
|
||||
}
|
||||
|
||||
const sessionName = `omo-team-${teamRunId}`
|
||||
const created = await runTmux(tmuxPath, ["new-session", "-d", "-s", sessionName, "-P", "-F", "#{window_id}"])
|
||||
if (!created.success || !created.output) return null
|
||||
|
||||
const focus = await createWindow(tmuxPath, sessionName, "focus", "main-vertical", members)
|
||||
const grid = await createWindow(tmuxPath, sessionName, "grid", "tiled", members)
|
||||
if (!focus || !grid) return null
|
||||
|
||||
return {
|
||||
focusWindowId: focus.windowId,
|
||||
gridWindowId: grid.windowId,
|
||||
panesByMember: focus.panesByMember,
|
||||
}
|
||||
} catch (error) {
|
||||
log("tmux visualization unavailable, skipping", { error: String(error) })
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function removeTeamLayout(teamRunId: string, tmuxMgr: TmuxSessionManager): Promise<void> {
|
||||
void tmuxMgr
|
||||
if (!canVisualize()) return
|
||||
|
||||
try {
|
||||
const tmuxPath = await getTmuxPath()
|
||||
if (!tmuxPath) return
|
||||
await runTmux(tmuxPath, ["kill-session", "-t", `omo-team-${teamRunId}`])
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
/// <reference types="bun-types" />
|
||||
|
||||
import { afterAll, expect, test } from "bun:test"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
import { findOrphanWorktrees } from "./cleanup"
|
||||
|
||||
const temporaryDirectories: string[] = []
|
||||
|
||||
afterAll(async () => {
|
||||
for (const directory of temporaryDirectories) {
|
||||
await fs.rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
test("given runtime mismatch when findOrphanWorktrees then returns orphan paths", async () => {
|
||||
// given
|
||||
const baseDir = await fs.mkdtemp(path.join(os.tmpdir(), "team-worktree-orphans-"))
|
||||
temporaryDirectories.push(baseDir)
|
||||
await fs.mkdir(path.join(baseDir, "worktrees", "t1", "m1"), { recursive: true })
|
||||
await fs.mkdir(path.join(baseDir, "runtime", "t1"), { recursive: true })
|
||||
await fs.writeFile(path.join(baseDir, "runtime", "t1", "state.json"), JSON.stringify({ status: "deleted" }))
|
||||
|
||||
// when
|
||||
const result = await findOrphanWorktrees(baseDir, {})
|
||||
|
||||
// then
|
||||
expect(result).toEqual([path.join(baseDir, "worktrees", "t1", "m1")])
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import fs from "node:fs/promises"
|
||||
import path from "node:path"
|
||||
|
||||
import type { TeamModeConfig } from "./manager"
|
||||
|
||||
async function runGit(args: string[]): Promise<{ code: number; stderr: string }> {
|
||||
const process = Bun.spawn({ cmd: ["git", ...args], stdout: "pipe", stderr: "pipe" })
|
||||
const [exitCode, stderrText] = await Promise.all([process.exited, new Response(process.stderr).text()])
|
||||
return { code: exitCode, stderr: stderrText }
|
||||
}
|
||||
|
||||
export async function removeWorktree(worktreePath: string): Promise<void> {
|
||||
await fs.rm(worktreePath, { recursive: true, force: true })
|
||||
|
||||
const rootLookup = await Bun.spawn({
|
||||
cmd: ["git", "-C", worktreePath, "rev-parse", "--show-superproject-working-tree"],
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
})
|
||||
const [rootExitCode, rootStdout] = await Promise.all([
|
||||
rootLookup.exited,
|
||||
new Response(rootLookup.stdout).text(),
|
||||
new Response(rootLookup.stderr).text(),
|
||||
])
|
||||
const result =
|
||||
rootExitCode === 0 && rootStdout.trim().length > 0
|
||||
? await runGit(["-C", rootStdout.trim(), "worktree", "remove", "--force", worktreePath])
|
||||
: await runGit(["worktree", "remove", "--force", worktreePath])
|
||||
|
||||
if (
|
||||
result.code !== 0 &&
|
||||
!result.stderr.includes("not a worktree") &&
|
||||
!result.stderr.includes("not a working tree") &&
|
||||
!result.stderr.includes("already removed")
|
||||
) {
|
||||
throw new Error(result.stderr.trim() || "git worktree remove failed")
|
||||
}
|
||||
|
||||
if (rootExitCode === 0 && rootStdout.trim().length > 0) {
|
||||
await runGit(["-C", rootStdout.trim(), "worktree", "prune"])
|
||||
}
|
||||
}
|
||||
|
||||
export async function findOrphanWorktrees(baseDir: string, _config: TeamModeConfig): Promise<string[]> {
|
||||
const orphanWorktrees: string[] = []
|
||||
const worktreesDir = path.join(baseDir, "worktrees")
|
||||
|
||||
let teamRunDirectories: string[]
|
||||
try {
|
||||
teamRunDirectories = await fs.readdir(worktreesDir)
|
||||
} catch {
|
||||
return orphanWorktrees
|
||||
}
|
||||
|
||||
for (const teamRunId of teamRunDirectories) {
|
||||
const teamRunPath = path.join(worktreesDir, teamRunId)
|
||||
const memberNames = await fs.readdir(teamRunPath).catch(() => [])
|
||||
|
||||
for (const memberName of memberNames) {
|
||||
const worktreePath = path.join(teamRunPath, memberName)
|
||||
const statePath = path.join(baseDir, "runtime", teamRunId, "state.json")
|
||||
|
||||
try {
|
||||
const stateContents = await fs.readFile(statePath, "utf8")
|
||||
const state = JSON.parse(stateContents) as { status?: string }
|
||||
|
||||
if (state.status !== "active" && state.status !== "shutdown_requested") {
|
||||
orphanWorktrees.push(worktreePath)
|
||||
}
|
||||
} catch {
|
||||
orphanWorktrees.push(worktreePath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return orphanWorktrees
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { GitUnavailableError, createWorktree, isGitAvailable, validateWorktreeSpec } from "./manager"
|
||||
export { findOrphanWorktrees, removeWorktree } from "./cleanup"
|
||||
@@ -0,0 +1,104 @@
|
||||
/// <reference types="bun-types" />
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, mock, test } from "bun:test"
|
||||
import { randomUUID } from "node:crypto"
|
||||
import fs from "node:fs/promises"
|
||||
import os from "node:os"
|
||||
import path from "node:path"
|
||||
|
||||
import { GitUnavailableError, createWorktree, setGitCommandRunnerForTests, validateWorktreeSpec } from "./manager"
|
||||
import { removeWorktree } from "./cleanup"
|
||||
|
||||
const temporaryDirectories: string[] = []
|
||||
|
||||
async function initGitRepo(): Promise<string> {
|
||||
const repositoryRoot = await fs.mkdtemp(path.join(os.tmpdir(), "team-worktree-"))
|
||||
temporaryDirectories.push(repositoryRoot)
|
||||
Bun.spawnSync(["git", "init"], { cwd: repositoryRoot, stdout: "pipe", stderr: "pipe" })
|
||||
await fs.writeFile(path.join(repositoryRoot, "README.md"), "hello\n")
|
||||
Bun.spawnSync(["git", "add", "README.md"], { cwd: repositoryRoot, stdout: "pipe", stderr: "pipe" })
|
||||
Bun.spawnSync(["git", "config", "user.email", "test@example.com"], { cwd: repositoryRoot, stdout: "pipe", stderr: "pipe" })
|
||||
Bun.spawnSync(["git", "config", "user.name", "Test User"], { cwd: repositoryRoot, stdout: "pipe", stderr: "pipe" })
|
||||
Bun.spawnSync(["git", "commit", "-m", "init"], { cwd: repositoryRoot, stdout: "pipe", stderr: "pipe" })
|
||||
return repositoryRoot
|
||||
}
|
||||
|
||||
beforeAll(() => {
|
||||
mock.restore()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
for (const directory of temporaryDirectories) {
|
||||
await fs.rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
mock.restore()
|
||||
})
|
||||
|
||||
describe("team-worktree manager", () => {
|
||||
test("given tmp git repo when createWorktree then registers detached worktree", async () => {
|
||||
// given
|
||||
const repositoryRoot = await initGitRepo()
|
||||
const worktreePath = `../worktree-${randomUUID()}`
|
||||
const worktreeDirectory = path.resolve(repositoryRoot, worktreePath)
|
||||
|
||||
// when
|
||||
const resultPath = await createWorktree(repositoryRoot, "t1", "m1", worktreePath, {})
|
||||
|
||||
// then
|
||||
expect(resultPath).toBe(worktreeDirectory)
|
||||
await expect(fs.stat(worktreeDirectory)).resolves.toBeDefined()
|
||||
const listResult = Bun.spawnSync(["git", "worktree", "list"], { cwd: repositoryRoot, stdout: "pipe", stderr: "pipe" })
|
||||
expect(new TextDecoder().decode(listResult.stdout)).toContain(worktreeDirectory)
|
||||
const headResult = Bun.spawnSync(["git", "-C", worktreeDirectory, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "pipe" })
|
||||
const repoHeadResult = Bun.spawnSync(["git", "-C", repositoryRoot, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "pipe" })
|
||||
expect(new TextDecoder().decode(headResult.stdout).trim()).toBe(new TextDecoder().decode(repoHeadResult.stdout).trim())
|
||||
})
|
||||
|
||||
test("validateWorktreeSpec rejects bare name", () => {
|
||||
// given
|
||||
const worktreePath = "feature-x"
|
||||
|
||||
// when
|
||||
const validate = () => validateWorktreeSpec(worktreePath)
|
||||
|
||||
// then
|
||||
expect(validate).toThrow("worktreePath must be a filesystem path (relative './...', '../...' or absolute '/...')")
|
||||
})
|
||||
|
||||
test("given git unavailable when createWorktree then throws unavailable error", async () => {
|
||||
// given
|
||||
const repositoryRoot = await initGitRepo()
|
||||
setGitCommandRunnerForTests(async (args) => {
|
||||
if (args[0] === "--version") {
|
||||
return { code: 1, stderr: "git missing" }
|
||||
}
|
||||
|
||||
return { code: 0, stderr: "" }
|
||||
})
|
||||
|
||||
// when
|
||||
const create = createWorktree(repositoryRoot, "t1", "m1", `../worktree-${randomUUID()}`, {})
|
||||
|
||||
// then
|
||||
await expect(create).rejects.toBeInstanceOf(GitUnavailableError)
|
||||
setGitCommandRunnerForTests(async (args) => {
|
||||
if (args[0] === "--version") {
|
||||
return { code: 0, stderr: "" }
|
||||
}
|
||||
|
||||
return { code: 0, stderr: "" }
|
||||
})
|
||||
})
|
||||
|
||||
test("given created worktree when removeWorktree then directory disappears", async () => {
|
||||
// given
|
||||
const repositoryRoot = await initGitRepo()
|
||||
const worktreePath = await createWorktree(repositoryRoot, "t1", "m1", `../worktree-${randomUUID()}`, {})
|
||||
|
||||
// when
|
||||
await removeWorktree(worktreePath)
|
||||
|
||||
// then
|
||||
await expect(fs.stat(worktreePath)).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,62 @@
|
||||
import path from "node:path"
|
||||
|
||||
export type TeamModeConfig = {
|
||||
worktreeBaseDir?: string
|
||||
}
|
||||
|
||||
export class GitUnavailableError extends Error {
|
||||
constructor() {
|
||||
super("git required for worktree members")
|
||||
this.name = "GitUnavailableError"
|
||||
}
|
||||
}
|
||||
|
||||
function countParentSegments(spec: string): number {
|
||||
return spec.split("/").filter((segment) => segment === "..").length
|
||||
}
|
||||
|
||||
async function runGit(args: string[], cwd?: string): Promise<{ code: number; stderr: string }> {
|
||||
const process = Bun.spawn({ cmd: ["git", ...args], cwd, stdout: "pipe", stderr: "pipe" })
|
||||
const [exitCode, stderrBytes] = await Promise.all([process.exited, new Response(process.stderr).text()])
|
||||
return { code: exitCode, stderr: stderrBytes }
|
||||
}
|
||||
|
||||
let gitCommandRunner = runGit
|
||||
|
||||
export function setGitCommandRunnerForTests(runner: typeof runGit): void {
|
||||
gitCommandRunner = runner
|
||||
}
|
||||
|
||||
export async function isGitAvailable(): Promise<boolean> {
|
||||
const result = await gitCommandRunner(["--version"])
|
||||
return result.code === 0
|
||||
}
|
||||
|
||||
export function validateWorktreeSpec(spec: string): void {
|
||||
if (!/^(\.\.?\/|\/).+/.test(spec) || countParentSegments(spec) > 2) {
|
||||
throw new Error("worktreePath must be a filesystem path (relative './...', '../...' or absolute '/...')")
|
||||
}
|
||||
}
|
||||
|
||||
export async function createWorktree(
|
||||
repoRoot: string,
|
||||
_teamRunId: string,
|
||||
_memberName: string,
|
||||
worktreePath: string,
|
||||
_config: TeamModeConfig,
|
||||
): Promise<string> {
|
||||
validateWorktreeSpec(worktreePath)
|
||||
|
||||
if (!(await isGitAvailable())) {
|
||||
throw new GitUnavailableError()
|
||||
}
|
||||
|
||||
const absolutePath = path.isAbsolute(worktreePath) ? worktreePath : path.resolve(repoRoot, worktreePath)
|
||||
const result = await gitCommandRunner(["-C", repoRoot, "worktree", "add", "--detach", absolutePath])
|
||||
|
||||
if (result.code !== 0) {
|
||||
throw new Error(result.stderr.trim() || "git worktree add failed")
|
||||
}
|
||||
|
||||
return absolutePath
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
AGENT_ELIGIBILITY_REGISTRY,
|
||||
CategoryMemberSchema,
|
||||
MemberSchema,
|
||||
SubagentMemberSchema,
|
||||
} from "./types"
|
||||
|
||||
describe("team-mode types", () => {
|
||||
test("member category branch parses and narrows", () => {
|
||||
// given
|
||||
const member = { kind: "category", name: "m1", category: "deep", prompt: "impl X" }
|
||||
|
||||
// when
|
||||
const result = MemberSchema.safeParse(member)
|
||||
|
||||
// then
|
||||
expect(result.success).toBe(true)
|
||||
if (result.success) {
|
||||
expect(result.data).toMatchObject(member)
|
||||
expect(result.data).toMatchObject({ kind: "category", category: "deep" })
|
||||
}
|
||||
})
|
||||
|
||||
test("both kinds rejected", () => {
|
||||
// given
|
||||
const member = {
|
||||
kind: "category",
|
||||
name: "m1",
|
||||
category: "deep",
|
||||
subagent_type: "sisyphus",
|
||||
prompt: "impl X",
|
||||
}
|
||||
|
||||
// when
|
||||
const result = MemberSchema.safeParse(member)
|
||||
|
||||
// then
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
test("category requires prompt", () => {
|
||||
// given
|
||||
const member = { kind: "category", name: "m1", category: "deep" }
|
||||
|
||||
// when
|
||||
const result = CategoryMemberSchema.safeParse(member)
|
||||
|
||||
// then
|
||||
expect(result.success).toBe(false)
|
||||
})
|
||||
|
||||
test("eligibility registry shape", () => {
|
||||
// given
|
||||
const entries = Object.entries(AGENT_ELIGIBILITY_REGISTRY)
|
||||
|
||||
// when
|
||||
const verdictCounts = entries.reduce(
|
||||
(counts, [, value]) => {
|
||||
counts[value.verdict] += 1
|
||||
return counts
|
||||
},
|
||||
{ eligible: 0, conditional: 0, "hard-reject": 0 },
|
||||
)
|
||||
|
||||
// then
|
||||
expect(entries).toHaveLength(11)
|
||||
expect(verdictCounts).toEqual({ eligible: 3, conditional: 1, "hard-reject": 7 })
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY.hephaestus.rejectionMessage).toBe(
|
||||
"Agent 'hephaestus' lacks teammate permission. Either apply D-36 (add teammate: \"allow\" in tool-config-handler.ts) or use subagent_type: \"sisyphus\" instead.",
|
||||
)
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY.oracle.rejectionMessage).toBe(
|
||||
"Agent 'oracle' is read-only (cannot write files). Team members must write to mailbox inbox files. Use delegate-task with subagent_type: 'oracle' for read-only analysis instead.",
|
||||
)
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY.librarian.rejectionMessage).toBe(
|
||||
"Agent 'librarian' is read-only (write/edit denied). Cannot write to mailbox as team member. Use delegate-task for research queries instead.",
|
||||
)
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY.explore.rejectionMessage).toBe(
|
||||
"Agent 'explore' is read-only (write/edit denied). Cannot write to mailbox as team member. Use delegate-task for codebase exploration instead.",
|
||||
)
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY["multimodal-looker"].rejectionMessage).toBe(
|
||||
"Agent 'multimodal-looker' has read-only tool access (only 'read' allowed). Cannot write to mailbox as team member.",
|
||||
)
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY.metis.rejectionMessage).toBe(
|
||||
"Agent 'metis' is read-only (pre-planning consultant). Cannot write to mailbox as team member. Use delegate-task for pre-planning analysis instead.",
|
||||
)
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY.momus.rejectionMessage).toBe(
|
||||
"Agent 'momus' is read-only (plan reviewer). Cannot write to mailbox as team member. Use delegate-task for plan review instead.",
|
||||
)
|
||||
expect(AGENT_ELIGIBILITY_REGISTRY.prometheus.rejectionMessage).toBe(
|
||||
"Agent 'prometheus' is plan-mode-only; can only write to .sisyphus/*.md (enforced by prometheusMdOnly hook). Cannot write to team mailbox. Use category: 'plan' instead.",
|
||||
)
|
||||
expect(CategoryMemberSchema).toBeDefined()
|
||||
expect(SubagentMemberSchema).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,190 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const MESSAGE_KINDS = [
|
||||
"message",
|
||||
"shutdown_request",
|
||||
"shutdown_approved",
|
||||
"shutdown_rejected",
|
||||
"announcement",
|
||||
] as const
|
||||
|
||||
export const MEMBER_KINDS = ["category", "subagent_type"] as const
|
||||
|
||||
export const TASK_STATUSES = ["pending", "claimed", "in_progress", "completed", "deleted"] as const
|
||||
|
||||
export const RUNTIME_STATUSES = [
|
||||
"creating",
|
||||
"active",
|
||||
"shutdown_requested",
|
||||
"deleting",
|
||||
"deleted",
|
||||
"failed",
|
||||
"orphaned",
|
||||
] as const
|
||||
|
||||
const MemberBaseSchema = z.object({
|
||||
name: z.string().min(1).regex(/^[a-z0-9-]+$/),
|
||||
cwd: z.string().optional(),
|
||||
worktreePath: z.string().optional(),
|
||||
subscriptions: z.array(z.string()).optional(),
|
||||
backendType: z.enum(["in-process", "tmux"]).default("in-process"),
|
||||
color: z.string().optional(),
|
||||
isActive: z.boolean().default(true),
|
||||
}).strict()
|
||||
|
||||
export const CategoryMemberSchema = MemberBaseSchema.extend({
|
||||
kind: z.literal("category"),
|
||||
category: z.string().min(1),
|
||||
prompt: z.string().min(1),
|
||||
})
|
||||
|
||||
export const SubagentMemberSchema = MemberBaseSchema.extend({
|
||||
kind: z.literal("subagent_type"),
|
||||
subagent_type: z.string().min(1),
|
||||
prompt: z.string().optional(),
|
||||
})
|
||||
|
||||
export const MemberSchema = z.discriminatedUnion("kind", [CategoryMemberSchema, SubagentMemberSchema])
|
||||
|
||||
const TeamReferenceSchema = z.object({
|
||||
path: z.string(),
|
||||
description: z.string().optional(),
|
||||
}).strict()
|
||||
|
||||
export const TeamSpecSchema = z.object({
|
||||
version: z.literal(1),
|
||||
name: z.string().min(1).regex(/^[a-z0-9-]+$/),
|
||||
description: z.string().optional(),
|
||||
createdAt: z.number().int().positive(),
|
||||
leadAgentId: z.string(),
|
||||
teamAllowedPaths: z.array(z.string()).optional(),
|
||||
sessionPermission: z.string().optional(),
|
||||
members: z.array(MemberSchema).min(1).max(8),
|
||||
})
|
||||
|
||||
export const MessageSchema = z.object({
|
||||
version: z.literal(1),
|
||||
messageId: z.string().uuid(),
|
||||
from: z.string(),
|
||||
to: z.string(),
|
||||
kind: z.enum(MESSAGE_KINDS),
|
||||
body: z.string().max(32 * 1024),
|
||||
summary: z.string().optional(),
|
||||
references: z.array(TeamReferenceSchema).optional(),
|
||||
timestamp: z.number().int().positive(),
|
||||
correlationId: z.string().uuid().optional(),
|
||||
color: z.string().optional(),
|
||||
})
|
||||
|
||||
export const TaskSchema = z.object({
|
||||
version: z.literal(1),
|
||||
id: z.string(),
|
||||
subject: z.string(),
|
||||
description: z.string(),
|
||||
activeForm: z.string().optional(),
|
||||
status: z.enum(TASK_STATUSES),
|
||||
owner: z.string().optional(),
|
||||
blocks: z.array(z.string()).default([]),
|
||||
blockedBy: z.array(z.string()).default([]),
|
||||
metadata: z.record(z.string(), z.unknown()).optional(),
|
||||
createdAt: z.number().int().positive(),
|
||||
updatedAt: z.number().int().positive(),
|
||||
claimedAt: z.number().int().positive().optional(),
|
||||
})
|
||||
|
||||
const RuntimeStateMemberSchema = z.object({
|
||||
name: z.string(),
|
||||
sessionId: z.string().optional(),
|
||||
tmuxPaneId: z.string().optional(),
|
||||
agentType: z.enum(["leader", "general-purpose"]),
|
||||
status: z.enum(["pending", "running", "idle", "errored", "completed", "shutdown_approved"]),
|
||||
color: z.string().optional(),
|
||||
worktreePath: z.string().optional(),
|
||||
lastInjectedTurnMarker: z.string().optional(),
|
||||
pendingInjectedMessageIds: z.array(z.string()).default([]),
|
||||
}).strict()
|
||||
|
||||
const RuntimeBoundsSchema = z.object({
|
||||
maxMembers: z.number().int().default(8),
|
||||
maxParallelMembers: z.number().int().default(4),
|
||||
maxMessagesPerRun: z.number().int().default(10000),
|
||||
maxWallClockMinutes: z.number().int().default(120),
|
||||
maxMemberTurns: z.number().int().default(500),
|
||||
}).strict()
|
||||
|
||||
const ShutdownRequestSchema = z.object({
|
||||
memberId: z.string(),
|
||||
requestedAt: z.number().int().positive(),
|
||||
approvedAt: z.number().int().positive().optional(),
|
||||
rejectedReason: z.string().optional(),
|
||||
}).strict()
|
||||
|
||||
export const RuntimeStateSchema = z.object({
|
||||
version: z.literal(1),
|
||||
teamRunId: z.string().uuid(),
|
||||
teamName: z.string(),
|
||||
specSource: z.enum(["project", "user"]),
|
||||
createdAt: z.number().int().positive(),
|
||||
status: z.enum(RUNTIME_STATUSES),
|
||||
leadSessionId: z.string().optional(),
|
||||
members: z.array(RuntimeStateMemberSchema),
|
||||
shutdownRequests: z.array(ShutdownRequestSchema).default([]),
|
||||
bounds: RuntimeBoundsSchema,
|
||||
})
|
||||
|
||||
export const AGENT_ELIGIBILITY_REGISTRY: Readonly<Record<string, {
|
||||
verdict: "eligible" | "conditional" | "hard-reject"
|
||||
rejectionMessage?: string
|
||||
}>> = {
|
||||
sisyphus: { verdict: "eligible" },
|
||||
hephaestus: {
|
||||
verdict: "conditional",
|
||||
rejectionMessage:
|
||||
"Agent 'hephaestus' lacks teammate permission. Either apply D-36 (add teammate: \"allow\" in tool-config-handler.ts) or use subagent_type: \"sisyphus\" instead.",
|
||||
},
|
||||
oracle: {
|
||||
verdict: "hard-reject",
|
||||
rejectionMessage:
|
||||
"Agent 'oracle' is read-only (cannot write files). Team members must write to mailbox inbox files. Use delegate-task with subagent_type: 'oracle' for read-only analysis instead.",
|
||||
},
|
||||
librarian: {
|
||||
verdict: "hard-reject",
|
||||
rejectionMessage:
|
||||
"Agent 'librarian' is read-only (write/edit denied). Cannot write to mailbox as team member. Use delegate-task for research queries instead.",
|
||||
},
|
||||
explore: {
|
||||
verdict: "hard-reject",
|
||||
rejectionMessage:
|
||||
"Agent 'explore' is read-only (write/edit denied). Cannot write to mailbox as team member. Use delegate-task for codebase exploration instead.",
|
||||
},
|
||||
"multimodal-looker": {
|
||||
verdict: "hard-reject",
|
||||
rejectionMessage:
|
||||
"Agent 'multimodal-looker' has read-only tool access (only 'read' allowed). Cannot write to mailbox as team member.",
|
||||
},
|
||||
metis: {
|
||||
verdict: "hard-reject",
|
||||
rejectionMessage:
|
||||
"Agent 'metis' is read-only (pre-planning consultant). Cannot write to mailbox as team member. Use delegate-task for pre-planning analysis instead.",
|
||||
},
|
||||
momus: {
|
||||
verdict: "hard-reject",
|
||||
rejectionMessage:
|
||||
"Agent 'momus' is read-only (plan reviewer). Cannot write to mailbox as team member. Use delegate-task for plan review instead.",
|
||||
},
|
||||
atlas: { verdict: "eligible" },
|
||||
prometheus: {
|
||||
verdict: "hard-reject",
|
||||
rejectionMessage:
|
||||
"Agent 'prometheus' is plan-mode-only; can only write to .sisyphus/*.md (enforced by prometheusMdOnly hook). Cannot write to team mailbox. Use category: 'plan' instead.",
|
||||
},
|
||||
"sisyphus-junior": { verdict: "eligible" },
|
||||
} as const
|
||||
|
||||
export type TeamSpec = z.infer<typeof TeamSpecSchema>
|
||||
export type Member = z.infer<typeof MemberSchema>
|
||||
export type CategoryMember = z.infer<typeof CategoryMemberSchema>
|
||||
export type SubagentMember = z.infer<typeof SubagentMemberSchema>
|
||||
export type Message = z.infer<typeof MessageSchema>
|
||||
export type Task = z.infer<typeof TaskSchema>
|
||||
export type RuntimeState = z.infer<typeof RuntimeStateSchema>
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { TmuxConfig } from "../../config/schema"
|
||||
import { log } from "../../shared"
|
||||
import type { TrackedSession } from "./types"
|
||||
import { queryWindowState } from "./pane-state-querier"
|
||||
import { executeAction } from "./action-executor"
|
||||
|
||||
export async function cleanupTmuxSessions(params: {
|
||||
tmuxConfig: TmuxConfig
|
||||
serverUrl: string
|
||||
sourcePaneId: string | undefined
|
||||
sessions: Map<string, TrackedSession>
|
||||
stopPolling: () => void
|
||||
}): Promise<void> {
|
||||
params.stopPolling()
|
||||
|
||||
if (params.sessions.size === 0) {
|
||||
log("[tmux-session-manager] cleanup complete")
|
||||
return
|
||||
}
|
||||
|
||||
log("[tmux-session-manager] closing all panes", { count: params.sessions.size })
|
||||
const state = params.sourcePaneId ? await queryWindowState(params.sourcePaneId) : null
|
||||
|
||||
if (state) {
|
||||
const closePromises = Array.from(params.sessions.values()).map((tracked) =>
|
||||
executeAction(
|
||||
{ type: "close", paneId: tracked.paneId, sessionId: tracked.sessionId },
|
||||
{ config: params.tmuxConfig, serverUrl: params.serverUrl, windowState: state },
|
||||
).catch((error) =>
|
||||
log("[tmux-session-manager] cleanup error for pane", {
|
||||
paneId: tracked.paneId,
|
||||
error: String(error),
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
await Promise.all(closePromises)
|
||||
}
|
||||
|
||||
params.sessions.clear()
|
||||
log("[tmux-session-manager] cleanup complete")
|
||||
}
|
||||
@@ -1,6 +1,2 @@
|
||||
export { coerceSessionCreatedEvent } from "./session-created-event"
|
||||
export type { SessionCreatedEvent } from "./session-created-event"
|
||||
export { handleSessionCreated } from "./session-created-handler"
|
||||
export type { SessionCreatedHandlerDeps } from "./session-created-handler"
|
||||
export { handleSessionDeleted } from "./session-deleted-handler"
|
||||
export type { SessionDeletedHandlerDeps } from "./session-deleted-handler"
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
export * from "./manager"
|
||||
export * from "./event-handlers"
|
||||
export * from "./polling"
|
||||
export * from "./cleanup"
|
||||
export * from "./session-created-event"
|
||||
export * from "./session-created-handler"
|
||||
export * from "./session-deleted-handler"
|
||||
export * from "./polling-constants"
|
||||
export * from "./session-status-parser"
|
||||
export * from "./session-message-count"
|
||||
|
||||
@@ -57,6 +57,8 @@ const mockSpawnTmuxSession = mock<(
|
||||
success: true,
|
||||
paneId: '%isolated-session',
|
||||
}))
|
||||
const mockKillTmuxSessionIfExists = mock<(sessionName: string) => Promise<boolean>>(async () => true)
|
||||
const mockSweepStaleOmoAgentSessions = mock<() => Promise<number>>(async () => 0)
|
||||
const mockIsInsideTmux = mock<() => boolean>(() => true)
|
||||
const mockGetCurrentPaneId = mock<() => string | undefined>(() => '%0')
|
||||
|
||||
@@ -99,6 +101,9 @@ mock.module('../../shared/tmux', () => {
|
||||
SESSION_READY_TIMEOUT_MS: 500,
|
||||
spawnTmuxWindow: mockSpawnTmuxWindow,
|
||||
spawnTmuxSession: mockSpawnTmuxSession,
|
||||
killTmuxSessionIfExists: mockKillTmuxSessionIfExists,
|
||||
getIsolatedSessionName: (pid: number = 12345) => `omo-agents-${pid}`,
|
||||
sweepStaleOmoAgentSessions: mockSweepStaleOmoAgentSessions,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1056,6 +1061,27 @@ describe('TmuxSessionManager', () => {
|
||||
logSpy.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
test('#given session.status never reports session ready #when onSessionCreated runs #then pane is tracked immediately without blocking', async () => {
|
||||
// given
|
||||
mockIsInsideTmux.mockReturnValue(true)
|
||||
mockQueryWindowState.mockImplementation(async () => createWindowState())
|
||||
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const ctx = createMockContext({ sessionStatusResult: { data: {} } })
|
||||
const config = createTmuxConfig({ enabled: true })
|
||||
const manager = new TmuxSessionManager(ctx, config, mockTmuxDeps)
|
||||
const event = createSessionCreatedEvent('ses_fast_track', 'ses_parent', 'Fast Track')
|
||||
|
||||
// when
|
||||
const start = Date.now()
|
||||
await manager.onSessionCreated(event)
|
||||
const elapsed = Date.now() - start
|
||||
|
||||
// then
|
||||
expect(elapsed < 500).toBe(true)
|
||||
expect(getTrackedSessions(manager).has('ses_fast_track')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('onSessionDeleted', () => {
|
||||
@@ -1831,6 +1857,141 @@ describe('TmuxSessionManager', () => {
|
||||
// then
|
||||
expect(mockExecuteAction).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
test('#given tmux isolation is "session" #when cleanup runs #then killTmuxSessionIfExists is invoked for the per-pid isolated session', async () => {
|
||||
// given
|
||||
mockKillTmuxSessionIfExists.mockClear()
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const manager = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'session',
|
||||
}), mockTmuxDeps)
|
||||
|
||||
// when
|
||||
await manager.cleanup()
|
||||
|
||||
// then
|
||||
expect(mockKillTmuxSessionIfExists).toHaveBeenCalledTimes(1)
|
||||
expect(mockKillTmuxSessionIfExists.mock.calls[0]?.[0]).toMatch(/^omo-agents-\d+$/)
|
||||
})
|
||||
|
||||
test('#given two manager instances #when both cleanup #then each kills its own isolated session name, not a shared one', async () => {
|
||||
// given
|
||||
mockKillTmuxSessionIfExists.mockClear()
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const managerA = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'session',
|
||||
}), mockTmuxDeps)
|
||||
const managerB = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'session',
|
||||
}), mockTmuxDeps)
|
||||
|
||||
// when
|
||||
await managerA.cleanup()
|
||||
await managerB.cleanup()
|
||||
|
||||
// then
|
||||
expect(mockKillTmuxSessionIfExists).toHaveBeenCalledTimes(2)
|
||||
const firstTarget = mockKillTmuxSessionIfExists.mock.calls[0]?.[0]
|
||||
const secondTarget = mockKillTmuxSessionIfExists.mock.calls[1]?.[0]
|
||||
expect(firstTarget).toMatch(/^omo-agents-\d+$/)
|
||||
expect(secondTarget).toMatch(/^omo-agents-\d+$/)
|
||||
})
|
||||
|
||||
test('#given tmux isolation is "inline" #when cleanup runs #then killTmuxSessionIfExists is NOT invoked', async () => {
|
||||
// given
|
||||
mockKillTmuxSessionIfExists.mockClear()
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const manager = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'inline',
|
||||
}), mockTmuxDeps)
|
||||
|
||||
// when
|
||||
await manager.cleanup()
|
||||
|
||||
// then
|
||||
expect(mockKillTmuxSessionIfExists).toHaveBeenCalledTimes(0)
|
||||
})
|
||||
|
||||
test('#given tmux isolation is "window" #when cleanup runs #then killTmuxSessionIfExists is NOT invoked', async () => {
|
||||
// given
|
||||
mockKillTmuxSessionIfExists.mockClear()
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const manager = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'window',
|
||||
}), mockTmuxDeps)
|
||||
|
||||
// when
|
||||
await manager.cleanup()
|
||||
|
||||
// then
|
||||
expect(mockKillTmuxSessionIfExists).toHaveBeenCalledTimes(0)
|
||||
})
|
||||
|
||||
test('#given sweepStaleOmoAgentSessions throws on first onSessionCreated #when second onSessionCreated fires #then sweep is retried instead of skipped forever', async () => {
|
||||
// given
|
||||
mockSweepStaleOmoAgentSessions.mockClear()
|
||||
mockSweepStaleOmoAgentSessions.mockImplementationOnce(async () => {
|
||||
throw new Error('simulated sweep failure')
|
||||
})
|
||||
mockIsInsideTmux.mockReturnValue(true)
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const manager = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'session',
|
||||
}), mockTmuxDeps)
|
||||
|
||||
// when
|
||||
await manager.onSessionCreated(createSessionCreatedEvent('ses_first', 'ses_parent', 'First'))
|
||||
await manager.onSessionCreated(createSessionCreatedEvent('ses_second', 'ses_parent', 'Second'))
|
||||
|
||||
// then
|
||||
expect(mockSweepStaleOmoAgentSessions).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
test('#given sweepStaleOmoAgentSessions succeeds #when additional onSessionCreated events fire in same process #then sweep runs exactly once', async () => {
|
||||
// given
|
||||
mockSweepStaleOmoAgentSessions.mockClear()
|
||||
mockSweepStaleOmoAgentSessions.mockImplementation(async () => 0)
|
||||
mockIsInsideTmux.mockReturnValue(true)
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const manager = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'session',
|
||||
}), mockTmuxDeps)
|
||||
|
||||
// when
|
||||
await manager.onSessionCreated(createSessionCreatedEvent('ses_a', 'ses_parent', 'A'))
|
||||
await manager.onSessionCreated(createSessionCreatedEvent('ses_b', 'ses_parent', 'B'))
|
||||
await manager.onSessionCreated(createSessionCreatedEvent('ses_c', 'ses_parent', 'C'))
|
||||
|
||||
// then
|
||||
expect(mockSweepStaleOmoAgentSessions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
test('#given killTmuxSessionIfExists throws #when cleanup runs #then cleanup still completes without throwing', async () => {
|
||||
// given
|
||||
mockKillTmuxSessionIfExists.mockClear()
|
||||
mockKillTmuxSessionIfExists.mockImplementationOnce(async () => {
|
||||
throw new Error('simulated teardown failure')
|
||||
})
|
||||
const { TmuxSessionManager } = await import('./manager')
|
||||
const manager = new TmuxSessionManager(createMockContext(), createTmuxConfig({
|
||||
enabled: true,
|
||||
isolation: 'session',
|
||||
}), mockTmuxDeps)
|
||||
|
||||
// when
|
||||
const cleanupPromise = manager.cleanup()
|
||||
|
||||
// then
|
||||
await expect(cleanupPromise).resolves.toBeUndefined()
|
||||
expect(mockKillTmuxSessionIfExists).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
})
|
||||
|
||||
@@ -10,6 +10,9 @@ import {
|
||||
SESSION_READY_TIMEOUT_MS,
|
||||
spawnTmuxWindow,
|
||||
spawnTmuxSession,
|
||||
killTmuxSessionIfExists,
|
||||
getIsolatedSessionName,
|
||||
sweepStaleOmoAgentSessions,
|
||||
} from "../../shared/tmux"
|
||||
import { queryWindowState } from "./pane-state-querier"
|
||||
import { decideSpawnActions, decideCloseAction, type SessionMapping } from "./decision-engine"
|
||||
@@ -63,6 +66,8 @@ export class TmuxSessionManager {
|
||||
private isolatedContainerPaneId: string | undefined
|
||||
private isolatedWindowPaneId: string | undefined
|
||||
private isolatedContainerNullStateCount = 0
|
||||
private staleSweepCompleted = false
|
||||
private staleSweepInProgress = false
|
||||
constructor(ctx: PluginInput, tmuxConfig: TmuxConfig, deps: TmuxUtilDeps = defaultTmuxDeps) {
|
||||
this.client = ctx.client
|
||||
this.tmuxConfig = tmuxConfig
|
||||
@@ -89,7 +94,8 @@ export class TmuxSessionManager {
|
||||
this.pollingManager = new TmuxPollingManager(
|
||||
this.client,
|
||||
this.sessions,
|
||||
this.closeSessionById.bind(this)
|
||||
this.closeSessionById.bind(this),
|
||||
this.retryPendingCloses.bind(this)
|
||||
)
|
||||
log("[tmux-session-manager] initialized", {
|
||||
configEnabled: this.tmuxConfig.enabled,
|
||||
@@ -511,7 +517,6 @@ export class TmuxSessionManager {
|
||||
if (deferred.retryIsolatedContainer) {
|
||||
const isolatedPaneId = await this.spawnInIsolatedContainer(sessionId, deferred.title)
|
||||
if (isolatedPaneId) {
|
||||
const sessionReady = await this.waitForSessionReady(sessionId)
|
||||
this.sessions.set(
|
||||
sessionId,
|
||||
createTrackedSession({
|
||||
@@ -525,8 +530,8 @@ export class TmuxSessionManager {
|
||||
log("[tmux-session-manager] deferred session attached in isolated window", {
|
||||
sessionId,
|
||||
paneId: isolatedPaneId,
|
||||
sessionReady,
|
||||
})
|
||||
this.logSessionReadinessInBackground(sessionId)
|
||||
return
|
||||
}
|
||||
}
|
||||
@@ -585,14 +590,6 @@ export class TmuxSessionManager {
|
||||
return
|
||||
}
|
||||
|
||||
const sessionReady = await this.waitForSessionReady(sessionId)
|
||||
if (!sessionReady) {
|
||||
log("[tmux-session-manager] deferred session not ready after timeout", {
|
||||
sessionId,
|
||||
paneId: result.spawnedPaneId,
|
||||
})
|
||||
}
|
||||
|
||||
this.sessions.set(
|
||||
sessionId,
|
||||
createTrackedSession({
|
||||
@@ -606,18 +603,27 @@ export class TmuxSessionManager {
|
||||
log("[tmux-session-manager] deferred session attached", {
|
||||
sessionId,
|
||||
paneId: result.spawnedPaneId,
|
||||
sessionReady,
|
||||
})
|
||||
this.logSessionReadinessInBackground(sessionId)
|
||||
}
|
||||
|
||||
private logSessionReadinessInBackground(sessionId: string): void {
|
||||
void this.waitForSessionReady(sessionId).catch((error) => {
|
||||
log("[tmux-session-manager] background readiness probe failed", {
|
||||
sessionId,
|
||||
error: String(error),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
private async waitForSessionReady(sessionId: string): Promise<boolean> {
|
||||
const startTime = Date.now()
|
||||
|
||||
|
||||
while (Date.now() - startTime < SESSION_READY_TIMEOUT_MS) {
|
||||
try {
|
||||
const statusResult = await this.client.session.status({ path: undefined })
|
||||
const allStatuses = normalizeSDKResponse(statusResult, {} as Record<string, { type: string }>)
|
||||
|
||||
|
||||
if (allStatuses[sessionId]) {
|
||||
log("[tmux-session-manager] session ready", {
|
||||
sessionId,
|
||||
@@ -629,10 +635,10 @@ export class TmuxSessionManager {
|
||||
} catch (err) {
|
||||
log("[tmux-session-manager] session status check error", { error: String(err) })
|
||||
}
|
||||
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, SESSION_READY_POLL_INTERVAL_MS))
|
||||
}
|
||||
|
||||
|
||||
log("[tmux-session-manager] session ready timeout", {
|
||||
sessionId,
|
||||
timeoutMs: SESSION_READY_TIMEOUT_MS,
|
||||
@@ -665,6 +671,7 @@ export class TmuxSessionManager {
|
||||
return
|
||||
}
|
||||
|
||||
await this.sweepStaleIsolatedSessionsOnce()
|
||||
await this.retryPendingCloses()
|
||||
|
||||
if (
|
||||
@@ -682,7 +689,6 @@ export class TmuxSessionManager {
|
||||
try {
|
||||
const isolatedPaneId = await this.spawnInIsolatedContainer(sessionId, title)
|
||||
if (isolatedPaneId) {
|
||||
const sessionReady = await this.waitForSessionReady(sessionId)
|
||||
this.sessions.set(
|
||||
sessionId,
|
||||
createTrackedSession({ sessionId, paneId: isolatedPaneId, description: title }),
|
||||
@@ -691,8 +697,8 @@ export class TmuxSessionManager {
|
||||
log("[tmux-session-manager] first subagent spawned in isolated window", {
|
||||
sessionId,
|
||||
paneId: isolatedPaneId,
|
||||
sessionReady,
|
||||
})
|
||||
this.logSessionReadinessInBackground(sessionId)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -773,15 +779,6 @@ export class TmuxSessionManager {
|
||||
}
|
||||
|
||||
if (result.success && result.spawnedPaneId) {
|
||||
const sessionReady = await this.waitForSessionReady(sessionId)
|
||||
|
||||
if (!sessionReady) {
|
||||
log("[tmux-session-manager] session not ready after timeout, tracking anyway", {
|
||||
sessionId,
|
||||
paneId: result.spawnedPaneId,
|
||||
})
|
||||
}
|
||||
|
||||
this.sessions.set(
|
||||
sessionId,
|
||||
createTrackedSession({
|
||||
@@ -793,9 +790,9 @@ export class TmuxSessionManager {
|
||||
log("[tmux-session-manager] pane spawned and tracked", {
|
||||
sessionId,
|
||||
paneId: result.spawnedPaneId,
|
||||
sessionReady,
|
||||
})
|
||||
this.pollingManager.startPolling()
|
||||
this.logSessionReadinessInBackground(sessionId)
|
||||
} else {
|
||||
log("[tmux-session-manager] spawn failed", {
|
||||
success: result.success,
|
||||
@@ -964,6 +961,49 @@ export class TmuxSessionManager {
|
||||
this.isolatedContainerPaneId = undefined
|
||||
this.isolatedWindowPaneId = undefined
|
||||
|
||||
if (this.tmuxConfig.isolation === "session") {
|
||||
const isolatedSessionName = getIsolatedSessionName()
|
||||
try {
|
||||
const killed = await killTmuxSessionIfExists(isolatedSessionName)
|
||||
log("[tmux-session-manager] isolated session teardown", {
|
||||
session: isolatedSessionName,
|
||||
killed,
|
||||
})
|
||||
} catch (error) {
|
||||
log("[tmux-session-manager] isolated session teardown failed", {
|
||||
session: isolatedSessionName,
|
||||
error: String(error),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
this.staleSweepCompleted = false
|
||||
this.staleSweepInProgress = false
|
||||
|
||||
log("[tmux-session-manager] cleanup complete")
|
||||
}
|
||||
|
||||
private async sweepStaleIsolatedSessionsOnce(): Promise<void> {
|
||||
if (this.staleSweepCompleted) return
|
||||
if (this.staleSweepInProgress) return
|
||||
if (this.tmuxConfig.isolation !== "session") {
|
||||
this.staleSweepCompleted = true
|
||||
return
|
||||
}
|
||||
|
||||
this.staleSweepInProgress = true
|
||||
try {
|
||||
const killed = await sweepStaleOmoAgentSessions()
|
||||
if (killed > 0) {
|
||||
log("[tmux-session-manager] stale isolated sessions swept", { killed })
|
||||
}
|
||||
this.staleSweepCompleted = true
|
||||
} catch (error) {
|
||||
log("[tmux-session-manager] stale sweep failed", {
|
||||
error: String(error),
|
||||
})
|
||||
} finally {
|
||||
this.staleSweepInProgress = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,8 @@ export class TmuxPollingManager {
|
||||
constructor(
|
||||
private client: OpencodeClient,
|
||||
private sessions: Map<string, TrackedSession>,
|
||||
private closeSessionById: (sessionId: string) => Promise<void>
|
||||
private closeSessionById: (sessionId: string) => Promise<void>,
|
||||
private retryPendingCloses?: () => Promise<void>
|
||||
) {}
|
||||
|
||||
handleEvent(event: { type: string; properties?: Record<string, unknown> }): void {
|
||||
@@ -134,6 +135,14 @@ export class TmuxPollingManager {
|
||||
log("[tmux-session-manager] closing session due to poll", { sessionId })
|
||||
await this.closeSessionById(sessionId)
|
||||
}
|
||||
|
||||
if (this.retryPendingCloses) {
|
||||
try {
|
||||
await this.retryPendingCloses()
|
||||
} catch (err) {
|
||||
log("[tmux-session-manager] retry pending closes failed", { error: String(err) })
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
log("[tmux-session-manager] poll error", { error: String(err) })
|
||||
} finally {
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
import type { PluginInput } from "@opencode-ai/plugin"
|
||||
import type { TmuxConfig } from "../../config/schema"
|
||||
import type { CapacityConfig, TrackedSession } from "./types"
|
||||
import { log } from "../../shared"
|
||||
import { queryWindowState } from "./pane-state-querier"
|
||||
import { decideSpawnActions, type SessionMapping } from "./decision-engine"
|
||||
import { executeActions } from "./action-executor"
|
||||
import type { SessionCreatedEvent } from "./session-created-event"
|
||||
import { createTrackedSession } from "./tracked-session-state"
|
||||
|
||||
type OpencodeClient = PluginInput["client"]
|
||||
|
||||
export interface SessionCreatedHandlerDeps {
|
||||
client: OpencodeClient
|
||||
tmuxConfig: TmuxConfig
|
||||
serverUrl: string
|
||||
sourcePaneId: string | undefined
|
||||
sessions: Map<string, TrackedSession>
|
||||
pendingSessions: Set<string>
|
||||
isInsideTmux: () => boolean
|
||||
isEnabled: () => boolean
|
||||
getCapacityConfig: () => CapacityConfig
|
||||
getSessionMappings: () => SessionMapping[]
|
||||
waitForSessionReady: (sessionId: string) => Promise<boolean>
|
||||
startPolling: () => void
|
||||
}
|
||||
|
||||
export async function handleSessionCreated(
|
||||
deps: SessionCreatedHandlerDeps,
|
||||
event: SessionCreatedEvent,
|
||||
): Promise<void> {
|
||||
const enabled = deps.isEnabled()
|
||||
log("[tmux-session-manager] onSessionCreated called", {
|
||||
enabled,
|
||||
tmuxConfigEnabled: deps.tmuxConfig.enabled,
|
||||
isInsideTmux: deps.isInsideTmux(),
|
||||
eventType: event.type,
|
||||
infoId: event.properties?.info?.id,
|
||||
infoParentID: event.properties?.info?.parentID,
|
||||
})
|
||||
|
||||
if (!enabled) return
|
||||
if (event.type !== "session.created") return
|
||||
|
||||
const info = event.properties?.info
|
||||
if (!info?.id || !info?.parentID) return
|
||||
|
||||
const sessionId = info.id
|
||||
const title = info.title ?? "Subagent"
|
||||
|
||||
if (deps.sessions.has(sessionId) || deps.pendingSessions.has(sessionId)) {
|
||||
log("[tmux-session-manager] session already tracked or pending", { sessionId })
|
||||
return
|
||||
}
|
||||
|
||||
if (!deps.sourcePaneId) {
|
||||
log("[tmux-session-manager] no source pane id")
|
||||
return
|
||||
}
|
||||
|
||||
deps.pendingSessions.add(sessionId)
|
||||
|
||||
try {
|
||||
const state = await queryWindowState(deps.sourcePaneId)
|
||||
if (!state) {
|
||||
log("[tmux-session-manager] failed to query window state")
|
||||
return
|
||||
}
|
||||
|
||||
log("[tmux-session-manager] window state queried", {
|
||||
windowWidth: state.windowWidth,
|
||||
mainPane: state.mainPane?.paneId,
|
||||
agentPaneCount: state.agentPanes.length,
|
||||
agentPanes: state.agentPanes.map((p) => p.paneId),
|
||||
})
|
||||
|
||||
const decision = decideSpawnActions(
|
||||
state,
|
||||
sessionId,
|
||||
title,
|
||||
deps.getCapacityConfig(),
|
||||
deps.getSessionMappings(),
|
||||
)
|
||||
|
||||
log("[tmux-session-manager] spawn decision", {
|
||||
canSpawn: decision.canSpawn,
|
||||
reason: decision.reason,
|
||||
actionCount: decision.actions.length,
|
||||
actions: decision.actions.map((a) => {
|
||||
if (a.type === "close") return { type: "close", paneId: a.paneId }
|
||||
if (a.type === "replace") {
|
||||
return { type: "replace", paneId: a.paneId, newSessionId: a.newSessionId }
|
||||
}
|
||||
return { type: "spawn", sessionId: a.sessionId }
|
||||
}),
|
||||
})
|
||||
|
||||
if (!decision.canSpawn) {
|
||||
log("[tmux-session-manager] cannot spawn", { reason: decision.reason })
|
||||
return
|
||||
}
|
||||
|
||||
const result = await executeActions(decision.actions, {
|
||||
config: deps.tmuxConfig,
|
||||
serverUrl: deps.serverUrl,
|
||||
windowState: state,
|
||||
})
|
||||
|
||||
for (const { action, result: actionResult } of result.results) {
|
||||
if (action.type === "close" && actionResult.success) {
|
||||
deps.sessions.delete(action.sessionId)
|
||||
log("[tmux-session-manager] removed closed session from cache", {
|
||||
sessionId: action.sessionId,
|
||||
})
|
||||
}
|
||||
if (action.type === "replace" && actionResult.success) {
|
||||
deps.sessions.delete(action.oldSessionId)
|
||||
log("[tmux-session-manager] removed replaced session from cache", {
|
||||
oldSessionId: action.oldSessionId,
|
||||
newSessionId: action.newSessionId,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (!result.success || !result.spawnedPaneId) {
|
||||
log("[tmux-session-manager] spawn failed", {
|
||||
success: result.success,
|
||||
results: result.results.map((r) => ({
|
||||
type: r.action.type,
|
||||
success: r.result.success,
|
||||
error: r.result.error,
|
||||
})),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const sessionReady = await deps.waitForSessionReady(sessionId)
|
||||
if (!sessionReady) {
|
||||
log("[tmux-session-manager] session not ready after timeout, closing spawned pane", {
|
||||
sessionId,
|
||||
paneId: result.spawnedPaneId,
|
||||
})
|
||||
|
||||
await executeActions(
|
||||
[{ type: "close", paneId: result.spawnedPaneId, sessionId }],
|
||||
{
|
||||
config: deps.tmuxConfig,
|
||||
serverUrl: deps.serverUrl,
|
||||
windowState: state,
|
||||
},
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
deps.sessions.set(
|
||||
sessionId,
|
||||
createTrackedSession({
|
||||
sessionId,
|
||||
paneId: result.spawnedPaneId,
|
||||
description: title,
|
||||
}),
|
||||
)
|
||||
|
||||
log("[tmux-session-manager] pane spawned and tracked", {
|
||||
sessionId,
|
||||
paneId: result.spawnedPaneId,
|
||||
sessionReady,
|
||||
})
|
||||
|
||||
deps.startPolling()
|
||||
} finally {
|
||||
deps.pendingSessions.delete(sessionId)
|
||||
}
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
import type { TmuxConfig } from "../../config/schema"
|
||||
import type { TrackedSession } from "./types"
|
||||
import { log } from "../../shared"
|
||||
import { queryWindowState } from "./pane-state-querier"
|
||||
import { decideCloseAction, type SessionMapping } from "./decision-engine"
|
||||
import { executeAction } from "./action-executor"
|
||||
|
||||
export interface SessionDeletedHandlerDeps {
|
||||
tmuxConfig: TmuxConfig
|
||||
serverUrl: string
|
||||
sourcePaneId: string | undefined
|
||||
sessions: Map<string, TrackedSession>
|
||||
isEnabled: () => boolean
|
||||
getSessionMappings: () => SessionMapping[]
|
||||
stopPolling: () => void
|
||||
}
|
||||
|
||||
export async function handleSessionDeleted(
|
||||
deps: SessionDeletedHandlerDeps,
|
||||
event: { sessionID: string },
|
||||
): Promise<void> {
|
||||
if (!deps.isEnabled()) return
|
||||
if (!deps.sourcePaneId) return
|
||||
|
||||
const tracked = deps.sessions.get(event.sessionID)
|
||||
if (!tracked) return
|
||||
|
||||
log("[tmux-session-manager] onSessionDeleted", { sessionId: event.sessionID })
|
||||
|
||||
const state = await queryWindowState(deps.sourcePaneId)
|
||||
if (!state) {
|
||||
deps.sessions.delete(event.sessionID)
|
||||
return
|
||||
}
|
||||
|
||||
const closeAction = decideCloseAction(state, event.sessionID, deps.getSessionMappings())
|
||||
if (closeAction) {
|
||||
await executeAction(closeAction, {
|
||||
config: deps.tmuxConfig,
|
||||
serverUrl: deps.serverUrl,
|
||||
windowState: state,
|
||||
})
|
||||
}
|
||||
|
||||
deps.sessions.delete(event.sessionID)
|
||||
|
||||
if (deps.sessions.size === 0) {
|
||||
deps.stopPolling()
|
||||
}
|
||||
}
|
||||
@@ -5,3 +5,10 @@ export {
|
||||
storeToolMetadata,
|
||||
} from "./store"
|
||||
export type { PendingToolMetadata } from "./store"
|
||||
export { resolveToolCallID } from "./resolve-tool-call-id"
|
||||
export type { ToolCallIDCarrier } from "./resolve-tool-call-id"
|
||||
export { buildTaskMetadataBlock, extractTaskLink, parseTaskMetadataBlock } from "./task-metadata-contract"
|
||||
export type { TaskLink } from "./task-metadata-contract"
|
||||
export { publishToolMetadata } from "./publish-tool-metadata"
|
||||
export { recoverToolMetadata } from "./recover-tool-metadata"
|
||||
export type { ToolMetadataPublisherContext } from "./publish-tool-metadata"
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { beforeEach, describe, expect, test } from "bun:test"
|
||||
|
||||
import { clearPendingStore, getPendingStoreSize } from "./store"
|
||||
import { publishToolMetadata } from "./publish-tool-metadata"
|
||||
import { recoverToolMetadata } from "./recover-tool-metadata"
|
||||
|
||||
describe("tool-metadata-store integration", () => {
|
||||
beforeEach(() => {
|
||||
clearPendingStore()
|
||||
})
|
||||
|
||||
test("#given stored metadata #when publishing then recovering #then the round trip preserves the payload", async () => {
|
||||
// given
|
||||
const payload = { title: "Task", metadata: { sessionId: "ses_child" } }
|
||||
|
||||
// when
|
||||
await publishToolMetadata({ sessionID: "ses_parent", callID: "call_123" }, payload)
|
||||
const recovered = recoverToolMetadata("ses_parent", { callID: "call_123" })
|
||||
|
||||
// then
|
||||
expect(recovered).toEqual(payload)
|
||||
})
|
||||
|
||||
test("#given call id casing mismatch #when publishing and recovering #then canonical resolution still matches", async () => {
|
||||
// given
|
||||
const payload = { title: "Task", metadata: { sessionId: "ses_child" } }
|
||||
|
||||
// when
|
||||
await publishToolMetadata({ sessionID: "ses_parent", callId: "call_case" }, payload)
|
||||
const recovered = recoverToolMetadata("ses_parent", { callID: "call_case" })
|
||||
|
||||
// then
|
||||
expect(recovered).toEqual(payload)
|
||||
})
|
||||
|
||||
test("#given blank call id #when publishing #then nothing is stored", async () => {
|
||||
// given
|
||||
const payload = { title: "Task" }
|
||||
|
||||
// when
|
||||
const result = await publishToolMetadata({ sessionID: "ses_parent", callID: " " }, payload)
|
||||
const recovered = recoverToolMetadata("ses_parent", { callID: "call_blank" })
|
||||
|
||||
// then
|
||||
expect(result).toEqual({ stored: false })
|
||||
expect(recovered).toBeUndefined()
|
||||
expect(getPendingStoreSize()).toBe(0)
|
||||
})
|
||||
|
||||
test("#given missing call id #when publishing #then nothing is stored", async () => {
|
||||
// given
|
||||
const payload = { title: "Task" }
|
||||
|
||||
// when
|
||||
const result = await publishToolMetadata({ sessionID: "ses_parent" }, payload)
|
||||
|
||||
// then
|
||||
expect(result).toEqual({ stored: false })
|
||||
expect(getPendingStoreSize()).toBe(0)
|
||||
})
|
||||
|
||||
test("#given same session with different call ids #when publishing twice #then each entry stays isolated", async () => {
|
||||
// given
|
||||
await publishToolMetadata({ sessionID: "ses_parent", callID: "call_a" }, { title: "A" })
|
||||
await publishToolMetadata({ sessionID: "ses_parent", callID: "call_b" }, { title: "B" })
|
||||
|
||||
// when
|
||||
const recoveredA = recoverToolMetadata("ses_parent", { callID: "call_a" })
|
||||
const recoveredB = recoverToolMetadata("ses_parent", { callID: "call_b" })
|
||||
|
||||
// then
|
||||
expect(recoveredA).toEqual({ title: "A" })
|
||||
expect(recoveredB).toEqual({ title: "B" })
|
||||
})
|
||||
|
||||
test("#given stale metadata #when a fresh entry is stored after the timeout #then stale entries are cleaned up", async () => {
|
||||
// given
|
||||
const originalDateNow = Date.now
|
||||
let now = 0
|
||||
Date.now = () => now
|
||||
|
||||
try {
|
||||
await publishToolMetadata({ sessionID: "ses_parent", callID: "call_old" }, { title: "Old" })
|
||||
now = 15 * 60 * 1000 + 1
|
||||
|
||||
// when
|
||||
await publishToolMetadata({ sessionID: "ses_parent", callID: "call_new" }, { title: "New" })
|
||||
|
||||
// then
|
||||
expect(recoverToolMetadata("ses_parent", { callID: "call_old" })).toBeUndefined()
|
||||
expect(recoverToolMetadata("ses_parent", { callID: "call_new" })).toEqual({ title: "New" })
|
||||
} finally {
|
||||
Date.now = originalDateNow
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
import { beforeEach, describe, expect, test } from "bun:test"
|
||||
|
||||
import { clearPendingStore, consumeToolMetadata } from "./store"
|
||||
import { publishToolMetadata } from "./publish-tool-metadata"
|
||||
|
||||
describe("publishToolMetadata", () => {
|
||||
beforeEach(() => {
|
||||
clearPendingStore()
|
||||
})
|
||||
|
||||
test("#given metadata context and call id #when publishing #then it awaits metadata and stores the payload", async () => {
|
||||
// given
|
||||
const calls: string[] = []
|
||||
let metadataFinished = false
|
||||
const payload = { title: "Task", metadata: { sessionId: "ses_child" } }
|
||||
|
||||
// when
|
||||
const result = await publishToolMetadata(
|
||||
{
|
||||
sessionID: "ses_parent",
|
||||
callID: "call_123",
|
||||
metadata: async input => {
|
||||
calls.push(input.title ?? "")
|
||||
await new Promise(resolve => setTimeout(resolve, 1))
|
||||
metadataFinished = true
|
||||
},
|
||||
},
|
||||
payload
|
||||
)
|
||||
|
||||
// then
|
||||
expect(result).toEqual({ stored: true })
|
||||
expect(metadataFinished).toBe(true)
|
||||
expect(calls).toEqual(["Task"])
|
||||
expect(consumeToolMetadata("ses_parent", "call_123")).toEqual(payload)
|
||||
})
|
||||
|
||||
test("#given legacy call id variant #when publishing #then it stores with the canonical resolver", async () => {
|
||||
// given
|
||||
const payload = { title: "Task", metadata: { sessionId: "ses_child" } }
|
||||
|
||||
// when
|
||||
const result = await publishToolMetadata(
|
||||
{
|
||||
sessionID: "ses_parent",
|
||||
callId: " call_legacy ",
|
||||
},
|
||||
payload
|
||||
)
|
||||
|
||||
// then
|
||||
expect(result).toEqual({ stored: true })
|
||||
expect(consumeToolMetadata("ses_parent", "call_legacy")).toEqual(payload)
|
||||
})
|
||||
|
||||
test("#given missing call id #when publishing #then it still emits metadata but skips storing", async () => {
|
||||
// given
|
||||
let metadataCalls = 0
|
||||
|
||||
// when
|
||||
const result = await publishToolMetadata(
|
||||
{
|
||||
sessionID: "ses_parent",
|
||||
metadata: () => {
|
||||
metadataCalls += 1
|
||||
},
|
||||
},
|
||||
{ title: "Task" }
|
||||
)
|
||||
|
||||
// then
|
||||
expect(result).toEqual({ stored: false })
|
||||
expect(metadataCalls).toBe(1)
|
||||
expect(consumeToolMetadata("ses_parent", "call_missing")).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,28 @@
|
||||
import { log } from "../../shared/logger"
|
||||
import { resolveToolCallID, type ToolCallIDCarrier } from "./resolve-tool-call-id"
|
||||
import { storeToolMetadata, type PendingToolMetadata } from "./store"
|
||||
|
||||
export interface ToolMetadataPublisherContext extends ToolCallIDCarrier {
|
||||
sessionID: string
|
||||
metadata?: (input: PendingToolMetadata) => void | Promise<void>
|
||||
}
|
||||
|
||||
export async function publishToolMetadata(
|
||||
ctx: ToolMetadataPublisherContext,
|
||||
payload: PendingToolMetadata
|
||||
): Promise<{ stored: boolean }> {
|
||||
await ctx.metadata?.(payload)
|
||||
|
||||
const callID = resolveToolCallID(ctx)
|
||||
if (!callID) {
|
||||
log("[tool-metadata-store] Skipping metadata store publish because tool call ID is unavailable", {
|
||||
sessionID: ctx.sessionID,
|
||||
hasTitle: typeof payload.title === "string",
|
||||
hasMetadata: payload.metadata !== undefined,
|
||||
})
|
||||
return { stored: false }
|
||||
}
|
||||
|
||||
storeToolMetadata(ctx.sessionID, callID, payload)
|
||||
return { stored: true }
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { beforeEach, describe, expect, test } from "bun:test"
|
||||
|
||||
import { recoverToolMetadata } from "./recover-tool-metadata"
|
||||
import { clearPendingStore, storeToolMetadata } from "./store"
|
||||
|
||||
describe("recoverToolMetadata", () => {
|
||||
beforeEach(() => {
|
||||
clearPendingStore()
|
||||
})
|
||||
|
||||
test("#given stored metadata and call id variant #when recovering #then it finds the stored payload", () => {
|
||||
// given
|
||||
const payload = { title: "Recovered", metadata: { sessionId: "ses_child" } }
|
||||
storeToolMetadata("ses_parent", "call_123", payload)
|
||||
|
||||
// when
|
||||
const recovered = recoverToolMetadata("ses_parent", { callId: " call_123 " })
|
||||
|
||||
// then
|
||||
expect(recovered).toEqual(payload)
|
||||
})
|
||||
|
||||
test("#given direct string call id #when recovering #then it consumes the stored payload", () => {
|
||||
// given
|
||||
const payload = { title: "Recovered" }
|
||||
storeToolMetadata("ses_parent", "call_456", payload)
|
||||
|
||||
// when
|
||||
const recovered = recoverToolMetadata("ses_parent", "call_456")
|
||||
|
||||
// then
|
||||
expect(recovered).toEqual(payload)
|
||||
})
|
||||
|
||||
test("#given missing or blank call id #when recovering #then it returns undefined", () => {
|
||||
// given
|
||||
storeToolMetadata("ses_parent", "call_789", { title: "Recovered" })
|
||||
|
||||
// when
|
||||
const missing = recoverToolMetadata("ses_parent", undefined)
|
||||
const blank = recoverToolMetadata("ses_parent", { callID: " " })
|
||||
|
||||
// then
|
||||
expect(missing).toBeUndefined()
|
||||
expect(blank).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,18 @@
|
||||
import { consumeToolMetadata, type PendingToolMetadata } from "./store"
|
||||
import { resolveToolCallID, type ToolCallIDCarrier } from "./resolve-tool-call-id"
|
||||
|
||||
export function recoverToolMetadata(
|
||||
sessionID: string,
|
||||
source: ToolCallIDCarrier | string | undefined
|
||||
): PendingToolMetadata | undefined {
|
||||
if (typeof source === "string") {
|
||||
return consumeToolMetadata(sessionID, source)
|
||||
}
|
||||
|
||||
const callID = source ? resolveToolCallID(source) : undefined
|
||||
if (!callID) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return consumeToolMetadata(sessionID, callID)
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import { resolveToolCallID, type ToolCallIDCarrier } from "./resolve-tool-call-id"
|
||||
|
||||
describe("resolveToolCallID", () => {
|
||||
function makeCtx(overrides: Partial<ToolCallIDCarrier> = {}): ToolCallIDCarrier {
|
||||
return {
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
test("#given callID is set #when resolving #then it returns callID", () => {
|
||||
// given
|
||||
const ctx = makeCtx({ callID: "call_abc" })
|
||||
|
||||
// when
|
||||
const result = resolveToolCallID(ctx)
|
||||
|
||||
// then
|
||||
expect(result).toBe("call_abc")
|
||||
})
|
||||
|
||||
test("#given only callId is set #when resolving #then it returns callId", () => {
|
||||
// given
|
||||
const ctx = makeCtx({ callId: "call_def" })
|
||||
|
||||
// when
|
||||
const result = resolveToolCallID(ctx)
|
||||
|
||||
// then
|
||||
expect(result).toBe("call_def")
|
||||
})
|
||||
|
||||
test("#given only call_id is set #when resolving #then it returns call_id", () => {
|
||||
// given
|
||||
const ctx = makeCtx({ call_id: "call_ghi" })
|
||||
|
||||
// when
|
||||
const result = resolveToolCallID(ctx)
|
||||
|
||||
// then
|
||||
expect(result).toBe("call_ghi")
|
||||
})
|
||||
|
||||
test("#given surrounding whitespace #when resolving #then it trims the value", () => {
|
||||
// given
|
||||
const ctx = makeCtx({ callID: " call_trimmed " })
|
||||
|
||||
// when
|
||||
const result = resolveToolCallID(ctx)
|
||||
|
||||
// then
|
||||
expect(result).toBe("call_trimmed")
|
||||
})
|
||||
|
||||
test("#given blank callID #when resolving #then it returns undefined", () => {
|
||||
// given
|
||||
const ctx = makeCtx({ callID: "" })
|
||||
|
||||
// when
|
||||
const result = resolveToolCallID(ctx)
|
||||
|
||||
// then
|
||||
expect(result).toBeUndefined()
|
||||
})
|
||||
|
||||
test("#given whitespace callID #when resolving #then it returns undefined", () => {
|
||||
// given
|
||||
const ctx = makeCtx({ callID: " " })
|
||||
|
||||
// when
|
||||
const result = resolveToolCallID(ctx)
|
||||
|
||||
// then
|
||||
expect(result).toBeUndefined()
|
||||
})
|
||||
|
||||
test("#given no call id variants #when resolving #then it returns undefined", () => {
|
||||
// given
|
||||
const ctx = makeCtx()
|
||||
|
||||
// when
|
||||
const result = resolveToolCallID(ctx)
|
||||
|
||||
// then
|
||||
expect(result).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { log } from "../../shared/logger"
|
||||
|
||||
export interface ToolCallIDCarrier {
|
||||
callID?: string
|
||||
callId?: string
|
||||
call_id?: string
|
||||
}
|
||||
|
||||
function normalizeCallID(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const trimmed = value.trim()
|
||||
return trimmed === "" ? undefined : trimmed
|
||||
}
|
||||
|
||||
export function resolveToolCallID(ctx: ToolCallIDCarrier): string | undefined {
|
||||
const resolved = normalizeCallID(ctx.callID) ?? normalizeCallID(ctx.callId) ?? normalizeCallID(ctx.call_id)
|
||||
|
||||
if (!resolved) {
|
||||
log("[tool-metadata-store] Missing tool call ID for metadata correlation")
|
||||
}
|
||||
|
||||
return resolved
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import { buildTaskMetadataBlock, extractTaskLink, parseTaskMetadataBlock } from "./task-metadata-contract"
|
||||
|
||||
describe("buildTaskMetadataBlock", () => {
|
||||
test("#given only session id #when building #then it preserves the frozen block format", () => {
|
||||
// given
|
||||
const link = { sessionId: "ses_abc" }
|
||||
|
||||
// when
|
||||
const block = buildTaskMetadataBlock(link)
|
||||
|
||||
// then
|
||||
expect(block).toBe("<task_metadata>\nsession_id: ses_abc\n</task_metadata>")
|
||||
})
|
||||
|
||||
test("#given extended task metadata #when building #then it emits optional lines in order", () => {
|
||||
// given
|
||||
const link = {
|
||||
sessionId: "ses_bg_123",
|
||||
taskId: "ses_bg_123",
|
||||
backgroundTaskId: "bg_123",
|
||||
agent: "explore",
|
||||
category: "quick",
|
||||
}
|
||||
|
||||
// when
|
||||
const block = buildTaskMetadataBlock(link)
|
||||
|
||||
// then
|
||||
expect(block).toBe(
|
||||
"<task_metadata>\nsession_id: ses_bg_123\ntask_id: ses_bg_123\nbackground_task_id: bg_123\nsubagent: explore\ncategory: quick\n</task_metadata>"
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe("parseTaskMetadataBlock", () => {
|
||||
test("#given a task metadata block #when parsing #then it extracts the structured link", () => {
|
||||
// given
|
||||
const text = "<task_metadata>\nsession_id: ses_sync_123\ntask_id: task_123\nbackground_task_id: bg_123\nsubagent: oracle\ncategory: deep\n</task_metadata>"
|
||||
|
||||
// when
|
||||
const parsed = parseTaskMetadataBlock(text)
|
||||
|
||||
// then
|
||||
expect(parsed).toEqual({
|
||||
sessionId: "ses_sync_123",
|
||||
taskId: "task_123",
|
||||
backgroundTaskId: "bg_123",
|
||||
agent: "oracle",
|
||||
category: "deep",
|
||||
})
|
||||
})
|
||||
|
||||
test("#given text without metadata #when parsing #then it returns an empty link", () => {
|
||||
// given
|
||||
const text = "Task completed without metadata"
|
||||
|
||||
// when
|
||||
const parsed = parseTaskMetadataBlock(text)
|
||||
|
||||
// then
|
||||
expect(parsed).toEqual({})
|
||||
})
|
||||
})
|
||||
|
||||
describe("extractTaskLink", () => {
|
||||
test("#given metadata session aliases #when extracting #then metadata wins over output text", () => {
|
||||
// given
|
||||
const metadata = {
|
||||
sessionID: "ses_meta_123",
|
||||
task_id: "task_meta_123",
|
||||
background_task_id: "bg_meta_123",
|
||||
subagent: "atlas",
|
||||
category: "unspecified-high",
|
||||
}
|
||||
const output = "<task_metadata>\nsession_id: ses_text_456\n</task_metadata>"
|
||||
|
||||
// when
|
||||
const extracted = extractTaskLink(metadata, output)
|
||||
|
||||
// then
|
||||
expect(extracted).toEqual({
|
||||
sessionId: "ses_meta_123",
|
||||
taskId: "task_meta_123",
|
||||
backgroundTaskId: "bg_meta_123",
|
||||
agent: "atlas",
|
||||
category: "unspecified-high",
|
||||
})
|
||||
})
|
||||
|
||||
test("#given missing metadata #when extracting #then it falls back to task metadata text", () => {
|
||||
// given
|
||||
const output = "Task completed.\n\n<task_metadata>\nsession_id: ses_text_456\nsubagent: oracle\n</task_metadata>"
|
||||
|
||||
// when
|
||||
const extracted = extractTaskLink(undefined, output)
|
||||
|
||||
// then
|
||||
expect(extracted).toEqual({
|
||||
sessionId: "ses_text_456",
|
||||
agent: "oracle",
|
||||
})
|
||||
})
|
||||
|
||||
test("#given explicit session id output #when extracting #then it preserves Session ID compatibility", () => {
|
||||
// given
|
||||
const output = "Background task launched.\n\nSession ID: ses_bg_789"
|
||||
|
||||
// when
|
||||
const extracted = extractTaskLink(undefined, output)
|
||||
|
||||
// then
|
||||
expect(extracted).toEqual({ sessionId: "ses_bg_789" })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,144 @@
|
||||
import { log } from "../../shared/logger"
|
||||
|
||||
export interface TaskLink {
|
||||
sessionId?: string
|
||||
taskId?: string
|
||||
backgroundTaskId?: string
|
||||
agent?: string
|
||||
category?: string
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null
|
||||
}
|
||||
|
||||
function readString(value: unknown): string | undefined {
|
||||
if (typeof value !== "string") {
|
||||
return undefined
|
||||
}
|
||||
|
||||
const trimmed = value.trim()
|
||||
return trimmed === "" ? undefined : trimmed
|
||||
}
|
||||
|
||||
function readSessionIdFromMetadata(metadata: Record<string, unknown>): string | undefined {
|
||||
return readString(metadata.sessionId) ?? readString(metadata.sessionID) ?? readString(metadata.session_id)
|
||||
}
|
||||
|
||||
function readTaskIdFromMetadata(metadata: Record<string, unknown>): string | undefined {
|
||||
return readString(metadata.taskId) ?? readString(metadata.taskID) ?? readString(metadata.task_id)
|
||||
}
|
||||
|
||||
function readBackgroundTaskIdFromMetadata(metadata: Record<string, unknown>): string | undefined {
|
||||
return readString(metadata.backgroundTaskId)
|
||||
?? readString(metadata.backgroundTaskID)
|
||||
?? readString(metadata.background_task_id)
|
||||
}
|
||||
|
||||
function readAgentFromMetadata(metadata: Record<string, unknown>): string | undefined {
|
||||
return readString(metadata.agent) ?? readString(metadata.subagent)
|
||||
}
|
||||
|
||||
function readCategoryFromMetadata(metadata: Record<string, unknown>): string | undefined {
|
||||
return readString(metadata.category)
|
||||
}
|
||||
|
||||
function extractTaskMetadataContent(text: string): string | undefined {
|
||||
const blocks = [...text.matchAll(/<task_metadata>([\s\S]*?)<\/task_metadata>/gi)]
|
||||
return blocks.at(-1)?.[1]
|
||||
}
|
||||
|
||||
function extractExplicitSessionId(text: string): string | undefined {
|
||||
const matches = [...text.matchAll(/Session ID:\s*(ses_[a-zA-Z0-9_-]+)/g)]
|
||||
return matches.at(-1)?.[1]
|
||||
}
|
||||
|
||||
export function buildTaskMetadataBlock(link: TaskLink): string {
|
||||
const lines: string[] = []
|
||||
|
||||
if (link.sessionId) {
|
||||
lines.push(`session_id: ${link.sessionId}`)
|
||||
}
|
||||
if (link.taskId) {
|
||||
lines.push(`task_id: ${link.taskId}`)
|
||||
}
|
||||
if (link.backgroundTaskId) {
|
||||
lines.push(`background_task_id: ${link.backgroundTaskId}`)
|
||||
}
|
||||
if (link.agent) {
|
||||
lines.push(`subagent: ${link.agent}`)
|
||||
}
|
||||
if (link.category) {
|
||||
lines.push(`category: ${link.category}`)
|
||||
}
|
||||
|
||||
return `<task_metadata>\n${lines.join("\n")}\n</task_metadata>`
|
||||
}
|
||||
|
||||
export function parseTaskMetadataBlock(text: string): TaskLink {
|
||||
const blockContent = extractTaskMetadataContent(text) ?? text
|
||||
const lines = blockContent
|
||||
.split("\n")
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean)
|
||||
|
||||
const parsed: TaskLink = {}
|
||||
|
||||
for (const line of lines) {
|
||||
const separatorIndex = line.indexOf(":")
|
||||
if (separatorIndex === -1) {
|
||||
continue
|
||||
}
|
||||
|
||||
const key = line.slice(0, separatorIndex).trim().toLowerCase()
|
||||
const value = readString(line.slice(separatorIndex + 1))
|
||||
|
||||
if (!value) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (key === "session_id") {
|
||||
parsed.sessionId = value
|
||||
} else if (key === "task_id") {
|
||||
parsed.taskId = value
|
||||
} else if (key === "background_task_id") {
|
||||
parsed.backgroundTaskId = value
|
||||
} else if (key === "subagent" || key === "agent") {
|
||||
parsed.agent = value
|
||||
} else if (key === "category") {
|
||||
parsed.category = value
|
||||
}
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function extractTaskLink(metadata: unknown, outputText: string): TaskLink {
|
||||
if (isRecord(metadata)) {
|
||||
const metadataLink: TaskLink = {
|
||||
sessionId: readSessionIdFromMetadata(metadata),
|
||||
taskId: readTaskIdFromMetadata(metadata),
|
||||
backgroundTaskId: readBackgroundTaskIdFromMetadata(metadata),
|
||||
agent: readAgentFromMetadata(metadata),
|
||||
category: readCategoryFromMetadata(metadata),
|
||||
}
|
||||
|
||||
if (metadataLink.sessionId || metadataLink.taskId || metadataLink.backgroundTaskId || metadataLink.agent || metadataLink.category) {
|
||||
return metadataLink
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = parseTaskMetadataBlock(outputText)
|
||||
if (parsed.sessionId || parsed.taskId || parsed.backgroundTaskId || parsed.agent || parsed.category) {
|
||||
log("[tool-metadata-store] Falling back to <task_metadata> parsing")
|
||||
return parsed
|
||||
}
|
||||
|
||||
const explicitSessionId = extractExplicitSessionId(outputText)
|
||||
if (explicitSessionId) {
|
||||
log("[tool-metadata-store] Falling back to explicit Session ID parsing")
|
||||
return { sessionId: explicitSessionId }
|
||||
}
|
||||
|
||||
return {}
|
||||
}
|
||||
Reference in New Issue
Block a user