@kolisachint/hoocode-agent 0.4.110 → 0.4.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +61 -0
- package/dist/core/format-duration.d.ts +7 -0
- package/dist/core/format-duration.d.ts.map +1 -0
- package/dist/core/format-duration.js +16 -0
- package/dist/core/format-duration.js.map +1 -0
- package/dist/core/keybindings.d.ts +10 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +10 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/lifeguard.d.ts +15 -0
- package/dist/core/lifeguard.d.ts.map +1 -1
- package/dist/core/lifeguard.js +48 -18
- package/dist/core/lifeguard.js.map +1 -1
- package/dist/core/subagent-inbox.d.ts +1 -1
- package/dist/core/subagent-inbox.d.ts.map +1 -1
- package/dist/core/subagent-inbox.js +2 -0
- package/dist/core/subagent-inbox.js.map +1 -1
- package/dist/core/subagent-pool-instance.d.ts.map +1 -1
- package/dist/core/subagent-pool-instance.js +18 -11
- package/dist/core/subagent-pool-instance.js.map +1 -1
- package/dist/core/subagent-pool.d.ts +25 -3
- package/dist/core/subagent-pool.d.ts.map +1 -1
- package/dist/core/subagent-pool.js +120 -25
- package/dist/core/subagent-pool.js.map +1 -1
- package/dist/core/subagent-result.d.ts.map +1 -1
- package/dist/core/subagent-result.js +6 -4
- package/dist/core/subagent-result.js.map +1 -1
- package/dist/core/task-store.d.ts +45 -3
- package/dist/core/task-store.d.ts.map +1 -1
- package/dist/core/task-store.js +51 -5
- package/dist/core/task-store.js.map +1 -1
- package/dist/core/team-view.d.ts.map +1 -1
- package/dist/core/team-view.js +2 -0
- package/dist/core/team-view.js.map +1 -1
- package/dist/core/token-budget.d.ts +13 -1
- package/dist/core/token-budget.d.ts.map +1 -1
- package/dist/core/token-budget.js +18 -1
- package/dist/core/token-budget.js.map +1 -1
- package/dist/core/tools/subagent.d.ts +1 -1
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +184 -53
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/tools/todo.d.ts.map +1 -1
- package/dist/core/tools/todo.js +39 -7
- package/dist/core/tools/todo.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +10 -0
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +27 -1
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/task-panel.d.ts +22 -1
- package/dist/modes/interactive/components/task-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/task-panel.js +302 -80
- package/dist/modes/interactive/components/task-panel.js.map +1 -1
- package/dist/modes/interactive/components/team-attach-panel.d.ts.map +1 -1
- package/dist/modes/interactive/components/team-attach-panel.js +15 -5
- package/dist/modes/interactive/components/team-attach-panel.js.map +1 -1
- package/dist/modes/interactive/theme/dark.json +8 -1
- package/dist/modes/interactive/theme/light.json +8 -1
- package/dist/modes/interactive/theme/theme-schema.json +28 -1
- package/dist/modes/interactive/theme/theme.d.ts +12 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +52 -0
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/interactive/voice/voice-panel.d.ts.map +1 -1
- package/dist/modes/interactive/voice/voice-panel.js +5 -2
- package/dist/modes/interactive/voice/voice-panel.js.map +1 -1
- package/dist/modes/rpc/jsonl.d.ts +16 -1
- package/dist/modes/rpc/jsonl.d.ts.map +1 -1
- package/dist/modes/rpc/jsonl.js +53 -8
- package/dist/modes/rpc/jsonl.js.map +1 -1
- package/dist/utils/atomic-file.d.ts +13 -0
- package/dist/utils/atomic-file.d.ts.map +1 -0
- package/dist/utils/atomic-file.js +26 -0
- package/dist/utils/atomic-file.js.map +1 -0
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-store.d.ts","sourceRoot":"","sources":["../../src/core/task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,aAAa,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEvE;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,KAAK,CAAC;AAE5C;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,CAAC;AAEzD,0EAA0E;AAC1E,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,CAAC;AAEtG;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,oGAAoG;IACpG,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,aAAa,CAAC;IACpB,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,8EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8EAA8E;IAC9E,KAAK,CAAC,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;CACxD;AAED,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,UAAU,CAAC;IACnB,qHAAqH;IACrH,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB;;;;OA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jD,OAAO,CAAC,UAAU,CAAK;IAEvB;;;;OAIG;IACH,KAAK,CAAC,EAAE,EAAE,MAAM,IAAI,GAAG,IAAI,CAQ1B;IAED,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,GAAE,iBAAsB,GAAG,IAAI,CAgB3D;IAED,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,GAAG,IAAI,CAgBzC;IAED;;;;OAIG;IACH,WAAW,CAAC,KAAK,EAAE;QAAE,EAAE,EAAE,MAAM,CAAA;KAAE,GAAG,cAAc,GAAG,IAAI,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC,GAAG,SAAS,CAoBhG;IAED,iFAA+E;IAC/E,UAAU,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,cAAc,GAAG,IAAI,CAKlD;IAED,8EAA8E;IAC9E,aAAa,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE;QAAE,KAAK,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAYzF;IAED,MAAM,IAAI,SAAS,SAAS,EAAE,CAE7B;IAED,OAAO,CAAC,eAAe;IAUvB,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAKvB;IAED;;;;;;;;;;;;;OAaG;IACH,KAAK,IAAI,IAAI,CAkBZ;IAED,IAAI,IAAI,SAAS,IAAI,EAAE,CAEtB;IAED,8EAA8E;IAC9E,KAAK,IAAI,IAAI,CAKZ;IAED,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAKxC;IAED,OAAO,CAAC,IAAI;CAMZ;AAED,uCAAuC;AACvC,eAAO,MAAM,SAAS,WAAkB,CAAC","sourcesContent":["/**\n * Minimal in-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\";\n\n/**\n * What kind of background work owns a task, surfaced as a source glyph in the\n * pane. Unset means the main agent. A \"team\" origin is reserved for the\n * hooteams integration and stays unwired until that lands.\n */\nexport type TaskSource = \"subagent\" | \"mcp\";\n\n/**\n * Kind of agent that can own tasks in the pane's grouped views:\n * the main session (orchestrator), a spawned subagent, or a named\n * team role-agent (e.g. fed by a hooteams bridge).\n */\nexport type TaskAgentKind = \"main\" | \"subagent\" | \"role\";\n\n/** Lifecycle word shown as the agent's `[state]` tag in grouped views. */\nexport type TaskAgentState = \"active\" | \"running\" | \"done\" | \"queued\" | \"idle\" | \"waiting\" | \"failed\";\n\n/**\n * An agent that owns tasks, rendered as a group header in the pane's\n * `subagents` / `teams` views. Subagent dispatches register themselves here;\n * external orchestrators (hooteams) can upsert role-agents with handoffs.\n */\nexport interface TaskAgent {\n\treadonly id: string;\n\tname: string;\n\t/** Short descriptor after the name: \"orchestrator\", \"subagent\", or a team role like \"architect\". */\n\trole?: string;\n\tkind: TaskAgentKind;\n\tstate?: TaskAgentState;\n\t/** Handoff arrow text for team views (e.g. \"→ reviewer\", \"← builder\"). */\n\thandoff?: string;\n\t/**\n\t * Live activity descriptor for a running subagent (e.g. the tool it is\n\t * currently executing), fed by the pool's `task_progress` events. Empty string\n\t * means \"no current activity\" — `applyAgentPatch` skips `undefined`, so callers\n\t * clear it by patching `\"\"`, not `undefined`.\n\t */\n\tactivity?: string;\n\t/** Per-agent token + cost totals, shown right-aligned on the group header. */\n\tstats?: { input: number; output: number; cost: number };\n}\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Origin of the task (subagent delegation vs MCP tool call; unset = main agent); drives the pane's source glyph. */\n\tsource?: TaskSource;\n\t/**\n\t * Origin label shown as the row's `[tag]` in the task pane: the subagent\n\t * type for delegations (e.g. \"explore\"), the MCP server name for MCP tasks\n\t * (e.g. \"github\").\n\t */\n\tsubagentMode?: string;\n\t/** Id of the owning TaskAgent; drives grouping in the pane's subagents/teams views. */\n\tagent?: string;\n\t/**\n\t * Id of the task that spawned this one, linking a dispatched subagent (and its\n\t * own delegations) back to the Task call that created it. Root tasks omit it.\n\t * Drives the subagents lens's recursive task tree: a node's children are the\n\t * tasks whose `parentTaskId` is its id, so nesting deeper than one level (a\n\t * subagent that spawns a subagent) is visible. Set when a child subagent's task\n\t * subtree is merged into the parent (see finalizeDispatchResult).\n\t */\n\tparentTaskId?: number;\n\t/**\n\t * Short warning note surfaced as a ⚠ cue in the task pane (e.g. the subagent\n\t * fell back to the inherited model, or was skipped because the provider was\n\t * exhausted). Kept terse so it fits the row's right column.\n\t */\n\tnote?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsource?: TaskSource;\n\tsubagentMode?: string;\n\tagent?: string;\n\tparentTaskId?: number;\n}\n\nexport type TaskPatch = Partial<\n\tPick<Task, \"title\" | \"status\" | \"source\" | \"subagentMode\" | \"agent\" | \"usage\" | \"note\" | \"parentTaskId\">\n>;\n\nexport type TaskAgentPatch = Partial<Omit<TaskAgent, \"id\">>;\n\n/**\n * Owner group for a task when no explicit agent is set: subagent-sourced work\n * falls into a generic \"subagent\" group, everything else belongs to main.\n * Shared by the store's reset() and the pane's grouped views so the two never\n * disagree about which agents still own live tasks.\n */\nexport function taskOwnerId(task: Pick<Task, \"agent\" | \"source\">): string {\n\tif (task.agent) return task.agent;\n\treturn task.source === \"subagent\" ? \"subagent\" : \"main\";\n}\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate taskAgents: TaskAgent[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\tprivate batchDepth = 0;\n\n\t/**\n\t * Run a series of mutations without notifying listeners until the batch\n\t * completes, so the TUI renders once instead of per-item. Nested batches are\n\t * supported: only the outermost batch flushes.\n\t */\n\tbatch(fn: () => void): void {\n\t\tthis.batchDepth++;\n\t\ttry {\n\t\t\tfn();\n\t\t} finally {\n\t\t\tthis.batchDepth--;\n\t\t\tif (this.batchDepth === 0) this.emit();\n\t\t}\n\t}\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsource: options.source,\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tagent: options.agent,\n\t\t\tparentTaskId: options.parentTaskId,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) {\n\t\t\tconsole.warn(`[task-store] update: unknown task id ${id}`);\n\t\t\treturn;\n\t\t}\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.source !== undefined) task.source = patch.source;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.agent !== undefined) task.agent = patch.agent;\n\t\tif (patch.parentTaskId !== undefined) task.parentTaskId = patch.parentTaskId;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\tif (patch.note !== undefined) task.note = patch.note;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Register or update an agent for the grouped task views. Merges into an\n\t * existing entry with the same id (accumulated stats survive a re-dispatch);\n\t * creates it otherwise.\n\t */\n\tupsertAgent(agent: { id: string } & TaskAgentPatch & Pick<TaskAgent, \"name\" | \"kind\">): TaskAgent {\n\t\tconst existing = this.taskAgents.find((a) => a.id === agent.id);\n\t\tif (existing) {\n\t\t\tthis.applyAgentPatch(existing, agent);\n\t\t\tthis.emit();\n\t\t\treturn existing;\n\t\t}\n\t\tconst created: TaskAgent = {\n\t\t\tid: agent.id,\n\t\t\tname: agent.name,\n\t\t\trole: agent.role,\n\t\t\tkind: agent.kind,\n\t\t\tstate: agent.state,\n\t\t\thandoff: agent.handoff,\n\t\t\tactivity: agent.activity,\n\t\t\tstats: agent.stats,\n\t\t};\n\t\tthis.taskAgents.push(created);\n\t\tthis.emit();\n\t\treturn created;\n\t}\n\n\t/** Patch an existing agent (state/handoff/stats…). Unknown ids are ignored. */\n\tpatchAgent(id: string, patch: TaskAgentPatch): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) return;\n\t\tthis.applyAgentPatch(agent, patch);\n\t\tthis.emit();\n\t}\n\n\t/** Add a usage delta to an agent's running totals (creating them at zero). */\n\taddAgentStats(id: string, delta: { input?: number; output?: number; cost?: number }): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) {\n\t\t\tconsole.warn(`[task-store] addAgentStats: unknown agent id \"${id}\"`);\n\t\t\treturn;\n\t\t}\n\t\tconst stats = agent.stats ?? { input: 0, output: 0, cost: 0 };\n\t\tstats.input += delta.input ?? 0;\n\t\tstats.output += delta.output ?? 0;\n\t\tstats.cost += delta.cost ?? 0;\n\t\tagent.stats = stats;\n\t\tthis.emit();\n\t}\n\n\tagents(): readonly TaskAgent[] {\n\t\treturn this.taskAgents;\n\t}\n\n\tprivate applyAgentPatch(agent: TaskAgent, patch: TaskAgentPatch): void {\n\t\tif (patch.name !== undefined) agent.name = patch.name;\n\t\tif (patch.role !== undefined) agent.role = patch.role;\n\t\tif (patch.kind !== undefined) agent.kind = patch.kind;\n\t\tif (patch.state !== undefined) agent.state = patch.state;\n\t\tif (patch.activity !== undefined) agent.activity = patch.activity;\n\t\tif (patch.handoff !== undefined) agent.handoff = patch.handoff;\n\t\tif (patch.stats !== undefined) agent.stats = patch.stats;\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Drop finished tasks and restart numbering from #1 once the pane is empty.\n\t *\n\t * Called when a new user message arrives: finished tasks from the previous turn\n\t * stay visible (with their final status) for the whole turn and are wiped only\n\t * when the user starts the next turn, so the next turn opens with an empty pane\n\t * and its first task is #1 again. Active (pending/in_progress) tasks are kept —\n\t * a follow-up/steer message can arrive while a subagent is still running, and\n\t * dropping its task here would orphan the live work (its later status update\n\t * would target a removed id and silently vanish). Numbering only restarts once\n\t * no active task survives, so ids never collide with a kept task.\n\t * Agents with accumulated stats are preserved across resets so cross-turn cost\n\t * accounting survives.\n\t */\n\treset(): void {\n\t\tconst active = this.tasks.filter((t) => t.status === \"pending\" || t.status === \"in_progress\");\n\t\tif (active.length === this.tasks.length && this.nextId === 1) return;\n\t\tthis.tasks = active;\n\t\tif (active.length === 0) {\n\t\t\tthis.nextId = 1;\n\t\t\t// Keep agents with non-zero accumulated stats so cross-turn cost accounting\n\t\t\t// survives; drop everyone else (fresh turn opens with a clean roster).\n\t\t\tthis.taskAgents = this.taskAgents.filter(\n\t\t\t\t(a) => a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0),\n\t\t\t);\n\t\t} else {\n\t\t\tconst liveOwners = new Set(active.map(taskOwnerId));\n\t\t\tthis.taskAgents = this.taskAgents.filter(\n\t\t\t\t(a) => liveOwners.has(a.id) || (a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0)),\n\t\t\t);\n\t\t}\n\t\tthis.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\t/** Wipe all tasks and restart numbering. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.taskAgents = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.batchDepth > 0) return;\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
|
|
1
|
+
{"version":3,"file":"task-store.d.ts","sourceRoot":"","sources":["../../src/core/task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG,SAAS,GAAG,aAAa,GAAG,MAAM,GAAG,QAAQ,GAAG,WAAW,CAAC;AAErF;;;;GAIG;AACH,MAAM,MAAM,UAAU,GAAG,UAAU,GAAG,KAAK,CAAC;AAE5C;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,GAAG,UAAU,GAAG,MAAM,CAAC;AAEzD,0EAA0E;AAC1E,MAAM,MAAM,cAAc,GAAG,QAAQ,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEpH;;;;GAIG;AACH,MAAM,WAAW,SAAS;IACzB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,oGAAoG;IACpG,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,aAAa,CAAC;IACpB,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,8EAA0E;IAC1E,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8EAA8E;IAC9E,KA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,MAAM,CAAA;KAAE,GAAG,IAAI,CAYzF;IAED,MAAM,IAAI,SAAS,SAAS,EAAE,CAE7B;IAED,OAAO,CAAC,eAAe;IAUvB,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAKvB;IAED;;;;;;OAMG;IACH,OAAO,CAAC,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,CAcpC;IAED;;;;;;;;;;;;;OAaG;IACH,KAAK,IAAI,IAAI,CAmBZ;IAED,IAAI,IAAI,SAAS,IAAI,EAAE,CAEtB;IAED,8EAA8E;IAC9E,KAAK,IAAI,IAAI,CAKZ;IAED,SAAS,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,IAAI,CAKxC;IAED,OAAO,CAAC,IAAI;CAOZ;AAED,uCAAuC;AACvC,eAAO,MAAM,SAAS,WAAkB,CAAC","sourcesContent":["/**\n * Minimal in-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\n/**\n * `cancelled` is a user-initiated stop (Esc/abort mid-run) — deliberately\n * distinct from `failed` so the panel doesn't paint an intentional interrupt\n * as an error.\n */\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\" | \"cancelled\";\n\n/**\n * What kind of background work owns a task, surfaced as a source glyph in the\n * pane. Unset means the main agent. A \"team\" origin is reserved for the\n * hooteams integration and stays unwired until that lands.\n */\nexport type TaskSource = \"subagent\" | \"mcp\";\n\n/**\n * Kind of agent that can own tasks in the pane's grouped views:\n * the main session (orchestrator), a spawned subagent, or a named\n * team role-agent (e.g. fed by a hooteams bridge).\n */\nexport type TaskAgentKind = \"main\" | \"subagent\" | \"role\";\n\n/** Lifecycle word shown as the agent's `[state]` tag in grouped views. */\nexport type TaskAgentState = \"active\" | \"running\" | \"done\" | \"queued\" | \"idle\" | \"waiting\" | \"failed\" | \"cancelled\";\n\n/**\n * An agent that owns tasks, rendered as a group header in the pane's\n * `subagents` / `teams` views. Subagent dispatches register themselves here;\n * external orchestrators (hooteams) can upsert role-agents with handoffs.\n */\nexport interface TaskAgent {\n\treadonly id: string;\n\tname: string;\n\t/** Short descriptor after the name: \"orchestrator\", \"subagent\", or a team role like \"architect\". */\n\trole?: string;\n\tkind: TaskAgentKind;\n\tstate?: TaskAgentState;\n\t/** Handoff arrow text for team views (e.g. \"→ reviewer\", \"← builder\"). */\n\thandoff?: string;\n\t/**\n\t * Live activity descriptor for a running subagent (e.g. the tool it is\n\t * currently executing), fed by the pool's `task_progress` events. Empty string\n\t * means \"no current activity\" — `applyAgentPatch` skips `undefined`, so callers\n\t * clear it by patching `\"\"`, not `undefined`.\n\t */\n\tactivity?: string;\n\t/** Per-agent token + cost totals, shown right-aligned on the group header. */\n\tstats?: { input: number; output: number; cost: number };\n}\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Origin of the task (subagent delegation vs MCP tool call; unset = main agent); drives the pane's source glyph. */\n\tsource?: TaskSource;\n\t/**\n\t * Origin label shown as the row's `[tag]` in the task pane: the subagent\n\t * type for delegations (e.g. \"explore\"), the MCP server name for MCP tasks\n\t * (e.g. \"github\").\n\t */\n\tsubagentMode?: string;\n\t/** Id of the owning TaskAgent; drives grouping in the pane's subagents/teams views. */\n\tagent?: string;\n\t/**\n\t * Id of the task that spawned this one, linking a dispatched subagent (and its\n\t * own delegations) back to the Task call that created it. Root tasks omit it.\n\t * Drives the subagents lens's recursive task tree: a node's children are the\n\t * tasks whose `parentTaskId` is its id, so nesting deeper than one level (a\n\t * subagent that spawns a subagent) is visible. Set when a child subagent's task\n\t * subtree is merged into the parent (see finalizeDispatchResult).\n\t */\n\tparentTaskId?: number;\n\t/**\n\t * Id of the main-agent (TodoWrite) task this run is working on, set at\n\t * dispatch time when exactly one plan item is in_progress. Purely a display\n\t * link: the flat (\"tasks\") lens nests the run under its plan item so the\n\t * plan and the agents executing it read as one picture. Deliberately NOT\n\t * `parentTaskId` — that field drives the subagents tree and the\n\t * cross-process subtree merge, and overloading it would move runs between\n\t * lenses. A dangling link (the todo was removed/replaced) is simply not\n\t * rendered.\n\t */\n\tlinkedTaskId?: number;\n\t/**\n\t * Short warning note surfaced as a ⚠ cue in the task pane (e.g. the subagent\n\t * fell back to the inherited model, or was skipped because the provider was\n\t * exhausted). Kept terse so it fits the row's right column.\n\t */\n\tnote?: string;\n\t/**\n\t * Canonical TodoWrite item content for main-plan tasks. `title` is the\n\t * *display* form and legitimately changes between `content` and `activeForm`\n\t * as the item's status moves, so it cannot identify an item across TodoWrite\n\t * calls. This field can: the tool reconciles incoming items against it by\n\t * identity first (position only as a fallback), keeping task ids — and the\n\t * subagent runs linked to them — attached to the same plan item when the\n\t * list is reordered or shrunk.\n\t */\n\ttodoContent?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsource?: TaskSource;\n\tsubagentMode?: string;\n\tagent?: string;\n\tparentTaskId?: number;\n\tlinkedTaskId?: number;\n}\n\nexport type TaskPatch = Partial<\n\tPick<\n\t\tTask,\n\t\t| \"title\"\n\t\t| \"status\"\n\t\t| \"source\"\n\t\t| \"subagentMode\"\n\t\t| \"agent\"\n\t\t| \"usage\"\n\t\t| \"note\"\n\t\t| \"parentTaskId\"\n\t\t| \"linkedTaskId\"\n\t\t| \"todoContent\"\n\t>\n>;\n\nexport type TaskAgentPatch = Partial<Omit<TaskAgent, \"id\">>;\n\n/**\n * Owner group for a task when no explicit agent is set: subagent-sourced work\n * falls into a generic \"subagent\" group, everything else belongs to main.\n * Shared by the store's reset() and the pane's grouped views so the two never\n * disagree about which agents still own live tasks.\n */\nexport function taskOwnerId(task: Pick<Task, \"agent\" | \"source\">): string {\n\tif (task.agent) return task.agent;\n\treturn task.source === \"subagent\" ? \"subagent\" : \"main\";\n}\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate taskAgents: TaskAgent[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\tprivate batchDepth = 0;\n\tprivate mutationCount = 0;\n\n\t/**\n\t * Monotonic counter bumped on every mutation (including those inside a\n\t * batch). Lets renderers cache derived state and invalidate it cheaply by\n\t * comparing versions instead of deep-diffing tasks/agents.\n\t */\n\tversion(): number {\n\t\treturn this.mutationCount;\n\t}\n\n\t/**\n\t * Run a series of mutations without notifying listeners until the batch\n\t * completes, so the TUI renders once instead of per-item. Nested batches are\n\t * supported: only the outermost batch flushes.\n\t */\n\tbatch(fn: () => void): void {\n\t\tthis.batchDepth++;\n\t\ttry {\n\t\t\tfn();\n\t\t} finally {\n\t\t\tthis.batchDepth--;\n\t\t\tif (this.batchDepth === 0) this.emit();\n\t\t}\n\t}\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsource: options.source,\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tagent: options.agent,\n\t\t\tparentTaskId: options.parentTaskId,\n\t\t\tlinkedTaskId: options.linkedTaskId,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) {\n\t\t\tconsole.warn(`[task-store] update: unknown task id ${id}`);\n\t\t\treturn;\n\t\t}\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.source !== undefined) task.source = patch.source;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.agent !== undefined) task.agent = patch.agent;\n\t\tif (patch.parentTaskId !== undefined) task.parentTaskId = patch.parentTaskId;\n\t\tif (patch.linkedTaskId !== undefined) task.linkedTaskId = patch.linkedTaskId;\n\t\tif (patch.todoContent !== undefined) task.todoContent = patch.todoContent;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\t// `note` is clearable: passing `note: undefined` explicitly removes a stale\n\t\t// ⚠ cue (e.g. a warning from a previous run of the same task row). Callers\n\t\t// that don't mention `note` leave it untouched.\n\t\tif (\"note\" in patch) task.note = patch.note;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Register or update an agent for the grouped task views. Merges into an\n\t * existing entry with the same id (accumulated stats survive a re-dispatch);\n\t * creates it otherwise.\n\t */\n\tupsertAgent(agent: { id: string } & TaskAgentPatch & Pick<TaskAgent, \"name\" | \"kind\">): TaskAgent {\n\t\tconst existing = this.taskAgents.find((a) => a.id === agent.id);\n\t\tif (existing) {\n\t\t\tthis.applyAgentPatch(existing, agent);\n\t\t\tthis.emit();\n\t\t\treturn existing;\n\t\t}\n\t\tconst created: TaskAgent = {\n\t\t\tid: agent.id,\n\t\t\tname: agent.name,\n\t\t\trole: agent.role,\n\t\t\tkind: agent.kind,\n\t\t\tstate: agent.state,\n\t\t\thandoff: agent.handoff,\n\t\t\tactivity: agent.activity,\n\t\t\tstats: agent.stats,\n\t\t};\n\t\tthis.taskAgents.push(created);\n\t\tthis.emit();\n\t\treturn created;\n\t}\n\n\t/** Patch an existing agent (state/handoff/stats…). Unknown ids are ignored. */\n\tpatchAgent(id: string, patch: TaskAgentPatch): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) return;\n\t\tthis.applyAgentPatch(agent, patch);\n\t\tthis.emit();\n\t}\n\n\t/** Add a usage delta to an agent's running totals (creating them at zero). */\n\taddAgentStats(id: string, delta: { input?: number; output?: number; cost?: number }): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) {\n\t\t\tconsole.warn(`[task-store] addAgentStats: unknown agent id \"${id}\"`);\n\t\t\treturn;\n\t\t}\n\t\tconst stats = agent.stats ?? { input: 0, output: 0, cost: 0 };\n\t\tstats.input += delta.input ?? 0;\n\t\tstats.output += delta.output ?? 0;\n\t\tstats.cost += delta.cost ?? 0;\n\t\tagent.stats = stats;\n\t\tthis.emit();\n\t}\n\n\tagents(): readonly TaskAgent[] {\n\t\treturn this.taskAgents;\n\t}\n\n\tprivate applyAgentPatch(agent: TaskAgent, patch: TaskAgentPatch): void {\n\t\tif (patch.name !== undefined) agent.name = patch.name;\n\t\tif (patch.role !== undefined) agent.role = patch.role;\n\t\tif (patch.kind !== undefined) agent.kind = patch.kind;\n\t\tif (patch.state !== undefined) agent.state = patch.state;\n\t\tif (patch.activity !== undefined) agent.activity = patch.activity;\n\t\tif (patch.handoff !== undefined) agent.handoff = patch.handoff;\n\t\tif (patch.stats !== undefined) agent.stats = patch.stats;\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Arrange the given tasks (by id) into the specified relative order, keeping\n\t * every other task fixed: the matched tasks permute among their existing\n\t * array slots. Lets TodoWrite render the plan in list order while ids stay\n\t * pinned to their items (its identity-based reconcile). Ignored unless every\n\t * id resolves to a task.\n\t */\n\tarrange(ids: readonly number[]): void {\n\t\tconst byId = new Map(this.tasks.map((t) => [t.id, t]));\n\t\tconst ordered = ids.map((id) => byId.get(id)).filter((t): t is Task => t !== undefined);\n\t\tif (ordered.length !== ids.length) return;\n\t\tconst idSet = new Set(ids);\n\t\tconst slots: number[] = [];\n\t\tfor (let i = 0; i < this.tasks.length; i++) {\n\t\t\tif (idSet.has(this.tasks[i]!.id)) slots.push(i);\n\t\t}\n\t\tif (slots.length !== ordered.length) return;\n\t\tfor (let k = 0; k < slots.length; k++) {\n\t\t\tthis.tasks[slots[k]!] = ordered[k]!;\n\t\t}\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Drop finished tasks and restart numbering from #1 once the pane is empty.\n\t *\n\t * Called when a new user message arrives: finished tasks from the previous turn\n\t * stay visible (with their final status) for the whole turn and are wiped only\n\t * when the user starts the next turn, so the next turn opens with an empty pane\n\t * and its first task is #1 again. Active (pending/in_progress) tasks are kept —\n\t * a follow-up/steer message can arrive while a subagent is still running, and\n\t * dropping its task here would orphan the live work (its later status update\n\t * would target a removed id and silently vanish). Numbering only restarts once\n\t * no active task survives, so ids never collide with a kept task.\n\t * Agents with accumulated stats are preserved across resets so cross-turn cost\n\t * accounting survives.\n\t */\n\treset(): void {\n\t\tconst active = this.tasks.filter((t) => t.status === \"pending\" || t.status === \"in_progress\");\n\t\tif (active.length === this.tasks.length && this.nextId === 1) return;\n\t\tthis.tasks = active;\n\t\t// Subagent rows are per-run (one roster entry per dispatch), so a settled\n\t\t// run whose task was just dropped is dead weight — keeping it would grow\n\t\t// the roster without bound across turns. Role/main agents with non-zero\n\t\t// accumulated stats survive so cross-turn team cost accounting holds.\n\t\tconst hasStats = (a: TaskAgent) => a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0);\n\t\tif (active.length === 0) {\n\t\t\tthis.nextId = 1;\n\t\t\tthis.taskAgents = this.taskAgents.filter((a) => a.kind !== \"subagent\" && hasStats(a));\n\t\t} else {\n\t\t\tconst liveOwners = new Set(active.map(taskOwnerId));\n\t\t\tthis.taskAgents = this.taskAgents.filter(\n\t\t\t\t(a) => liveOwners.has(a.id) || (a.kind !== \"subagent\" && hasStats(a)),\n\t\t\t);\n\t\t}\n\t\tthis.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\t/** Wipe all tasks and restart numbering. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.taskAgents = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tprivate emit(): void {\n\t\tthis.mutationCount++;\n\t\tif (this.batchDepth > 0) return;\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
|
package/dist/core/task-store.js
CHANGED
|
@@ -23,6 +23,15 @@ class TaskStore {
|
|
|
23
23
|
nextId = 1;
|
|
24
24
|
listeners = new Set();
|
|
25
25
|
batchDepth = 0;
|
|
26
|
+
mutationCount = 0;
|
|
27
|
+
/**
|
|
28
|
+
* Monotonic counter bumped on every mutation (including those inside a
|
|
29
|
+
* batch). Lets renderers cache derived state and invalidate it cheaply by
|
|
30
|
+
* comparing versions instead of deep-diffing tasks/agents.
|
|
31
|
+
*/
|
|
32
|
+
version() {
|
|
33
|
+
return this.mutationCount;
|
|
34
|
+
}
|
|
26
35
|
/**
|
|
27
36
|
* Run a series of mutations without notifying listeners until the batch
|
|
28
37
|
* completes, so the TUI renders once instead of per-item. Nested batches are
|
|
@@ -49,6 +58,7 @@ class TaskStore {
|
|
|
49
58
|
subagentMode: options.subagentMode,
|
|
50
59
|
agent: options.agent,
|
|
51
60
|
parentTaskId: options.parentTaskId,
|
|
61
|
+
linkedTaskId: options.linkedTaskId,
|
|
52
62
|
createdAt: now,
|
|
53
63
|
updatedAt: now,
|
|
54
64
|
};
|
|
@@ -74,9 +84,16 @@ class TaskStore {
|
|
|
74
84
|
task.agent = patch.agent;
|
|
75
85
|
if (patch.parentTaskId !== undefined)
|
|
76
86
|
task.parentTaskId = patch.parentTaskId;
|
|
87
|
+
if (patch.linkedTaskId !== undefined)
|
|
88
|
+
task.linkedTaskId = patch.linkedTaskId;
|
|
89
|
+
if (patch.todoContent !== undefined)
|
|
90
|
+
task.todoContent = patch.todoContent;
|
|
77
91
|
if (patch.usage !== undefined)
|
|
78
92
|
task.usage = patch.usage;
|
|
79
|
-
|
|
93
|
+
// `note` is clearable: passing `note: undefined` explicitly removes a stale
|
|
94
|
+
// ⚠ cue (e.g. a warning from a previous run of the same task row). Callers
|
|
95
|
+
// that don't mention `note` leave it untouched.
|
|
96
|
+
if ("note" in patch)
|
|
80
97
|
task.note = patch.note;
|
|
81
98
|
task.updatedAt = Date.now();
|
|
82
99
|
this.emit();
|
|
@@ -155,6 +172,31 @@ class TaskStore {
|
|
|
155
172
|
this.tasks.splice(idx, 1);
|
|
156
173
|
this.emit();
|
|
157
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* Arrange the given tasks (by id) into the specified relative order, keeping
|
|
177
|
+
* every other task fixed: the matched tasks permute among their existing
|
|
178
|
+
* array slots. Lets TodoWrite render the plan in list order while ids stay
|
|
179
|
+
* pinned to their items (its identity-based reconcile). Ignored unless every
|
|
180
|
+
* id resolves to a task.
|
|
181
|
+
*/
|
|
182
|
+
arrange(ids) {
|
|
183
|
+
const byId = new Map(this.tasks.map((t) => [t.id, t]));
|
|
184
|
+
const ordered = ids.map((id) => byId.get(id)).filter((t) => t !== undefined);
|
|
185
|
+
if (ordered.length !== ids.length)
|
|
186
|
+
return;
|
|
187
|
+
const idSet = new Set(ids);
|
|
188
|
+
const slots = [];
|
|
189
|
+
for (let i = 0; i < this.tasks.length; i++) {
|
|
190
|
+
if (idSet.has(this.tasks[i].id))
|
|
191
|
+
slots.push(i);
|
|
192
|
+
}
|
|
193
|
+
if (slots.length !== ordered.length)
|
|
194
|
+
return;
|
|
195
|
+
for (let k = 0; k < slots.length; k++) {
|
|
196
|
+
this.tasks[slots[k]] = ordered[k];
|
|
197
|
+
}
|
|
198
|
+
this.emit();
|
|
199
|
+
}
|
|
158
200
|
/**
|
|
159
201
|
* Drop finished tasks and restart numbering from #1 once the pane is empty.
|
|
160
202
|
*
|
|
@@ -174,15 +216,18 @@ class TaskStore {
|
|
|
174
216
|
if (active.length === this.tasks.length && this.nextId === 1)
|
|
175
217
|
return;
|
|
176
218
|
this.tasks = active;
|
|
219
|
+
// Subagent rows are per-run (one roster entry per dispatch), so a settled
|
|
220
|
+
// run whose task was just dropped is dead weight — keeping it would grow
|
|
221
|
+
// the roster without bound across turns. Role/main agents with non-zero
|
|
222
|
+
// accumulated stats survive so cross-turn team cost accounting holds.
|
|
223
|
+
const hasStats = (a) => a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0);
|
|
177
224
|
if (active.length === 0) {
|
|
178
225
|
this.nextId = 1;
|
|
179
|
-
|
|
180
|
-
// survives; drop everyone else (fresh turn opens with a clean roster).
|
|
181
|
-
this.taskAgents = this.taskAgents.filter((a) => a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0));
|
|
226
|
+
this.taskAgents = this.taskAgents.filter((a) => a.kind !== "subagent" && hasStats(a));
|
|
182
227
|
}
|
|
183
228
|
else {
|
|
184
229
|
const liveOwners = new Set(active.map(taskOwnerId));
|
|
185
|
-
this.taskAgents = this.taskAgents.filter((a) => liveOwners.has(a.id) || (a.
|
|
230
|
+
this.taskAgents = this.taskAgents.filter((a) => liveOwners.has(a.id) || (a.kind !== "subagent" && hasStats(a)));
|
|
186
231
|
}
|
|
187
232
|
this.emit();
|
|
188
233
|
}
|
|
@@ -203,6 +248,7 @@ class TaskStore {
|
|
|
203
248
|
};
|
|
204
249
|
}
|
|
205
250
|
emit() {
|
|
251
|
+
this.mutationCount++;
|
|
206
252
|
if (this.batchDepth > 0)
|
|
207
253
|
return;
|
|
208
254
|
for (const listener of this.listeners) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"task-store.js","sourceRoot":"","sources":["../../src/core/task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAoGH;;;;;GAKG;AACH,MAAM,U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EAAE,CAAC;QACZ,CAAC;IAAA,CACD;CACD;AAED,uCAAuC;AACvC,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,SAAS,EAAE,CAAC","sourcesContent":["/**\n * Minimal in-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\";\n\n/**\n * What kind of background work owns a task, surfaced as a source glyph in the\n * pane. Unset means the main agent. A \"team\" origin is reserved for the\n * hooteams integration and stays unwired until that lands.\n */\nexport type TaskSource = \"subagent\" | \"mcp\";\n\n/**\n * Kind of agent that can own tasks in the pane's grouped views:\n * the main session (orchestrator), a spawned subagent, or a named\n * team role-agent (e.g. fed by a hooteams bridge).\n */\nexport type TaskAgentKind = \"main\" | \"subagent\" | \"role\";\n\n/** Lifecycle word shown as the agent's `[state]` tag in grouped views. */\nexport type TaskAgentState = \"active\" | \"running\" | \"done\" | \"queued\" | \"idle\" | \"waiting\" | \"failed\";\n\n/**\n * An agent that owns tasks, rendered as a group header in the pane's\n * `subagents` / `teams` views. Subagent dispatches register themselves here;\n * external orchestrators (hooteams) can upsert role-agents with handoffs.\n */\nexport interface TaskAgent {\n\treadonly id: string;\n\tname: string;\n\t/** Short descriptor after the name: \"orchestrator\", \"subagent\", or a team role like \"architect\". */\n\trole?: string;\n\tkind: TaskAgentKind;\n\tstate?: TaskAgentState;\n\t/** Handoff arrow text for team views (e.g. \"→ reviewer\", \"← builder\"). */\n\thandoff?: string;\n\t/**\n\t * Live activity descriptor for a running subagent (e.g. the tool it is\n\t * currently executing), fed by the pool's `task_progress` events. Empty string\n\t * means \"no current activity\" — `applyAgentPatch` skips `undefined`, so callers\n\t * clear it by patching `\"\"`, not `undefined`.\n\t */\n\tactivity?: string;\n\t/** Per-agent token + cost totals, shown right-aligned on the group header. */\n\tstats?: { input: number; output: number; cost: number };\n}\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Origin of the task (subagent delegation vs MCP tool call; unset = main agent); drives the pane's source glyph. */\n\tsource?: TaskSource;\n\t/**\n\t * Origin label shown as the row's `[tag]` in the task pane: the subagent\n\t * type for delegations (e.g. \"explore\"), the MCP server name for MCP tasks\n\t * (e.g. \"github\").\n\t */\n\tsubagentMode?: string;\n\t/** Id of the owning TaskAgent; drives grouping in the pane's subagents/teams views. */\n\tagent?: string;\n\t/**\n\t * Id of the task that spawned this one, linking a dispatched subagent (and its\n\t * own delegations) back to the Task call that created it. Root tasks omit it.\n\t * Drives the subagents lens's recursive task tree: a node's children are the\n\t * tasks whose `parentTaskId` is its id, so nesting deeper than one level (a\n\t * subagent that spawns a subagent) is visible. Set when a child subagent's task\n\t * subtree is merged into the parent (see finalizeDispatchResult).\n\t */\n\tparentTaskId?: number;\n\t/**\n\t * Short warning note surfaced as a ⚠ cue in the task pane (e.g. the subagent\n\t * fell back to the inherited model, or was skipped because the provider was\n\t * exhausted). Kept terse so it fits the row's right column.\n\t */\n\tnote?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsource?: TaskSource;\n\tsubagentMode?: string;\n\tagent?: string;\n\tparentTaskId?: number;\n}\n\nexport type TaskPatch = Partial<\n\tPick<Task, \"title\" | \"status\" | \"source\" | \"subagentMode\" | \"agent\" | \"usage\" | \"note\" | \"parentTaskId\">\n>;\n\nexport type TaskAgentPatch = Partial<Omit<TaskAgent, \"id\">>;\n\n/**\n * Owner group for a task when no explicit agent is set: subagent-sourced work\n * falls into a generic \"subagent\" group, everything else belongs to main.\n * Shared by the store's reset() and the pane's grouped views so the two never\n * disagree about which agents still own live tasks.\n */\nexport function taskOwnerId(task: Pick<Task, \"agent\" | \"source\">): string {\n\tif (task.agent) return task.agent;\n\treturn task.source === \"subagent\" ? \"subagent\" : \"main\";\n}\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate taskAgents: TaskAgent[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\tprivate batchDepth = 0;\n\n\t/**\n\t * Run a series of mutations without notifying listeners until the batch\n\t * completes, so the TUI renders once instead of per-item. Nested batches are\n\t * supported: only the outermost batch flushes.\n\t */\n\tbatch(fn: () => void): void {\n\t\tthis.batchDepth++;\n\t\ttry {\n\t\t\tfn();\n\t\t} finally {\n\t\t\tthis.batchDepth--;\n\t\t\tif (this.batchDepth === 0) this.emit();\n\t\t}\n\t}\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsource: options.source,\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tagent: options.agent,\n\t\t\tparentTaskId: options.parentTaskId,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) {\n\t\t\tconsole.warn(`[task-store] update: unknown task id ${id}`);\n\t\t\treturn;\n\t\t}\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.source !== undefined) task.source = patch.source;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.agent !== undefined) task.agent = patch.agent;\n\t\tif (patch.parentTaskId !== undefined) task.parentTaskId = patch.parentTaskId;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\tif (patch.note !== undefined) task.note = patch.note;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Register or update an agent for the grouped task views. Merges into an\n\t * existing entry with the same id (accumulated stats survive a re-dispatch);\n\t * creates it otherwise.\n\t */\n\tupsertAgent(agent: { id: string } & TaskAgentPatch & Pick<TaskAgent, \"name\" | \"kind\">): TaskAgent {\n\t\tconst existing = this.taskAgents.find((a) => a.id === agent.id);\n\t\tif (existing) {\n\t\t\tthis.applyAgentPatch(existing, agent);\n\t\t\tthis.emit();\n\t\t\treturn existing;\n\t\t}\n\t\tconst created: TaskAgent = {\n\t\t\tid: agent.id,\n\t\t\tname: agent.name,\n\t\t\trole: agent.role,\n\t\t\tkind: agent.kind,\n\t\t\tstate: agent.state,\n\t\t\thandoff: agent.handoff,\n\t\t\tactivity: agent.activity,\n\t\t\tstats: agent.stats,\n\t\t};\n\t\tthis.taskAgents.push(created);\n\t\tthis.emit();\n\t\treturn created;\n\t}\n\n\t/** Patch an existing agent (state/handoff/stats…). Unknown ids are ignored. */\n\tpatchAgent(id: string, patch: TaskAgentPatch): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) return;\n\t\tthis.applyAgentPatch(agent, patch);\n\t\tthis.emit();\n\t}\n\n\t/** Add a usage delta to an agent's running totals (creating them at zero). */\n\taddAgentStats(id: string, delta: { input?: number; output?: number; cost?: number }): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) {\n\t\t\tconsole.warn(`[task-store] addAgentStats: unknown agent id \"${id}\"`);\n\t\t\treturn;\n\t\t}\n\t\tconst stats = agent.stats ?? { input: 0, output: 0, cost: 0 };\n\t\tstats.input += delta.input ?? 0;\n\t\tstats.output += delta.output ?? 0;\n\t\tstats.cost += delta.cost ?? 0;\n\t\tagent.stats = stats;\n\t\tthis.emit();\n\t}\n\n\tagents(): readonly TaskAgent[] {\n\t\treturn this.taskAgents;\n\t}\n\n\tprivate applyAgentPatch(agent: TaskAgent, patch: TaskAgentPatch): void {\n\t\tif (patch.name !== undefined) agent.name = patch.name;\n\t\tif (patch.role !== undefined) agent.role = patch.role;\n\t\tif (patch.kind !== undefined) agent.kind = patch.kind;\n\t\tif (patch.state !== undefined) agent.state = patch.state;\n\t\tif (patch.activity !== undefined) agent.activity = patch.activity;\n\t\tif (patch.handoff !== undefined) agent.handoff = patch.handoff;\n\t\tif (patch.stats !== undefined) agent.stats = patch.stats;\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Drop finished tasks and restart numbering from #1 once the pane is empty.\n\t *\n\t * Called when a new user message arrives: finished tasks from the previous turn\n\t * stay visible (with their final status) for the whole turn and are wiped only\n\t * when the user starts the next turn, so the next turn opens with an empty pane\n\t * and its first task is #1 again. Active (pending/in_progress) tasks are kept —\n\t * a follow-up/steer message can arrive while a subagent is still running, and\n\t * dropping its task here would orphan the live work (its later status update\n\t * would target a removed id and silently vanish). Numbering only restarts once\n\t * no active task survives, so ids never collide with a kept task.\n\t * Agents with accumulated stats are preserved across resets so cross-turn cost\n\t * accounting survives.\n\t */\n\treset(): void {\n\t\tconst active = this.tasks.filter((t) => t.status === \"pending\" || t.status === \"in_progress\");\n\t\tif (active.length === this.tasks.length && this.nextId === 1) return;\n\t\tthis.tasks = active;\n\t\tif (active.length === 0) {\n\t\t\tthis.nextId = 1;\n\t\t\t// Keep agents with non-zero accumulated stats so cross-turn cost accounting\n\t\t\t// survives; drop everyone else (fresh turn opens with a clean roster).\n\t\t\tthis.taskAgents = this.taskAgents.filter(\n\t\t\t\t(a) => a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0),\n\t\t\t);\n\t\t} else {\n\t\t\tconst liveOwners = new Set(active.map(taskOwnerId));\n\t\t\tthis.taskAgents = this.taskAgents.filter(\n\t\t\t\t(a) => liveOwners.has(a.id) || (a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0)),\n\t\t\t);\n\t\t}\n\t\tthis.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\t/** Wipe all tasks and restart numbering. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.taskAgents = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tprivate emit(): void {\n\t\tif (this.batchDepth > 0) return;\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
|
|
1
|
+
{"version":3,"file":"task-store.js","sourceRoot":"","sources":["../../src/core/task-store.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AA2IH;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,IAAoC,EAAU;IACzE,IAAI,IAAI,CAAC,KAAK;QAAE,OAAO,IAAI,CAAC,KAAK,CAAC;IAClC,OAAO,IAAI,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC;AAAA,CACxD;AAID,MAAM,SAAS;IACN,KAAK,GAAW,EAAE,CAAC;IACnB,UAAU,GAAgB,EAAE,CAAC;IAC7B,MAAM,GAAG,CAAC,CAAC;IACF,SAAS,GAAG,IAAI,GAAG,EAAY,CAAC;IACzC,UAAU,GAAG,CAAC,CAAC;IACf,aAAa,GAAG,CAAC,CAAC;IAE1B;;;;OAIG;IACH,OAAO,GAAW;QACjB,OAAO,IAAI,CAAC,aAAa,CAAC;IAAA,CAC1B;IAED;;;;OAIG;IACH,KAAK,CAAC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-process task store.\n *\n * Tracks short-lived tasks (e.g. subagent delegations) so the TUI task panel can\n * display active work. It is a process-level singleton because the tool that\n * creates tasks and the footer that renders them live in the same process and\n * there is no cross-process boundary to cross.\n */\n\n/**\n * `cancelled` is a user-initiated stop (Esc/abort mid-run) — deliberately\n * distinct from `failed` so the panel doesn't paint an intentional interrupt\n * as an error.\n */\nexport type TaskStatus = \"pending\" | \"in_progress\" | \"done\" | \"failed\" | \"cancelled\";\n\n/**\n * What kind of background work owns a task, surfaced as a source glyph in the\n * pane. Unset means the main agent. A \"team\" origin is reserved for the\n * hooteams integration and stays unwired until that lands.\n */\nexport type TaskSource = \"subagent\" | \"mcp\";\n\n/**\n * Kind of agent that can own tasks in the pane's grouped views:\n * the main session (orchestrator), a spawned subagent, or a named\n * team role-agent (e.g. fed by a hooteams bridge).\n */\nexport type TaskAgentKind = \"main\" | \"subagent\" | \"role\";\n\n/** Lifecycle word shown as the agent's `[state]` tag in grouped views. */\nexport type TaskAgentState = \"active\" | \"running\" | \"done\" | \"queued\" | \"idle\" | \"waiting\" | \"failed\" | \"cancelled\";\n\n/**\n * An agent that owns tasks, rendered as a group header in the pane's\n * `subagents` / `teams` views. Subagent dispatches register themselves here;\n * external orchestrators (hooteams) can upsert role-agents with handoffs.\n */\nexport interface TaskAgent {\n\treadonly id: string;\n\tname: string;\n\t/** Short descriptor after the name: \"orchestrator\", \"subagent\", or a team role like \"architect\". */\n\trole?: string;\n\tkind: TaskAgentKind;\n\tstate?: TaskAgentState;\n\t/** Handoff arrow text for team views (e.g. \"→ reviewer\", \"← builder\"). */\n\thandoff?: string;\n\t/**\n\t * Live activity descriptor for a running subagent (e.g. the tool it is\n\t * currently executing), fed by the pool's `task_progress` events. Empty string\n\t * means \"no current activity\" — `applyAgentPatch` skips `undefined`, so callers\n\t * clear it by patching `\"\"`, not `undefined`.\n\t */\n\tactivity?: string;\n\t/** Per-agent token + cost totals, shown right-aligned on the group header. */\n\tstats?: { input: number; output: number; cost: number };\n}\n\nexport interface Task {\n\treadonly id: number;\n\ttitle: string;\n\tstatus: TaskStatus;\n\t/** Origin of the task (subagent delegation vs MCP tool call; unset = main agent); drives the pane's source glyph. */\n\tsource?: TaskSource;\n\t/**\n\t * Origin label shown as the row's `[tag]` in the task pane: the subagent\n\t * type for delegations (e.g. \"explore\"), the MCP server name for MCP tasks\n\t * (e.g. \"github\").\n\t */\n\tsubagentMode?: string;\n\t/** Id of the owning TaskAgent; drives grouping in the pane's subagents/teams views. */\n\tagent?: string;\n\t/**\n\t * Id of the task that spawned this one, linking a dispatched subagent (and its\n\t * own delegations) back to the Task call that created it. Root tasks omit it.\n\t * Drives the subagents lens's recursive task tree: a node's children are the\n\t * tasks whose `parentTaskId` is its id, so nesting deeper than one level (a\n\t * subagent that spawns a subagent) is visible. Set when a child subagent's task\n\t * subtree is merged into the parent (see finalizeDispatchResult).\n\t */\n\tparentTaskId?: number;\n\t/**\n\t * Id of the main-agent (TodoWrite) task this run is working on, set at\n\t * dispatch time when exactly one plan item is in_progress. Purely a display\n\t * link: the flat (\"tasks\") lens nests the run under its plan item so the\n\t * plan and the agents executing it read as one picture. Deliberately NOT\n\t * `parentTaskId` — that field drives the subagents tree and the\n\t * cross-process subtree merge, and overloading it would move runs between\n\t * lenses. A dangling link (the todo was removed/replaced) is simply not\n\t * rendered.\n\t */\n\tlinkedTaskId?: number;\n\t/**\n\t * Short warning note surfaced as a ⚠ cue in the task pane (e.g. the subagent\n\t * fell back to the inherited model, or was skipped because the provider was\n\t * exhausted). Kept terse so it fits the row's right column.\n\t */\n\tnote?: string;\n\t/**\n\t * Canonical TodoWrite item content for main-plan tasks. `title` is the\n\t * *display* form and legitimately changes between `content` and `activeForm`\n\t * as the item's status moves, so it cannot identify an item across TodoWrite\n\t * calls. This field can: the tool reconciles incoming items against it by\n\t * identity first (position only as a fallback), keeping task ids — and the\n\t * subagent runs linked to them — attached to the same plan item when the\n\t * list is reordered or shrunk.\n\t */\n\ttodoContent?: string;\n\treadonly createdAt: number;\n\tupdatedAt: number;\n\t/** Token and cost usage attributed to this task (e.g. from a subagent session). */\n\tusage?: {\n\t\tinput: number;\n\t\toutput: number;\n\t\tcacheRead: number;\n\t\tcacheWrite: number;\n\t\tcost: number;\n\t};\n}\n\nexport interface CreateTaskOptions {\n\tsource?: TaskSource;\n\tsubagentMode?: string;\n\tagent?: string;\n\tparentTaskId?: number;\n\tlinkedTaskId?: number;\n}\n\nexport type TaskPatch = Partial<\n\tPick<\n\t\tTask,\n\t\t| \"title\"\n\t\t| \"status\"\n\t\t| \"source\"\n\t\t| \"subagentMode\"\n\t\t| \"agent\"\n\t\t| \"usage\"\n\t\t| \"note\"\n\t\t| \"parentTaskId\"\n\t\t| \"linkedTaskId\"\n\t\t| \"todoContent\"\n\t>\n>;\n\nexport type TaskAgentPatch = Partial<Omit<TaskAgent, \"id\">>;\n\n/**\n * Owner group for a task when no explicit agent is set: subagent-sourced work\n * falls into a generic \"subagent\" group, everything else belongs to main.\n * Shared by the store's reset() and the pane's grouped views so the two never\n * disagree about which agents still own live tasks.\n */\nexport function taskOwnerId(task: Pick<Task, \"agent\" | \"source\">): string {\n\tif (task.agent) return task.agent;\n\treturn task.source === \"subagent\" ? \"subagent\" : \"main\";\n}\n\ntype Listener = () => void;\n\nclass TaskStore {\n\tprivate tasks: Task[] = [];\n\tprivate taskAgents: TaskAgent[] = [];\n\tprivate nextId = 1;\n\tprivate readonly listeners = new Set<Listener>();\n\tprivate batchDepth = 0;\n\tprivate mutationCount = 0;\n\n\t/**\n\t * Monotonic counter bumped on every mutation (including those inside a\n\t * batch). Lets renderers cache derived state and invalidate it cheaply by\n\t * comparing versions instead of deep-diffing tasks/agents.\n\t */\n\tversion(): number {\n\t\treturn this.mutationCount;\n\t}\n\n\t/**\n\t * Run a series of mutations without notifying listeners until the batch\n\t * completes, so the TUI renders once instead of per-item. Nested batches are\n\t * supported: only the outermost batch flushes.\n\t */\n\tbatch(fn: () => void): void {\n\t\tthis.batchDepth++;\n\t\ttry {\n\t\t\tfn();\n\t\t} finally {\n\t\t\tthis.batchDepth--;\n\t\t\tif (this.batchDepth === 0) this.emit();\n\t\t}\n\t}\n\n\tcreate(title: string, options: CreateTaskOptions = {}): Task {\n\t\tconst now = Date.now();\n\t\tconst task: Task = {\n\t\t\tid: this.nextId++,\n\t\t\ttitle: title.trim() || \"(untitled task)\",\n\t\t\tstatus: \"pending\",\n\t\t\tsource: options.source,\n\t\t\tsubagentMode: options.subagentMode,\n\t\t\tagent: options.agent,\n\t\t\tparentTaskId: options.parentTaskId,\n\t\t\tlinkedTaskId: options.linkedTaskId,\n\t\t\tcreatedAt: now,\n\t\t\tupdatedAt: now,\n\t\t};\n\t\tthis.tasks.push(task);\n\t\tthis.emit();\n\t\treturn task;\n\t}\n\n\tupdate(id: number, patch: TaskPatch): void {\n\t\tconst task = this.tasks.find((t) => t.id === id);\n\t\tif (!task) {\n\t\t\tconsole.warn(`[task-store] update: unknown task id ${id}`);\n\t\t\treturn;\n\t\t}\n\t\tif (patch.title !== undefined) task.title = patch.title;\n\t\tif (patch.status !== undefined) task.status = patch.status;\n\t\tif (patch.source !== undefined) task.source = patch.source;\n\t\tif (patch.subagentMode !== undefined) task.subagentMode = patch.subagentMode;\n\t\tif (patch.agent !== undefined) task.agent = patch.agent;\n\t\tif (patch.parentTaskId !== undefined) task.parentTaskId = patch.parentTaskId;\n\t\tif (patch.linkedTaskId !== undefined) task.linkedTaskId = patch.linkedTaskId;\n\t\tif (patch.todoContent !== undefined) task.todoContent = patch.todoContent;\n\t\tif (patch.usage !== undefined) task.usage = patch.usage;\n\t\t// `note` is clearable: passing `note: undefined` explicitly removes a stale\n\t\t// ⚠ cue (e.g. a warning from a previous run of the same task row). Callers\n\t\t// that don't mention `note` leave it untouched.\n\t\tif (\"note\" in patch) task.note = patch.note;\n\t\ttask.updatedAt = Date.now();\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Register or update an agent for the grouped task views. Merges into an\n\t * existing entry with the same id (accumulated stats survive a re-dispatch);\n\t * creates it otherwise.\n\t */\n\tupsertAgent(agent: { id: string } & TaskAgentPatch & Pick<TaskAgent, \"name\" | \"kind\">): TaskAgent {\n\t\tconst existing = this.taskAgents.find((a) => a.id === agent.id);\n\t\tif (existing) {\n\t\t\tthis.applyAgentPatch(existing, agent);\n\t\t\tthis.emit();\n\t\t\treturn existing;\n\t\t}\n\t\tconst created: TaskAgent = {\n\t\t\tid: agent.id,\n\t\t\tname: agent.name,\n\t\t\trole: agent.role,\n\t\t\tkind: agent.kind,\n\t\t\tstate: agent.state,\n\t\t\thandoff: agent.handoff,\n\t\t\tactivity: agent.activity,\n\t\t\tstats: agent.stats,\n\t\t};\n\t\tthis.taskAgents.push(created);\n\t\tthis.emit();\n\t\treturn created;\n\t}\n\n\t/** Patch an existing agent (state/handoff/stats…). Unknown ids are ignored. */\n\tpatchAgent(id: string, patch: TaskAgentPatch): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) return;\n\t\tthis.applyAgentPatch(agent, patch);\n\t\tthis.emit();\n\t}\n\n\t/** Add a usage delta to an agent's running totals (creating them at zero). */\n\taddAgentStats(id: string, delta: { input?: number; output?: number; cost?: number }): void {\n\t\tconst agent = this.taskAgents.find((a) => a.id === id);\n\t\tif (!agent) {\n\t\t\tconsole.warn(`[task-store] addAgentStats: unknown agent id \"${id}\"`);\n\t\t\treturn;\n\t\t}\n\t\tconst stats = agent.stats ?? { input: 0, output: 0, cost: 0 };\n\t\tstats.input += delta.input ?? 0;\n\t\tstats.output += delta.output ?? 0;\n\t\tstats.cost += delta.cost ?? 0;\n\t\tagent.stats = stats;\n\t\tthis.emit();\n\t}\n\n\tagents(): readonly TaskAgent[] {\n\t\treturn this.taskAgents;\n\t}\n\n\tprivate applyAgentPatch(agent: TaskAgent, patch: TaskAgentPatch): void {\n\t\tif (patch.name !== undefined) agent.name = patch.name;\n\t\tif (patch.role !== undefined) agent.role = patch.role;\n\t\tif (patch.kind !== undefined) agent.kind = patch.kind;\n\t\tif (patch.state !== undefined) agent.state = patch.state;\n\t\tif (patch.activity !== undefined) agent.activity = patch.activity;\n\t\tif (patch.handoff !== undefined) agent.handoff = patch.handoff;\n\t\tif (patch.stats !== undefined) agent.stats = patch.stats;\n\t}\n\n\tremove(id: number): void {\n\t\tconst idx = this.tasks.findIndex((t) => t.id === id);\n\t\tif (idx === -1) return;\n\t\tthis.tasks.splice(idx, 1);\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Arrange the given tasks (by id) into the specified relative order, keeping\n\t * every other task fixed: the matched tasks permute among their existing\n\t * array slots. Lets TodoWrite render the plan in list order while ids stay\n\t * pinned to their items (its identity-based reconcile). Ignored unless every\n\t * id resolves to a task.\n\t */\n\tarrange(ids: readonly number[]): void {\n\t\tconst byId = new Map(this.tasks.map((t) => [t.id, t]));\n\t\tconst ordered = ids.map((id) => byId.get(id)).filter((t): t is Task => t !== undefined);\n\t\tif (ordered.length !== ids.length) return;\n\t\tconst idSet = new Set(ids);\n\t\tconst slots: number[] = [];\n\t\tfor (let i = 0; i < this.tasks.length; i++) {\n\t\t\tif (idSet.has(this.tasks[i]!.id)) slots.push(i);\n\t\t}\n\t\tif (slots.length !== ordered.length) return;\n\t\tfor (let k = 0; k < slots.length; k++) {\n\t\t\tthis.tasks[slots[k]!] = ordered[k]!;\n\t\t}\n\t\tthis.emit();\n\t}\n\n\t/**\n\t * Drop finished tasks and restart numbering from #1 once the pane is empty.\n\t *\n\t * Called when a new user message arrives: finished tasks from the previous turn\n\t * stay visible (with their final status) for the whole turn and are wiped only\n\t * when the user starts the next turn, so the next turn opens with an empty pane\n\t * and its first task is #1 again. Active (pending/in_progress) tasks are kept —\n\t * a follow-up/steer message can arrive while a subagent is still running, and\n\t * dropping its task here would orphan the live work (its later status update\n\t * would target a removed id and silently vanish). Numbering only restarts once\n\t * no active task survives, so ids never collide with a kept task.\n\t * Agents with accumulated stats are preserved across resets so cross-turn cost\n\t * accounting survives.\n\t */\n\treset(): void {\n\t\tconst active = this.tasks.filter((t) => t.status === \"pending\" || t.status === \"in_progress\");\n\t\tif (active.length === this.tasks.length && this.nextId === 1) return;\n\t\tthis.tasks = active;\n\t\t// Subagent rows are per-run (one roster entry per dispatch), so a settled\n\t\t// run whose task was just dropped is dead weight — keeping it would grow\n\t\t// the roster without bound across turns. Role/main agents with non-zero\n\t\t// accumulated stats survive so cross-turn team cost accounting holds.\n\t\tconst hasStats = (a: TaskAgent) => a.stats && (a.stats.input > 0 || a.stats.output > 0 || a.stats.cost > 0);\n\t\tif (active.length === 0) {\n\t\t\tthis.nextId = 1;\n\t\t\tthis.taskAgents = this.taskAgents.filter((a) => a.kind !== \"subagent\" && hasStats(a));\n\t\t} else {\n\t\t\tconst liveOwners = new Set(active.map(taskOwnerId));\n\t\t\tthis.taskAgents = this.taskAgents.filter(\n\t\t\t\t(a) => liveOwners.has(a.id) || (a.kind !== \"subagent\" && hasStats(a)),\n\t\t\t);\n\t\t}\n\t\tthis.emit();\n\t}\n\n\tlist(): readonly Task[] {\n\t\treturn this.tasks;\n\t}\n\n\t/** Wipe all tasks and restart numbering. Intended for test isolation only. */\n\tclear(): void {\n\t\tthis.tasks = [];\n\t\tthis.taskAgents = [];\n\t\tthis.nextId = 1;\n\t\tthis.emit();\n\t}\n\n\tsubscribe(listener: Listener): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tprivate emit(): void {\n\t\tthis.mutationCount++;\n\t\tif (this.batchDepth > 0) return;\n\t\tfor (const listener of this.listeners) {\n\t\t\tlistener();\n\t\t}\n\t}\n}\n\n/** Shared, process-wide task store. */\nexport const taskStore = new TaskStore();\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team-view.d.ts","sourceRoot":"","sources":["../../src/core/team-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAwC,SAAS,EAAE,MAAM,iBAAiB,CAAC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AI,MAAM,CAAC;CAC1B;AAKD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,kBAAkB,CA8H9F","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n\t/** Task lifecycle fields carried by task_* events from the orchestrator. */\n\ttaskId?: string;\n\t/** Approval gate carried by task_paused. */\n\tquestion?: string;\n\toptions?: string[];\n\t/** Answer carried by task_resumed. */\n\tchosenOption?: string;\n\t/** \"done\" | \"error\" on task_finished. */\n\tstatus?: string;\n\t/** Run id carried by dag_complete / dag_failed. */\n\trunId?: string;\n}\n\n/** One unanswered approval gate from GET /tasks/pending. */\nexport interface TeamPendingApproval {\n\ttaskId: string;\n\tquestion: string;\n\toptions: string[];\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tcase \"paused\":\n\t\t\treturn \"waiting\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\" || state === \"waiting\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\t// Dag settlement events are tagged role=\"orchestrator\" — they describe\n\t\t// the run, not a member, and must not create a phantom roster entry.\n\t\tif (event.type === \"dag_complete\" || event.type === \"dag_failed\") return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; a paused run (waiting on an approval gate)\n\t\t\t\t// stays waiting — hooteams mirrors agent_end right after task_paused, so\n\t\t\t\t// without this guard the gate's \"waiting\" state would flip to idle and the\n\t\t\t\t// roster would read as done while the AskOptions pane is still open.\n\t\t\t\t// agent_end only marks clean completions (mirrors hooteams' own tracking).\n\t\t\t\tconst current = this.store.agents().find((a) => a.id === this.agentId(role))?.state;\n\t\t\t\tif (current !== \"failed\" && current !== \"waiting\") {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_started\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_paused\": {\n\t\t\t\tconst title = `awaiting approval: ${event.question ?? \"?\"}`;\n\t\t\t\tthis.ensureRole(role, \"waiting\", title);\n\t\t\t\tthis.patchRole(role, \"waiting\", title);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_resumed\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_finished\": {\n\t\t\t\tconst state = event.status === \"error\" ? \"failed\" : \"done\";\n\t\t\t\tthis.ensureRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tthis.patchRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Answer a paused task: POST /tasks/:taskId/resume { option, feedback? }.\n\t * Rejects with \"answered elsewhere\" on 409 (first answer wins across\n\t * surfaces) and with HTTP/network errors otherwise.\n\t */\n\tresume(taskId: string, option: string, feedback?: string): Promise<void>;\n\t/**\n\t * GET /tasks/pending — gates that opened before we attached. Resolves to\n\t * [] when the server has no active run (404) so callers need no special\n\t * casing.\n\t */\n\tpendingApprovals(): Promise<TeamPendingApproval[]>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync resume(taskId: string, option: string, feedback?: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/tasks/${encodeURIComponent(taskId)}/resume`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ option, ...(feedback !== undefined ? { feedback } : {}) }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 409) throw new Error(`task \"${taskId}\" was answered elsewhere`);\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync pendingApprovals(): Promise<TeamPendingApproval[]> {\n\t\t\tconst response = await fetch(`${base}/tasks/pending`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 404) return [];\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tconst body = (await response.json()) as { pending?: TeamPendingApproval[] };\n\t\t\treturn Array.isArray(body.pending) ? body.pending : [];\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team-view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D;;;;OAIG;IACH,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,aAAa,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IAChE,gEAAgE;IAChE,eAAe,IAAI,MAAM,CAAC;CAC1B;AAKD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,GAAE,eAAoB,GAAG,kBAAkB,CA8H9F","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n\t/** Task lifecycle fields carried by task_* events from the orchestrator. */\n\ttaskId?: string;\n\t/** Approval gate carried by task_paused. */\n\tquestion?: string;\n\toptions?: string[];\n\t/** Answer carried by task_resumed. */\n\tchosenOption?: string;\n\t/** \"done\" | \"error\" on task_finished. */\n\tstatus?: string;\n\t/** Run id carried by dag_complete / dag_failed. */\n\trunId?: string;\n}\n\n/** One unanswered approval gate from GET /tasks/pending. */\nexport interface TeamPendingApproval {\n\ttaskId: string;\n\tquestion: string;\n\toptions: string[];\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tcase \"paused\":\n\t\t\treturn \"waiting\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"cancelled\":\n\t\t\treturn \"cancelled\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\" || state === \"waiting\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\t// Dag settlement events are tagged role=\"orchestrator\" — they describe\n\t\t// the run, not a member, and must not create a phantom roster entry.\n\t\tif (event.type === \"dag_complete\" || event.type === \"dag_failed\") return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; a paused run (waiting on an approval gate)\n\t\t\t\t// stays waiting — hooteams mirrors agent_end right after task_paused, so\n\t\t\t\t// without this guard the gate's \"waiting\" state would flip to idle and the\n\t\t\t\t// roster would read as done while the AskOptions pane is still open.\n\t\t\t\t// agent_end only marks clean completions (mirrors hooteams' own tracking).\n\t\t\t\tconst current = this.store.agents().find((a) => a.id === this.agentId(role))?.state;\n\t\t\t\tif (current !== \"failed\" && current !== \"waiting\") {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_started\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_paused\": {\n\t\t\t\tconst title = `awaiting approval: ${event.question ?? \"?\"}`;\n\t\t\t\tthis.ensureRole(role, \"waiting\", title);\n\t\t\t\tthis.patchRole(role, \"waiting\", title);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_resumed\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_finished\": {\n\t\t\t\tconst state = event.status === \"error\" ? \"failed\" : \"done\";\n\t\t\t\tthis.ensureRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tthis.patchRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Answer a paused task: POST /tasks/:taskId/resume { option, feedback? }.\n\t * Rejects with \"answered elsewhere\" on 409 (first answer wins across\n\t * surfaces) and with HTTP/network errors otherwise.\n\t */\n\tresume(taskId: string, option: string, feedback?: string): Promise<void>;\n\t/**\n\t * GET /tasks/pending — gates that opened before we attached. Resolves to\n\t * [] when the server has no active run (404) so callers need no special\n\t * casing.\n\t */\n\tpendingApprovals(): Promise<TeamPendingApproval[]>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync resume(taskId: string, option: string, feedback?: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/tasks/${encodeURIComponent(taskId)}/resume`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ option, ...(feedback !== undefined ? { feedback } : {}) }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 409) throw new Error(`task \"${taskId}\" was answered elsewhere`);\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync pendingApprovals(): Promise<TeamPendingApproval[]> {\n\t\t\tconst response = await fetch(`${base}/tasks/pending`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 404) return [];\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tconst body = (await response.json()) as { pending?: TeamPendingApproval[] };\n\t\t\treturn Array.isArray(body.pending) ? body.pending : [];\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
package/dist/core/team-view.js
CHANGED
|
@@ -40,6 +40,8 @@ function taskStatusFromState(state) {
|
|
|
40
40
|
return "done";
|
|
41
41
|
case "failed":
|
|
42
42
|
return "failed";
|
|
43
|
+
case "cancelled":
|
|
44
|
+
return "cancelled";
|
|
43
45
|
case "idle":
|
|
44
46
|
// Idle is settled, not queued: a "pending" task here would survive every
|
|
45
47
|
// taskStore.reset() and pin the pane at "working" for the whole session.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"team-view.js","sourceRoot":"","sources":["../../src/core/team-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAwC,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAyClF,4DAA0D;AAC1D,SAAS,eAAe,CAAC,MAA0B,EAAkB;IACpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,UAAU,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,QAAQ,CAAC;QACjB,KAAK,MAAM;YACV,OAAO,SAAS,CAAC;QAClB,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,OAAO;YACX,OAAO,QAAQ,CAAC;QACjB,KAAK,QAAQ;YACZ,OAAO,SAAS,CAAC;QAClB;YACC,OAAO,MAAM,CAAC;IAChB,CAAC;AAAA,CACD;AAED,SAAS,mBAAmB,CAAC,KAAqB,EAAc;IAC/D,QAAQ,KAAK,EAAE,CAAC;QACf,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,QAAQ;YACZ,OAAO,QAAQ,CAAC;QACjB,KAAK,MAAM;YACV,yEAAyE;YACzE,yEAAyE;YACzE,OAAO,MAAM,CAAC;QACf;Y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F,IAAI,CAAC,QAAQ,CAAC,EAAE;gBAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QAAA,CAC7D;QACD,KAAK,CAAC,gBAAgB,GAAmC;YACxD,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,IAAI,gBAAgB,EAAE;gBACrD,MAAM,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,CAAC,MAAM,EAAE,WAAW,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC,CAAC;aACpF,CAAC,CAAC;YACH,IAAI,QAAQ,CAAC,MAAM,KAAK,GAAG;gBAAE,OAAO,EAAE,CAAC;YACvC,IAAI,CAAC,QAAQ,CAAC,EAAE;gBAAE,MAAM,IAAI,KAAK,CAAC,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7D,MAAM,IAAI,GAAG,CAAC,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAwC,CAAC;YAC5E,OAAO,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC;QAAA,CACvD;QACD,SAAS,CAAC,QAAwC,EAAc;YAC/D,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,OAAO,GAAG,EAAE,CAAC;gBACZ,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAAA,CAC3B,CAAC;QAAA,CACF;QACD,eAAe,GAAW;YACzB,OAAO,SAAS,CAAC,IAAI,CAAC;QAAA,CACtB;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n\t/** Task lifecycle fields carried by task_* events from the orchestrator. */\n\ttaskId?: string;\n\t/** Approval gate carried by task_paused. */\n\tquestion?: string;\n\toptions?: string[];\n\t/** Answer carried by task_resumed. */\n\tchosenOption?: string;\n\t/** \"done\" | \"error\" on task_finished. */\n\tstatus?: string;\n\t/** Run id carried by dag_complete / dag_failed. */\n\trunId?: string;\n}\n\n/** One unanswered approval gate from GET /tasks/pending. */\nexport interface TeamPendingApproval {\n\ttaskId: string;\n\tquestion: string;\n\toptions: string[];\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tcase \"paused\":\n\t\t\treturn \"waiting\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\" || state === \"waiting\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\t// Dag settlement events are tagged role=\"orchestrator\" — they describe\n\t\t// the run, not a member, and must not create a phantom roster entry.\n\t\tif (event.type === \"dag_complete\" || event.type === \"dag_failed\") return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; a paused run (waiting on an approval gate)\n\t\t\t\t// stays waiting — hooteams mirrors agent_end right after task_paused, so\n\t\t\t\t// without this guard the gate's \"waiting\" state would flip to idle and the\n\t\t\t\t// roster would read as done while the AskOptions pane is still open.\n\t\t\t\t// agent_end only marks clean completions (mirrors hooteams' own tracking).\n\t\t\t\tconst current = this.store.agents().find((a) => a.id === this.agentId(role))?.state;\n\t\t\t\tif (current !== \"failed\" && current !== \"waiting\") {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_started\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_paused\": {\n\t\t\t\tconst title = `awaiting approval: ${event.question ?? \"?\"}`;\n\t\t\t\tthis.ensureRole(role, \"waiting\", title);\n\t\t\t\tthis.patchRole(role, \"waiting\", title);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_resumed\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_finished\": {\n\t\t\t\tconst state = event.status === \"error\" ? \"failed\" : \"done\";\n\t\t\t\tthis.ensureRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tthis.patchRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Answer a paused task: POST /tasks/:taskId/resume { option, feedback? }.\n\t * Rejects with \"answered elsewhere\" on 409 (first answer wins across\n\t * surfaces) and with HTTP/network errors otherwise.\n\t */\n\tresume(taskId: string, option: string, feedback?: string): Promise<void>;\n\t/**\n\t * GET /tasks/pending — gates that opened before we attached. Resolves to\n\t * [] when the server has no active run (404) so callers need no special\n\t * casing.\n\t */\n\tpendingApprovals(): Promise<TeamPendingApproval[]>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync resume(taskId: string, option: string, feedback?: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/tasks/${encodeURIComponent(taskId)}/resume`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ option, ...(feedback !== undefined ? { feedback } : {}) }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 409) throw new Error(`task \"${taskId}\" was answered elsewhere`);\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync pendingApprovals(): Promise<TeamPendingApproval[]> {\n\t\t\tconst response = await fetch(`${base}/tasks/pending`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 404) return [];\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tconst body = (await response.json()) as { pending?: TeamPendingApproval[] };\n\t\t\treturn Array.isArray(body.pending) ? body.pending : [];\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"team-view.js","sourceRoot":"","sources":["../../src/core/team-view.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAwC,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAyClF,4DAA0D;AAC1D,SAAS,eAAe,CAAC,MAA0B,EAAkB;IACpE,QAAQ,MAAM,EAAE,CAAC;QAChB,KAAK,MAAM;YACV,OAAO,MAAM,CAAC;QACf,KAAK,UAAU,CAAC;QAChB,KAAK,WAAW;YACf,OAAO,QAAQ,CAAC;Q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CAAC;QAAA,CACvD;QACD,SAAS,CAAC,QAAwC,EAAc;YAC/D,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,OAAO,GAAG,EAAE,CAAC;gBACZ,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAAA,CAC3B,CAAC;QAAA,CACF;QACD,eAAe,GAAW;YACzB,OAAO,SAAS,CAAC,IAAI,CAAC;QAAA,CACtB;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * hooteams team client (`--team <url>`).\n *\n * Connects to a running hooteams server, registers every role as a\n * kind=\"role\" agent in the task store, and maps the server's TeamEvent SSE\n * stream onto task-store patches so the task panel's existing \"teams\" view\n * shows live role state. On top of that mirror the connection exposes\n * steering (POST /steer) and an event subscription used by the attach\n * side-panel — both share the single /events stream; no second SSE\n * connection is ever opened.\n *\n * The connection is best-effort by design — a connect failure or a later\n * drop logs a warning and never blocks (or crashes) the main agent. At most\n * one SSE connection (to /events) is open at any time.\n */\n\nimport { type TaskAgentState, type TaskStatus, taskStore } from \"./task-store.js\";\n\n/** Shape of GET /status: coarse per-role status keyed by role name. */\nexport type TeamStatusSnapshot = Record<string, { status?: string; lastEventType?: string }>;\n\n/** One frame of GET /events: a hoocode AgentEvent tagged with its producer. */\nexport interface TeamViewEvent {\n\ttype: string;\n\trole: string;\n\tagentId?: string;\n\tts?: number;\n\ttoolName?: string;\n\targs?: unknown;\n\tisError?: boolean;\n\t/** Streaming assistant-message delta carried by message_update events. */\n\tassistantMessageEvent?: { type?: string; delta?: string };\n\tmessage?: {\n\t\trole?: string;\n\t\terrorMessage?: string;\n\t\tusage?: { input?: number; output?: number; cost?: { total?: number } };\n\t};\n\t/** Task lifecycle fields carried by task_* events from the orchestrator. */\n\ttaskId?: string;\n\t/** Approval gate carried by task_paused. */\n\tquestion?: string;\n\toptions?: string[];\n\t/** Answer carried by task_resumed. */\n\tchosenOption?: string;\n\t/** \"done\" | \"error\" on task_finished. */\n\tstatus?: string;\n\t/** Run id carried by dag_complete / dag_failed. */\n\trunId?: string;\n}\n\n/** One unanswered approval gate from GET /tasks/pending. */\nexport interface TeamPendingApproval {\n\ttaskId: string;\n\tquestion: string;\n\toptions: string[];\n}\n\n/** hooteams AgentStatus word → task panel agent state. */\nfunction stateFromStatus(status: string | undefined): TaskAgentState {\n\tswitch (status) {\n\t\tcase \"idle\":\n\t\t\treturn \"idle\";\n\t\tcase \"thinking\":\n\t\tcase \"streaming\":\n\t\t\treturn \"active\";\n\t\tcase \"tool\":\n\t\t\treturn \"running\";\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"error\":\n\t\t\treturn \"failed\";\n\t\tcase \"paused\":\n\t\t\treturn \"waiting\";\n\t\tdefault:\n\t\t\treturn \"idle\";\n\t}\n}\n\nfunction taskStatusFromState(state: TaskAgentState): TaskStatus {\n\tswitch (state) {\n\t\tcase \"done\":\n\t\t\treturn \"done\";\n\t\tcase \"failed\":\n\t\t\treturn \"failed\";\n\t\tcase \"cancelled\":\n\t\t\treturn \"cancelled\";\n\t\tcase \"idle\":\n\t\t\t// Idle is settled, not queued: a \"pending\" task here would survive every\n\t\t\t// taskStore.reset() and pin the pane at \"working\" for the whole session.\n\t\t\treturn \"done\";\n\t\tdefault:\n\t\t\treturn \"in_progress\";\n\t}\n}\n\n/** Only these states represent activity worth a task row of its own. */\nfunction stateWarrantsTask(state: TaskAgentState): boolean {\n\treturn state === \"active\" || state === \"running\" || state === \"failed\" || state === \"waiting\";\n}\n\n/**\n * Maps team status snapshots and TeamEvents onto task-store patches.\n *\n * Each role owns one roster entry (id `team:<role>`) and at most one task whose\n * title tracks the role's latest activity. Tasks exist only while a role is\n * actually doing something (active/running, or failed so the error is visible);\n * idle roles keep their roster entry but no task — the panel's teams lens\n * renders them as placeholder groups, so a quiet team reads as an idle roster\n * instead of pinning the pane at \"working\". Entries are re-created on demand\n * because taskStore.reset() wipes finished tasks between user turns.\n */\nexport class TeamViewMapper {\n\tprivate readonly store: typeof taskStore;\n\tprivate readonly taskIds = new Map<string, number>();\n\n\tconstructor(store: typeof taskStore = taskStore) {\n\t\tthis.store = store;\n\t}\n\n\t/** Register roles from a GET /status snapshot. */\n\tapplyStatus(snapshot: TeamStatusSnapshot): void {\n\t\tfor (const [role, info] of Object.entries(snapshot)) {\n\t\t\tconst state = stateFromStatus(info?.status);\n\t\t\tthis.ensureRole(role, state, info?.lastEventType ?? \"connected\");\n\t\t\tthis.patchRole(role, state);\n\t\t}\n\t}\n\n\t/** Map one TeamEvent from GET /events onto the store. */\n\tapplyEvent(event: TeamViewEvent): void {\n\t\tif (!event || typeof event.role !== \"string\" || event.role.length === 0) return;\n\t\t// Dag settlement events are tagged role=\"orchestrator\" — they describe\n\t\t// the run, not a member, and must not create a phantom roster entry.\n\t\tif (event.type === \"dag_complete\" || event.type === \"dag_failed\") return;\n\t\tconst role = event.role;\n\t\tswitch (event.type) {\n\t\t\tcase \"agent_start\":\n\t\t\tcase \"turn_start\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"message_start\":\n\t\t\tcase \"message_update\":\n\t\t\tcase \"message_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"responding\");\n\t\t\t\tthis.patchRole(role, \"active\");\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_start\":\n\t\t\t\tthis.ensureRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"running\", `tool: ${event.toolName ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"tool_execution_end\":\n\t\t\t\tthis.ensureRole(role, \"active\", \"thinking\");\n\t\t\t\tthis.patchRole(role, \"active\", \"thinking\");\n\t\t\t\tbreak;\n\t\t\tcase \"turn_end\":\n\t\t\t\tif (event.message?.role === \"assistant\" && event.message.errorMessage) {\n\t\t\t\t\tthis.ensureRole(role, \"failed\", \"error\");\n\t\t\t\t\tthis.patchRole(role, \"failed\", \"error\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"agent_end\": {\n\t\t\t\t// A failed run stays failed; a paused run (waiting on an approval gate)\n\t\t\t\t// stays waiting — hooteams mirrors agent_end right after task_paused, so\n\t\t\t\t// without this guard the gate's \"waiting\" state would flip to idle and the\n\t\t\t\t// roster would read as done while the AskOptions pane is still open.\n\t\t\t\t// agent_end only marks clean completions (mirrors hooteams' own tracking).\n\t\t\t\tconst current = this.store.agents().find((a) => a.id === this.agentId(role))?.state;\n\t\t\t\tif (current !== \"failed\" && current !== \"waiting\") {\n\t\t\t\t\tthis.ensureRole(role, \"done\", \"idle\");\n\t\t\t\t\tthis.patchRole(role, \"done\", \"idle\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_started\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_paused\": {\n\t\t\t\tconst title = `awaiting approval: ${event.question ?? \"?\"}`;\n\t\t\t\tthis.ensureRole(role, \"waiting\", title);\n\t\t\t\tthis.patchRole(role, \"waiting\", title);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"task_resumed\":\n\t\t\t\tthis.ensureRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tthis.patchRole(role, \"active\", `task: ${event.taskId ?? \"?\"}`);\n\t\t\t\tbreak;\n\t\t\tcase \"task_finished\": {\n\t\t\t\tconst state = event.status === \"error\" ? \"failed\" : \"done\";\n\t\t\t\tthis.ensureRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tthis.patchRole(role, state, state === \"failed\" ? \"error\" : \"idle\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\t// Unknown event types still prove the role exists.\n\t\t\t\tthis.ensureRole(role, \"idle\", event.type);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate agentId(role: string): string {\n\t\treturn `team:${role}`;\n\t}\n\n\t/**\n\t * Make sure the role's roster entry exists, plus its task when the state\n\t * warrants one (reset() may have dropped both). Idle/done states never\n\t * create a task — only patch one that live activity already opened.\n\t */\n\tprivate ensureRole(role: string, state: TaskAgentState, title: string): void {\n\t\tconst id = this.agentId(role);\n\t\tthis.store.upsertAgent({ id, name: role, kind: \"role\", state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tconst existing = taskId !== undefined ? this.store.list().find((task) => task.id === taskId) : undefined;\n\t\tif (!existing && stateWarrantsTask(state)) {\n\t\t\tconst task = this.store.create(title, { agent: id });\n\t\t\tthis.store.update(task.id, { status: taskStatusFromState(state) });\n\t\t\tthis.taskIds.set(role, task.id);\n\t\t}\n\t}\n\n\tprivate patchRole(role: string, state: TaskAgentState, title?: string): void {\n\t\tthis.store.patchAgent(this.agentId(role), { state });\n\t\tconst taskId = this.taskIds.get(role);\n\t\tif (taskId === undefined) return;\n\t\tthis.store.update(taskId, { status: taskStatusFromState(state), ...(title !== undefined ? { title } : {}) });\n\t}\n}\n\nexport interface TeamViewOptions {\n\t/** Warning sink; defaults to console.error. */\n\twarn?: (message: string) => void;\n\t/** Store override for tests. */\n\tstore?: typeof taskStore;\n\t/** Delay between reconnect attempts in ms (default 5000). */\n\tretryDelayMs?: number;\n}\n\nexport interface TeamViewConnection {\n\t/** Close the SSE connection and stop reconnecting. */\n\tstop(): void;\n\t/** POST /steer { role, message }. Rejects on network or HTTP error. */\n\tsteer(role: string, message: string): Promise<void>;\n\t/**\n\t * Answer a paused task: POST /tasks/:taskId/resume { option, feedback? }.\n\t * Rejects with \"answered elsewhere\" on 409 (first answer wins across\n\t * surfaces) and with HTTP/network errors otherwise.\n\t */\n\tresume(taskId: string, option: string, feedback?: string): Promise<void>;\n\t/**\n\t * GET /tasks/pending — gates that opened before we attached. Resolves to\n\t * [] when the server has no active run (404) so callers need no special\n\t * casing.\n\t */\n\tpendingApprovals(): Promise<TeamPendingApproval[]>;\n\t/**\n\t * Subscribe to every TeamEvent delivered by the shared /events stream.\n\t * Returns an unsubscribe function. Listeners receive events for all roles;\n\t * per-role filtering is the subscriber's job (the attach panel filters).\n\t */\n\tsubscribe(listener: (event: TeamViewEvent) => void): () => void;\n\t/** Number of live event subscribers. Exposed for leak tests. */\n\tsubscriberCount(): number;\n}\n\nconst STATUS_TIMEOUT_MS = 5000;\nconst STEER_TIMEOUT_MS = 5000;\n\n/**\n * Start the read-only team view against a hooteams server base URL.\n *\n * Returns immediately; all network work happens in the background and any\n * failure is reported through `warn` without ever throwing.\n */\nexport function connectTeamView(url: string, options: TeamViewOptions = {}): TeamViewConnection {\n\tconst base = url.replace(/\\/+$/, \"\");\n\tconst warn = options.warn ?? ((message: string) => console.error(message));\n\tconst retryDelayMs = options.retryDelayMs ?? 5000;\n\tconst mapper = new TeamViewMapper(options.store);\n\tconst controller = new AbortController();\n\tconst listeners = new Set<(event: TeamViewEvent) => void>();\n\tlet stopped = false;\n\n\tconst deliver = (event: TeamViewEvent): void => {\n\t\tmapper.applyEvent(event);\n\t\tfor (const listener of listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(event);\n\t\t\t} catch {\n\t\t\t\t// A broken subscriber must not take down the stream or its peers.\n\t\t\t}\n\t\t}\n\t};\n\n\tconst run = async (): Promise<void> => {\n\t\t// 1. Status snapshot: register the current roles.\n\t\ttry {\n\t\t\tconst response = await fetch(`${base}/status`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tmapper.applyStatus((await response.json()) as TeamStatusSnapshot);\n\t\t} catch (error) {\n\t\t\tif (stopped) return;\n\t\t\twarn(`team view: failed to fetch ${base}/status (${String(error)}); continuing without the team view`);\n\t\t}\n\n\t\t// 2. Single SSE subscription, reconnecting on drops.\n\t\tlet announcedDrop = false;\n\t\twhile (!stopped) {\n\t\t\ttry {\n\t\t\t\tconst response = await fetch(`${base}/events`, { signal: controller.signal });\n\t\t\t\tif (!response.ok || !response.body) throw new Error(`HTTP ${response.status}`);\n\t\t\t\tconst reader = response.body.getReader();\n\t\t\t\tconst decoder = new TextDecoder();\n\t\t\t\tlet buffer = \"\";\n\t\t\t\twhile (true) {\n\t\t\t\t\tconst { value, done } = await reader.read();\n\t\t\t\t\tif (done) break;\n\t\t\t\t\t// Only a stream that actually delivers data counts as recovered. A 200\n\t\t\t\t\t// that closes immediately (e.g. a server that answers /events without\n\t\t\t\t\t// streaming) used to re-arm the warning and repeat it every retry.\n\t\t\t\t\tannouncedDrop = false;\n\t\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\t\tlet index = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\twhile (index !== -1) {\n\t\t\t\t\t\tconst frame = buffer.slice(0, index);\n\t\t\t\t\t\tbuffer = buffer.slice(index + 2);\n\t\t\t\t\t\tfor (const line of frame.split(\"\\n\")) {\n\t\t\t\t\t\t\tif (!line.startsWith(\"data:\")) continue;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tdeliver(JSON.parse(line.slice(5).trim()) as TeamViewEvent);\n\t\t\t\t\t\t\t} catch {\n\t\t\t\t\t\t\t\t// Malformed frames are dropped; the stream stays up.\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tindex = buffer.indexOf(\"\\n\\n\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (stopped) return;\n\t\t\t\tthrow new Error(\"stream ended\");\n\t\t\t} catch (error) {\n\t\t\t\tif (stopped || controller.signal.aborted) return;\n\t\t\t\tif (!announcedDrop) {\n\t\t\t\t\tannouncedDrop = true;\n\t\t\t\t\twarn(`team view: lost connection to ${base}/events (${String(error)}); retrying in background`);\n\t\t\t\t}\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, retryDelayMs));\n\t\t\t}\n\t\t}\n\t};\n\n\tvoid run().catch((error) => {\n\t\tif (!stopped) warn(`team view: unexpected error (${String(error)})`);\n\t});\n\n\treturn {\n\t\tstop() {\n\t\t\tstopped = true;\n\t\t\tlisteners.clear();\n\t\t\tcontroller.abort();\n\t\t},\n\t\tasync steer(role: string, message: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/steer`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ role, message }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync resume(taskId: string, option: string, feedback?: string): Promise<void> {\n\t\t\tconst response = await fetch(`${base}/tasks/${encodeURIComponent(taskId)}/resume`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ option, ...(feedback !== undefined ? { feedback } : {}) }),\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STEER_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 409) throw new Error(`task \"${taskId}\" was answered elsewhere`);\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t},\n\t\tasync pendingApprovals(): Promise<TeamPendingApproval[]> {\n\t\t\tconst response = await fetch(`${base}/tasks/pending`, {\n\t\t\t\tsignal: AbortSignal.any([controller.signal, AbortSignal.timeout(STATUS_TIMEOUT_MS)]),\n\t\t\t});\n\t\t\tif (response.status === 404) return [];\n\t\t\tif (!response.ok) throw new Error(`HTTP ${response.status}`);\n\t\t\tconst body = (await response.json()) as { pending?: TeamPendingApproval[] };\n\t\t\treturn Array.isArray(body.pending) ? body.pending : [];\n\t\t},\n\t\tsubscribe(listener: (event: TeamViewEvent) => void): () => void {\n\t\t\tlisteners.add(listener);\n\t\t\treturn () => {\n\t\t\t\tlisteners.delete(listener);\n\t\t\t};\n\t\t},\n\t\tsubscriberCount(): number {\n\t\t\treturn listeners.size;\n\t\t},\n\t};\n}\n"]}
|
|
@@ -43,7 +43,19 @@ export declare class TokenBudget extends EventEmitter {
|
|
|
43
43
|
limit?: number;
|
|
44
44
|
cwd?: string;
|
|
45
45
|
});
|
|
46
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* Process one complete JSONL line from the subagent's stdout. Use this when
|
|
48
|
+
* an upstream reader already handles framing (UTF-8-safe reassembly of chunks
|
|
49
|
+
* split mid-line or mid-character) — the pool feeds this from its single
|
|
50
|
+
* attachJsonlLineReader so the stream is parsed exactly once.
|
|
51
|
+
*/
|
|
52
|
+
processLine(line: string): void;
|
|
53
|
+
/**
|
|
54
|
+
* Process a raw chunk of stdout data from the subagent, buffering until
|
|
55
|
+
* newlines. Prefer processLine() when a UTF-8-safe line reader is available:
|
|
56
|
+
* chunk boundaries here can split multi-byte characters, which corrupts the
|
|
57
|
+
* line they fall in.
|
|
58
|
+
*/
|
|
47
59
|
processStdout(chunk: string): void;
|
|
48
60
|
/** Flush any remaining buffered stdout. Call when the stream ends. */
|
|
49
61
|
flush(): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"token-budget.d.ts","sourceRoot":"","sources":["../../src/core/token-budget.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAK3C,MAAM,WAAW,iBAAiB;IACjC,8BAA8B;IAC9B,KAAK,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,gBAAgB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,OAAO,CAAC;IAChB,QAAQ,EA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from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { getDispatchTaskDir } from \"../config.js\";\n\nexport interface TokenBudgetConfig {\n\t/** Budget limit in tokens. */\n\tlimit: number;\n}\n\nexport interface TokenBudgetState {\n\ttask_id: string;\n\tagent_type: string;\n\tbudget: number;\n\tused: number;\n\twarned: boolean;\n\texceeded: boolean;\n\tlast_updated: number;\n}\n\n/**\n * Default token budgets per agent type (in tokens). Raised from the previous\n * 8k–16k range, which was too low and hard-stopped subagents mid-task. Keyed by\n * the built-in agents; custom agents fall back to the default below.\n * - explore: 35 000 (read-only scanning, tracing deps)\n * - plan: 35 000 (read-only research to back a plan)\n * - general-purpose: 60 000 (reads, plans, writes, runs, iterates — heaviest)\n */\nconst DEFAULT_BUDGETS: Record<string, number> = {\n\texplore: 35000,\n\tplan: 35000,\n\t\"general-purpose\": 60000,\n};\n\n/** Get the default budget for an agent type. */\nexport function getDefaultBudget(agent_type: string): number {\n\treturn DEFAULT_BUDGETS[agent_type] ?? 35000;\n}\n\n/**\n * Tracks cumulative token usage for a single subagent task by parsing\n * newline-delimited JSON events from the subagent's stdout stream.\n *\n * Advisory only: this never stops or penalizes a subagent. The guaranteed hard\n * stop is the per-subagent turn cap (--max-turns); these events exist purely for\n * telemetry and for callers that want to surface usage.\n *\n * Emits:\n * - \"budget_warning\" when 80% of the budget is consumed\n * - \"budget_exceeded\" when 100% of the budget is consumed\n */\nexport class TokenBudget extends EventEmitter {\n\tprivate readonly task_id: string;\n\tprivate readonly agent_type: string;\n\tprivate readonly limit: number;\n\tprivate readonly cwd: string;\n\n\tprivate used = 0;\n\tprivate warned = false;\n\tprivate exceeded = false;\n\tprivate stdoutBuffer = \"\";\n\n\t/** Warning threshold (80%). */\n\tprivate readonly warningThreshold: number;\n\t/** Hard-stop threshold (100%). */\n\tprivate readonly exceededThreshold: number;\n\n\tconstructor(task_id: string, agent_type: string, options: { limit?: number; cwd?: string } = {}) {\n\t\tsuper();\n\t\tthis.task_id = task_id;\n\t\tthis.agent_type = agent_type;\n\t\tthis.limit = options.limit ?? getDefaultBudget(agent_type);\n\t\tthis.cwd = options.cwd ?? process.cwd();\n\t\tthis.warningThreshold = Math.floor(this.limit * 0.8);\n\t\tthis.exceededThreshold = this.limit;\n\t}\n\n\t/**\n\t * Process one complete JSONL line from the subagent's stdout. Use this when\n\t * an upstream reader already handles framing (UTF-8-safe reassembly of chunks\n\t * split mid-line or mid-character) — the pool feeds this from its single\n\t * attachJsonlLineReader so the stream is parsed exactly once.\n\t */\n\tprocessLine(line: string): void {\n\t\tconst trimmed = line.trim();\n\t\tif (trimmed) {\n\t\t\tthis.parseLine(trimmed);\n\t\t}\n\t}\n\n\t/**\n\t * Process a raw chunk of stdout data from the subagent, buffering until\n\t * newlines. Prefer processLine() when a UTF-8-safe line reader is available:\n\t * chunk boundaries here can split multi-byte characters, which corrupts the\n\t * line they fall in.\n\t */\n\tprocessStdout(chunk: string): void {\n\t\tthis.stdoutBuffer += chunk;\n\n\t\twhile (true) {\n\t\t\tconst lineEnd = this.stdoutBuffer.indexOf(\"\\n\");\n\t\t\tif (lineEnd === -1) break;\n\t\t\tconst line = this.stdoutBuffer.slice(0, lineEnd).trimEnd();\n\t\t\tthis.stdoutBuffer = this.stdoutBuffer.slice(lineEnd + 1);\n\t\t\tif (line) {\n\t\t\t\tthis.parseLine(line);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Flush any remaining buffered stdout. Call when the stream ends. */\n\tflush(): void {\n\t\tif (this.stdoutBuffer.trim()) {\n\t\t\tthis.parseLine(this.stdoutBuffer.trim());\n\t\t\tthis.stdoutBuffer = \"\";\n\t\t}\n\t}\n\n\t/** Current cumulative token usage. */\n\tgetUsed(): number {\n\t\treturn this.used;\n\t}\n\n\t/** Configured token budget limit. */\n\tgetLimit(): number {\n\t\treturn this.limit;\n\t}\n\n\t/** Whether the budget warning has been triggered. */\n\tisWarned(): boolean {\n\t\treturn this.warned;\n\t}\n\n\t/** Whether the budget has been exceeded. */\n\tisExceeded(): boolean {\n\t\treturn this.exceeded;\n\t}\n\n\t/** Persist current budget state to disk. */\n\tpersist(): void {\n\t\tconst state: TokenBudgetState = {\n\t\t\ttask_id: this.task_id,\n\t\t\tagent_type: this.agent_type,\n\t\t\tbudget: this.limit,\n\t\t\tused: this.used,\n\t\t\twarned: this.warned,\n\t\t\texceeded: this.exceeded,\n\t\t\tlast_updated: Date.now(),\n\t\t};\n\n\t\tconst path = this.budgetPath();\n\t\ttry {\n\t\t\tmkdirSync(dirname(path), { recursive: true });\n\t\t\twriteFileSync(path, JSON.stringify(state, null, 2));\n\t\t} catch {\n\t\t\t// Persistence is best-effort; silently ignore write failures\n\t\t}\n\t}\n\n\tprivate budgetPath(): string {\n\t\treturn join(getDispatchTaskDir(this.cwd, this.task_id), \"budget.json\");\n\t}\n\n\tprivate parseLine(line: string): void {\n\t\tlet event: unknown;\n\t\ttry {\n\t\t\tevent = JSON.parse(line);\n\t\t} catch {\n\t\t\treturn; // Not valid JSON, ignore\n\t\t}\n\n\t\tif (!event || typeof event !== \"object\") return;\n\n\t\t// Look for message_end events with assistant messages that have usage\n\t\tconst typedEvent = event as Record<string, unknown>;\n\t\tif (typedEvent.type !== \"message_end\") return;\n\n\t\tconst message = typedEvent.message as Record<string, unknown> | undefined;\n\t\tif (!message) return;\n\t\tif (message.role !== \"assistant\") return;\n\n\t\tconst usage = message.usage as Record<string, unknown> | undefined;\n\t\tif (!usage) return;\n\n\t\tconst totalTokens = typeof usage.totalTokens === \"number\" ? usage.totalTokens : undefined;\n\t\tif (totalTokens === undefined || totalTokens <= 0) return;\n\n\t\tthis.used += totalTokens;\n\n\t\t// Check thresholds\n\t\tif (!this.warned && this.used >= this.warningThreshold) {\n\t\t\tthis.warned = true;\n\t\t\tthis.emit(\"budget_warning\", {\n\t\t\t\ttask_id: this.task_id,\n\t\t\t\tmessage: \"You are near token limit. Summarize and write result.json now.\",\n\t\t\t\tused: this.used,\n\t\t\t\tlimit: this.limit,\n\t\t\t});\n\t\t}\n\n\t\tif (!this.exceeded && this.used >= this.exceededThreshold) {\n\t\t\tthis.exceeded = true;\n\t\t\tthis.emit(\"budget_exceeded\", {\n\t\t\t\ttask_id: this.task_id,\n\t\t\t\tused: this.used,\n\t\t\t\tlimit: this.limit,\n\t\t\t});\n\t\t}\n\n\t\tthis.persist();\n\t}\n}\n"]}
|