dsh-taskboard 0.6.7 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -14
- package/lib/client.js +56 -8
- package/lib/host/assets.js +139 -0
- package/lib/host/assets.js.map +1 -0
- package/lib/host/routes.js +87 -0
- package/lib/host/routes.js.map +1 -1
- package/lib/host/storage-queue.js +14 -0
- package/lib/host/storage-queue.js.map +1 -0
- package/lib/host/storage.js +249 -0
- package/lib/host/storage.js.map +1 -0
- package/lib/host/store.js +34 -7
- package/lib/host/store.js.map +1 -1
- package/lib/host/templates.js +62 -38
- package/lib/host/templates.js.map +1 -1
- package/lib/host/tools.js +6 -4
- package/lib/host/tools.js.map +1 -1
- package/lib/index.js +83 -27
- package/lib/index.js.map +1 -1
- package/lib/shared/api.js.map +1 -1
- package/package.json +12 -11
- package/src/client/api.ts +30 -0
- package/src/client/board/SettingsModal.tsx +67 -4
- package/src/client/board/SlashPromptInput.tsx +80 -1
- package/src/client/board/TaskDetail.tsx +71 -8
- package/src/client/board/TaskFormModal.tsx +8 -5
- package/src/client/controller.ts +44 -2
- package/src/client/i18n/en.ts +17 -3
- package/src/client/i18n/zh.ts +17 -3
- package/src/client/image-insert.ts +29 -0
- package/src/client/styles.ts +34 -1
- package/src/host/assets.ts +120 -0
- package/src/host/routes.ts +92 -0
- package/src/host/storage-queue.ts +10 -0
- package/src/host/storage.ts +212 -0
- package/src/host/store.ts +40 -12
- package/src/host/templates.ts +30 -7
- package/src/host/tools.ts +8 -4
- package/src/index.ts +88 -33
- package/src/shared/api.ts +26 -0
- package/src/shared/version.ts +1 -1
package/lib/host/tools.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tools.js","names":["v"],"sources":["../../src/host/tools.ts"],"sourcesContent":["import type { SessionArchiveResult } from '../shared/api.ts'\nimport { archiveTaskSessions } from './archive-sessions.ts'\n/**\n * The ten `taskboard_*` agent tools. All writes require a calling agent\n * session (ownership audit), carry optimistic-version checks, and enforce\n * the protocol gates in CODE, not in prompt text:\n *\n * - `move → done` is rejected for agent callers (user confirmation only)\n * - `move todo → in_progress` requires the calling session's workspace to\n * match the task's project (claim boundary)\n * - taking over a task held by another session is rejected\n * - `delete` for agent callers only sets the soft-delete marker\n * - checklist items may be added/checked by agents, but checking never\n * completes the task (done stays user-only)\n *\n * OUTPUT CONTRACT (lesson: registry `createSuccessResult` renders\n * `output.render(args, value)` into `result.content`, and the loop feeds\n * exactly that content to the model — the raw JSON `value` never reaches\n * the model): render() IS the model-facing tool result. Every render must\n * carry the complete facts an agent needs to act (ids, versions, statuses);\n * a \"terse UI summary\" here starves the agent.\n *\n * @module dsh-taskboard/host/tools\n */\nimport type { WorkspaceRegistry } from '@deepseek-ai/dsh-workspace'\nimport { defineTool } from './sdk.ts'\nimport {\n MAX_CHECKLIST_ITEMS,\n asIsolation,\n asStatus,\n asUrgency,\n canTransition,\n checklistFromTexts,\n defaultIsolationOf,\n effectivePrompt,\n isClaim,\n isClaimedBy,\n newChecklistItemId,\n newCommentId,\n newTaskId,\n normalizeBody,\n normalizeExecution,\n normalizeExecutionReport,\n normalizeModel,\n normalizePrompt,\n normalizeTitle,\n summarize,\n syncClaim,\n type Actor,\n type ChecklistItem,\n type TaskLedger,\n type TaskModel,\n type TaskRecord,\n} from '../shared/protocol.ts'\nimport type { TaskStore } from './store.ts'\n\n/** Render side: one compact task line (id/status/version are load-bearing). */\nfunction taskLine(t: {\n id: string\n title: string\n status: string\n urgency: string\n version: number\n workspaceId: string\n blocked: boolean\n executionMode: string\n commentCount?: number\n lastExecutionOutcome?: string\n checklist?: { done: number; total: number }\n trashed?: boolean\n}): string {\n const parts = [\n `- ${t.id} [${t.status}] v${t.version} · ${t.urgency} · 项目 ${t.workspaceId}`,\n `「${t.title}」`,\n ]\n if (t.blocked) parts.push('·受阻')\n if (t.executionMode === 'scheduled') parts.push('·定时')\n if (t.commentCount !== undefined && t.commentCount > 0) parts.push(`·评论${t.commentCount}`)\n if (t.checklist !== undefined && t.checklist.total > 0) parts.push(`·清单${t.checklist.done}/${t.checklist.total}`)\n if (t.lastExecutionOutcome !== undefined) parts.push(`·上次执行${t.lastExecutionOutcome}`)\n if (t.trashed === true) parts.push('·已删')\n return parts.join(' ')\n}\n\n/** Render side: the full task detail block (everything an executor needs). */\nfunction taskDetail(t: TaskRecord & { effectivePrompt?: string }): string {\n const lines: string[] = [\n `任务 ${t.id} 「${t.title}」`,\n `状态: ${t.status} (v${t.version}) · 紧急度: ${t.urgency} · 项目: ${t.workspaceId}${t.blocked ? ' · 受阻' : ''}`,\n `执行方式: ${t.execution.mode}${t.execution.cron !== undefined ? ` cron=${t.execution.cron}` : ''}`,\n `隔离: ${t.isolation === 'none' ? '关闭(原目录执行)' : 'Git Worktree'}${t.branch !== undefined ? `(分支 ${t.branch})` : ''}${t.branches !== undefined ? `(多仓库镜像 ${Object.keys(t.branches).length + (t.branch !== undefined ? 1 : 0)} 个仓库)` : ''}`,\n ]\n const holder = isClaimedBy(t)\n if (holder !== undefined) lines.push(`认领: agent ${String(holder).slice(0, 24)}(持有期间其他会话不可移动)`)\n if (t.execution.nextRunAt !== undefined) lines.push(`下次触发: ${new Date(t.execution.nextRunAt).toISOString()}`)\n if (t.model !== undefined) lines.push(`固定模型: ${t.model.provider}/${t.model.model}${t.model.reasoningEffort !== undefined ? ` (思考强度: ${t.model.reasoningEffort})` : ''}`)\n if (t.presetId !== undefined) lines.push(`执行模式: ${t.presetId}(未指定时为部署默认 preset)`)\n lines.push(`描述: ${t.description.length > 0 ? t.description : '(无)'}`)\n lines.push(`执行 Prompt: ${t.effectivePrompt ?? effectivePrompt(t)}`)\n if (t.checklist !== undefined && t.checklist.length > 0) {\n const done = t.checklist.filter(i => i.checked).length\n lines.push(`验收清单 (${done}/${t.checklist.length}):`)\n for (const [index, item] of t.checklist.entries()) {\n const mark = item.checked ? '☑' : '☐'\n const who = item.checkedBy === undefined ? '' : item.checkedBy === 'user' ? ' ·用户勾选' : ` ·agent ${String(item.checkedBy).slice(0, 24)}勾选`\n const note = item.note !== undefined ? ` ·证据: ${item.note}` : ''\n // Carry the checklist item id so `taskboard_checklist check/uncheck` can\n // address it without guessing — a terse render starves the agent (render\n // is fed to the model as result.content). Mirrors the index+id carried\n // by the taskboard_checklist tool output.\n lines.push(` ${mark} [${index + 1}] ${item.text}${who}${note} id=${item.id}`)\n }\n }\n if (t.comments.length > 0) {\n lines.push(`评论 (${t.comments.length}):`)\n for (const c of t.comments) {\n const who = c.threadId !== undefined ? `agent ${String(c.threadId).slice(0, 24)}` : 'user'\n lines.push(` - [${who} ${new Date(c.createdAt).toISOString()}] ${c.body}`)\n }\n } else {\n lines.push('评论: 无')\n }\n if (t.executions.length > 0) {\n lines.push(`执行记录 (${t.executions.length}):`)\n for (const e of t.executions) {\n const at = e.startedAt !== undefined ? new Date(e.startedAt).toISOString() : '?'\n const err = e.error !== undefined ? ` 错误: ${e.error}` : ''\n const report = e.report !== undefined ? ' [已交报告]' : ''\n lines.push(` - [${e.trigger} ${at}] ${e.outcome}${report}${err}`)\n }\n } else {\n lines.push('执行记录: 无')\n }\n const updatedBy = t.updatedBy.kind === 'agent' ? `agent ${String(t.updatedBy.sessionId).slice(0, 24)}` : t.updatedBy.kind === 'system' ? 'system' : 'user'\n lines.push(`更新: ${new Date(t.updatedAt).toISOString()} 由 ${updatedBy}`)\n return lines.join('\\n')\n}\n\n/** Stable error codes surfaced at the head of tool error messages. */\nexport const ERR = {\n notFound: 'not_found',\n versionConflict: 'version_conflict',\n workspaceMismatch: 'workspace_mismatch',\n invalidTransition: 'invalid_transition',\n forbidden: 'forbidden',\n requiresAgent: 'unauthorized_actor',\n invalidInput: 'invalid_input',\n} as const\n\n/** Tool failure: an Error whose message starts with a stable code. The code\n * is also carried structurally so the routes layer can map failures without\n * re-parsing messages (review P2). */\nexport class ToolError extends Error {\n constructor(readonly code: string, detail: string) {\n super(`Error: ${code}: ${detail}`)\n }\n}\n\n/** The workspace face the tools need (narrow for tests). */\nexport interface WorkspaceFace {\n /** Resolve the workspace owning a canonical cwd, if any. */\n resolveByPath(path: string): Promise<{ id: string } | undefined>\n /** Get a workspace by id. */\n get(id: string): { id: string; path: string; title: string } | undefined\n /** List all workspaces. */\n list(): Array<{ id: string; path: string; title: string }>\n /** Archive one session durably (when supported by runtime workspaceRegistry). */\n archiveSession?(sessionId: string): Promise<void>\n}\n\n/** Adapt the real registry to the narrow face. */\nexport function workspaceFace(registry: WorkspaceRegistry): WorkspaceFace {\n // Explicit field mapping: Workspace entities expose path/title as prototype\n // getters, which JSON.stringify skips (own enumerable properties only).\n return {\n resolveByPath: async (path) => {\n const ws = await registry.resolveByPath(path as never)\n return ws === undefined ? undefined : { id: ws.id }\n },\n get: id => {\n const ws = registry.get(id as never)\n return ws === undefined ? undefined : { id: ws.id, path: ws.path, title: ws.title }\n },\n list: () => registry.list().map(ws => ({ id: ws.id, path: ws.path, title: ws.title })),\n ...(typeof registry.archiveSession === 'function'\n ? { archiveSession: (sessionId: string) => registry.archiveSession(sessionId as Parameters<WorkspaceRegistry['archiveSession']>[0]) }\n : {}),\n }\n}\n\n/** Everything the tool set needs. */\nexport interface ToolDeps {\n store: TaskStore\n workspaces: WorkspaceFace\n /** Current epoch ms (injectable for tests). */\n now: () => number\n /**\n * Registered model provider routes (from the host llm runtime), for\n * advisory validation of pinned models; undefined = runtime unavailable,\n * in which case only the structural check applies.\n */\n modelProviders?: () => string[] | undefined\n}\n\n/** Validate a pinned model: structural check always, provider route when known. */\nfunction checkModel(deps: ToolDeps, raw: unknown): TaskModel {\n const model = normalizeModel(raw)\n const providers = deps.modelProviders?.()\n if (providers !== undefined && !providers.includes(model.provider)) {\n throw new ToolError(ERR.invalidInput, `model provider \"${model.provider}\" has no registered route (available: ${providers.join(', ')})`)\n }\n return model\n}\n\n/** Resolve the calling agent's actor and session id. */\nfunction caller(exec: ToolRunContext): { actor: Actor & { kind: 'agent' }; sessionId: string } {\n if (!exec.agent) throw new ToolError(ERR.requiresAgent, 'taskboard tools require a calling agent session')\n const sessionId = exec.agent.id\n return { actor: { kind: 'agent', sessionId }, sessionId }\n}\n\n/** The calling session's workspace id (undefined when unaffiliated). */\nasync function callerWorkspace(deps: ToolDeps, exec: ToolRunContext): Promise<string | undefined> {\n const cwd = exec.agent?.session.header.cwd\n if (typeof cwd !== 'string' || cwd.length === 0) return undefined\n const ws = await deps.workspaces.resolveByPath(cwd)\n return ws?.id\n}\n\n/** Guard: version match. */\nfunction versionGuard(task: TaskRecord, ifVersion: number | undefined): void {\n if (ifVersion === undefined) {\n throw new ToolError(ERR.versionConflict, 'this write requires ifVersion; read the task first')\n }\n if (ifVersion !== task.version) {\n throw new ToolError(ERR.versionConflict, `stale version ${ifVersion} (current ${task.version}); re-read the task and retry once`)\n }\n}\n\n/**\n * Find a live (non-trashed) task INSIDE a mutator (R1: every guard must run\n * on the fresh draft the serial queue hands us, never on a pre-read clone —\n * a pre-read can pass its version check and then blind-overwrite a task that\n * changed while the caller awaited). Throws not_found for missing/trashed.\n */\nfunction liveTaskAt(ledger: TaskLedger, id: string): { index: number; task: TaskRecord } {\n const index = ledger.tasks.findIndex(t => t.id === id)\n if (index < 0) throw new ToolError(ERR.notFound, `no task ${id}`)\n const task = ledger.tasks[index]!\n if (task.trashedAt !== undefined) throw new ToolError(ERR.notFound, `no task ${id}`)\n return { index, task }\n}\n\n/** Re-throw with a stable code; non-ToolErrors become invalid_input. */\nfunction fail(error: unknown): never {\n if (error instanceof ToolError) throw error\n const message = error instanceof Error ? error.message : String(error)\n throw new ToolError(ERR.invalidInput, message)\n}\n\n/** Loose json output schema shared by every taskboard tool. */\nconst JSON_OUT = { type: 'json' } as const\n\n/** Deep-JSON a value for a json-rooted tool output (spread results lose implicit index signatures). */\nfunction json<T>(value: T): Record<string, unknown> {\n return JSON.parse(JSON.stringify(value)) as Record<string, unknown>\n}\n\n/** The exec context face the tools read (agent identity + session cwd). */\nexport interface ToolRunContext {\n agent?: { id: string; session: { header: { cwd?: string } } }\n}\n\n/** Registry-like context face (tests stub this). */\nexport interface ToolContextFace {\n tools: { register(tool: { name: string }): unknown }\n}\n\n/**\n * Register all ten tools.\n * @param ctx - a context exposing `tools.register`.\n * @param deps - store + workspaces + clock.\n * @returns dispose functions, one per tool.\n */\nexport function registerTaskboardTools(ctx: ToolContextFace, deps: ToolDeps): Array<() => void> {\n const disposers: Array<() => void> = []\n const { store, workspaces } = deps\n\n // Env-gated tool-call tracing (ATB_TRACE=1) — evidence for protocol E2E.\n const register = (tool: { name: string; execute?: unknown }) => {\n if (process.env.ATB_TRACE === '1' && typeof tool.execute === 'function') {\n const orig = tool.execute as (args: unknown, exec: unknown) => Promise<unknown>\n tool.execute = async (args: unknown, exec: unknown) => {\n console.error(`[atb ▶] ${tool.name}`, JSON.stringify(args).slice(0, 300))\n try {\n const result = await orig(args, exec)\n console.error(`[atb ✓] ${tool.name}`, JSON.stringify(result).slice(0, 300))\n return result\n } catch (error) {\n console.error(`[atb ✗] ${tool.name}`, String(error).slice(0, 400))\n throw error\n }\n }\n }\n return ctx.tools.register(tool as { name: string })\n }\n\n // ------------------------------------------------------------------ list\n disposers.push(register(defineTool({\n name: 'taskboard_list',\n description:\n 'List task-board tasks. Filter by project (workspaceId), status, or urgency. '\n + 'Returns compact summaries (id, title, status, urgency, version, claim owner). '\n + 'Check this before starting work to find claimable todo tasks in your project.',\n parameters: {\n workspaceId: { type: 'string', description: 'Filter by project (DSH workspace id).' },\n status: { type: 'string', description: 'Filter by exact status (backlog/todo/in_progress/in_review/done/canceled/archived).' },\n urgency: { type: 'string', description: 'Filter by urgency (urgent/normal/relaxed).' },\n includeTrashed: { type: 'boolean', description: 'Include soft-deleted tasks (default false).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { revision?: number; tasks?: Array<Record<string, unknown>> }\n const tasks = v.tasks ?? []\n const head = `任务 ${tasks.length} 条(台账 rev ${v.revision ?? '?'})`\n if (tasks.length === 0) return [{ type: 'text', text: `${head}:无匹配任务。` }]\n return [{ type: 'text', text: [head, ...tasks.map(t => taskLine(t as never))].join('\\n') }]\n },\n },\n async execute(args) {\n try {\n const a = args as { workspaceId?: string; status?: string; urgency?: string; includeTrashed?: boolean }\n const tasks = store.snapshot().tasks.filter(t =>\n (a.workspaceId === undefined || t.workspaceId === a.workspaceId)\n && (a.status === undefined || t.status === a.status)\n && (a.urgency === undefined || t.urgency === a.urgency)\n && (a.includeTrashed === true || t.trashedAt === undefined))\n return json({ revision: store.snapshot().revision, tasks: tasks.map(summarize) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ------------------------------------------------------------------- get\n disposers.push(register(defineTool({\n name: 'taskboard_get',\n description:\n 'Read one task in full: description, prompt, project, urgency, status, comments, executions, version. '\n + 'Read this (and the comments) BEFORE claiming or starting work on a task.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id from the board.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: TaskRecord & { effectivePrompt?: string } }\n return [{ type: 'text', text: v.task === undefined ? '任务不存在。' : taskDetail(v.task) }]\n },\n },\n async execute(args: { id: string }) {\n try {\n const { id } = args\n const task = store.get(id)\n if (task === undefined || task.trashedAt !== undefined) throw new ToolError(ERR.notFound, `no task ${id}`)\n return json({ task: { ...task, effectivePrompt: effectivePrompt(task) } })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ---------------------------------------------------------------- create\n disposers.push(register(defineTool({\n name: 'taskboard_create',\n description:\n 'Create a task on the board. Required: title, workspaceId (project), urgency (urgent/normal/relaxed). '\n + 'Optional: description, prompt (sent to a fresh session on execution), status (default todo), '\n + 'execution mode (claim|scheduled + cron), model {provider, model} to pin executions to a model. '\n + 'Do not track trivial requests as tasks.',\n parameters: {\n title: { type: 'string', required: true, description: 'Short imperative line (1..200 chars).' },\n workspaceId: { type: 'string', required: true, description: 'Project (DSH workspace id) this task belongs to.' },\n urgency: { type: 'string', required: true, description: 'urgent (red) | normal (purple) | relaxed (blue).' },\n description: { type: 'string', description: 'What the task involves (plain text).' },\n prompt: { type: 'string', description: 'Extra execution instructions; the session receives title+description+this prompt.' },\n status: { type: 'string', description: 'Initial status; default todo. backlog = not approved for execution.' },\n execution: {\n type: 'object',\n additionalProperties: false,\n description: 'Execution config: { mode: \"claim\" } (default) or { mode: \"scheduled\", cron: \"m h dom mon dow\" }.',\n properties: {\n mode: { type: 'string', description: 'claim | scheduled.' },\n cron: { type: 'string', description: 'Five-field cron expression (scheduled only).' },\n },\n },\n model: {\n type: 'object',\n additionalProperties: false,\n description: 'Pin executions to one configured model: { provider, model, reasoningEffort? }. Omit to use the default model.',\n properties: {\n provider: { type: 'string', description: 'Provider route id.' },\n model: { type: 'string', description: 'Provider-owned model id.' },\n reasoningEffort: { type: 'string', description: 'Optional thinking intensity / reasoning effort (e.g. low, medium, high).' },\n },\n },\n isolation: {\n type: 'string',\n description: 'Code isolation for executions: \"worktree\" (each run gets a fresh git worktree on branch task/<标题>+<taskId>) or \"none\" (run in the project directory, zero git interaction). Omitted → the board default (看板设置 → 默认执行隔离; factory default \"none\").',\n },\n presetId: {\n type: 'string',\n description: 'Agent preset the execution session is composed from (its tool set / persona); default = the deployment default preset. Optional.',\n },\n checklist: {\n type: 'array',\n description: `Acceptance checklist (DoD) item texts (≤${MAX_CHECKLIST_ITEMS} × 200 chars); agents check them off at handoff, the user reviews.`,\n items: { type: 'string' },\n },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; status?: string; version?: number }; sessionArchive?: SessionArchiveResult }\n const t = v.task\n return [{ type: 'text', text: t === undefined ? '创建失败。' : `已创建任务 ${t.id} [${t.status}] v${t.version}。写入前先 taskboard_get 读取。` }]\n },\n },\n async execute(args: {\n title: string\n workspaceId: string\n urgency: string\n status?: string\n description?: string\n prompt?: string\n execution?: { mode?: string; cron?: string }\n model?: { provider?: string; model?: string }\n isolation?: string\n presetId?: string\n checklist?: string[]\n }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n const title = normalizeTitle(args.title)\n if (workspaces.get(args.workspaceId) === undefined) {\n throw new ToolError(ERR.notFound, `unknown workspaceId ${args.workspaceId}`)\n }\n const urgency = asUrgency(args.urgency)\n const status = args.status === undefined ? 'todo' as const : asStatus(args.status)\n if (status !== 'backlog' && status !== 'todo') {\n throw new ToolError(ERR.invalidTransition, 'a new task must start as backlog or todo (in_progress requires claiming the task)')\n }\n const execution = normalizeExecution(args.execution ?? {}, deps.now())\n const model = args.model !== undefined ? checkModel(deps, args.model) : undefined\n // 0.5.0: an omitted isolation is MATERIALIZED from the board setting\n // (看板设置) at creation, so later setting changes never rewrite\n // existing tasks.\n const isolation = args.isolation === undefined ? defaultIsolationOf(store.snapshot().settings) : asIsolation(args.isolation)\n const presetId = args.presetId?.trim() || undefined\n // T9: match the GUI create route — trim and drop blank lines instead\n // of failing the whole call over one empty string.\n const checklistTexts = args.checklist?.map(c => c.trim()).filter(c => c.length > 0)\n const checklist = checklistTexts !== undefined && checklistTexts.length > 0 ? checklistFromTexts(checklistTexts) : undefined\n const now = deps.now()\n const task: TaskRecord = {\n id: newTaskId(),\n title,\n description: (args.description ?? '').trim(),\n prompt: normalizePrompt(args.prompt),\n workspaceId: args.workspaceId,\n urgency,\n status,\n blocked: false,\n execution,\n model,\n isolation,\n ...(presetId !== undefined ? { presetId } : {}),\n ...(checklist !== undefined ? { checklist } : {}),\n version: 1,\n createdAt: now,\n updatedAt: now,\n createdBy: actor,\n updatedBy: actor,\n comments: [],\n executions: [],\n }\n await store.mutate('task-created', ledger => {\n ledger.tasks.push(task)\n return [task]\n })\n return json({ task: summarize(task) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ---------------------------------------------------------------- update\n disposers.push(register(defineTool({\n name: 'taskboard_update',\n description:\n 'Update a task\\'s title/description/prompt/urgency/blocked. Requires ifVersion (read first). '\n + 'The model and execution config are read-only through this tool (they belong to the task owner/user).',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n ifVersion: { type: 'number', required: true, description: 'The task version you read; the write fails on mismatch.' },\n title: { type: 'string', description: 'New title.' },\n description: { type: 'string', description: 'New description.' },\n prompt: { type: 'string', description: 'New execution prompt.' },\n urgency: { type: 'string', description: 'urgent | normal | relaxed.' },\n blocked: { type: 'boolean', description: 'Blocked marker (work cannot continue right now).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; status?: string; version?: number }; sessionArchive?: SessionArchiveResult }\n const t = v.task\n return [{ type: 'text', text: t === undefined ? '更新失败。' : `已更新任务 ${t.id},当前 v${t.version} [${t.status}]。` }]\n },\n },\n async execute(args: {\n id: string\n ifVersion: number\n title?: string\n description?: string\n prompt?: string\n urgency?: string\n blocked?: boolean\n }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n // R1: lookup + version guard + write run inside the serial-queue\n // mutation, on the fresh draft — a pre-read clone could pass its\n // version check and then blind-overwrite a concurrent writer.\n let next: TaskRecord | undefined\n await store.mutate('task-updated', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n if (task.status === 'archived') throw new ToolError(ERR.invalidTransition, 'archived tasks are immutable')\n next = structuredClone(task)\n if (args.title !== undefined) next.title = normalizeTitle(args.title)\n if (args.description !== undefined) next.description = args.description.trim()\n if (args.prompt !== undefined) next.prompt = normalizePrompt(args.prompt)\n if (args.urgency !== undefined) next.urgency = asUrgency(args.urgency)\n if (args.blocked !== undefined) next.blocked = args.blocked\n next.version = task.version + 1\n next.updatedAt = deps.now()\n next.updatedBy = actor\n ledger.tasks[index] = next\n return [next]\n })\n return json({ task: summarize(next!) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ------------------------------------------------------------------ move\n disposers.push(register(defineTool({\n name: 'taskboard_move',\n description:\n 'Move a task between statuses (requires ifVersion). Claim = todo→in_progress (only a session '\n + 'inside the task\\'s project may claim; never take over a task held by another session). '\n + 'After implementing and self-verifying: comment, then in_progress→in_review. '\n + 'You can NEVER move a task to done — that requires explicit user confirmation.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n status: { type: 'string', required: true, description: 'Target status.' },\n ifVersion: { type: 'number', required: true, description: 'Task version you read; fails on mismatch.' },\n archiveSessions: { type: 'boolean', description: 'When moving to archived: whether to archive associated execution sessions as well. Defaults to false.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; status?: string; version?: number }; sessionArchive?: SessionArchiveResult }\n const t = v.task\n return [{ type: 'text', text: t === undefined ? '移动失败。' : `任务 ${t.id} 已移到 ${t.status},当前 v${t.version}。${v.sessionArchive === undefined ? '' : ` 会话归档结果:${JSON.stringify(v.sessionArchive)}`}` }]\n },\n },\n async execute(args: { id: string; status: string; ifVersion: number; archiveSessions?: boolean }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n const to = asStatus(args.status)\n // Claim boundary (policy gate): resolving the caller's workspace is\n // async, so it happens BEFORE the mutation — the comparison runs INSIDE\n // against the FRESH task (stronger than the old stale-clone compare).\n const callerWsId = to === 'in_progress'\n ? await callerWorkspace(deps, exec as ToolRunContext)\n : undefined\n // R1: every state guard + the write itself run inside the mutation.\n let next: TaskRecord | undefined\n let beforeTask: TaskRecord | undefined\n await store.mutate('task-moved', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n beforeTask = task\n\n // Code-level gate: agents never complete a task.\n if (to === 'done') {\n throw new ToolError(ERR.forbidden, 'moving a task to done requires explicit user confirmation (GUI); agents cannot do it')\n }\n if (!canTransition(task.status, to)) {\n throw new ToolError(ERR.invalidTransition, `illegal transition ${task.status} → ${to}`)\n }\n // Exclusive hold: while a task is in_progress under a session\n // (explicit claimedBy — an agent claim or a live execution), no other\n // session may move it (that would be a takeover).\n if (task.status === 'in_progress' && task.claimedBy !== undefined && task.claimedBy !== actor.sessionId) {\n throw new ToolError(ERR.forbidden, `task is held by session ${task.claimedBy}; never take over another session's claim`)\n }\n // Claim boundary: the calling session must belong to the task's project.\n if (isClaim(task.status, to) && callerWsId !== task.workspaceId) {\n throw new ToolError(ERR.workspaceMismatch, 'only a session inside this task\\'s project may claim it')\n }\n next = structuredClone(task)\n next.status = to\n next.version = task.version + 1\n next.updatedAt = deps.now()\n next.updatedBy = actor\n if (isClaim(task.status, to)) next.blocked = false\n // Record the holder on a claim; every move out of in_progress releases it.\n syncClaim(next, to, deps.now(), isClaim(task.status, to) ? actor.sessionId : undefined)\n ledger.tasks[index] = next\n return [next]\n })\n const sessionArchive = to === 'archived' && args.archiveSessions === true\n ? await archiveTaskSessions(beforeTask ?? next!, deps.workspaces.archiveSession)\n : undefined\n return json({ task: summarize(next!), ...(sessionArchive !== undefined ? { sessionArchive } : {}) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ----------------------------------------------------------- comment_add\n disposers.push(register(defineTool({\n name: 'taskboard_comment_add',\n description:\n 'Append a progress/report comment to a task. When handing off to review, the comment should cover: '\n + 'what changed, how it was verified, outcome, and remaining risks.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n body: { type: 'string', required: true, description: 'Comment text (1..4000 chars).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { comment?: { id?: string }; task?: { id?: string; version?: number; status?: string } }\n const c = v.comment\n const t = v.task\n if (c === undefined || t === undefined) return [{ type: 'text', text: '评论失败。' }]\n // The comment bumped the version — echo it so the agent can chain the\n // next write (e.g. move → in_review) WITHOUT re-reading.\n return [{\n type: 'text',\n text: `评论 ${c.id} 已添加;任务 ${t.id} 当前 v${t.version} [${t.status}](后续写操作用此版本号).`,\n }]\n },\n },\n async execute(args: { id: string; body: string }, exec: unknown) {\n try {\n const { sessionId } = caller(exec as ToolRunContext)\n const comment = {\n id: newCommentId(),\n body: normalizeBody(args.body),\n version: 1,\n createdAt: deps.now(),\n threadId: sessionId,\n }\n // R1: find + append inside the mutation (no ifVersion by design —\n // comments are append-only — but the write must not clobber a task\n // that changed while we were queued).\n let next: TaskRecord | undefined\n await store.mutate('comment-added', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n if (task.status === 'archived') throw new ToolError(ERR.invalidTransition, 'archived tasks are immutable')\n next = structuredClone(task)\n next.comments.push(comment)\n next.version = task.version + 1\n next.updatedAt = deps.now()\n ledger.tasks[index] = next\n return [next]\n })\n return json({ comment, task: { id: next!.id, version: next!.version, status: next!.status } })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // -------------------------------------------------------------- comments\n disposers.push(register(defineTool({\n name: 'taskboard_comments',\n description: 'List a task\\'s comments, oldest first. Read them before deciding to start work.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { comments?: unknown[] }\n const list = v.comments as Array<{ body: string; createdAt: number; threadId?: string }> | undefined\n if (list === undefined || list.length === 0) return [{ type: 'text', text: '无评论。' }]\n const lines = list.map(c => {\n const who = c.threadId !== undefined ? `agent ${String(c.threadId).slice(0, 24)}` : 'user'\n return `- [${who} ${new Date(c.createdAt).toISOString()}] ${c.body}`\n })\n return [{ type: 'text', text: `评论 ${list.length} 条:\\n${lines.join('\\n')}` }]\n },\n },\n async execute(args: { id: string }) {\n try {\n const task = store.get(args.id)\n if (task === undefined || task.trashedAt !== undefined) throw new ToolError(ERR.notFound, `no task ${args.id}`)\n return json({ comments: task.comments })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ---------------------------------------------------------------- delete\n disposers.push(register(defineTool({\n name: 'taskboard_delete',\n description:\n 'Soft-delete a task (marks it trashed; the user confirms the purge in the GUI). '\n + 'Requires ifVersion. Prefer canceled/archived over delete unless the task was a mistake.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n ifVersion: { type: 'number', required: true, description: 'Task version you read.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { trashed?: boolean }\n return [{ type: 'text', text: v.trashed === true ? '任务已标记删除(等待用户在 GUI 清除)。' : '删除失败。' }]\n },\n },\n async execute(args: { id: string; ifVersion: number }, exec: unknown) {\n try {\n caller(exec as ToolRunContext)\n // R1: guards inside the mutation. S5: a running execution keeps\n // writing to the task (report, settlement) — refuse the soft-delete\n // until it is cancelled or settled. T8: clear claim residue.\n let next: TaskRecord | undefined\n await store.mutate('task-deleted', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n if (task.executions.some(e => e.outcome === 'running')) {\n throw new ToolError(ERR.invalidInput, '任务有正在运行的执行(先在 GUI 取消或等它结束再删除)')\n }\n next = structuredClone(task)\n next.trashedAt = deps.now()\n next.version = task.version + 1\n delete next.claimedBy\n delete next.claimedAt\n next.blocked = false\n ledger.tasks[index] = next\n return [next]\n })\n return { trashed: true }\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // -------------------------------------------------------------- checklist\n disposers.push(register(defineTool({\n name: 'taskboard_checklist',\n description:\n `Manage the task's acceptance checklist (DoD). Actions: \"add\" (append item texts, ≤10 per call), `\n + '\"check\" (mark an item done, with an optional evidence note), \"uncheck\" (reopen an item). '\n + 'Checking items NEVER completes the task — done stays a user-only action. Requires ifVersion.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n action: { type: 'string', required: true, description: 'add | check | uncheck.' },\n ifVersion: { type: 'number', required: true, description: 'Task version you read; fails on mismatch.' },\n items: {\n type: 'array',\n description: 'Item texts to append (action=add only; 1..10 per call, 200 chars each).',\n items: { type: 'string' },\n },\n itemId: { type: 'string', description: 'The checklist item id (action=check/uncheck).' },\n note: { type: 'string', description: 'Evidence note recorded with the check (≤400 chars).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; version?: number }; checklist?: Array<Record<string, unknown>>; done?: number; total?: number }\n if (v.task === undefined || v.checklist === undefined) return [{ type: 'text', text: '清单操作失败。' }]\n const lines = v.checklist.map((i, index) => `${i.checked === true ? '☑' : '☐'} [${index + 1}] ${String(i.text)}${i.note !== undefined ? `(证据: ${String(i.note)})` : ''} id=${String(i.id)}`)\n return [{\n type: 'text',\n text: `任务 ${v.task.id} 验收清单 ${v.done ?? 0}/${v.total ?? 0} 已完成,当前 v${v.task.version}:\\n${lines.join('\\n')}`,\n }]\n },\n },\n async execute(args: {\n id: string\n action: string\n ifVersion: number\n items?: string[]\n itemId?: string\n note?: string\n }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n // R1: guards + the checklist edit itself run inside the mutation.\n let next: TaskRecord | undefined\n await store.mutate('task-updated', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n if (task.status === 'archived') throw new ToolError(ERR.invalidTransition, 'archived tasks are immutable')\n next = structuredClone(task)\n const checklist: ChecklistItem[] = next.checklist === undefined ? [] : [...next.checklist]\n\n if (args.action === 'add') {\n const texts = args.items ?? []\n if (texts.length === 0 || texts.length > 10) {\n throw new ToolError(ERR.invalidInput, 'items must carry 1..10 texts per add call')\n }\n if (checklist.length + texts.length > MAX_CHECKLIST_ITEMS) {\n throw new ToolError(ERR.invalidInput, `checklist may hold at most ${MAX_CHECKLIST_ITEMS} items (currently ${checklist.length})`)\n }\n checklist.push(...checklistFromTexts(texts))\n } else if (args.action === 'check') {\n if (args.itemId === undefined) throw new ToolError(ERR.invalidInput, 'itemId is required for check')\n const item = checklist.find(i => i.id === args.itemId)\n if (item === undefined) throw new ToolError(ERR.notFound, `no checklist item ${args.itemId} (task ${args.id})`)\n const note = args.note !== undefined && args.note.trim().length > 0 ? args.note.trim().slice(0, 400) : undefined\n item.checked = true\n item.checkedBy = actor.sessionId\n item.checkedAt = deps.now()\n if (note !== undefined) item.note = note\n } else if (args.action === 'uncheck') {\n if (args.itemId === undefined) throw new ToolError(ERR.invalidInput, 'itemId is required for uncheck')\n const item = checklist.find(i => i.id === args.itemId)\n if (item === undefined) throw new ToolError(ERR.notFound, `no checklist item ${args.itemId} (task ${args.id})`)\n item.checked = false\n delete item.checkedBy\n delete item.checkedAt\n delete item.note\n } else {\n throw new ToolError(ERR.invalidInput, `action must be add | check | uncheck (got \"${args.action}\")`)\n }\n\n if (checklist.length > 0) next.checklist = checklist\n else delete next.checklist\n next.version = task.version + 1\n next.updatedAt = deps.now()\n next.updatedBy = actor\n ledger.tasks[index] = next\n return [next]\n })\n const progress = next!.checklist !== undefined\n ? { done: next!.checklist.filter(i => i.checked).length, total: next!.checklist.length }\n : { done: 0, total: 0 }\n return json({ task: { id: next!.id, version: next!.version }, checklist: next!.checklist ?? [], ...progress })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ------------------------------------------------------- execution report\n disposers.push(register(defineTool({\n name: 'taskboard_execution_report',\n description:\n 'Submit the structured execution report for the task you are currently executing (summary / changed '\n + 'files / how you verified / artifacts / remaining risk). Submit BEFORE moving the task to in_review; '\n + 'a later submission overwrites the previous report. If your run already settled, you may back-submit '\n + 'onto your latest succeeded execution while you still hold the task. Commits and diffs are host-collected.',\n parameters: {\n summary: { type: 'string', required: true, description: 'What was done (1..2000 chars).' },\n changedFiles: {\n type: 'array',\n description: 'Files you changed (paths, ≤50 × 300 chars).',\n items: { type: 'string' },\n },\n checks: {\n type: 'array',\n description: 'How the work was verified (e.g. test commands + outcomes, ≤50 entries).',\n items: { type: 'string' },\n },\n artifacts: {\n type: 'array',\n description: 'Artifacts worth reviewing (build outputs, screenshots, docs, ≤30 entries).',\n items: { type: 'string' },\n },\n risk: { type: 'string', description: 'Known remaining risks or follow-ups (≤2000 chars, optional).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { taskId?: string; executionId?: string; report?: { summary?: string } }\n if (v.taskId === undefined || v.report === undefined) return [{ type: 'text', text: '报告提交失败。' }]\n return [{\n type: 'text',\n text: `执行报告已记录到任务 ${v.taskId}(执行 ${v.executionId}):${v.report.summary?.slice(0, 120) ?? ''}\\n`\n + '接下来:taskboard_comment_add 留交接评论,然后 taskboard_move 移至待验收 in_review。',\n }]\n },\n },\n async execute(args: {\n summary: string\n changedFiles?: string[]\n checks?: string[]\n artifacts?: string[]\n risk?: string\n }, exec: unknown) {\n try {\n const { sessionId } = caller(exec as ToolRunContext)\n const report = normalizeExecutionReport(args)\n // Path 1 (unchanged): attach to the RUNNING execution this session\n // owns — reports ride the live run, so the agent never needs ids.\n let taskId: string | undefined\n let executionId: string | undefined\n await store.mutate('execution-recorded', ledger => {\n for (const task of ledger.tasks) {\n const execution = task.executions.find(e => e.sessionId === sessionId && e.outcome === 'running')\n if (execution !== undefined) {\n execution.report = report\n taskId = task.id\n executionId = execution.id\n return [task]\n }\n }\n return undefined\n })\n // Path 2 (review follow-up, P2): back-submit onto a session-owned\n // SETTLED execution — the main conversation claims tasks directly and\n // has no live run. Allowed when the session holds the task or owns\n // its latest successful execution; never touches anyone else's runs.\n if (taskId === undefined || executionId === undefined) {\n await store.mutate('execution-recorded', ledger => {\n for (const task of ledger.tasks) {\n if (task.trashedAt !== undefined || task.status === 'archived') continue\n const last = task.executions[task.executions.length - 1]\n const owned = last !== undefined && last.sessionId === sessionId && last.outcome === 'succeeded'\n const holds = task.claimedBy === sessionId && last !== undefined && last.sessionId === sessionId\n if (!owned && !holds) continue\n last!.report = report\n taskId = task.id\n executionId = last!.id\n return [task]\n }\n return undefined\n })\n }\n if (taskId === undefined || executionId === undefined) {\n throw new ToolError(ERR.forbidden, 'no running execution and no settled execution of yours to report on — reports attach to your running execution, or back-submit onto your latest succeeded one while you hold the task')\n }\n return json({ taskId, executionId, report })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n return disposers\n}\n"],"mappings":";;;;;AAyDA,SAAS,SAAS,GAaP;CACT,MAAM,QAAQ,CACZ,KAAK,EAAE,GAAG,IAAI,EAAE,OAAO,KAAK,EAAE,QAAQ,KAAK,EAAE,QAAQ,QAAQ,EAAE,eAC/D,IAAI,EAAE,MAAM,EACd;C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AAO,CAAC;GAC7C,SAAS,OAAO;IAAE,KAAK,KAAK;GAAE;EAChC;CACF,CAAC,CAAC,CAAe;CAEjB,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"tools.js","names":["v"],"sources":["../../src/host/tools.ts"],"sourcesContent":["import type { SessionArchiveResult } from '../shared/api.ts'\nimport { archiveTaskSessions } from './archive-sessions.ts'\n/**\n * The ten `taskboard_*` agent tools. All writes require a calling agent\n * session (ownership audit), carry optimistic-version checks, and enforce\n * the protocol gates in CODE, not in prompt text:\n *\n * - `move → done` is rejected for agent callers (user confirmation only)\n * - `move todo → in_progress` requires the calling session's workspace to\n * match the task's project (claim boundary)\n * - taking over a task held by another session is rejected\n * - `delete` for agent callers only sets the soft-delete marker\n * - checklist items may be added/checked by agents, but checking never\n * completes the task (done stays user-only)\n *\n * OUTPUT CONTRACT (lesson: registry `createSuccessResult` renders\n * `output.render(args, value)` into `result.content`, and the loop feeds\n * exactly that content to the model — the raw JSON `value` never reaches\n * the model): render() IS the model-facing tool result. Every render must\n * carry the complete facts an agent needs to act (ids, versions, statuses);\n * a \"terse UI summary\" here starves the agent.\n *\n * @module dsh-taskboard/host/tools\n */\nimport type { WorkspaceRegistry } from '@deepseek-ai/dsh-workspace'\nimport { defineTool } from './sdk.ts'\nimport {\n MAX_CHECKLIST_ITEMS,\n asIsolation,\n asStatus,\n asUrgency,\n canTransition,\n checklistFromTexts,\n defaultIsolationOf,\n effectivePrompt,\n isClaim,\n isClaimedBy,\n newChecklistItemId,\n newCommentId,\n newTaskId,\n normalizeBody,\n normalizeExecution,\n normalizeExecutionReport,\n normalizeModel,\n normalizePrompt,\n normalizeTitle,\n summarize,\n syncClaim,\n type Actor,\n type ChecklistItem,\n type TaskLedger,\n type TaskModel,\n type TaskRecord,\n} from '../shared/protocol.ts'\nimport type { TaskStore } from './store.ts'\n\n/** Render side: one compact task line (id/status/version are load-bearing). */\nfunction taskLine(t: {\n id: string\n title: string\n status: string\n urgency: string\n version: number\n workspaceId: string\n blocked: boolean\n executionMode: string\n commentCount?: number\n lastExecutionOutcome?: string\n checklist?: { done: number; total: number }\n trashed?: boolean\n}): string {\n const parts = [\n `- ${t.id} [${t.status}] v${t.version} · ${t.urgency} · 项目 ${t.workspaceId}`,\n `「${t.title}」`,\n ]\n if (t.blocked) parts.push('·受阻')\n if (t.executionMode === 'scheduled') parts.push('·定时')\n if (t.commentCount !== undefined && t.commentCount > 0) parts.push(`·评论${t.commentCount}`)\n if (t.checklist !== undefined && t.checklist.total > 0) parts.push(`·清单${t.checklist.done}/${t.checklist.total}`)\n if (t.lastExecutionOutcome !== undefined) parts.push(`·上次执行${t.lastExecutionOutcome}`)\n if (t.trashed === true) parts.push('·已删')\n return parts.join(' ')\n}\n\n/** Render side: the full task detail block (everything an executor needs). */\nfunction taskDetail(t: TaskRecord & { effectivePrompt?: string }): string {\n const lines: string[] = [\n `任务 ${t.id} 「${t.title}」`,\n `状态: ${t.status} (v${t.version}) · 紧急度: ${t.urgency} · 项目: ${t.workspaceId}${t.blocked ? ' · 受阻' : ''}`,\n `执行方式: ${t.execution.mode}${t.execution.cron !== undefined ? ` cron=${t.execution.cron}` : ''}`,\n `隔离: ${t.isolation === 'none' ? '关闭(原目录执行)' : 'Git Worktree'}${t.branch !== undefined ? `(分支 ${t.branch})` : ''}${t.branches !== undefined ? `(多仓库镜像 ${Object.keys(t.branches).length + (t.branch !== undefined ? 1 : 0)} 个仓库)` : ''}`,\n ]\n const holder = isClaimedBy(t)\n if (holder !== undefined) lines.push(`认领: agent ${String(holder).slice(0, 24)}(持有期间其他会话不可移动)`)\n if (t.execution.nextRunAt !== undefined) lines.push(`下次触发: ${new Date(t.execution.nextRunAt).toISOString()}`)\n if (t.model !== undefined) lines.push(`固定模型: ${t.model.provider}/${t.model.model}${t.model.reasoningEffort !== undefined ? ` (思考强度: ${t.model.reasoningEffort})` : ''}`)\n if (t.presetId !== undefined) lines.push(`执行模式: ${t.presetId}(未指定时为部署默认 preset)`)\n lines.push(`描述: ${t.description.length > 0 ? t.description : '(无)'}`)\n lines.push(`执行 Prompt: ${t.effectivePrompt ?? effectivePrompt(t)}`)\n if (t.checklist !== undefined && t.checklist.length > 0) {\n const done = t.checklist.filter(i => i.checked).length\n lines.push(`验收清单 (${done}/${t.checklist.length}):`)\n for (const [index, item] of t.checklist.entries()) {\n const mark = item.checked ? '☑' : '☐'\n const who = item.checkedBy === undefined ? '' : item.checkedBy === 'user' ? ' ·用户勾选' : ` ·agent ${String(item.checkedBy).slice(0, 24)}勾选`\n const note = item.note !== undefined ? ` ·证据: ${item.note}` : ''\n // Carry the checklist item id so `taskboard_checklist check/uncheck` can\n // address it without guessing — a terse render starves the agent (render\n // is fed to the model as result.content). Mirrors the index+id carried\n // by the taskboard_checklist tool output.\n lines.push(` ${mark} [${index + 1}] ${item.text}${who}${note} id=${item.id}`)\n }\n }\n if (t.comments.length > 0) {\n lines.push(`评论 (${t.comments.length}):`)\n for (const c of t.comments) {\n const who = c.threadId !== undefined ? `agent ${String(c.threadId).slice(0, 24)}` : 'user'\n lines.push(` - [${who} ${new Date(c.createdAt).toISOString()}] ${c.body}`)\n }\n } else {\n lines.push('评论: 无')\n }\n if (t.executions.length > 0) {\n lines.push(`执行记录 (${t.executions.length}):`)\n for (const e of t.executions) {\n const at = e.startedAt !== undefined ? new Date(e.startedAt).toISOString() : '?'\n const err = e.error !== undefined ? ` 错误: ${e.error}` : ''\n const report = e.report !== undefined ? ' [已交报告]' : ''\n lines.push(` - [${e.trigger} ${at}] ${e.outcome}${report}${err}`)\n }\n } else {\n lines.push('执行记录: 无')\n }\n const updatedBy = t.updatedBy.kind === 'agent' ? `agent ${String(t.updatedBy.sessionId).slice(0, 24)}` : t.updatedBy.kind === 'system' ? 'system' : 'user'\n lines.push(`更新: ${new Date(t.updatedAt).toISOString()} 由 ${updatedBy}`)\n return lines.join('\\n')\n}\n\n/** Stable error codes surfaced at the head of tool error messages. */\nexport const ERR = {\n notReady: 'taskboard_not_ready',\n notFound: 'not_found',\n versionConflict: 'version_conflict',\n workspaceMismatch: 'workspace_mismatch',\n invalidTransition: 'invalid_transition',\n forbidden: 'forbidden',\n requiresAgent: 'unauthorized_actor',\n invalidInput: 'invalid_input',\n} as const\n\n/** Tool failure: an Error whose message starts with a stable code. The code\n * is also carried structurally so the routes layer can map failures without\n * re-parsing messages (review P2). */\nexport class ToolError extends Error {\n constructor(readonly code: string, detail: string) {\n super(`Error: ${code}: ${detail}`)\n }\n}\n\n/** The workspace face the tools need (narrow for tests). */\nexport interface WorkspaceFace {\n /** Resolve the workspace owning a canonical cwd, if any. */\n resolveByPath(path: string): Promise<{ id: string } | undefined>\n /** Get a workspace by id. */\n get(id: string): { id: string; path: string; title: string } | undefined\n /** List all workspaces. */\n list(): Array<{ id: string; path: string; title: string }>\n /** Archive one session durably (when supported by runtime workspaceRegistry). */\n archiveSession?(sessionId: string): Promise<void>\n}\n\n/** Adapt the real registry to the narrow face. */\nexport function workspaceFace(registry: WorkspaceRegistry): WorkspaceFace {\n // Explicit field mapping: Workspace entities expose path/title as prototype\n // getters, which JSON.stringify skips (own enumerable properties only).\n return {\n resolveByPath: async (path) => {\n const ws = await registry.resolveByPath(path as never)\n return ws === undefined ? undefined : { id: ws.id }\n },\n get: id => {\n const ws = registry.get(id as never)\n return ws === undefined ? undefined : { id: ws.id, path: ws.path, title: ws.title }\n },\n list: () => registry.list().map(ws => ({ id: ws.id, path: ws.path, title: ws.title })),\n ...(typeof registry.archiveSession === 'function'\n ? { archiveSession: (sessionId: string) => registry.archiveSession(sessionId as Parameters<WorkspaceRegistry['archiveSession']>[0]) }\n : {}),\n }\n}\n\n/** Everything the tool set needs. */\nexport interface ToolDeps {\n store: TaskStore\n workspaces: WorkspaceFace\n /** Current epoch ms (injectable for tests). */\n now: () => number\n /** Shared startup barrier; tool definitions stay registered while services initialize. */\n ready?: () => Promise<void>\n /**\n * Registered model provider routes (from the host llm runtime), for\n * advisory validation of pinned models; undefined = runtime unavailable,\n * in which case only the structural check applies.\n */\n modelProviders?: () => string[] | undefined\n}\n\n/** Validate a pinned model: structural check always, provider route when known. */\nfunction checkModel(deps: ToolDeps, raw: unknown): TaskModel {\n const model = normalizeModel(raw)\n const providers = deps.modelProviders?.()\n if (providers !== undefined && !providers.includes(model.provider)) {\n throw new ToolError(ERR.invalidInput, `model provider \"${model.provider}\" has no registered route (available: ${providers.join(', ')})`)\n }\n return model\n}\n\n/** Resolve the calling agent's actor and session id. */\nfunction caller(exec: ToolRunContext): { actor: Actor & { kind: 'agent' }; sessionId: string } {\n if (!exec.agent) throw new ToolError(ERR.requiresAgent, 'taskboard tools require a calling agent session')\n const sessionId = exec.agent.id\n return { actor: { kind: 'agent', sessionId }, sessionId }\n}\n\n/** The calling session's workspace id (undefined when unaffiliated). */\nasync function callerWorkspace(deps: ToolDeps, exec: ToolRunContext): Promise<string | undefined> {\n const cwd = exec.agent?.session.header.cwd\n if (typeof cwd !== 'string' || cwd.length === 0) return undefined\n const ws = await deps.workspaces.resolveByPath(cwd)\n return ws?.id\n}\n\n/** Guard: version match. */\nfunction versionGuard(task: TaskRecord, ifVersion: number | undefined): void {\n if (ifVersion === undefined) {\n throw new ToolError(ERR.versionConflict, 'this write requires ifVersion; read the task first')\n }\n if (ifVersion !== task.version) {\n throw new ToolError(ERR.versionConflict, `stale version ${ifVersion} (current ${task.version}); re-read the task and retry once`)\n }\n}\n\n/**\n * Find a live (non-trashed) task INSIDE a mutator (R1: every guard must run\n * on the fresh draft the serial queue hands us, never on a pre-read clone —\n * a pre-read can pass its version check and then blind-overwrite a task that\n * changed while the caller awaited). Throws not_found for missing/trashed.\n */\nfunction liveTaskAt(ledger: TaskLedger, id: string): { index: number; task: TaskRecord } {\n const index = ledger.tasks.findIndex(t => t.id === id)\n if (index < 0) throw new ToolError(ERR.notFound, `no task ${id}`)\n const task = ledger.tasks[index]!\n if (task.trashedAt !== undefined) throw new ToolError(ERR.notFound, `no task ${id}`)\n return { index, task }\n}\n\n/** Re-throw with a stable code; non-ToolErrors become invalid_input. */\nfunction fail(error: unknown): never {\n if (error instanceof ToolError) throw error\n const message = error instanceof Error ? error.message : String(error)\n throw new ToolError(ERR.invalidInput, message)\n}\n\n/** Loose json output schema shared by every taskboard tool. */\nconst JSON_OUT = { type: 'json' } as const\n\n/** Deep-JSON a value for a json-rooted tool output (spread results lose implicit index signatures). */\nfunction json<T>(value: T): Record<string, unknown> {\n return JSON.parse(JSON.stringify(value)) as Record<string, unknown>\n}\n\n/** The exec context face the tools read (agent identity + session cwd). */\nexport interface ToolRunContext {\n agent?: { id: string; session: { header: { cwd?: string } } }\n}\n\n/** Registry-like context face (tests stub this). */\nexport interface ToolContextFace {\n tools: { register(tool: { name: string }): unknown }\n}\n\n/**\n * Register all ten tools.\n * @param ctx - a context exposing `tools.register`.\n * @param deps - store + workspaces + clock.\n * @returns dispose functions, one per tool.\n */\nexport function registerTaskboardTools(ctx: ToolContextFace, deps: ToolDeps): Array<() => void> {\n const disposers: Array<() => void> = []\n const { store, workspaces } = deps\n\n // Env-gated tool-call tracing (ATB_TRACE=1) — evidence for protocol E2E.\n const register = (tool: { name: string; execute?: unknown }) => {\n if (typeof tool.execute === 'function') {\n const orig = tool.execute as (args: unknown, exec: unknown) => Promise<unknown>\n tool.execute = async (args: unknown, exec: unknown) => {\n await deps.ready?.()\n if (process.env.ATB_TRACE === '1') console.error(`[atb ▶] ${tool.name}`, JSON.stringify(args).slice(0, 300))\n try {\n const result = await orig(args, exec)\n if (process.env.ATB_TRACE === '1') console.error(`[atb ✓] ${tool.name}`, JSON.stringify(result).slice(0, 300))\n return result\n } catch (error) {\n if (process.env.ATB_TRACE === '1') console.error(`[atb ✗] ${tool.name}`, String(error).slice(0, 400))\n throw error\n }\n }\n }\n return ctx.tools.register(tool as { name: string })\n }\n\n // ------------------------------------------------------------------ list\n disposers.push(register(defineTool({\n name: 'taskboard_list',\n description:\n 'List task-board tasks. Filter by project (workspaceId), status, or urgency. '\n + 'Returns compact summaries (id, title, status, urgency, version, claim owner). '\n + 'Check this before starting work to find claimable todo tasks in your project.',\n parameters: {\n workspaceId: { type: 'string', description: 'Filter by project (DSH workspace id).' },\n status: { type: 'string', description: 'Filter by exact status (backlog/todo/in_progress/in_review/done/canceled/archived).' },\n urgency: { type: 'string', description: 'Filter by urgency (urgent/normal/relaxed).' },\n includeTrashed: { type: 'boolean', description: 'Include soft-deleted tasks (default false).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { revision?: number; tasks?: Array<Record<string, unknown>> }\n const tasks = v.tasks ?? []\n const head = `任务 ${tasks.length} 条(台账 rev ${v.revision ?? '?'})`\n if (tasks.length === 0) return [{ type: 'text', text: `${head}:无匹配任务。` }]\n return [{ type: 'text', text: [head, ...tasks.map(t => taskLine(t as never))].join('\\n') }]\n },\n },\n async execute(args) {\n try {\n const a = args as { workspaceId?: string; status?: string; urgency?: string; includeTrashed?: boolean }\n const tasks = store.snapshot().tasks.filter(t =>\n (a.workspaceId === undefined || t.workspaceId === a.workspaceId)\n && (a.status === undefined || t.status === a.status)\n && (a.urgency === undefined || t.urgency === a.urgency)\n && (a.includeTrashed === true || t.trashedAt === undefined))\n return json({ revision: store.snapshot().revision, tasks: tasks.map(summarize) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ------------------------------------------------------------------- get\n disposers.push(register(defineTool({\n name: 'taskboard_get',\n description:\n 'Read one task in full: description, prompt, project, urgency, status, comments, executions, version. '\n + 'Read this (and the comments) BEFORE claiming or starting work on a task.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id from the board.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: TaskRecord & { effectivePrompt?: string } }\n return [{ type: 'text', text: v.task === undefined ? '任务不存在。' : taskDetail(v.task) }]\n },\n },\n async execute(args: { id: string }) {\n try {\n const { id } = args\n const task = store.get(id)\n if (task === undefined || task.trashedAt !== undefined) throw new ToolError(ERR.notFound, `no task ${id}`)\n return json({ task: { ...task, effectivePrompt: effectivePrompt(task) } })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ---------------------------------------------------------------- create\n disposers.push(register(defineTool({\n name: 'taskboard_create',\n description:\n 'Create a task on the board. Required: title, workspaceId (project), urgency (urgent/normal/relaxed). '\n + 'Optional: description, prompt (sent to a fresh session on execution), status (default todo), '\n + 'execution mode (claim|scheduled + cron), model {provider, model} to pin executions to a model. '\n + 'Do not track trivial requests as tasks.',\n parameters: {\n title: { type: 'string', required: true, description: 'Short imperative line (1..200 chars).' },\n workspaceId: { type: 'string', required: true, description: 'Project (DSH workspace id) this task belongs to.' },\n urgency: { type: 'string', required: true, description: 'urgent (red) | normal (purple) | relaxed (blue).' },\n description: { type: 'string', description: 'What the task involves (plain text).' },\n prompt: { type: 'string', description: 'Extra execution instructions; the session receives title+description+this prompt.' },\n status: { type: 'string', description: 'Initial status; default todo. backlog = not approved for execution.' },\n execution: {\n type: 'object',\n additionalProperties: false,\n description: 'Execution config: { mode: \"claim\" } (default) or { mode: \"scheduled\", cron: \"m h dom mon dow\" }.',\n properties: {\n mode: { type: 'string', description: 'claim | scheduled.' },\n cron: { type: 'string', description: 'Five-field cron expression (scheduled only).' },\n },\n },\n model: {\n type: 'object',\n additionalProperties: false,\n description: 'Pin executions to one configured model: { provider, model, reasoningEffort? }. Omit to use the default model.',\n properties: {\n provider: { type: 'string', description: 'Provider route id.' },\n model: { type: 'string', description: 'Provider-owned model id.' },\n reasoningEffort: { type: 'string', description: 'Optional thinking intensity / reasoning effort (e.g. low, medium, high).' },\n },\n },\n isolation: {\n type: 'string',\n description: 'Code isolation for executions: \"worktree\" (each run gets a fresh git worktree on branch task/<标题>+<taskId>) or \"none\" (run in the project directory, zero git interaction). Omitted → the board default (看板设置 → 默认执行隔离; factory default \"none\").',\n },\n presetId: {\n type: 'string',\n description: 'Agent preset the execution session is composed from (its tool set / persona); default = the deployment default preset. Optional.',\n },\n checklist: {\n type: 'array',\n description: `Acceptance checklist (DoD) item texts (≤${MAX_CHECKLIST_ITEMS} × 200 chars); agents check them off at handoff, the user reviews.`,\n items: { type: 'string' },\n },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; status?: string; version?: number }; sessionArchive?: SessionArchiveResult }\n const t = v.task\n return [{ type: 'text', text: t === undefined ? '创建失败。' : `已创建任务 ${t.id} [${t.status}] v${t.version}。写入前先 taskboard_get 读取。` }]\n },\n },\n async execute(args: {\n title: string\n workspaceId: string\n urgency: string\n status?: string\n description?: string\n prompt?: string\n execution?: { mode?: string; cron?: string }\n model?: { provider?: string; model?: string }\n isolation?: string\n presetId?: string\n checklist?: string[]\n }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n const title = normalizeTitle(args.title)\n if (workspaces.get(args.workspaceId) === undefined) {\n throw new ToolError(ERR.notFound, `unknown workspaceId ${args.workspaceId}`)\n }\n const urgency = asUrgency(args.urgency)\n const status = args.status === undefined ? 'todo' as const : asStatus(args.status)\n if (status !== 'backlog' && status !== 'todo') {\n throw new ToolError(ERR.invalidTransition, 'a new task must start as backlog or todo (in_progress requires claiming the task)')\n }\n const execution = normalizeExecution(args.execution ?? {}, deps.now())\n const model = args.model !== undefined ? checkModel(deps, args.model) : undefined\n // 0.5.0: an omitted isolation is MATERIALIZED from the board setting\n // (看板设置) at creation, so later setting changes never rewrite\n // existing tasks.\n const isolation = args.isolation === undefined ? defaultIsolationOf(store.snapshot().settings) : asIsolation(args.isolation)\n const presetId = args.presetId?.trim() || undefined\n // T9: match the GUI create route — trim and drop blank lines instead\n // of failing the whole call over one empty string.\n const checklistTexts = args.checklist?.map(c => c.trim()).filter(c => c.length > 0)\n const checklist = checklistTexts !== undefined && checklistTexts.length > 0 ? checklistFromTexts(checklistTexts) : undefined\n const now = deps.now()\n const task: TaskRecord = {\n id: newTaskId(),\n title,\n description: (args.description ?? '').trim(),\n prompt: normalizePrompt(args.prompt),\n workspaceId: args.workspaceId,\n urgency,\n status,\n blocked: false,\n execution,\n model,\n isolation,\n ...(presetId !== undefined ? { presetId } : {}),\n ...(checklist !== undefined ? { checklist } : {}),\n version: 1,\n createdAt: now,\n updatedAt: now,\n createdBy: actor,\n updatedBy: actor,\n comments: [],\n executions: [],\n }\n await store.mutate('task-created', ledger => {\n ledger.tasks.push(task)\n return [task]\n })\n return json({ task: summarize(task) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ---------------------------------------------------------------- update\n disposers.push(register(defineTool({\n name: 'taskboard_update',\n description:\n 'Update a task\\'s title/description/prompt/urgency/blocked. Requires ifVersion (read first). '\n + 'The model and execution config are read-only through this tool (they belong to the task owner/user).',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n ifVersion: { type: 'number', required: true, description: 'The task version you read; the write fails on mismatch.' },\n title: { type: 'string', description: 'New title.' },\n description: { type: 'string', description: 'New description.' },\n prompt: { type: 'string', description: 'New execution prompt.' },\n urgency: { type: 'string', description: 'urgent | normal | relaxed.' },\n blocked: { type: 'boolean', description: 'Blocked marker (work cannot continue right now).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; status?: string; version?: number }; sessionArchive?: SessionArchiveResult }\n const t = v.task\n return [{ type: 'text', text: t === undefined ? '更新失败。' : `已更新任务 ${t.id},当前 v${t.version} [${t.status}]。` }]\n },\n },\n async execute(args: {\n id: string\n ifVersion: number\n title?: string\n description?: string\n prompt?: string\n urgency?: string\n blocked?: boolean\n }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n // R1: lookup + version guard + write run inside the serial-queue\n // mutation, on the fresh draft — a pre-read clone could pass its\n // version check and then blind-overwrite a concurrent writer.\n let next: TaskRecord | undefined\n await store.mutate('task-updated', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n if (task.status === 'archived') throw new ToolError(ERR.invalidTransition, 'archived tasks are immutable')\n next = structuredClone(task)\n if (args.title !== undefined) next.title = normalizeTitle(args.title)\n if (args.description !== undefined) next.description = args.description.trim()\n if (args.prompt !== undefined) next.prompt = normalizePrompt(args.prompt)\n if (args.urgency !== undefined) next.urgency = asUrgency(args.urgency)\n if (args.blocked !== undefined) next.blocked = args.blocked\n next.version = task.version + 1\n next.updatedAt = deps.now()\n next.updatedBy = actor\n ledger.tasks[index] = next\n return [next]\n })\n return json({ task: summarize(next!) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ------------------------------------------------------------------ move\n disposers.push(register(defineTool({\n name: 'taskboard_move',\n description:\n 'Move a task between statuses (requires ifVersion). Claim = todo→in_progress (only a session '\n + 'inside the task\\'s project may claim; never take over a task held by another session). '\n + 'After implementing and self-verifying: comment, then in_progress→in_review. '\n + 'You can NEVER move a task to done — that requires explicit user confirmation.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n status: { type: 'string', required: true, description: 'Target status.' },\n ifVersion: { type: 'number', required: true, description: 'Task version you read; fails on mismatch.' },\n archiveSessions: { type: 'boolean', description: 'When moving to archived: whether to archive associated execution sessions as well. Defaults to false.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; status?: string; version?: number }; sessionArchive?: SessionArchiveResult }\n const t = v.task\n return [{ type: 'text', text: t === undefined ? '移动失败。' : `任务 ${t.id} 已移到 ${t.status},当前 v${t.version}。${v.sessionArchive === undefined ? '' : ` 会话归档结果:${JSON.stringify(v.sessionArchive)}`}` }]\n },\n },\n async execute(args: { id: string; status: string; ifVersion: number; archiveSessions?: boolean }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n const to = asStatus(args.status)\n // Claim boundary (policy gate): resolving the caller's workspace is\n // async, so it happens BEFORE the mutation — the comparison runs INSIDE\n // against the FRESH task (stronger than the old stale-clone compare).\n const callerWsId = to === 'in_progress'\n ? await callerWorkspace(deps, exec as ToolRunContext)\n : undefined\n // R1: every state guard + the write itself run inside the mutation.\n let next: TaskRecord | undefined\n let beforeTask: TaskRecord | undefined\n await store.mutate('task-moved', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n beforeTask = task\n\n // Code-level gate: agents never complete a task.\n if (to === 'done') {\n throw new ToolError(ERR.forbidden, 'moving a task to done requires explicit user confirmation (GUI); agents cannot do it')\n }\n if (!canTransition(task.status, to)) {\n throw new ToolError(ERR.invalidTransition, `illegal transition ${task.status} → ${to}`)\n }\n // Exclusive hold: while a task is in_progress under a session\n // (explicit claimedBy — an agent claim or a live execution), no other\n // session may move it (that would be a takeover).\n if (task.status === 'in_progress' && task.claimedBy !== undefined && task.claimedBy !== actor.sessionId) {\n throw new ToolError(ERR.forbidden, `task is held by session ${task.claimedBy}; never take over another session's claim`)\n }\n // Claim boundary: the calling session must belong to the task's project.\n if (isClaim(task.status, to) && callerWsId !== task.workspaceId) {\n throw new ToolError(ERR.workspaceMismatch, 'only a session inside this task\\'s project may claim it')\n }\n next = structuredClone(task)\n next.status = to\n next.version = task.version + 1\n next.updatedAt = deps.now()\n next.updatedBy = actor\n if (isClaim(task.status, to)) next.blocked = false\n // Record the holder on a claim; every move out of in_progress releases it.\n syncClaim(next, to, deps.now(), isClaim(task.status, to) ? actor.sessionId : undefined)\n ledger.tasks[index] = next\n return [next]\n })\n const sessionArchive = to === 'archived' && args.archiveSessions === true\n ? await archiveTaskSessions(beforeTask ?? next!, deps.workspaces.archiveSession)\n : undefined\n return json({ task: summarize(next!), ...(sessionArchive !== undefined ? { sessionArchive } : {}) })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ----------------------------------------------------------- comment_add\n disposers.push(register(defineTool({\n name: 'taskboard_comment_add',\n description:\n 'Append a progress/report comment to a task. When handing off to review, the comment should cover: '\n + 'what changed, how it was verified, outcome, and remaining risks.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n body: { type: 'string', required: true, description: 'Comment text (1..4000 chars).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { comment?: { id?: string }; task?: { id?: string; version?: number; status?: string } }\n const c = v.comment\n const t = v.task\n if (c === undefined || t === undefined) return [{ type: 'text', text: '评论失败。' }]\n // The comment bumped the version — echo it so the agent can chain the\n // next write (e.g. move → in_review) WITHOUT re-reading.\n return [{\n type: 'text',\n text: `评论 ${c.id} 已添加;任务 ${t.id} 当前 v${t.version} [${t.status}](后续写操作用此版本号).`,\n }]\n },\n },\n async execute(args: { id: string; body: string }, exec: unknown) {\n try {\n const { sessionId } = caller(exec as ToolRunContext)\n const comment = {\n id: newCommentId(),\n body: normalizeBody(args.body),\n version: 1,\n createdAt: deps.now(),\n threadId: sessionId,\n }\n // R1: find + append inside the mutation (no ifVersion by design —\n // comments are append-only — but the write must not clobber a task\n // that changed while we were queued).\n let next: TaskRecord | undefined\n await store.mutate('comment-added', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n if (task.status === 'archived') throw new ToolError(ERR.invalidTransition, 'archived tasks are immutable')\n next = structuredClone(task)\n next.comments.push(comment)\n next.version = task.version + 1\n next.updatedAt = deps.now()\n ledger.tasks[index] = next\n return [next]\n })\n return json({ comment, task: { id: next!.id, version: next!.version, status: next!.status } })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // -------------------------------------------------------------- comments\n disposers.push(register(defineTool({\n name: 'taskboard_comments',\n description: 'List a task\\'s comments, oldest first. Read them before deciding to start work.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { comments?: unknown[] }\n const list = v.comments as Array<{ body: string; createdAt: number; threadId?: string }> | undefined\n if (list === undefined || list.length === 0) return [{ type: 'text', text: '无评论。' }]\n const lines = list.map(c => {\n const who = c.threadId !== undefined ? `agent ${String(c.threadId).slice(0, 24)}` : 'user'\n return `- [${who} ${new Date(c.createdAt).toISOString()}] ${c.body}`\n })\n return [{ type: 'text', text: `评论 ${list.length} 条:\\n${lines.join('\\n')}` }]\n },\n },\n async execute(args: { id: string }) {\n try {\n const task = store.get(args.id)\n if (task === undefined || task.trashedAt !== undefined) throw new ToolError(ERR.notFound, `no task ${args.id}`)\n return json({ comments: task.comments })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ---------------------------------------------------------------- delete\n disposers.push(register(defineTool({\n name: 'taskboard_delete',\n description:\n 'Soft-delete a task (marks it trashed; the user confirms the purge in the GUI). '\n + 'Requires ifVersion. Prefer canceled/archived over delete unless the task was a mistake.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n ifVersion: { type: 'number', required: true, description: 'Task version you read.' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { trashed?: boolean }\n return [{ type: 'text', text: v.trashed === true ? '任务已标记删除(等待用户在 GUI 清除)。' : '删除失败。' }]\n },\n },\n async execute(args: { id: string; ifVersion: number }, exec: unknown) {\n try {\n caller(exec as ToolRunContext)\n // R1: guards inside the mutation. S5: a running execution keeps\n // writing to the task (report, settlement) — refuse the soft-delete\n // until it is cancelled or settled. T8: clear claim residue.\n let next: TaskRecord | undefined\n await store.mutate('task-deleted', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n if (task.executions.some(e => e.outcome === 'running')) {\n throw new ToolError(ERR.invalidInput, '任务有正在运行的执行(先在 GUI 取消或等它结束再删除)')\n }\n next = structuredClone(task)\n next.trashedAt = deps.now()\n next.version = task.version + 1\n delete next.claimedBy\n delete next.claimedAt\n next.blocked = false\n ledger.tasks[index] = next\n return [next]\n })\n return { trashed: true }\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // -------------------------------------------------------------- checklist\n disposers.push(register(defineTool({\n name: 'taskboard_checklist',\n description:\n `Manage the task's acceptance checklist (DoD). Actions: \"add\" (append item texts, ≤10 per call), `\n + '\"check\" (mark an item done, with an optional evidence note), \"uncheck\" (reopen an item). '\n + 'Checking items NEVER completes the task — done stays a user-only action. Requires ifVersion.',\n parameters: {\n id: { type: 'string', required: true, description: 'Task id.' },\n action: { type: 'string', required: true, description: 'add | check | uncheck.' },\n ifVersion: { type: 'number', required: true, description: 'Task version you read; fails on mismatch.' },\n items: {\n type: 'array',\n description: 'Item texts to append (action=add only; 1..10 per call, 200 chars each).',\n items: { type: 'string' },\n },\n itemId: { type: 'string', description: 'The checklist item id (action=check/uncheck).' },\n note: { type: 'string', description: 'Evidence note recorded with the check (≤400 chars).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { task?: { id?: string; version?: number }; checklist?: Array<Record<string, unknown>>; done?: number; total?: number }\n if (v.task === undefined || v.checklist === undefined) return [{ type: 'text', text: '清单操作失败。' }]\n const lines = v.checklist.map((i, index) => `${i.checked === true ? '☑' : '☐'} [${index + 1}] ${String(i.text)}${i.note !== undefined ? `(证据: ${String(i.note)})` : ''} id=${String(i.id)}`)\n return [{\n type: 'text',\n text: `任务 ${v.task.id} 验收清单 ${v.done ?? 0}/${v.total ?? 0} 已完成,当前 v${v.task.version}:\\n${lines.join('\\n')}`,\n }]\n },\n },\n async execute(args: {\n id: string\n action: string\n ifVersion: number\n items?: string[]\n itemId?: string\n note?: string\n }, exec: unknown) {\n try {\n const { actor } = caller(exec as ToolRunContext)\n // R1: guards + the checklist edit itself run inside the mutation.\n let next: TaskRecord | undefined\n await store.mutate('task-updated', ledger => {\n const { index, task } = liveTaskAt(ledger, args.id)\n versionGuard(task, args.ifVersion)\n if (task.status === 'archived') throw new ToolError(ERR.invalidTransition, 'archived tasks are immutable')\n next = structuredClone(task)\n const checklist: ChecklistItem[] = next.checklist === undefined ? [] : [...next.checklist]\n\n if (args.action === 'add') {\n const texts = args.items ?? []\n if (texts.length === 0 || texts.length > 10) {\n throw new ToolError(ERR.invalidInput, 'items must carry 1..10 texts per add call')\n }\n if (checklist.length + texts.length > MAX_CHECKLIST_ITEMS) {\n throw new ToolError(ERR.invalidInput, `checklist may hold at most ${MAX_CHECKLIST_ITEMS} items (currently ${checklist.length})`)\n }\n checklist.push(...checklistFromTexts(texts))\n } else if (args.action === 'check') {\n if (args.itemId === undefined) throw new ToolError(ERR.invalidInput, 'itemId is required for check')\n const item = checklist.find(i => i.id === args.itemId)\n if (item === undefined) throw new ToolError(ERR.notFound, `no checklist item ${args.itemId} (task ${args.id})`)\n const note = args.note !== undefined && args.note.trim().length > 0 ? args.note.trim().slice(0, 400) : undefined\n item.checked = true\n item.checkedBy = actor.sessionId\n item.checkedAt = deps.now()\n if (note !== undefined) item.note = note\n } else if (args.action === 'uncheck') {\n if (args.itemId === undefined) throw new ToolError(ERR.invalidInput, 'itemId is required for uncheck')\n const item = checklist.find(i => i.id === args.itemId)\n if (item === undefined) throw new ToolError(ERR.notFound, `no checklist item ${args.itemId} (task ${args.id})`)\n item.checked = false\n delete item.checkedBy\n delete item.checkedAt\n delete item.note\n } else {\n throw new ToolError(ERR.invalidInput, `action must be add | check | uncheck (got \"${args.action}\")`)\n }\n\n if (checklist.length > 0) next.checklist = checklist\n else delete next.checklist\n next.version = task.version + 1\n next.updatedAt = deps.now()\n next.updatedBy = actor\n ledger.tasks[index] = next\n return [next]\n })\n const progress = next!.checklist !== undefined\n ? { done: next!.checklist.filter(i => i.checked).length, total: next!.checklist.length }\n : { done: 0, total: 0 }\n return json({ task: { id: next!.id, version: next!.version }, checklist: next!.checklist ?? [], ...progress })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n // ------------------------------------------------------- execution report\n disposers.push(register(defineTool({\n name: 'taskboard_execution_report',\n description:\n 'Submit the structured execution report for the task you are currently executing (summary / changed '\n + 'files / how you verified / artifacts / remaining risk). Submit BEFORE moving the task to in_review; '\n + 'a later submission overwrites the previous report. If your run already settled, you may back-submit '\n + 'onto your latest succeeded execution while you still hold the task. Commits and diffs are host-collected.',\n parameters: {\n summary: { type: 'string', required: true, description: 'What was done (1..2000 chars).' },\n changedFiles: {\n type: 'array',\n description: 'Files you changed (paths, ≤50 × 300 chars).',\n items: { type: 'string' },\n },\n checks: {\n type: 'array',\n description: 'How the work was verified (e.g. test commands + outcomes, ≤50 entries).',\n items: { type: 'string' },\n },\n artifacts: {\n type: 'array',\n description: 'Artifacts worth reviewing (build outputs, screenshots, docs, ≤30 entries).',\n items: { type: 'string' },\n },\n risk: { type: 'string', description: 'Known remaining risks or follow-ups (≤2000 chars, optional).' },\n },\n output: {\n schema: JSON_OUT,\n render: (_args, value) => {\n const v = value as { taskId?: string; executionId?: string; report?: { summary?: string } }\n if (v.taskId === undefined || v.report === undefined) return [{ type: 'text', text: '报告提交失败。' }]\n return [{\n type: 'text',\n text: `执行报告已记录到任务 ${v.taskId}(执行 ${v.executionId}):${v.report.summary?.slice(0, 120) ?? ''}\\n`\n + '接下来:taskboard_comment_add 留交接评论,然后 taskboard_move 移至待验收 in_review。',\n }]\n },\n },\n async execute(args: {\n summary: string\n changedFiles?: string[]\n checks?: string[]\n artifacts?: string[]\n risk?: string\n }, exec: unknown) {\n try {\n const { sessionId } = caller(exec as ToolRunContext)\n const report = normalizeExecutionReport(args)\n // Path 1 (unchanged): attach to the RUNNING execution this session\n // owns — reports ride the live run, so the agent never needs ids.\n let taskId: string | undefined\n let executionId: string | undefined\n await store.mutate('execution-recorded', ledger => {\n for (const task of ledger.tasks) {\n const execution = task.executions.find(e => e.sessionId === sessionId && e.outcome === 'running')\n if (execution !== undefined) {\n execution.report = report\n taskId = task.id\n executionId = execution.id\n return [task]\n }\n }\n return undefined\n })\n // Path 2 (review follow-up, P2): back-submit onto a session-owned\n // SETTLED execution — the main conversation claims tasks directly and\n // has no live run. Allowed when the session holds the task or owns\n // its latest successful execution; never touches anyone else's runs.\n if (taskId === undefined || executionId === undefined) {\n await store.mutate('execution-recorded', ledger => {\n for (const task of ledger.tasks) {\n if (task.trashedAt !== undefined || task.status === 'archived') continue\n const last = task.executions[task.executions.length - 1]\n const owned = last !== undefined && last.sessionId === sessionId && last.outcome === 'succeeded'\n const holds = task.claimedBy === sessionId && last !== undefined && last.sessionId === sessionId\n if (!owned && !holds) continue\n last!.report = report\n taskId = task.id\n executionId = last!.id\n return [task]\n }\n return undefined\n })\n }\n if (taskId === undefined || executionId === undefined) {\n throw new ToolError(ERR.forbidden, 'no running execution and no settled execution of yours to report on — reports attach to your running execution, or back-submit onto your latest succeeded one while you hold the task')\n }\n return json({ taskId, executionId, report })\n } catch (error) { fail(error) }\n },\n })) as () => void)\n\n return disposers\n}\n"],"mappings":";;;;;AAyDA,SAAS,SAAS,GAaP;CACT,MAAM,QAAQ,CACZ,KAAK,EAAE,GAAG,IAAI,EAAE,OAAO,KAAK,EAAE,QAAQ,KAAK,EAAE,QAAQ,QAAQ,EAAE,eAC/D,IAAI,EAAE,MAAM,EACd;CACA,IAAI,EAAE,SAAS,MAAM,KAAK,KAAK;CAC/B,IAAI,EAAE,kBAAkB,aAAa,MAAM,KAAK,KAAK;CACrD,IAAI,EAAE,iBAAiB,KAAA,KAAa,EAAE,eAAe,GAAG,MAAM,KAAK,MAAM,EAAE,cAAc;CACzF,IAAI,EAAE,cAAc,KAAA,KAAa,EAAE,UAAU,QAAQ,GAAG,MAAM,KAAK,MAAM,EAAE,UAAU,KAAK,GAAG,EAAE,UAAU,OAAO;CAChH,IAAI,EAAE,yBAAyB,KAAA,GAAW,MAAM,KAAK,QAAQ,EAAE,sBAAsB;CACrF,IAAI,EAAE,YAAY,MAAM,MAAM,KAAK,KAAK;CACxC,OAAO,MAAM,KAAK,GAAG;AACvB;;AAGA,SAAS,WAAW,GAAsD;CACxE,MAAM,QAAkB;EACtB,MAAM,EAAE,GAAG,IAAI,EAAE,MAAM;EACvB,OAAO,EAAE,OAAO,KAAK,EAAE,QAAQ,WAAW,EAAE,QAAQ,SAAS,EAAE,cAAc,EAAE,UAAU,UAAU;EACnG,SAAS,EAAE,UAAU,OAAO,EAAE,UAAU,SAAS,KAAA,IAAY,SAAS,EAAE,UAAU,SAAS;EAC3F,OAAO,EAAE,cAAc,SAAS,cAAc,iBAAiB,EAAE,WAAW,KAAA,IAAY,OAAO,EAAE,OAAO,KAAK,KAAK,EAAE,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O,OAAO;MAC/B,IAAI,KAAK,cAAc,KAAA,KAAa,KAAK,WAAW,YAAY;MAChE,MAAM,OAAO,KAAK,WAAW,KAAK,WAAW,SAAS;MACtD,MAAM,QAAQ,SAAS,KAAA,KAAa,KAAK,cAAc,aAAa,KAAK,YAAY;MACrF,MAAM,QAAQ,KAAK,cAAc,aAAa,SAAS,KAAA,KAAa,KAAK,cAAc;MACvF,IAAI,CAAC,SAAS,CAAC,OAAO;MACtB,KAAM,SAAS;MACf,SAAS,KAAK;MACd,cAAc,KAAM;MACpB,OAAO,CAAC,IAAI;KACd;IAEF,CAAC;IAEH,IAAI,WAAW,KAAA,KAAa,gBAAgB,KAAA,GAC1C,MAAM,IAAI,UAAU,IAAI,WAAW,uLAAuL;IAE5N,OAAO,KAAK;KAAE;KAAQ;KAAa;IAAO,CAAC;GAC7C,SAAS,OAAO;IAAE,KAAK,KAAK;GAAE;EAChC;CACF,CAAC,CAAC,CAAe;CAEjB,OAAO;AACT"}
|
package/lib/index.js
CHANGED
|
@@ -3,17 +3,21 @@ import { createGitFace } from "./host/git.js";
|
|
|
3
3
|
import { createRepoScanner } from "./host/repos.js";
|
|
4
4
|
import { dshHomePath } from "./host/sdk.js";
|
|
5
5
|
import { ExecutionService } from "./host/execution.js";
|
|
6
|
-
import {
|
|
6
|
+
import { AssetStore } from "./host/assets.js";
|
|
7
|
+
import { ERR, ToolError, registerTaskboardTools, workspaceFace } from "./host/tools.js";
|
|
7
8
|
import { registerTaskboardRoutes } from "./host/routes.js";
|
|
8
9
|
import { SchedulerService } from "./host/scheduler.js";
|
|
9
10
|
import { TaskStore } from "./host/store.js";
|
|
10
11
|
import { TemplateStore } from "./host/templates.js";
|
|
11
12
|
import { ExternalSessionSyncService } from "./host/session-sync.js";
|
|
13
|
+
import { STORAGE_CONFIG_FILE, StorageCoordinator } from "./host/storage.js";
|
|
12
14
|
//#region src/index.ts
|
|
13
|
-
/** Ledger file name under the
|
|
15
|
+
/** Ledger file name under the active taskboard data directory. */
|
|
14
16
|
const LEDGER_FILE = "dsh-taskboard.json";
|
|
15
|
-
/** Task-template side file name under the
|
|
17
|
+
/** Task-template side file name under the active data directory. */
|
|
16
18
|
const TEMPLATES_FILE = "dsh-taskboard-templates.json";
|
|
19
|
+
/** Content-addressed image attachment directory under the active data directory. */
|
|
20
|
+
const ASSETS_DIR = "dsh-taskboard-assets";
|
|
17
21
|
/** Cordis plugin name. */
|
|
18
22
|
const name = "dsh-taskboard";
|
|
19
23
|
/** Required host services (tool registry + prompt assembly). */
|
|
@@ -23,9 +27,26 @@ const inject = ["tools", "systemPrompt"];
|
|
|
23
27
|
* @param ctx - the plugin context (tools + systemPrompt injected).
|
|
24
28
|
*/
|
|
25
29
|
function apply(ctx) {
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
30
|
+
const storage = new StorageCoordinator({
|
|
31
|
+
defaultDirectory: dshHomePath(),
|
|
32
|
+
configFile: dshHomePath(STORAGE_CONFIG_FILE),
|
|
33
|
+
ledgerName: LEDGER_FILE,
|
|
34
|
+
templatesName: TEMPLATES_FILE,
|
|
35
|
+
assetsName: ASSETS_DIR
|
|
36
|
+
});
|
|
37
|
+
const store = new TaskStore({
|
|
38
|
+
file: storage.ledgerPath(),
|
|
39
|
+
queue: storage.queue
|
|
40
|
+
});
|
|
41
|
+
const templates = new TemplateStore(storage.templatesPath(), storage.queue);
|
|
42
|
+
const assets = new AssetStore(storage.assetsPath(), () => Date.now(), storage.queue);
|
|
43
|
+
storage.attach({
|
|
44
|
+
ledger: store,
|
|
45
|
+
templates,
|
|
46
|
+
assets
|
|
47
|
+
});
|
|
48
|
+
const storeReady = storage.ready().then(() => store.load());
|
|
49
|
+
storeReady.then(() => assets.cleanup(JSON.stringify(store.snapshot())));
|
|
29
50
|
const now = () => Date.now();
|
|
30
51
|
const maxConcurrent = Math.max(1, Number.parseInt(process.env.DSH_TASKBOARD_MAX_CONCURRENT ?? "", 10) || 3);
|
|
31
52
|
const disposeSection = ctx.systemPrompt.section({
|
|
@@ -34,22 +55,46 @@ function apply(ctx) {
|
|
|
34
55
|
text: TASKBOARD_PROTOCOL
|
|
35
56
|
});
|
|
36
57
|
ctx.effect(() => disposeSection, "dsh-taskboard: protocol section");
|
|
58
|
+
let activeWorkspaces;
|
|
59
|
+
let activeWorkspaceContext;
|
|
60
|
+
const requireWorkspaces = () => {
|
|
61
|
+
if (activeWorkspaces === void 0) throw new ToolError(ERR.notReady, "workspace service is not ready; retry after host startup completes");
|
|
62
|
+
return activeWorkspaces;
|
|
63
|
+
};
|
|
64
|
+
const workspaces = {
|
|
65
|
+
resolveByPath: (path) => requireWorkspaces().resolveByPath(path),
|
|
66
|
+
get: (id) => requireWorkspaces().get(id),
|
|
67
|
+
list: () => requireWorkspaces().list()
|
|
68
|
+
};
|
|
69
|
+
Object.defineProperty(workspaces, "archiveSession", {
|
|
70
|
+
enumerable: true,
|
|
71
|
+
get: () => activeWorkspaces?.archiveSession === void 0 ? void 0 : (sessionId) => requireWorkspaces().archiveSession(sessionId)
|
|
72
|
+
});
|
|
73
|
+
const modelProviders = () => {
|
|
74
|
+
try {
|
|
75
|
+
const llm = activeWorkspaceContext?.get("llm");
|
|
76
|
+
return llm === void 0 || typeof llm.listProviders !== "function" ? void 0 : llm.listProviders().map((p) => p.id);
|
|
77
|
+
} catch {
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
const disposeTools = registerTaskboardTools(ctx, {
|
|
82
|
+
store,
|
|
83
|
+
workspaces,
|
|
84
|
+
now,
|
|
85
|
+
modelProviders,
|
|
86
|
+
ready: async () => {
|
|
87
|
+
if (activeWorkspaces === void 0) throw new ToolError(ERR.notReady, "workspace service is not ready; retry after host startup completes");
|
|
88
|
+
await storeReady;
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
ctx.effect(() => () => {
|
|
92
|
+
for (const dispose of disposeTools.splice(0)) dispose();
|
|
93
|
+
}, "dsh-taskboard: tools");
|
|
37
94
|
ctx.inject(["workspaceRegistry"], (wsCtx) => {
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const llm = wsCtx.get("llm");
|
|
42
|
-
return llm === void 0 || typeof llm.listProviders !== "function" ? void 0 : llm.listProviders().map((p) => p.id);
|
|
43
|
-
} catch {
|
|
44
|
-
return;
|
|
45
|
-
}
|
|
46
|
-
};
|
|
47
|
-
disposers.push(...registerTaskboardTools(wsCtx, {
|
|
48
|
-
store,
|
|
49
|
-
workspaces: workspaceFace(wsCtx.workspaceRegistry),
|
|
50
|
-
now,
|
|
51
|
-
modelProviders
|
|
52
|
-
}));
|
|
95
|
+
const workspaceDisposers = [];
|
|
96
|
+
activeWorkspaces = workspaceFace(wsCtx.workspaceRegistry);
|
|
97
|
+
activeWorkspaceContext = wsCtx;
|
|
53
98
|
const events = { onSessionEvent: (listener) => wsCtx.on("session/event", (session, event) => {
|
|
54
99
|
listener(session.id, event, session);
|
|
55
100
|
}) };
|
|
@@ -76,10 +121,11 @@ function apply(ctx) {
|
|
|
76
121
|
},
|
|
77
122
|
now
|
|
78
123
|
});
|
|
79
|
-
|
|
124
|
+
workspaceDisposers.push(() => sessionSync.dispose());
|
|
80
125
|
const git = createGitFace();
|
|
81
126
|
const scanner = createRepoScanner();
|
|
82
127
|
wsCtx.inject(["agents"], (agentCtx) => {
|
|
128
|
+
const agentDisposers = [];
|
|
83
129
|
agentSessions = agentCtx.get("sessions");
|
|
84
130
|
const execution = new ExecutionService({
|
|
85
131
|
store,
|
|
@@ -144,6 +190,11 @@ function apply(ctx) {
|
|
|
144
190
|
git,
|
|
145
191
|
scanner,
|
|
146
192
|
templates,
|
|
193
|
+
assets,
|
|
194
|
+
storage,
|
|
195
|
+
ready: async () => {
|
|
196
|
+
await storeReady;
|
|
197
|
+
},
|
|
147
198
|
promptCompletions: async () => {
|
|
148
199
|
try {
|
|
149
200
|
const skillsService = agentCtx.get("skills");
|
|
@@ -229,19 +280,24 @@ function apply(ctx) {
|
|
|
229
280
|
maxConcurrent
|
|
230
281
|
});
|
|
231
282
|
scheduler.start();
|
|
232
|
-
|
|
233
|
-
|
|
283
|
+
agentDisposers.push(() => scheduler.dispose());
|
|
284
|
+
agentDisposers.push(() => execution.dispose());
|
|
234
285
|
return () => {
|
|
235
286
|
disposeRoutes?.();
|
|
236
|
-
|
|
287
|
+
agentSessions = void 0;
|
|
288
|
+
for (const dispose of agentDisposers.splice(0)) dispose();
|
|
237
289
|
};
|
|
238
290
|
});
|
|
239
291
|
return () => {
|
|
240
|
-
|
|
292
|
+
if (activeWorkspaceContext === wsCtx) {
|
|
293
|
+
activeWorkspaceContext = void 0;
|
|
294
|
+
activeWorkspaces = void 0;
|
|
295
|
+
}
|
|
296
|
+
for (const dispose of workspaceDisposers.splice(0)) dispose();
|
|
241
297
|
};
|
|
242
298
|
});
|
|
243
299
|
}
|
|
244
300
|
//#endregion
|
|
245
|
-
export { LEDGER_FILE, TEMPLATES_FILE, apply, inject, name };
|
|
301
|
+
export { ASSETS_DIR, LEDGER_FILE, TEMPLATES_FILE, apply, inject, name };
|
|
246
302
|
|
|
247
303
|
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Host loader entry for dsh-taskboard.\n *\n * Wiring: the ledger store (one JSON file under the DSH home), the ten\n * `taskboard_*` agent tools, the agent workflow-protocol system-prompt\n * section, the /taskboard JSON+SSE routes (when a webServer is served),\n * the host execution service (fresh in-project sessions, pinned models), and\n * the host-side cron scheduler for scheduled tasks.\n *\n * Export shape follows the dsh-tool-todo lesson: a function/namespace plugin —\n * `name` / `inject` / `apply`, NO default export.\n *\n * @module dsh-taskboard\n */\nimport type { Context } from '@deepseek-ai/cordis'\n// Type-only module imports: they load the cordis Context augmentations\n// (ctx.tools / ctx.systemPrompt / ctx.agents) and vanish at compile time —\n// the built host half keeps ZERO runtime @deepseek-ai imports.\nimport type {} from '@deepseek-ai/dsh-tools'\nimport type {} from '@deepseek-ai/dsh-system-prompt'\nimport type {} from '@deepseek-ai/dsh-agent'\nimport { PROTOCOL_SECTION_NAME, PROTOCOL_SECTION_ORDER, TASKBOARD_PROTOCOL } from './host/protocol-text.ts'\nimport { DEFAULT_MAX_CONCURRENT, ExecutionService, type EventsFace } from './host/execution.ts'\nimport { createGitFace } from './host/git.ts'\nimport { createRepoScanner } from './host/repos.ts'\nimport { registerTaskboardRoutes } from './host/routes.ts'\nimport { SchedulerService } from './host/scheduler.ts'\nimport { dshHomePath } from './host/sdk.ts'\nimport { TaskStore } from './host/store.ts'\nimport { TemplateStore } from './host/templates.ts'\nimport { ExternalSessionSyncService } from './host/session-sync.ts'\nimport { registerTaskboardTools, workspaceFace } from './host/tools.ts'\n\n/** Ledger file name under the DSH home. */\nexport const LEDGER_FILE = 'dsh-taskboard.json'\n\n/** Task-template side file name under the DSH home (0.4.0). */\nexport const TEMPLATES_FILE = 'dsh-taskboard-templates.json'\n\n/** Cordis plugin name. */\nexport const name = 'dsh-taskboard'\n\n/** Required host services (tool registry + prompt assembly). */\nexport const inject = ['tools', 'systemPrompt']\n\n/**\n * Mount the host half.\n * @param ctx - the plugin context (tools + systemPrompt injected).\n */\nexport function apply(ctx: Context): void {\n const store = new TaskStore({ file: dshHomePath(LEDGER_FILE) })\n const templates = new TemplateStore(dshHomePath(TEMPLATES_FILE))\n // Eager first load: the tools and most routes read snapshot()/get() without\n // triggering the lazy load, so a fresh boot used to serve an EMPTY board to\n // taskboard_list/get until the scheduler catchup tick or the first\n // GET /state happened to load the file (review P0). load() never throws —\n // a corrupt ledger is quarantined instead.\n void store.load()\n const now = () => Date.now()\n // Global execution concurrency cap (DSH_TASKBOARD_MAX_CONCURRENT overrides).\n const maxConcurrent = Math.max(1, Number.parseInt(process.env.DSH_TASKBOARD_MAX_CONCURRENT ?? '', 10) || DEFAULT_MAX_CONCURRENT)\n\n // Agent workflow protocol (claim discipline, retry rules, done-gate).\n const disposeSection = ctx.systemPrompt.section({\n name: PROTOCOL_SECTION_NAME,\n order: PROTOCOL_SECTION_ORDER,\n text: TASKBOARD_PROTOCOL,\n })\n ctx.effect(() => disposeSection, 'dsh-taskboard: protocol section')\n\n // Tools, routes, execution, and the scheduler all come up with the\n // workspace registry (claim boundary + project execution need it).\n ctx.inject(['workspaceRegistry'], (wsCtx: Context) => {\n const disposers: Array<() => void> = []\n\n // Registered model provider routes (from the host llm runtime), read\n // lazily at call time so late availability still applies; undefined when\n // the runtime is absent → only structural model validation runs.\n const modelProviders = (): string[] | undefined => {\n try {\n const llm = wsCtx.get('llm') as { listProviders?: () => Array<{ id: string }> } | undefined\n return llm === undefined || typeof llm.listProviders !== 'function'\n ? undefined\n : llm.listProviders().map(p => p.id)\n } catch { return undefined }\n }\n\n disposers.push(...registerTaskboardTools(wsCtx, {\n store,\n workspaces: workspaceFace(wsCtx.workspaceRegistry),\n now,\n modelProviders,\n }))\n\n // Settlement listener over the session event bus.\n const events: EventsFace = {\n onSessionEvent: (listener) => wsCtx.on('session/event', (session, event) => {\n listener(session.id, event as { type: string; data?: unknown }, session as never)\n }),\n }\n\n let agentSessions: { get?: (id: string) => unknown; list?: () => unknown[] } | undefined\n\n // External workspace sessions sync service (0.5.4).\n const sessionSync = new ExternalSessionSyncService({\n store,\n workspaces: workspaceFace(wsCtx.workspaceRegistry),\n events,\n sessions: {\n get: id => {\n try {\n const registry = (agentSessions ?? wsCtx.get('sessions') ?? wsCtx.get('sessionRegistry') ?? wsCtx.root?.get('sessions')) as { get?: (id: string) => unknown } | undefined\n return registry?.get?.(id)\n } catch { return undefined }\n },\n list: () => {\n try {\n const registry = (agentSessions ?? wsCtx.get('sessions') ?? wsCtx.get('sessionRegistry') ?? wsCtx.root?.get('sessions')) as { list?: () => unknown[] } | undefined\n return registry?.list?.() ?? []\n } catch { return [] }\n },\n },\n now,\n })\n disposers.push(() => sessionSync.dispose())\n\n // The narrow git face shared by execution (worktree isolation) and the\n // routes (merge / remove / workspace detection), plus the shared\n // nested-repo scanner for multi-repo mirrors (0.6.3).\n const git = createGitFace()\n const scanner = createRepoScanner()\n\n wsCtx.inject(['agents'], (agentCtx: Context) => {\n agentSessions = agentCtx.get('sessions') as { get?: (id: string) => unknown; list?: () => unknown[] } | undefined\n const execution = new ExecutionService({\n store,\n agents: {\n create: (options): Promise<never> => agentCtx.agents.create(options as never) as Promise<never>,\n },\n workspaces: {\n get: id => workspaceFace(wsCtx.workspaceRegistry).get(id),\n attach: async (workspaceId, sessionId) => {\n const ws = wsCtx.workspaceRegistry.get(workspaceId as never)\n if (ws !== undefined) await ws.attachSession(sessionId as never)\n },\n },\n events,\n now,\n git,\n scanner,\n // Preset composition (0.3.3): mirror apiproxy's composeAgent — resolve\n // the id BEFORE creation (the session header snapshots meta), mount\n // inside the factory's setup callback. No roster service → undefined\n // (bare host composition, the pre-preset behavior).\n composeAgent: async (presetId) => {\n const presets = agentCtx.get('agentPresets') as {\n resolve(id?: string): Promise<{ id: string }>\n mount(agentCtx: unknown, id?: string): Promise<unknown>\n } | undefined\n if (presets === undefined) return undefined\n const resolved = await presets.resolve(presetId)\n return {\n agentPreset: resolved.id,\n setup: async (ctx: unknown) => { await presets.mount(ctx, resolved.id) },\n }\n },\n renameSession: (sessionId, title) => {\n // Best-effort: pin the execution session's title to the task title\n // through the log-backed session-title service (user-sourced rename).\n try {\n const sessions = agentCtx.get('sessions') as { get(id: string): unknown } | undefined\n const sessionTitle = agentCtx.get('sessionTitle') as { rename(session: unknown, title: string): unknown } | undefined\n const session = sessions?.get(sessionId)\n if (session !== undefined && sessionTitle !== undefined) sessionTitle.rename(session, title)\n } catch { /* cosmetic */ }\n },\n defaultModel: () => {\n try {\n const selection = agentCtx.get('agentDefaultModel') as { currentSelection?: () => { provider: string; model: string } | undefined } | undefined\n const read = selection?.currentSelection\n return read === undefined ? undefined : read.call(selection)\n } catch { return undefined }\n },\n setPermission: (sessionId, permission) => {\n try {\n const permService = agentCtx.get('permissionPresets') as { set(session: unknown, name: string): void } | undefined\n const sessions = agentCtx.get('sessions') as { get(id: string): unknown } | undefined\n const session = sessions?.get(sessionId)\n if (session !== undefined && permService !== undefined) {\n permService.set(session, permission)\n }\n } catch { /* cosmetic */ }\n },\n maxConcurrent,\n })\n\n // /dsh-taskboard routes (the run action reaches the execution service).\n let disposeRoutes: (() => void) | undefined\n agentCtx.inject(['webServer'], (webCtx: Context) => {\n disposeRoutes = registerTaskboardRoutes(webCtx, {\n store,\n workspaces: workspaceFace(wsCtx.workspaceRegistry),\n now,\n run: (taskId: string, runOptions?: { reuseWorktree?: boolean }) => execution.run(taskId, 'manual', runOptions),\n cancel: (taskId: string) => execution.cancel(taskId),\n modelProviders,\n git,\n scanner,\n templates,\n promptCompletions: async () => {\n try {\n const skillsService = agentCtx.get('skills') as { list?(options?: unknown): Promise<Array<{ name: string; description?: string }>> } | undefined\n const commandsService = agentCtx.get('commands') as { list?(): Array<{ name: string; description?: string; input?: { hint?: string } }> } | undefined\n const rawSkills = skillsService?.list ? await skillsService.list().catch(() => []) : []\n const rawCommands = commandsService?.list ? commandsService.list() : []\n return {\n skills: Array.isArray(rawSkills) ? rawSkills.map(s => ({ name: s.name, description: s.description })) : [],\n commands: Array.isArray(rawCommands) ? rawCommands.map(c => ({ name: c.name, description: c.description, hint: c.input?.hint })) : [],\n }\n } catch {\n return { skills: [], commands: [] }\n }\n },\n modelCatalog: async () => {\n try {\n type ModelItem = {\n provider: string\n model: string\n name?: string\n description?: string\n reasoning?: {\n efforts: Array<{ id: string; name: string; description?: string }>\n defaultEffort?: string\n }\n }\n const models: ModelItem[] = []\n\n const llm = (agentCtx.get('llm') ?? wsCtx.get('llm')) as {\n listProviders?(): Array<{ id: string; name?: string }>\n listModels?(provider: string): Promise<Array<{ id: string; name?: string; description?: string }>>\n resolveModelInfo?(provider: string, model: string): Promise<{ reasoning?: { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort?: string } }>\n resolveModel?(provider: string, model: string): Promise<{ reasoning?: { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort?: string } }>\n } | undefined\n\n if (llm?.listProviders !== undefined && llm.listModels !== undefined) {\n const providers = llm.listProviders()\n for (const p of providers) {\n try {\n const list = await llm.listModels(p.id)\n for (const m of list) {\n let reasoning: { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort?: string } | undefined\n try {\n const meta = llm.resolveModelInfo !== undefined\n ? await llm.resolveModelInfo(p.id, m.id)\n : llm.resolveModel !== undefined ? await llm.resolveModel(p.id, m.id) : undefined\n if (meta?.reasoning !== undefined) {\n reasoning = meta.reasoning\n }\n } catch { /* ignore */ }\n\n models.push({\n provider: p.id,\n model: m.id,\n name: m.name,\n ...(m.description ? { description: m.description } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n })\n }\n } catch { /* continue */ }\n }\n }\n\n const presetsService = agentCtx.get('agentPresets') as {\n list?(): Promise<{ ok: boolean; value?: { presets: Array<{ id: string; name?: string; isDefault?: boolean }> } } | Array<{ id: string; name?: string; isDefault?: boolean }>>\n } | undefined\n const presets: Array<{ id: string; name?: string }> = []\n let defaultPresetId: string | undefined\n\n if (presetsService?.list !== undefined) {\n try {\n const raw = await presetsService.list()\n const list = (raw as { ok?: boolean; value?: { presets?: unknown[] } }).ok === true\n ? (raw as { value: { presets: Array<{ id: string; name?: string; isDefault?: boolean }> } }).value.presets\n : Array.isArray(raw) ? raw : []\n for (const p of list) {\n presets.push({ id: p.id, name: p.name })\n if (p.isDefault) defaultPresetId = p.id\n }\n } catch { /* continue */ }\n }\n\n return { models, presets, ...(defaultPresetId !== undefined ? { defaultPresetId } : {}) }\n } catch {\n return { models: [], presets: [] }\n }\n },\n })\n return () => disposeRoutes?.()\n })\n\n // Startup reconciliation: executions left 'running' by a previous host\n // process are marked failed and their tasks handed back to todo (their\n // settlement watchers died with that process).\n void execution.reconcile()\n\n // Host-side cron scheduler: due scheduled tasks execute even with no\n // browser open. Shares the execution concurrency cap.\n const scheduler = new SchedulerService({ store, execution, now, maxConcurrent })\n scheduler.start()\n disposers.push(() => scheduler.dispose())\n // Detach the settlement listener with the plugin — a hot reload must\n // not leave stale services reacting to turn/end errors (review P1).\n disposers.push(() => execution.dispose())\n\n return () => {\n disposeRoutes?.()\n for (const dispose of disposers.splice(0)) dispose()\n }\n })\n\n return () => {\n for (const dispose of disposers.splice(0)) dispose()\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;AAkCA,MAAa,cAAc;;AAG3B,MAAa,iBAAiB;;AAG9B,MAAa,OAAO;;AAGpB,MAAa,SAAS,CAAC,SAAS,cAAc;;;;;AAM9C,SAAgB,MAAM,KAAoB;CACxC,MAAM,QAAQ,IAAI,UAAU,EAAE,MAAM,YAAY,WAAW,EAAE,CAAC;CAC9D,MAAM,YAAY,IAAI,cAAc,YAAY,cAAc,CAAC;CAM/D,MAAW,KAAK;CAChB,MAAM,YAAY,KAAK,IAAI;CAE3B,MAAM,gBAAgB,KAAK,IAAI,GAAG,OAAO,SAAS,QAAQ,IAAI,gCAAgC,IAAI,EAAE,KAAA,CAA2B;CAG/H,MAAM,iBAAiB,IAAI,aAAa,QAAQ;EAC9C,MAAM;EACN,OAAA;EACA,MAAM;CACR,CAAC;CACD,IAAI,aAAa,gBAAgB,iCAAiC;CAIlE,IAAI,OAAO,CAAC,mBAAmB,IAAI,UAAmB;EACpD,MAAM,YAA+B,CAAC;EAKtC,MAAM,uBAA6C;GACjD,IAAI;IACF,MAAM,MAAM,MAAM,IAAI,KAAK;IAC3B,OAAO,QAAQ,KAAA,KAAa,OAAO,IAAI,kBAAkB,aACrD,KAAA,IACA,IAAI,cAAc,CAAC,CAAC,KAAI,MAAK,EAAE,EAAE;GACvC,QAAQ;IAAE;GAAiB;EAC7B;EAEA,UAAU,KAAK,GAAG,uBAAuB,OAAO;GAC9C;GACA,YAAY,cAAc,MAAM,iBAAiB;GACjD;GACA;EACF,CAAC,CAAC;EAGF,MAAM,SAAqB,EACzB,iBAAiB,aAAa,MAAM,GAA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B;OAEA,MAAM,iBAAiB,SAAS,IAAI,cAAc;OAGlD,MAAM,UAAgD,CAAC;OACvD,IAAI;OAEJ,IAAI,gBAAgB,SAAS,KAAA,GAC3B,IAAI;QACF,MAAM,MAAM,MAAM,eAAe,KAAK;QACtC,MAAM,OAAQ,IAA0D,OAAO,OAC1E,IAA0F,MAAM,UACjG,MAAM,QAAQ,GAAG,IAAI,MAAM,CAAC;QAChC,KAAK,MAAM,KAAK,MAAM;SACpB,QAAQ,KAAK;UAAE,IAAI,EAAE;UAAI,MAAM,EAAE;SAAK,CAAC;SACvC,IAAI,EAAE,WAAW,kBAAkB,EAAE;QACvC;OACF,QAAQ,CAAiB;OAG3B,OAAO;QAAE;QAAQ;QAAS,GAAI,oBAAoB,KAAA,IAAY,EAAE,gBAAgB,IAAI,CAAC;OAAG;MAC1F,QAAQ;OACN,OAAO;QAAE,QAAQ,CAAC;QAAG,SAAS,CAAC;OAAE;MACnC;KACF;IACF,CAAC;IACD,aAAa,gBAAgB;GAC/B,CAAC;GAKD,UAAe,UAAU;GAIzB,MAAM,YAAY,IAAI,iBAAiB;IAAE;IAAO;IAAW;IAAK;GAAc,CAAC;GAC/E,UAAU,MAAM;GAChB,UAAU,WAAW,UAAU,QAAQ,CAAC;GAGxC,UAAU,WAAW,UAAU,QAAQ,CAAC;GAExC,aAAa;IACX,gBAAgB;IAChB,KAAK,MAAM,WAAW,UAAU,OAAO,CAAC,GAAG,QAAQ;GACrD;EACF,CAAC;EAED,aAAa;GACX,KAAK,MAAM,WAAW,UAAU,OAAO,CAAC,GAAG,QAAQ;EACrD;CACF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Host loader entry for dsh-taskboard.\n *\n * Wiring: the configurable local data stores, the ten\n * `taskboard_*` agent tools, the agent workflow-protocol system-prompt\n * section, the /taskboard JSON+SSE routes (when a webServer is served),\n * the host execution service (fresh in-project sessions, pinned models), and\n * the host-side cron scheduler for scheduled tasks.\n *\n * Export shape follows the dsh-tool-todo lesson: a function/namespace plugin —\n * `name` / `inject` / `apply`, NO default export.\n *\n * @module dsh-taskboard\n */\nimport type { Context } from '@deepseek-ai/cordis'\n// Type-only module imports: they load the cordis Context augmentations\n// (ctx.tools / ctx.systemPrompt / ctx.agents) and vanish at compile time —\n// the built host half keeps ZERO runtime @deepseek-ai imports.\nimport type {} from '@deepseek-ai/dsh-tools'\nimport type {} from '@deepseek-ai/dsh-system-prompt'\nimport type {} from '@deepseek-ai/dsh-agent'\nimport { PROTOCOL_SECTION_NAME, PROTOCOL_SECTION_ORDER, TASKBOARD_PROTOCOL } from './host/protocol-text.ts'\nimport { DEFAULT_MAX_CONCURRENT, ExecutionService, type EventsFace } from './host/execution.ts'\nimport { createGitFace } from './host/git.ts'\nimport { createRepoScanner } from './host/repos.ts'\nimport { registerTaskboardRoutes } from './host/routes.ts'\nimport { SchedulerService } from './host/scheduler.ts'\nimport { dshHomePath } from './host/sdk.ts'\nimport { TaskStore } from './host/store.ts'\nimport { TemplateStore } from './host/templates.ts'\nimport { ExternalSessionSyncService } from './host/session-sync.ts'\nimport { ERR, ToolError, registerTaskboardTools, workspaceFace, type WorkspaceFace } from './host/tools.ts'\nimport { AssetStore } from './host/assets.ts'\nimport { STORAGE_CONFIG_FILE, StorageCoordinator } from './host/storage.ts'\n\n/** Ledger file name under the active taskboard data directory. */\nexport const LEDGER_FILE = 'dsh-taskboard.json'\n\n/** Task-template side file name under the active data directory. */\nexport const TEMPLATES_FILE = 'dsh-taskboard-templates.json'\n\n/** Content-addressed image attachment directory under the active data directory. */\nexport const ASSETS_DIR = 'dsh-taskboard-assets'\n\n/** Cordis plugin name. */\nexport const name = 'dsh-taskboard'\n\n/** Required host services (tool registry + prompt assembly). */\nexport const inject = ['tools', 'systemPrompt']\n\n/**\n * Mount the host half.\n * @param ctx - the plugin context (tools + systemPrompt injected).\n */\nexport function apply(ctx: Context): void {\n const storage = new StorageCoordinator({\n defaultDirectory: dshHomePath(),\n configFile: dshHomePath(STORAGE_CONFIG_FILE),\n ledgerName: LEDGER_FILE,\n templatesName: TEMPLATES_FILE,\n assetsName: ASSETS_DIR,\n })\n const store = new TaskStore({ file: storage.ledgerPath(), queue: storage.queue })\n const templates = new TemplateStore(storage.templatesPath(), storage.queue)\n const assets = new AssetStore(storage.assetsPath(), () => Date.now(), storage.queue)\n storage.attach({ ledger: store, templates, assets })\n // Eager first load: the tools and most routes read snapshot()/get() without\n // triggering the lazy load, so a fresh boot used to serve an EMPTY board to\n // taskboard_list/get until the scheduler catchup tick or the first\n // GET /state happened to load the file (review P0). load() never throws —\n // a corrupt ledger is quarantined instead.\n const storeReady = storage.ready().then(() => store.load())\n void storeReady.then(() => assets.cleanup(JSON.stringify(store.snapshot())))\n const now = () => Date.now()\n // Global execution concurrency cap (DSH_TASKBOARD_MAX_CONCURRENT overrides).\n const maxConcurrent = Math.max(1, Number.parseInt(process.env.DSH_TASKBOARD_MAX_CONCURRENT ?? '', 10) || DEFAULT_MAX_CONCURRENT)\n\n // Agent workflow protocol (claim discipline, retry rules, done-gate).\n const disposeSection = ctx.systemPrompt.section({\n name: PROTOCOL_SECTION_NAME,\n order: PROTOCOL_SECTION_ORDER,\n text: TASKBOARD_PROTOCOL,\n })\n ctx.effect(() => disposeSection, 'dsh-taskboard: protocol section')\n\n // Register the complete tool schema in the same synchronous mount as the\n // protocol. Keeping schemas stable from the first request preserves the\n // provider's prefix cache; calls use the live workspace service below.\n let activeWorkspaces: WorkspaceFace | undefined\n let activeWorkspaceContext: Context | undefined\n const requireWorkspaces = (): WorkspaceFace => {\n if (activeWorkspaces === undefined) {\n throw new ToolError(ERR.notReady, 'workspace service is not ready; retry after host startup completes')\n }\n return activeWorkspaces\n }\n const workspaces: WorkspaceFace = {\n resolveByPath: path => requireWorkspaces().resolveByPath(path),\n get: id => requireWorkspaces().get(id),\n list: () => requireWorkspaces().list(),\n }\n // Preserve the optional archive capability without replacing the stable\n // facade captured by the tool definitions.\n Object.defineProperty(workspaces, 'archiveSession', {\n enumerable: true,\n get: () => activeWorkspaces?.archiveSession === undefined\n ? undefined\n : (sessionId: string) => requireWorkspaces().archiveSession!(sessionId),\n })\n const modelProviders = (): string[] | undefined => {\n try {\n const llm = activeWorkspaceContext?.get('llm') as { listProviders?: () => Array<{ id: string }> } | undefined\n return llm === undefined || typeof llm.listProviders !== 'function'\n ? undefined\n : llm.listProviders().map(p => p.id)\n } catch { return undefined }\n }\n const disposeTools = registerTaskboardTools(ctx, {\n store,\n workspaces,\n now,\n modelProviders,\n ready: async () => {\n if (activeWorkspaces === undefined) {\n throw new ToolError(ERR.notReady, 'workspace service is not ready; retry after host startup completes')\n }\n await storeReady\n },\n })\n ctx.effect(() => () => {\n for (const dispose of disposeTools.splice(0)) dispose()\n }, 'dsh-taskboard: tools')\n\n // Runtime services come and go with the workspace registry. Tool schemas\n // remain mounted and resolve this current service only when called.\n ctx.inject(['workspaceRegistry'], (wsCtx: Context) => {\n const workspaceDisposers: Array<() => void> = []\n activeWorkspaces = workspaceFace(wsCtx.workspaceRegistry)\n activeWorkspaceContext = wsCtx\n\n // Settlement listener over the session event bus.\n const events: EventsFace = {\n onSessionEvent: (listener) => wsCtx.on('session/event', (session, event) => {\n listener(session.id, event as { type: string; data?: unknown }, session as never)\n }),\n }\n\n let agentSessions: { get?: (id: string) => unknown; list?: () => unknown[] } | undefined\n\n // External workspace sessions sync service (0.5.4).\n const sessionSync = new ExternalSessionSyncService({\n store,\n workspaces: workspaceFace(wsCtx.workspaceRegistry),\n events,\n sessions: {\n get: id => {\n try {\n const registry = (agentSessions ?? wsCtx.get('sessions') ?? wsCtx.get('sessionRegistry') ?? wsCtx.root?.get('sessions')) as { get?: (id: string) => unknown } | undefined\n return registry?.get?.(id)\n } catch { return undefined }\n },\n list: () => {\n try {\n const registry = (agentSessions ?? wsCtx.get('sessions') ?? wsCtx.get('sessionRegistry') ?? wsCtx.root?.get('sessions')) as { list?: () => unknown[] } | undefined\n return registry?.list?.() ?? []\n } catch { return [] }\n },\n },\n now,\n })\n workspaceDisposers.push(() => sessionSync.dispose())\n\n // The narrow git face shared by execution (worktree isolation) and the\n // routes (merge / remove / workspace detection), plus the shared\n // nested-repo scanner for multi-repo mirrors (0.6.3).\n const git = createGitFace()\n const scanner = createRepoScanner()\n\n wsCtx.inject(['agents'], (agentCtx: Context) => {\n const agentDisposers: Array<() => void> = []\n agentSessions = agentCtx.get('sessions') as { get?: (id: string) => unknown; list?: () => unknown[] } | undefined\n const execution = new ExecutionService({\n store,\n agents: {\n create: (options): Promise<never> => agentCtx.agents.create(options as never) as Promise<never>,\n },\n workspaces: {\n get: id => workspaceFace(wsCtx.workspaceRegistry).get(id),\n attach: async (workspaceId, sessionId) => {\n const ws = wsCtx.workspaceRegistry.get(workspaceId as never)\n if (ws !== undefined) await ws.attachSession(sessionId as never)\n },\n },\n events,\n now,\n git,\n scanner,\n // Preset composition (0.3.3): mirror apiproxy's composeAgent — resolve\n // the id BEFORE creation (the session header snapshots meta), mount\n // inside the factory's setup callback. No roster service → undefined\n // (bare host composition, the pre-preset behavior).\n composeAgent: async (presetId) => {\n const presets = agentCtx.get('agentPresets') as {\n resolve(id?: string): Promise<{ id: string }>\n mount(agentCtx: unknown, id?: string): Promise<unknown>\n } | undefined\n if (presets === undefined) return undefined\n const resolved = await presets.resolve(presetId)\n return {\n agentPreset: resolved.id,\n setup: async (ctx: unknown) => { await presets.mount(ctx, resolved.id) },\n }\n },\n renameSession: (sessionId, title) => {\n // Best-effort: pin the execution session's title to the task title\n // through the log-backed session-title service (user-sourced rename).\n try {\n const sessions = agentCtx.get('sessions') as { get(id: string): unknown } | undefined\n const sessionTitle = agentCtx.get('sessionTitle') as { rename(session: unknown, title: string): unknown } | undefined\n const session = sessions?.get(sessionId)\n if (session !== undefined && sessionTitle !== undefined) sessionTitle.rename(session, title)\n } catch { /* cosmetic */ }\n },\n defaultModel: () => {\n try {\n const selection = agentCtx.get('agentDefaultModel') as { currentSelection?: () => { provider: string; model: string } | undefined } | undefined\n const read = selection?.currentSelection\n return read === undefined ? undefined : read.call(selection)\n } catch { return undefined }\n },\n setPermission: (sessionId, permission) => {\n try {\n const permService = agentCtx.get('permissionPresets') as { set(session: unknown, name: string): void } | undefined\n const sessions = agentCtx.get('sessions') as { get(id: string): unknown } | undefined\n const session = sessions?.get(sessionId)\n if (session !== undefined && permService !== undefined) {\n permService.set(session, permission)\n }\n } catch { /* cosmetic */ }\n },\n maxConcurrent,\n })\n\n // /dsh-taskboard routes (the run action reaches the execution service).\n let disposeRoutes: (() => void) | undefined\n agentCtx.inject(['webServer'], (webCtx: Context) => {\n disposeRoutes = registerTaskboardRoutes(webCtx, {\n store,\n workspaces: workspaceFace(wsCtx.workspaceRegistry),\n now,\n run: (taskId: string, runOptions?: { reuseWorktree?: boolean }) => execution.run(taskId, 'manual', runOptions),\n cancel: (taskId: string) => execution.cancel(taskId),\n modelProviders,\n git,\n scanner,\n templates,\n assets,\n storage,\n ready: async () => { await storeReady },\n promptCompletions: async () => {\n try {\n const skillsService = agentCtx.get('skills') as { list?(options?: unknown): Promise<Array<{ name: string; description?: string }>> } | undefined\n const commandsService = agentCtx.get('commands') as { list?(): Array<{ name: string; description?: string; input?: { hint?: string } }> } | undefined\n const rawSkills = skillsService?.list ? await skillsService.list().catch(() => []) : []\n const rawCommands = commandsService?.list ? commandsService.list() : []\n return {\n skills: Array.isArray(rawSkills) ? rawSkills.map(s => ({ name: s.name, description: s.description })) : [],\n commands: Array.isArray(rawCommands) ? rawCommands.map(c => ({ name: c.name, description: c.description, hint: c.input?.hint })) : [],\n }\n } catch {\n return { skills: [], commands: [] }\n }\n },\n modelCatalog: async () => {\n try {\n type ModelItem = {\n provider: string\n model: string\n name?: string\n description?: string\n reasoning?: {\n efforts: Array<{ id: string; name: string; description?: string }>\n defaultEffort?: string\n }\n }\n const models: ModelItem[] = []\n\n const llm = (agentCtx.get('llm') ?? wsCtx.get('llm')) as {\n listProviders?(): Array<{ id: string; name?: string }>\n listModels?(provider: string): Promise<Array<{ id: string; name?: string; description?: string }>>\n resolveModelInfo?(provider: string, model: string): Promise<{ reasoning?: { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort?: string } }>\n resolveModel?(provider: string, model: string): Promise<{ reasoning?: { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort?: string } }>\n } | undefined\n\n if (llm?.listProviders !== undefined && llm.listModels !== undefined) {\n const providers = llm.listProviders()\n for (const p of providers) {\n try {\n const list = await llm.listModels(p.id)\n for (const m of list) {\n let reasoning: { efforts: Array<{ id: string; name: string; description?: string }>; defaultEffort?: string } | undefined\n try {\n const meta = llm.resolveModelInfo !== undefined\n ? await llm.resolveModelInfo(p.id, m.id)\n : llm.resolveModel !== undefined ? await llm.resolveModel(p.id, m.id) : undefined\n if (meta?.reasoning !== undefined) {\n reasoning = meta.reasoning\n }\n } catch { /* ignore */ }\n\n models.push({\n provider: p.id,\n model: m.id,\n name: m.name,\n ...(m.description ? { description: m.description } : {}),\n ...(reasoning !== undefined ? { reasoning } : {}),\n })\n }\n } catch { /* continue */ }\n }\n }\n\n const presetsService = agentCtx.get('agentPresets') as {\n list?(): Promise<{ ok: boolean; value?: { presets: Array<{ id: string; name?: string; isDefault?: boolean }> } } | Array<{ id: string; name?: string; isDefault?: boolean }>>\n } | undefined\n const presets: Array<{ id: string; name?: string }> = []\n let defaultPresetId: string | undefined\n\n if (presetsService?.list !== undefined) {\n try {\n const raw = await presetsService.list()\n const list = (raw as { ok?: boolean; value?: { presets?: unknown[] } }).ok === true\n ? (raw as { value: { presets: Array<{ id: string; name?: string; isDefault?: boolean }> } }).value.presets\n : Array.isArray(raw) ? raw : []\n for (const p of list) {\n presets.push({ id: p.id, name: p.name })\n if (p.isDefault) defaultPresetId = p.id\n }\n } catch { /* continue */ }\n }\n\n return { models, presets, ...(defaultPresetId !== undefined ? { defaultPresetId } : {}) }\n } catch {\n return { models: [], presets: [] }\n }\n },\n })\n return () => disposeRoutes?.()\n })\n\n // Startup reconciliation: executions left 'running' by a previous host\n // process are marked failed and their tasks handed back to todo (their\n // settlement watchers died with that process).\n void execution.reconcile()\n\n // Host-side cron scheduler: due scheduled tasks execute even with no\n // browser open. Shares the execution concurrency cap.\n const scheduler = new SchedulerService({ store, execution, now, maxConcurrent })\n scheduler.start()\n agentDisposers.push(() => scheduler.dispose())\n // Detach the settlement listener with the plugin — a hot reload must\n // not leave stale services reacting to turn/end errors (review P1).\n agentDisposers.push(() => execution.dispose())\n\n return () => {\n disposeRoutes?.()\n agentSessions = undefined\n for (const dispose of agentDisposers.splice(0)) dispose()\n }\n })\n\n return () => {\n if (activeWorkspaceContext === wsCtx) {\n activeWorkspaceContext = undefined\n activeWorkspaces = undefined\n }\n for (const dispose of workspaceDisposers.splice(0)) dispose()\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoCA,MAAa,cAAc;;AAG3B,MAAa,iBAAiB;;AAG9B,MAAa,aAAa;;AAG1B,MAAa,OAAO;;AAGpB,MAAa,SAAS,CAAC,SAAS,cAAc;;;;;AAM9C,SAAgB,MAAM,KAAoB;CACxC,MAAM,UAAU,IAAI,mBAAmB;EACrC,kBAAkB,YAAY;EAC9B,YAAY,YAAY,mBAAmB;EAC3C,YAAY;EACZ,eAAe;EACf,YAAY;CACd,CAAC;CACD,MAAM,QAAQ,IAAI,UAAU;EAAE,MAAM,QAAQ,WAAW;EAAG,OAAO,QAAQ;CAAM,CAAC;CAChF,MAAM,YAAY,IAAI,cAAc,QAAQ,cAAc,GAAG,QAAQ,KAAK;CAC1E,MAAM,SAAS,IAAI,WAAW,QAAQ,WAAW,SAAS,KAAK,IAAI,GAAG,QAAQ,KAAK;CACnF,QAAQ,OAAO;EAAE,QAAQ;EAAO;EAAW;CAAO,CAAC;CAMnD,MAAM,aAAa,QAAQ,MAAM,CAAC,CAAC,WAAW,MAAM,KAAK,CAAC;CAC1D,WAAgB,WAAW,OAAO,QAAQ,KAAK,UAAU,MAAM,SAAS,CAAC,CAAC,CAA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