@open-mercato/cezar 0.9.1 → 0.9.2-pr780.1061
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 +29 -11
- package/dist/agent-config/account-identity.d.ts +44 -0
- package/dist/agent-config/account-identity.js +128 -0
- package/dist/agent-config/account-identity.js.map +1 -0
- package/dist/agent-config/catalog.d.ts +9 -1
- package/dist/agent-config/catalog.js +18 -0
- package/dist/agent-config/catalog.js.map +1 -1
- package/dist/agent-config/files.d.ts +1 -1
- package/dist/agent-config/model-settings/claude.d.ts +2 -0
- package/dist/agent-config/model-settings/claude.js +11 -0
- package/dist/agent-config/model-settings/claude.js.map +1 -0
- package/dist/agent-config/model-settings/codex.d.ts +2 -0
- package/dist/agent-config/model-settings/codex.js +16 -0
- package/dist/agent-config/model-settings/codex.js.map +1 -0
- package/dist/agent-config/model-settings/opencode.d.ts +2 -0
- package/dist/agent-config/model-settings/opencode.js +8 -0
- package/dist/agent-config/model-settings/opencode.js.map +1 -0
- package/dist/agent-config/model-settings/shared.d.ts +9 -0
- package/dist/agent-config/model-settings/shared.js +93 -0
- package/dist/agent-config/model-settings/shared.js.map +1 -0
- package/dist/agent-config/model-settings/types.d.ts +9 -0
- package/dist/agent-config/model-settings/types.js +2 -0
- package/dist/agent-config/model-settings/types.js.map +1 -0
- package/dist/agent-config/models.d.ts +9 -0
- package/dist/agent-config/models.js +30 -0
- package/dist/agent-config/models.js.map +1 -0
- package/dist/agent-config/service.d.ts +1 -1
- package/dist/agent-config/service.js +4 -4
- package/dist/agent-config/service.js.map +1 -1
- package/dist/agent-config/validate.d.ts +1 -1
- package/dist/automations/coordinator.d.ts +26 -0
- package/dist/automations/coordinator.js +66 -0
- package/dist/automations/coordinator.js.map +1 -0
- package/dist/automations/github-poller.d.ts +74 -0
- package/dist/automations/github-poller.js +234 -0
- package/dist/automations/github-poller.js.map +1 -0
- package/dist/automations/scheduler.d.ts +42 -0
- package/dist/automations/scheduler.js +192 -0
- package/dist/automations/scheduler.js.map +1 -0
- package/dist/automations/store.d.ts +65 -0
- package/dist/automations/store.js +298 -0
- package/dist/automations/store.js.map +1 -0
- package/dist/automations/task-template.d.ts +18 -0
- package/dist/automations/task-template.js +95 -0
- package/dist/automations/task-template.js.map +1 -0
- package/dist/automations/types.d.ts +251 -0
- package/dist/automations/types.js +158 -0
- package/dist/automations/types.js.map +1 -0
- package/dist/config.d.ts +17 -112
- package/dist/config.js +45 -4
- package/dist/config.js.map +1 -1
- package/dist/contract/agent-config.d.ts +151 -0
- package/dist/contract/agent-profiles.d.ts +332 -0
- package/dist/contract/automations.d.ts +919 -0
- package/dist/contract/events.d.ts +45 -0
- package/dist/contract/github.d.ts +467 -0
- package/dist/contract/health.d.ts +96 -0
- package/dist/contract/index.d.ts +16 -0
- package/dist/contract/index.js +1593 -0
- package/dist/contract/projects.d.ts +185 -0
- package/dist/contract/repo.d.ts +234 -0
- package/dist/contract/runs.d.ts +1239 -0
- package/dist/contract/skills.d.ts +227 -0
- package/dist/contract/workflows.d.ts +212 -0
- package/dist/contract/workspace.d.ts +470 -0
- package/dist/core/agent-env.d.ts +1 -1
- package/dist/core/agent-model-policy.d.ts +10 -0
- package/dist/core/agent-model-policy.js +36 -0
- package/dist/core/agent-model-policy.js.map +1 -0
- package/dist/core/agent-profiles.d.ts +59 -0
- package/dist/core/agent-profiles.js +83 -0
- package/dist/core/agent-profiles.js.map +1 -0
- package/dist/core/agent-runner.d.ts +12 -1
- package/dist/core/agent-runner.js +13 -0
- package/dist/core/agent-runner.js.map +1 -1
- package/dist/core/ask.d.ts +45 -124
- package/dist/core/ask.js +103 -13
- package/dist/core/ask.js.map +1 -1
- package/dist/core/backend-detect.js +7 -2
- package/dist/core/backend-detect.js.map +1 -1
- package/dist/core/claude-cli-runner.d.ts +2 -2
- package/dist/core/claude-cli-runner.js +52 -9
- package/dist/core/claude-cli-runner.js.map +1 -1
- package/dist/core/claude-ui-mapper.d.ts +1 -1
- package/dist/core/codex-app-server-runner.d.ts +1 -1
- package/dist/core/codex-app-server-runner.js +60 -3
- package/dist/core/codex-app-server-runner.js.map +1 -1
- package/dist/core/codex-app-server-transport.d.ts +6 -1
- package/dist/core/codex-app-server-transport.js +12 -3
- package/dist/core/codex-app-server-transport.js.map +1 -1
- package/dist/core/codex-model-catalog.d.ts +1 -1
- package/dist/core/codex-ui-mapper.d.ts +5 -1
- package/dist/core/codex-ui-mapper.js +74 -17
- package/dist/core/codex-ui-mapper.js.map +1 -1
- package/dist/core/model-identity.d.ts +13 -6
- package/dist/core/model-identity.js +32 -17
- package/dist/core/model-identity.js.map +1 -1
- package/dist/core/model-presets.d.ts +2 -2
- package/dist/core/model-presets.js +1 -1
- package/dist/core/opencode-server-runner.d.ts +2 -2
- package/dist/core/opencode-ui-mapper.d.ts +4 -1
- package/dist/core/opencode-ui-mapper.js +45 -7
- package/dist/core/opencode-ui-mapper.js.map +1 -1
- package/dist/core/provider-auth.d.ts +154 -0
- package/dist/core/provider-auth.js +488 -0
- package/dist/core/provider-auth.js.map +1 -0
- package/dist/core/provider-availability.d.ts +3 -0
- package/dist/core/provider-availability.js +14 -0
- package/dist/core/provider-availability.js.map +1 -0
- package/dist/core/runner-factory.d.ts +1 -1
- package/dist/core/runner-model-catalog.d.ts +1 -1
- package/dist/core/shell-env.d.ts +28 -0
- package/dist/core/shell-env.js +56 -0
- package/dist/core/shell-env.js.map +1 -0
- package/dist/core/tool-display.d.ts +1 -1
- package/dist/core/ui-events.d.ts +1 -1
- package/dist/core/ui-events.js +1 -1
- package/dist/git-diff-base.d.ts +60 -0
- package/dist/git-diff-base.js +54 -0
- package/dist/git-diff-base.js.map +1 -0
- package/dist/git-worktree.d.ts +37 -6
- package/dist/git-worktree.js +39 -9
- package/dist/git-worktree.js.map +1 -1
- package/dist/handoff.d.ts +2 -2
- package/dist/handoff.js +1 -1
- package/dist/index.js +65 -8
- package/dist/index.js.map +1 -1
- package/dist/paths.d.ts +69 -6
- package/dist/paths.js +86 -9
- package/dist/paths.js.map +1 -1
- package/dist/planner.d.ts +2 -2
- package/dist/planner.js +7 -1
- package/dist/planner.js.map +1 -1
- package/dist/release/manifests.d.ts +81 -0
- package/dist/release/manifests.js +74 -0
- package/dist/release/manifests.js.map +1 -0
- package/dist/release/snapshot.d.ts +9 -23
- package/dist/release/snapshot.js +9 -22
- package/dist/release/snapshot.js.map +1 -1
- package/dist/release/stable.d.ts +15 -29
- package/dist/release/stable.js +14 -27
- package/dist/release/stable.js.map +1 -1
- package/dist/runs/auto-name.d.ts +1 -1
- package/dist/runs/auto-name.js +6 -1
- package/dist/runs/auto-name.js.map +1 -1
- package/dist/runs/retention.d.ts +1 -1
- package/dist/runs/store.d.ts +147 -336
- package/dist/runs/store.js +148 -9
- package/dist/runs/store.js.map +1 -1
- package/dist/runs/ui-event-sink.d.ts +1 -1
- package/dist/server/app-type.d.ts +21 -0
- package/dist/server/app-type.js +2 -0
- package/dist/server/app-type.js.map +1 -0
- package/dist/server/capabilities.d.ts +6 -5
- package/dist/server/capabilities.js +11 -0
- package/dist/server/capabilities.js.map +1 -1
- package/dist/server/forge/github.d.ts +58 -151
- package/dist/server/forge/github.js +530 -6
- package/dist/server/forge/github.js.map +1 -1
- package/dist/server/forge/index.d.ts +10 -3
- package/dist/server/forge/index.js +14 -1
- package/dist/server/forge/index.js.map +1 -1
- package/dist/server/forge/types.d.ts +86 -1
- package/dist/server/git-changes.d.ts +8 -8
- package/dist/server/git-changes.js +14 -17
- package/dist/server/git-changes.js.map +1 -1
- package/dist/server/git.d.ts +2 -0
- package/dist/server/git.js +9 -0
- package/dist/server/git.js.map +1 -1
- package/dist/server/github.d.ts +3 -3
- package/dist/server/github.js +1 -1
- package/dist/server/github.js.map +1 -1
- package/dist/server/open-in-terminal.d.ts +8 -1
- package/dist/server/open-in-terminal.js +16 -8
- package/dist/server/open-in-terminal.js.map +1 -1
- package/dist/server/pr.d.ts +2 -2
- package/dist/server/project-context.d.ts +20 -3
- package/dist/server/project-context.js +30 -1
- package/dist/server/project-context.js.map +1 -1
- package/dist/server/provider-action-gate.d.ts +8 -0
- package/dist/server/provider-action-gate.js +54 -0
- package/dist/server/provider-action-gate.js.map +1 -0
- package/dist/server/provider-auth-runtime.d.ts +21 -0
- package/dist/server/provider-auth-runtime.js +66 -0
- package/dist/server/provider-auth-runtime.js.map +1 -0
- package/dist/server/server.d.ts +11958 -47
- package/dist/server/server.js +2612 -923
- package/dist/server/server.js.map +1 -1
- package/dist/server/validators.d.ts +97 -0
- package/dist/server/validators.js +86 -0
- package/dist/server/validators.js.map +1 -0
- package/dist/server/ws.d.ts +2 -2
- package/dist/server/ws.js +2 -2
- package/dist/server/ws.js.map +1 -1
- package/dist/server-install/engine.d.ts +1 -1
- package/dist/server-install/platforms/macosx-ngrok.d.ts +1 -1
- package/dist/server-install/platforms/ubuntu-vps.d.ts +16 -1
- package/dist/server-install/platforms/ubuntu-vps.js +83 -1
- package/dist/server-install/platforms/ubuntu-vps.js.map +1 -1
- package/dist/server-install/state.d.ts +1 -1
- package/dist/server-install/steps.d.ts +2 -2
- package/dist/server-install/strategies.d.ts +1 -1
- package/dist/server-install/types.d.ts +38 -424
- package/dist/server-install/ui.d.ts +1 -1
- package/dist/skills-banner.d.ts +7 -6
- package/dist/skills-banner.js +7 -6
- package/dist/skills-banner.js.map +1 -1
- package/dist/skills-remote.d.ts +2 -2
- package/dist/skills-update.d.ts +88 -0
- package/dist/skills-update.js +392 -0
- package/dist/skills-update.js.map +1 -0
- package/dist/skills.d.ts +2 -0
- package/dist/skills.js +7 -2
- package/dist/skills.js.map +1 -1
- package/dist/todos.d.ts +2 -28
- package/dist/todos.js +1 -1
- package/dist/ui-state.d.ts +16 -2
- package/dist/ui-state.js +14 -1
- package/dist/ui-state.js.map +1 -1
- package/dist/workflows/load.d.ts +1 -1
- package/dist/workflows/run.d.ts +76 -12
- package/dist/workflows/run.js +528 -71
- package/dist/workflows/run.js.map +1 -1
- package/dist/workflows/types.d.ts +59 -224
- package/dist/workflows/types.js +14 -0
- package/dist/workflows/types.js.map +1 -1
- package/dist/workspace/agent-accounts.d.ts +149 -0
- package/dist/workspace/agent-accounts.js +303 -0
- package/dist/workspace/agent-accounts.js.map +1 -0
- package/dist/workspace/agent-profiles.d.ts +78 -0
- package/dist/workspace/agent-profiles.js +115 -0
- package/dist/workspace/agent-profiles.js.map +1 -0
- package/dist/workspace/config.d.ts +81 -206
- package/dist/workspace/config.js +175 -14
- package/dist/workspace/config.js.map +1 -1
- package/dist/workspace/migrations.d.ts +1 -1
- package/dist/workspace/migrations.js +19 -4
- package/dist/workspace/migrations.js.map +1 -1
- package/dist/workspace/projects.d.ts +8 -2
- package/dist/workspace/projects.js +9 -3
- package/dist/workspace/projects.js.map +1 -1
- package/dist/workspace/semaphore.d.ts +6 -0
- package/dist/workspace/semaphore.js +14 -1
- package/dist/workspace/semaphore.js.map +1 -1
- package/dist/workspace/ui-state.d.ts +13 -3
- package/dist/workspace/ui-state.js +15 -5
- package/dist/workspace/ui-state.js.map +1 -1
- package/package.json +17 -39
- package/scripts/inline-contract.mjs +112 -0
- package/scripts/mock-claude.mjs +39 -1
- package/scripts/sync-readme.mjs +20 -0
- package/web/dist/assets/alert-dialog-CCX7vbLv.js +1 -0
- package/web/dist/assets/arrow-down-DXSvIdBy.js +1 -0
- package/web/dist/assets/arrow-left-CH1QDJ9J.js +1 -0
- package/web/dist/assets/bundle-mjs-BT31bpU6.js +1 -0
- package/web/dist/assets/centered-state-CXI997hI.js +43 -0
- package/web/dist/assets/chevron-right-Djmw1pir.js +1 -0
- package/web/dist/assets/{chunk-BO2N2NFS-DtrdTCWa.js → chunk-BO2N2NFS-DE6qKn3r.js} +8 -8
- package/web/dist/assets/circle-check-DJRWwnU0.js +1 -0
- package/web/dist/assets/circle-x-aJMtmDfr.js +1 -0
- package/web/dist/assets/collapsible-Btoo8CMa.js +1 -0
- package/web/dist/assets/commit-list-Cj3KHeTw.js +1 -0
- package/web/dist/assets/compare-variants-twOpd5eU.js +1 -0
- package/web/dist/assets/{core-DePtBHcl.js → core-BCsw8oQw.js} +1 -1
- package/web/dist/assets/diff-DEY8e-KQ.js +3 -0
- package/web/dist/assets/diff-stat-Coewcn_A.js +1 -0
- package/web/dist/assets/{diff-view-DCeSegKk.js → diff-view-DmqZuw0o.js} +4 -4
- package/web/dist/assets/dropdown-menu-C4IVZ4Cy.js +1 -0
- package/web/dist/assets/editable-title-B5Nz9Ifq.js +1 -0
- package/web/dist/assets/{ellipsis-vertical-CNnSLn5a.js → ellipsis-vertical-CFm090OY.js} +1 -1
- package/web/dist/assets/{file-D4GBh1ao.js → file-ChFcXCdF.js} +1 -1
- package/web/dist/assets/folder-JGQS95UK.js +1 -0
- package/web/dist/assets/{git-pull-request-DnR8Xh4_.js → git-pull-request-5QyNQHb4.js} +1 -1
- package/web/dist/assets/git-toolbar-BSAiDPXd.js +1 -0
- package/web/dist/assets/github-DnS2irZI.js +1 -0
- package/web/dist/assets/highlighted-body-OFNGDK62-BL-MfFgl.js +1 -0
- package/web/dist/assets/highlighter-CdHqIwFr.js +3 -0
- package/web/dist/assets/image-preview-DmcNMtBK.js +1 -0
- package/web/dist/assets/index-B84F80Q8.css +2 -0
- package/web/dist/assets/index-BohAT06J.js +6 -0
- package/web/dist/assets/lib-BQXq3kEf.js +1 -0
- package/web/dist/assets/lib-BxQXEXDF.js +1 -0
- package/web/dist/assets/markdown-DFnhId9R.js +2 -0
- package/web/dist/assets/mermaid-GHXKKRXX-C4jxqUUb.js +1 -0
- package/web/dist/assets/new-task-form-Dem8-EfF.js +1 -0
- package/web/dist/assets/pill-Bughljxv.js +1 -0
- package/web/dist/assets/project-router-DBpBMLHW.js +1 -0
- package/web/dist/assets/prompt-templates-Cj7wWXn2.js +15 -0
- package/web/dist/assets/react-runtime-CCIEwYL0.js +9 -0
- package/web/dist/assets/{refresh-cw-BT8E96Tm.js → refresh-cw-BWZQNIR7.js} +1 -1
- package/web/dist/assets/repo-git-Dhm-EROZ.js +1 -0
- package/web/dist/assets/rolldown-runtime-QTnfLwEv.js +1 -0
- package/web/dist/assets/run-diff-CXcSp_gT.js +3 -0
- package/web/dist/assets/run-header-CRr16SfL.js +1 -0
- package/web/dist/assets/{search-x-BDjaMrzG.js → search-x-BIhOTY_E.js} +1 -1
- package/web/dist/assets/skill-empty-hint-BN_ePNxo.js +1 -0
- package/web/dist/assets/skills-BiWfHmCR.js +1 -0
- package/web/dist/assets/skills-Cxj8xuN8.js +1 -0
- package/web/dist/assets/sparkles-CZEWgaOW.js +1 -0
- package/web/dist/assets/{square-terminal-Ckjjn0vb.js → square-terminal-B4KCKyUb.js} +1 -1
- package/web/dist/assets/tab-link-CYoA7evO.js +1 -0
- package/web/dist/assets/task-changes-BRkjXilr.js +1 -0
- package/web/dist/assets/task-commits-Bs8tVHdp.js +1 -0
- package/web/dist/assets/task-files-B83mmDc7.js +2 -0
- package/web/dist/assets/task-thread-B8SnpMda.js +9 -0
- package/web/dist/assets/textarea-GBSG043_.js +1 -0
- package/web/dist/assets/thread-loading-D-W1aDRr.js +1 -0
- package/web/dist/assets/{trash-2-DAyZ0VSi.js → trash-2-DscaMdyt.js} +1 -1
- package/web/dist/assets/{triangle-alert-Uy8rokUh.js → triangle-alert-DG4Zrdw_.js} +1 -1
- package/web/dist/assets/{upload-CDdyPPo_.js → upload-V_HWlzmF.js} +1 -1
- package/web/dist/assets/use-desktop-BeTfs42t.js +1 -0
- package/web/dist/assets/use-submit-shortcut-ceAGZrbH.js +1 -0
- package/web/dist/assets/utils-Dh89nMsg.js +64 -0
- package/web/dist/assets/workflows-LuXn4DOU.js +11 -0
- package/web/dist/assets/zoomable-image-DBPkskS9.js +1 -0
- package/web/dist/index.html +33 -13
- package/scripts/dev.mjs +0 -74
- package/scripts/release-snapshot.mjs +0 -130
- package/scripts/release.mjs +0 -119
- package/web/dist/assets/arrow-left-CnSdp92h.js +0 -1
- package/web/dist/assets/bundle-mjs-BegPhL5c.js +0 -1
- package/web/dist/assets/centered-state-DOsTcJZF.js +0 -43
- package/web/dist/assets/commit-list-BrxBEzRK.js +0 -1
- package/web/dist/assets/compare-variants-Bv2c9ORF.js +0 -1
- package/web/dist/assets/dist-B6XQOhgM.js +0 -1
- package/web/dist/assets/git-toolbar-pIC1ubPM.js +0 -1
- package/web/dist/assets/github-DTTSG0ht.js +0 -1
- package/web/dist/assets/highlighted-body-OFNGDK62-BuFJwunK.js +0 -1
- package/web/dist/assets/image-preview-DEhW0TFz.js +0 -1
- package/web/dist/assets/index-Cijmlz7q.js +0 -30
- package/web/dist/assets/index-DzroxqBG.css +0 -2
- package/web/dist/assets/lib-DPEZDBUN.js +0 -1
- package/web/dist/assets/lib-uHpeUPzK.js +0 -1
- package/web/dist/assets/mermaid-GHXKKRXX-CN2zQue0.js +0 -1
- package/web/dist/assets/open-mercato-toBr6SOa.svg +0 -11
- package/web/dist/assets/project-router-BMx4e8m-.js +0 -1
- package/web/dist/assets/repo-git-BusYfa3t.js +0 -1
- package/web/dist/assets/run-diff-wOJ3odA-.js +0 -3
- package/web/dist/assets/run-header-Cg5incil.js +0 -1
- package/web/dist/assets/skill-empty-hint-DTUSp6Vl.js +0 -1
- package/web/dist/assets/skills-PpP2owbM.js +0 -1
- package/web/dist/assets/tab-link-F3uQrdm2.js +0 -1
- package/web/dist/assets/task-changes-iD9kS79I.js +0 -1
- package/web/dist/assets/task-commits-COkLaUri.js +0 -1
- package/web/dist/assets/task-files-Ckttz7XH.js +0 -2
- package/web/dist/assets/task-thread-CQD91VPt.js +0 -9
- package/web/dist/assets/textarea-Bj_LCreg.js +0 -1
- package/web/dist/assets/use-desktop-DUh0STzq.js +0 -3
- package/web/dist/assets/utils-B8s5qIcK.js +0 -1
- package/web/dist/assets/workflows-BFk8C0co.js +0 -11
- package/web/dist/assets/zoomable-image-PEDOqyLQ.js +0 -1
- /package/web/{open-mercato.svg → dist/open-mercato.svg} +0 -0
package/dist/server/server.js
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { AutomationStore } from '../automations/store.js';
|
|
4
|
+
import { AutomationCoordinator } from '../automations/coordinator.js';
|
|
5
|
+
import { GithubPoller } from '../automations/github-poller.js';
|
|
6
|
+
import { ProjectAutomationScheduler, WorkspaceAutomationScheduler } from '../automations/scheduler.js';
|
|
7
|
+
import { launchAutomationRun, reconcileAutomationReceipts, validateAutomationPrompt } from '../automations/task-template.js';
|
|
8
|
+
import { automationEventSchema, automationFiltersSchema, automationLogResultSchema, automationTaskSchema, } from '../automations/types.js';
|
|
2
9
|
import { access, constants as fsConstants, mkdir, readFile, realpath, stat, unlink, writeFile } from 'node:fs/promises';
|
|
3
10
|
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
4
11
|
import { fileURLToPath } from 'node:url';
|
|
@@ -6,16 +13,21 @@ import { Hono } from 'hono';
|
|
|
6
13
|
import { serve } from '@hono/node-server';
|
|
7
14
|
import { bodyLimit } from 'hono/body-limit';
|
|
8
15
|
import { streamSSE } from 'hono/streaming';
|
|
16
|
+
import { jsonZodValidator, paramZodValidator, queryZodValidator } from './validators.js';
|
|
9
17
|
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
|
10
18
|
import { z } from 'zod';
|
|
11
19
|
import { detectEnvironment } from '../core/backend-detect.js';
|
|
20
|
+
import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
|
|
12
21
|
import { discoverCodexModels } from '../core/codex-model-catalog.js';
|
|
22
|
+
import { PROVIDER_IDS, ProviderAuthService, providerAuthChecksDisabled, } from '../core/provider-auth.js';
|
|
23
|
+
import { applyProviderEnablement } from '../core/provider-availability.js';
|
|
13
24
|
import { RunnerModelCatalog } from '../core/runner-model-catalog.js';
|
|
14
25
|
import { currentUsage, onUsage } from '../core/process-usage.js';
|
|
15
26
|
import { WORKFLOWS_DIR, loadWorkflows } from '../workflows/load.js';
|
|
16
27
|
import { QUICK_TASK_WORKFLOW, normalizeWorkflowDoc, skillStackOf, skillsToSteps, stepsIssue, workflowFileSchema, workflowStepSchema, } from '../workflows/types.js';
|
|
17
28
|
import { planChain, slugify } from '../planner.js';
|
|
18
29
|
import { discoverSkills } from '../skills.js';
|
|
30
|
+
import { SkillsUpdateConflictError, SkillsUpdateCoordinator, SkillsUpdateService } from '../skills-update.js';
|
|
19
31
|
import { getTeamSkillsCached, refreshTeamSkills, waitForTeamSkills } from '../skills-remote.js';
|
|
20
32
|
import { appendHandoffHeartbeat, handoffProgressExcerpt, readHandoff } from '../handoff.js';
|
|
21
33
|
import { markStarted, onTodosChanged, readTodos, removeTodo, todoTaskText } from '../todos.js';
|
|
@@ -26,47 +38,157 @@ import { getBranches, getCommit, getDiff, getLog, getRepoInfo, getStatus } from
|
|
|
26
38
|
import { collectChanges, collectCommitChanges, collectRunCommits, commitAll, createOrSwitchBranch, imageMimeType, isOsOpenableImage, pushCurrentBranch, readWorktreePath, } from './git-changes.js';
|
|
27
39
|
import { gatedSkillsRepos, loadConfig, resolveWorktreeRetention } from '../config.js';
|
|
28
40
|
import { findConfigFile } from '../agent-config/catalog.js';
|
|
29
|
-
import { readConfigFile, writeConfigFile } from '../agent-config/files.js';
|
|
41
|
+
import { readConfigFile, statConfigPath, writeConfigFile } from '../agent-config/files.js';
|
|
42
|
+
import { readAgentModelDefaults } from '../agent-config/models.js';
|
|
30
43
|
import { listAgentConfig } from '../agent-config/service.js';
|
|
31
|
-
import {
|
|
44
|
+
import { listConfigFiles } from '../agent-config/catalog.js';
|
|
45
|
+
import { readAccountIdentity } from '../agent-config/account-identity.js';
|
|
46
|
+
import { PROJECT_ID_RE, defaultWorkspaceConfig, effectiveSkillsAutoUpdate, loadWorkspaceConfig, mergeWriteWorkspaceConfig, effectiveComposerDefault, } from '../workspace/config.js';
|
|
47
|
+
import { CONTROL_CHARS_RE, DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, isAbsoluteConfigDir, loadAgentAccounts, mergeWriteAgentAccounts, } from '../workspace/agent-accounts.js';
|
|
48
|
+
import { defaultAgentProfile, listAgentProfiles, profileDirState, resolveProfileEnvForRoot, resolveStoredProfile, sameProfileDir, } from '../workspace/agent-profiles.js';
|
|
49
|
+
import { PROFILE_CAPABLE_PROVIDERS, profileEnv, supportsProfiles } from '../core/agent-profiles.js';
|
|
50
|
+
import { withEnvPrefix } from '../core/shell-env.js';
|
|
32
51
|
import { allocateProjectSlug, listProjects, probeProjectStatus, registerProject, removeProject, shouldRegisterProject, } from '../workspace/projects.js';
|
|
33
52
|
import { mergeWriteWorkspaceUiState, readWorkspaceUiState } from '../workspace/ui-state.js';
|
|
34
53
|
import { checkoutRepo } from './checkout.js';
|
|
35
54
|
import { ProjectContextError, ProjectContexts } from './project-context.js';
|
|
36
55
|
import { reviewGateEnabled } from '../runs/review-gate.js';
|
|
37
56
|
import { readUiState, uiStatePath } from '../ui-state.js';
|
|
38
|
-
import { expandTilde } from '../paths.js';
|
|
57
|
+
import { agentHomePaths, expandTilde } from '../paths.js';
|
|
39
58
|
import { isLoopbackHostHeader, normalizeHostname, resolveCapabilities } from './capabilities.js';
|
|
40
59
|
import { createSocketHub } from './ws.js';
|
|
41
60
|
import { browseDirectory, isInsideBrowseRoot, isLexicallyInsideBrowseRoot, resolveBrowseRoot } from './fs-browse.js';
|
|
42
|
-
import { resolveForge } from './forge/index.js';
|
|
43
|
-
import { fetchGithub, fetchGithubComments } from './github.js';
|
|
61
|
+
import { parseRemote, resolveForge } from './forge/index.js';
|
|
62
|
+
import { fetchGithub, fetchGithubChecks, fetchGithubComments, fetchGithubPrDiff, GithubPrNotFoundError, GH_CHECKS_MAX } from './github.js';
|
|
44
63
|
import { ensureLaunchKey } from './launch-key.js';
|
|
45
64
|
import { openInTerminal } from './open-in-terminal.js';
|
|
46
65
|
import { agentCliRunner, detectOpenTargets, openFileInDefaultApp, openInApp } from './open-in-app.js';
|
|
47
66
|
import { createDraftPr } from './pr.js';
|
|
67
|
+
import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
|
|
68
|
+
import { providerForActiveRun, providerForExistingRun, providersRequiredByWorkflow, unavailableProviderMessage, } from './provider-action-gate.js';
|
|
48
69
|
import { ASSET_CACHE_CONTROL, BUILD_HINT_HTML, assetContentType, isSafeAssetFilename, resolveGetRequest, } from './static-ui.js';
|
|
49
70
|
/** `projectId` gate at the route boundary (spec "Project identity"): the slug
|
|
50
71
|
* shape or the reserved `default` alias — validated BEFORE touching any map
|
|
51
72
|
* or path. (`default` matches the slug regex too; the literal keeps the
|
|
52
73
|
* contract explicit.) */
|
|
53
74
|
const projectIdSchema = z.union([z.literal('default'), z.string().regex(PROJECT_ID_RE)]);
|
|
54
|
-
const
|
|
75
|
+
const providerConnectSchema = z.object({
|
|
76
|
+
provider: z.enum(PROVIDER_IDS),
|
|
77
|
+
/** Which agent account to sign in (spec 2026-07-29-agent-profiles). Absent = the discovered
|
|
78
|
+
* default, which is what every pre-profiles client sends. Without this, "Connect" on a second
|
|
79
|
+
* Claude account would open a login for the FIRST one and report success. */
|
|
80
|
+
profileId: z.string().max(64).optional(),
|
|
81
|
+
}).strict();
|
|
82
|
+
/** Agent-account bodies (spec 2026-07-29-agent-profiles). Bounds mirror `agentProfileSchema` in
|
|
83
|
+
* src/workspace/config.ts exactly, so a value these accept can never be degraded away by the
|
|
84
|
+
* next load's `.catch`. The id is allocated server-side and is never a request field. */
|
|
85
|
+
const createAgentProfileSchema = z.object({
|
|
86
|
+
provider: z.enum(PROVIDER_IDS),
|
|
87
|
+
label: z.string().trim().max(200).optional(),
|
|
88
|
+
configDir: z.string().trim().min(1).max(4096),
|
|
89
|
+
}).strict();
|
|
90
|
+
/** `POST …/agent-profiles/:id/open` — a catalog id (or `folder`) plus an optional open target. */
|
|
91
|
+
const openAgentAccountFileSchema = z.object({
|
|
92
|
+
file: z.string().min(1).max(200),
|
|
93
|
+
target: z.string().min(1).max(64).optional(),
|
|
94
|
+
}).strict();
|
|
95
|
+
const updateAgentProfileSchema = z.object({
|
|
96
|
+
label: z.string().trim().max(200).optional(),
|
|
97
|
+
configDir: z.string().trim().min(1).max(4096).optional(),
|
|
98
|
+
}).strict().refine((value) => value.label !== undefined || value.configDir !== undefined, 'send label or configDir');
|
|
99
|
+
/** `PUT …/agent-profiles/selection` — which account a project uses for one provider. `null`
|
|
100
|
+
* clears it back to the discovered account. */
|
|
101
|
+
const selectAgentProfileSchema = z.object({
|
|
102
|
+
/** `null` targets the machine-wide default rather than one repo. */
|
|
103
|
+
projectId: z.string().min(1).max(64).nullable(),
|
|
104
|
+
provider: z.enum(PROVIDER_IDS),
|
|
105
|
+
profileId: z.string().max(64).nullable(),
|
|
106
|
+
}).strict();
|
|
107
|
+
/** The hosted-mode refusal, worded like the agent-config one it mirrors. */
|
|
108
|
+
const hostedProfileRefusal = {
|
|
109
|
+
error: 'agent accounts are managed from the machine that owns the checkout (this cockpit runs in hosted mode)',
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Allocate a profile id from the label (or, with no label, the folder name).
|
|
113
|
+
*
|
|
114
|
+
* Reuses the project allocator's shape, and deliberately its reserved set too: `default` is the
|
|
115
|
+
* discovered profile here exactly as it is the boot alias there, so a folder called `default/`
|
|
116
|
+
* becomes `default-2` and can never shadow it.
|
|
117
|
+
*/
|
|
118
|
+
function allocateAgentProfileId(source, taken) {
|
|
119
|
+
// `allocateProjectSlug` already basenames its argument and enforces the shared
|
|
120
|
+
// `^[a-z0-9][a-z0-9-]{0,63}$` shape, so `~/.claude-klaudiusz` slugs to `claude-klaudiusz`.
|
|
121
|
+
return allocateProjectSlug(source, taken);
|
|
122
|
+
}
|
|
123
|
+
const providerParamSchema = z.enum(PROVIDER_IDS);
|
|
124
|
+
const providerEnabledSchema = z.object({ enabled: z.boolean() }).strict();
|
|
125
|
+
const providerRetrySchema = z.object({
|
|
126
|
+
authFailureId: z.string().min(1).max(128),
|
|
127
|
+
}).strict();
|
|
128
|
+
const automationEditableSchema = z
|
|
129
|
+
.object({
|
|
130
|
+
name: z.string().trim().min(1).max(200),
|
|
131
|
+
description: z.string().max(2_000).optional(),
|
|
132
|
+
enabled: z.boolean().optional(),
|
|
133
|
+
events: z.array(automationEventSchema).min(1).max(4),
|
|
134
|
+
intervalSeconds: z.number().int().min(60).max(86_400),
|
|
135
|
+
filters: automationFiltersSchema,
|
|
136
|
+
task: automationTaskSchema,
|
|
137
|
+
})
|
|
138
|
+
.strict();
|
|
139
|
+
const automationCreateSchema = automationEditableSchema.extend({ enable: z.boolean().optional() });
|
|
140
|
+
const automationUpdateSchema = automationEditableSchema.extend({ expectedRevision: z.number().int().positive() });
|
|
141
|
+
const automationCheckRequestSchema = z.object({ mode: z.enum(['preview', 'execute']) }).strict();
|
|
142
|
+
const automationLogQuerySchema = z.object({
|
|
143
|
+
automationId: z.string().optional(),
|
|
144
|
+
result: automationLogResultSchema.optional(),
|
|
145
|
+
event: automationEventSchema.optional(),
|
|
146
|
+
since: z.string().datetime().optional(),
|
|
147
|
+
cursor: z.coerce.number().int().positive().optional(),
|
|
148
|
+
// Optional, not `.default(100)`: `AutomationStore.logs` already clamps `limit ?? 100` into
|
|
149
|
+
// 1..100, so the default here was a second copy of it — and a defaulted key is REQUIRED in the
|
|
150
|
+
// request type `queryZodValidator` publishes (see validators.ts on why the request side falls
|
|
151
|
+
// back to the schema's output), which would have made every caller send a `?limit=` this route
|
|
152
|
+
// never needed.
|
|
153
|
+
limit: z.coerce.number().int().min(1).max(100).optional(),
|
|
154
|
+
});
|
|
155
|
+
function editableAutomation(definition) {
|
|
156
|
+
return {
|
|
157
|
+
name: definition.name,
|
|
158
|
+
description: definition.description,
|
|
159
|
+
enabled: definition.enabled,
|
|
160
|
+
events: definition.events,
|
|
161
|
+
intervalSeconds: definition.intervalSeconds,
|
|
162
|
+
filters: definition.filters,
|
|
163
|
+
task: definition.task,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* The public API surface (spec 2026-07-23-independent-server-web-packages).
|
|
168
|
+
*
|
|
169
|
+
* Every route lives under this one prefix. The unversioned `/api/*` spelling the cockpit used
|
|
170
|
+
* to speak was removed once the whole API was reachable here — carrying two spellings meant two
|
|
171
|
+
* surfaces to keep working, and only one of them could be the typed contract. Bumping to `v2`
|
|
172
|
+
* means mounting a second table beside this one, not editing route paths.
|
|
173
|
+
*/
|
|
174
|
+
const V1_PREFIX = '/api/v1';
|
|
175
|
+
/** Project scoping inside the versioned surface. The version is the OUTER dimension, so a
|
|
176
|
+
* consumer picks its API version once and then addresses projects inside it. */
|
|
177
|
+
const V1_SCOPED_PREFIX = `${V1_PREFIX}/p/:projectId`;
|
|
55
178
|
/**
|
|
56
|
-
* The project-scoped route table of a `createApp()` app, derived from its
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
* `/api/p/default/<path>`.
|
|
179
|
+
* The project-scoped route table of a `createApp()` app, derived from its actual registrations
|
|
180
|
+
* (so it can never drift from the code): every method+path mounted under
|
|
181
|
+
* `/api/v1/p/:projectId/…`, minus the scope-resolver middleware (method ALL), deduped. The
|
|
182
|
+
* alias-parity suite iterates this to assert `/api/v1/<path>` ≡ `/api/v1/p/<boot>/<path>` ≡
|
|
183
|
+
* `/api/v1/p/default/<path>`.
|
|
62
184
|
*/
|
|
63
185
|
export function projectRouteManifest(app) {
|
|
64
186
|
const seen = new Set();
|
|
65
187
|
const manifest = [];
|
|
66
188
|
for (const route of app.routes) {
|
|
67
|
-
if (route.method === 'ALL' || !route.path.startsWith(`${
|
|
189
|
+
if (route.method === 'ALL' || !route.path.startsWith(`${V1_SCOPED_PREFIX}/`))
|
|
68
190
|
continue;
|
|
69
|
-
const path = route.path.slice(
|
|
191
|
+
const path = route.path.slice(V1_SCOPED_PREFIX.length);
|
|
70
192
|
const key = `${route.method} ${path}`;
|
|
71
193
|
if (seen.has(key))
|
|
72
194
|
continue;
|
|
@@ -81,10 +203,11 @@ const FOLLOWUPS_OFF = 'the follow-up inbox is disabled — set CEZ_FOLLOWUPS=1 t
|
|
|
81
203
|
* The in-process bus for workspace-level SSE events. The registry-mutating
|
|
82
204
|
* routes (`POST /api/projects` — step 4.2, emits `project-added` for a
|
|
83
205
|
* genuinely new entry; `DELETE /api/projects/:projectId` — step 4.4) and the
|
|
84
|
-
* checkout flow (step 4.3) call `emit()`;
|
|
85
|
-
*
|
|
86
|
-
* event verbatim under its name. Injectable via
|
|
87
|
-
* so tests (and any out-of-createApp emitter) can
|
|
206
|
+
* checkout flow (step 4.3) call `emit()`; runtime provider auth observation
|
|
207
|
+
* emits host-wide `provider-status`; every open `/api/workspace/events` stream
|
|
208
|
+
* relays the event verbatim under its name. Injectable via
|
|
209
|
+
* `ServerDeps.workspaceEvents` so tests (and any out-of-createApp emitter) can
|
|
210
|
+
* drive the stream.
|
|
88
211
|
*/
|
|
89
212
|
export class WorkspaceEventBus {
|
|
90
213
|
listeners = new Set();
|
|
@@ -120,15 +243,19 @@ const startRunSchema = z
|
|
|
120
243
|
// other prompt fields (`systemPrompt` 20k, message `text` 100k) so an
|
|
121
244
|
// unbounded body can't be piped into a spawned process (#429). 100k chars
|
|
122
245
|
// (~25k tokens) is well past any hand-written task.
|
|
123
|
-
task: z.string().min(1).max(100_000, '
|
|
246
|
+
task: z.string().min(1).max(100_000, 'must be at most 100000 characters'),
|
|
124
247
|
model: z.string().optional(),
|
|
125
248
|
// Agent backend for this task (falls back to config `defaultRunner`).
|
|
126
249
|
runner: z.enum(['claude', 'codex', 'opencode']).optional(),
|
|
250
|
+
// Agent account for this task (spec 2026-07-29-agent-profiles). Falls back to the project's
|
|
251
|
+
// own selection, then the discovered default. Bounded like a profile id in the workspace
|
|
252
|
+
// schema, so a value this route accepts can never be degraded away by the next load.
|
|
253
|
+
agentProfile: z.string().max(64).optional(),
|
|
127
254
|
// Parallel variants (spec 010): ×2/×3 runs the task as 2–3 competing
|
|
128
255
|
// agents in separate worktrees; the user compares diffs and picks one.
|
|
129
256
|
variants: z.number().int().min(1).max(3).optional(),
|
|
130
257
|
// Composer worktree opt-out (#worktree-toggle): false runs in the repo
|
|
131
|
-
// working tree
|
|
258
|
+
// working tree. Ignored when variants > 1.
|
|
132
259
|
worktree: z.boolean().optional(),
|
|
133
260
|
// Autonomous mode (#autonomous): the run never parks at `waiting` — it
|
|
134
261
|
// auto-continues until the agent signals done. No "needs you" is raised.
|
|
@@ -145,7 +272,7 @@ const startRunSchema = z
|
|
|
145
272
|
systemPrompt: z
|
|
146
273
|
.string()
|
|
147
274
|
.trim()
|
|
148
|
-
.max(20_000, '
|
|
275
|
+
.max(20_000, 'must be at most 20000 characters')
|
|
149
276
|
.optional()
|
|
150
277
|
.transform((s) => (s ? s : undefined)),
|
|
151
278
|
// Screenshots pasted into the new-task form — same shape and limits as a
|
|
@@ -163,7 +290,7 @@ const startRunSchema = z
|
|
|
163
290
|
// started — the same bookkeeping POST /api/todos/:id/start does, so the
|
|
164
291
|
// audit trail survives the composer detour. Bounded like every other
|
|
165
292
|
// string here; a todo id is a short generated key.
|
|
166
|
-
todoId: z.string().min(1).max(200, '
|
|
293
|
+
todoId: z.string().min(1).max(200, 'must be at most 200 characters').optional(),
|
|
167
294
|
})
|
|
168
295
|
.refine((b) => Boolean(b.workflow) !== Boolean(b.steps), {
|
|
169
296
|
message: 'provide either "workflow" or "steps", not both',
|
|
@@ -173,7 +300,7 @@ const pickSchema = z.object({
|
|
|
173
300
|
});
|
|
174
301
|
const planSchema = z.object({
|
|
175
302
|
// Same bound as `startRunSchema.task` — this flows into `planChain` (#429).
|
|
176
|
-
task: z.string().trim().min(1).max(100_000, '
|
|
303
|
+
task: z.string().trim().min(1).max(100_000, 'must be at most 100000 characters'),
|
|
177
304
|
});
|
|
178
305
|
// A saved workflow carries full `steps` OR the builder's `skills` stack
|
|
179
306
|
// (spec 012). `overwrite: true` is the builder's Save on an existing file —
|
|
@@ -183,7 +310,7 @@ const saveWorkflowSchema = z
|
|
|
183
310
|
name: z.string().trim().min(1).max(80),
|
|
184
311
|
// Written into a YAML file on disk (#429) — a workflow description is a
|
|
185
312
|
// short blurb, so a 2k cap is generous without allowing a file-bloat write.
|
|
186
|
-
description: z.string().max(2_000, '
|
|
313
|
+
description: z.string().max(2_000, 'must be at most 2000 characters').optional(),
|
|
187
314
|
steps: z.array(workflowStepSchema).min(1).max(8).optional(),
|
|
188
315
|
skills: z.array(z.string().trim().min(1)).min(1).max(8).optional(),
|
|
189
316
|
overwrite: z.boolean().optional(),
|
|
@@ -206,14 +333,32 @@ const SKILL_USAGE_MAX_ENTRIES = 200;
|
|
|
206
333
|
// generous for GUI prefs; over-limit is a 400, never a silent strip. Shared by
|
|
207
334
|
// BOTH ui-state routes (per-repo and workspace) via `parseUiStateBody`.
|
|
208
335
|
const UI_STATE_MAX_KEYS = 200;
|
|
209
|
-
/** Settings → Appearance (redesign R6): accent + density
|
|
210
|
-
* ui-state files — per-repo (the legacy home, kept so an older
|
|
211
|
-
* same repo still honours it) and workspace
|
|
212
|
-
* post-migration home — multi-project spec,
|
|
336
|
+
/** Settings → Appearance (redesign R6): accent + density + reading width. ONE
|
|
337
|
+
* schema for both ui-state files — per-repo (the legacy home, kept so an older
|
|
338
|
+
* cezar in the same repo still honours it) and workspace
|
|
339
|
+
* (`~/.cezar/ui-state.json`, its post-migration home — multi-project spec,
|
|
340
|
+
* Data Model).
|
|
341
|
+
*
|
|
342
|
+
* Every key is `.optional()` so an older ui-state.json parses unchanged, but
|
|
343
|
+
* each one must be listed HERE: the enclosing `workspaceUiStateSchema` is
|
|
344
|
+
* `.passthrough()` at the top level only, so an unlisted key inside
|
|
345
|
+
* `appearance` is stripped by zod and then wiped from the file by the shallow
|
|
346
|
+
* merge-on-write. The cockpit adopts the PUT response as authoritative, so a
|
|
347
|
+
* stripped key does not merely fail to persist — it visibly reverts the
|
|
348
|
+
* control the user just touched. Adding an appearance preference means adding
|
|
349
|
+
* it here in the same change. */
|
|
213
350
|
const appearanceSchema = z.object({
|
|
214
351
|
accent: z.enum(['lime', 'violet']).optional(),
|
|
215
352
|
density: z.enum(['comfortable', 'compact', 'ultra']).optional(),
|
|
353
|
+
width: z.enum(['narrow', 'wide']).optional(),
|
|
216
354
|
});
|
|
355
|
+
const providerAuthDismissalsSchema = z
|
|
356
|
+
.object({
|
|
357
|
+
claude: z.string().min(1).max(128).optional(),
|
|
358
|
+
codex: z.string().min(1).max(128).optional(),
|
|
359
|
+
opencode: z.string().min(1).max(128).optional(),
|
|
360
|
+
})
|
|
361
|
+
.strict();
|
|
217
362
|
/** Global GUI state (`~/.cezar/ui-state.json`, step 2.7) — the workspace twin
|
|
218
363
|
* of `uiStateSchema` below, sharing its `.passthrough()` + key-cap + shallow
|
|
219
364
|
* merge-on-write semantics via `parseUiStateBody`. Known keys are the
|
|
@@ -223,6 +368,16 @@ const workspaceUiStateSchema = z
|
|
|
223
368
|
.object({
|
|
224
369
|
appearance: appearanceSchema.optional(),
|
|
225
370
|
notifications: z.object({ enabled: z.boolean().optional() }).passthrough().optional(),
|
|
371
|
+
dismissedProviderAuthFailures: providerAuthDismissalsSchema.optional(),
|
|
372
|
+
lastLocation: z
|
|
373
|
+
.object({
|
|
374
|
+
projectId: z.string().min(1).max(64),
|
|
375
|
+
pathname: z.string().min(1).max(2048).startsWith('/p/'),
|
|
376
|
+
search: z.string().max(4096).startsWith('?').optional(),
|
|
377
|
+
hash: z.string().max(2048).startsWith('#').optional(),
|
|
378
|
+
})
|
|
379
|
+
.strict()
|
|
380
|
+
.optional(),
|
|
226
381
|
// Sidebar per-project collapse map, keyed by project id (slug ≤ 64 chars).
|
|
227
382
|
// Entry-capped like `skillUsage`: the map is written straight to a file the
|
|
228
383
|
// cockpit GETs on every load, so it must stay bounded on every axis.
|
|
@@ -330,7 +485,7 @@ const patchRunSchema = z.object({
|
|
|
330
485
|
});
|
|
331
486
|
// Session commit (redesign R5 — §"Git/session API additions").
|
|
332
487
|
const gitCommitSchema = z.object({
|
|
333
|
-
message: z.string().trim().min(1, '
|
|
488
|
+
message: z.string().trim().min(1, 'must not be empty').max(5_000),
|
|
334
489
|
});
|
|
335
490
|
// "Open in…" (#open-in / #365): `target` selects the app; `path` (optional, worktree-relative)
|
|
336
491
|
// narrows the target's own worktree/repo-root default to one file — used by the diff pane's
|
|
@@ -387,7 +542,7 @@ function foldedLength(task, stack) {
|
|
|
387
542
|
// follow-up composer is a full composer, so a screenshot pasted into it must reach the reopened
|
|
388
543
|
// session rather than being silently dropped.
|
|
389
544
|
const continueSchema = z.object({
|
|
390
|
-
text: z.string().max(100_000, '
|
|
545
|
+
text: z.string().max(100_000, 'must be at most 100000 characters').optional(),
|
|
391
546
|
images: z.array(imageInputSchema).max(4).optional(),
|
|
392
547
|
runner: z.enum(['claude', 'codex', 'opencode']).optional(),
|
|
393
548
|
model: z.string().max(200).optional(),
|
|
@@ -406,7 +561,7 @@ const startTodoSchema = z
|
|
|
406
561
|
prompt: z
|
|
407
562
|
.string()
|
|
408
563
|
.trim()
|
|
409
|
-
.max(20_000, '
|
|
564
|
+
.max(20_000, 'must be at most 20000 characters')
|
|
410
565
|
.optional()
|
|
411
566
|
.transform((s) => (s ? s : undefined)),
|
|
412
567
|
})
|
|
@@ -432,21 +587,100 @@ function stripHostPort(host) {
|
|
|
432
587
|
return bracketed[1];
|
|
433
588
|
return host.replace(/:\d+$/, '');
|
|
434
589
|
}
|
|
435
|
-
/** The shared write-side half of BOTH ui-state routes (per-repo `/api/ui-state`
|
|
436
|
-
* and workspace `/api/workspace/ui-state`) — the factored split the
|
|
437
|
-
* multi-project spec calls for instead of a copy:
|
|
438
|
-
*
|
|
439
|
-
*
|
|
440
|
-
*
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
590
|
+
/** The shared write-side half of BOTH ui-state routes (per-repo `/api/v1/ui-state`
|
|
591
|
+
* and workspace `/api/v1/workspace/ui-state`) — the factored split the
|
|
592
|
+
* multi-project spec calls for instead of a copy: the route's own schema, plus a
|
|
593
|
+
* cap on the top-level key count so a `.passthrough()` schema can't accumulate an
|
|
594
|
+
* unbounded key set (#429). The cap rides as a refinement so the whole thing is one
|
|
595
|
+
* schema and can go through `jsonBody` like every other mutating route. The
|
|
596
|
+
* merge-on-write stays with each route (they write different files) but is shallow
|
|
597
|
+
* in both. */
|
|
598
|
+
function capUiStateKeys(data, ctx) {
|
|
599
|
+
if (Object.keys(data).length > UI_STATE_MAX_KEYS) {
|
|
600
|
+
ctx.addIssue({ code: z.ZodIssueCode.custom, message: `ui-state has too many keys (max ${UI_STATE_MAX_KEYS})` });
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
// Derived once per route instead of by a generic `wrap(schema)` helper called at the route: a
|
|
604
|
+
// generic wrapper leaves the schema type unresolved where `jsonBody` needs it, and Hono answers
|
|
605
|
+
// that by dropping the whole PUT from the route schema rather than erroring — both ui-state PUTs
|
|
606
|
+
// silently vanished from `AppType`. Concrete consts keep them visible to `hc`.
|
|
607
|
+
const workspaceUiStateBody = workspaceUiStateSchema.superRefine(capUiStateKeys);
|
|
608
|
+
const uiStateBody = uiStateSchema.superRefine(capUiStateKeys);
|
|
609
|
+
/**
|
|
610
|
+
* Query schemas for the READ routes — deliberately permissive.
|
|
611
|
+
*
|
|
612
|
+
* These exist to make a query key VISIBLE to the route type (`hc` refuses a `query` argument for
|
|
613
|
+
* a key no validator declares), NOT to narrow what the route accepts. Every one of these handlers
|
|
614
|
+
* compares `=== '1'` and treats everything else as false, so `?refresh=0` is a successful request
|
|
615
|
+
* today; a literal schema would silently turn it into a 400. The comparison stays in the handler
|
|
616
|
+
* and the validator stays out of its way.
|
|
617
|
+
*
|
|
618
|
+
* The one route that really is strict on the wire — `GET /github/prs/:number/changes`, which 400s
|
|
619
|
+
* on `?refresh=true` — keeps its own `z.enum(['1'])` schema next to the route.
|
|
620
|
+
*/
|
|
621
|
+
/**
|
|
622
|
+
* One query value, matching what `c.req.query('k')` did before these routes were validated.
|
|
623
|
+
*
|
|
624
|
+
* Hono's query validator hands a REPEATED key as an array (`?wait=1&wait=1` → `['1','1']`), where
|
|
625
|
+
* `c.req.query()` silently took the first. A plain `z.string()` therefore turns a request that
|
|
626
|
+
* used to answer 200 into a 400 — a wire change no caller asked for. Collapsing to the first
|
|
627
|
+
* value keeps the old behaviour, and the client still sees a plain `key?: string`.
|
|
628
|
+
*/
|
|
629
|
+
const queryValue = z.union([z.string(), z.array(z.string()).transform((v) => v[0])]).optional();
|
|
630
|
+
const refreshQuery = z.object({ refresh: queryValue });
|
|
631
|
+
const waitQuery = z.object({ wait: queryValue });
|
|
632
|
+
function parseAccept(header) {
|
|
633
|
+
const ranges = [];
|
|
634
|
+
for (const part of header.split(',')) {
|
|
635
|
+
const [range = '', ...params] = part.split(';');
|
|
636
|
+
const [type = '', subtype = ''] = range.trim().toLowerCase().split('/');
|
|
637
|
+
if (type === '' || subtype === '')
|
|
638
|
+
continue;
|
|
639
|
+
const weight = params.map((p) => p.trim().toLowerCase()).find((p) => p.startsWith('q='));
|
|
640
|
+
const parsed = weight === undefined ? 1 : Number.parseFloat(weight.slice(2));
|
|
641
|
+
const q = Number.isFinite(parsed) ? Math.min(Math.max(parsed, 0), 1) : 0;
|
|
642
|
+
if (q > 0)
|
|
643
|
+
ranges.push({ type, subtype, q });
|
|
644
|
+
}
|
|
645
|
+
return ranges;
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* The best of `offers` for this `Accept`, or `null` for "no preference expressed" — which is what
|
|
649
|
+
* an absent header, a `*<slash>*`-only header and a header naming nothing on offer all mean, and
|
|
650
|
+
* what leaves the caller on its route's default.
|
|
651
|
+
*
|
|
652
|
+
* `offers` is the server's own preference order: an offer may itself be a wildcard (`image/*`,
|
|
653
|
+
* since the concrete image type is not known until the file is read), and equal q-values go to the
|
|
654
|
+
* EARLIER offer, so each route lists its default representation first.
|
|
655
|
+
*/
|
|
656
|
+
function negotiate(accept, offers) {
|
|
657
|
+
if (accept === undefined)
|
|
658
|
+
return null;
|
|
659
|
+
const ranges = parseAccept(accept);
|
|
660
|
+
let best = null;
|
|
661
|
+
for (const offer of offers) {
|
|
662
|
+
const [type = '', subtype = ''] = offer.split('/');
|
|
663
|
+
let q = 0;
|
|
664
|
+
for (const range of ranges) {
|
|
665
|
+
if (range.type === '*' && range.subtype === '*')
|
|
666
|
+
continue; // "anything" is not a preference
|
|
667
|
+
const typeMatches = range.type === type || range.type === '*' || type === '*';
|
|
668
|
+
const subtypeMatches = range.subtype === subtype || range.subtype === '*' || subtype === '*';
|
|
669
|
+
if (typeMatches && subtypeMatches && range.q > q)
|
|
670
|
+
q = range.q;
|
|
671
|
+
}
|
|
672
|
+
if (q > 0 && (best === null || q > best.q))
|
|
673
|
+
best = { offer, q };
|
|
447
674
|
}
|
|
448
|
-
return
|
|
675
|
+
return best?.offer ?? null;
|
|
449
676
|
}
|
|
677
|
+
/** What `GET /repo/commit/:sha` offers, DEFAULT FIRST: the legacy `text/plain` blob is what a
|
|
678
|
+
* request with no opinion has always received (§2), so it also wins an Accept tie. */
|
|
679
|
+
const COMMIT_FORMATS = ['text/plain', 'application/json'];
|
|
680
|
+
/** What `GET /runs/:id/files` offers, DEFAULT FIRST. `image/*` rather than a concrete type: which
|
|
681
|
+
* image type the bytes are is only known once the path resolves, and the raw branch refuses
|
|
682
|
+
* everything that is not an image anyway. */
|
|
683
|
+
const FILE_FORMATS = ['application/json', 'image/*'];
|
|
450
684
|
/** Workspace-root writability probe (multi-project spec, "API Contracts"):
|
|
451
685
|
* optional `mkdir -p`, `access W_OK`, then a real create/delete round-trip — W_OK alone
|
|
452
686
|
* can lie (e.g. a read-only mount still reports writable permission bits).
|
|
@@ -469,6 +703,10 @@ async function probeWritableDir(dir, create) {
|
|
|
469
703
|
return err instanceof Error ? err.message : String(err);
|
|
470
704
|
}
|
|
471
705
|
}
|
|
706
|
+
// The return type is INFERRED on purpose: it is the chained app type built at the bottom of
|
|
707
|
+
// this function, and `AppType` (src/server/app-type.ts) is `ReturnType<typeof createApp>`.
|
|
708
|
+
// Annotating it `Hono` here would erase every route from the type and leave the typed client
|
|
709
|
+
// with nothing to offer. See the `routed` assembly at the end of the function.
|
|
472
710
|
export function createApp(deps) {
|
|
473
711
|
const { version, update, bindHost, bootProjectId } = deps;
|
|
474
712
|
// Boot singletons keep DELIBERATELY distinct names (`boot*`): every
|
|
@@ -481,6 +719,54 @@ export function createApp(deps) {
|
|
|
481
719
|
const modelCatalog = deps.modelCatalog ?? new RunnerModelCatalog({
|
|
482
720
|
adapters: { codex: { discover: () => discoverCodexModels({ cwd: bootRoot }) } },
|
|
483
721
|
});
|
|
722
|
+
const providerAuth = deps.providerAuth ?? new ProviderAuthService();
|
|
723
|
+
const workspaceConfig = deps.workspaceConfig ?? {
|
|
724
|
+
load: loadWorkspaceConfig,
|
|
725
|
+
mergeWrite: mergeWriteWorkspaceConfig,
|
|
726
|
+
};
|
|
727
|
+
const providerStatus = async (options) => {
|
|
728
|
+
if (providerAuthChecksDisabled()) {
|
|
729
|
+
return applyProviderEnablement(await providerAuth.status(options?.refresh ? { refresh: true } : undefined), []);
|
|
730
|
+
}
|
|
731
|
+
const [discovered, workspace] = await Promise.all([
|
|
732
|
+
providerAuth.status(options?.refresh ? { refresh: true } : undefined),
|
|
733
|
+
workspaceConfig.load(),
|
|
734
|
+
]);
|
|
735
|
+
return applyProviderEnablement(discovered, workspace.disabledProviders);
|
|
736
|
+
};
|
|
737
|
+
/**
|
|
738
|
+
* The gate: why a run cannot start against `required`, or null when it can.
|
|
739
|
+
*
|
|
740
|
+
* VERIFY BEFORE YOU REFUSE. Auth state is served stale-while-revalidate (see
|
|
741
|
+
* `ProviderAuthService.status`), so a cached "disconnected" may predate a login cezar could not
|
|
742
|
+
* observe — someone running `claude auth login` in a terminal. Refusing on that would lock a user
|
|
743
|
+
* out of their own cockpit with no way back but waiting. So a believed-unavailable provider is
|
|
744
|
+
* re-probed, and only a refusal that survives the fresh answer is returned.
|
|
745
|
+
*
|
|
746
|
+
* The cost lands where it belongs: the common path (connected, warm) pays nothing at all, and the
|
|
747
|
+
* probe is only spawned when cezar is about to say no — a rare, interactive moment. This is also
|
|
748
|
+
* what lets the cache hold a negative for a minute instead of five seconds, which is what made
|
|
749
|
+
* every reader of `GET /providers/status` periodically pay for a CLI spawn.
|
|
750
|
+
*
|
|
751
|
+
* A runtime auth latch is deliberately NOT escaped by this: `withRuntimeFailures` keeps forcing
|
|
752
|
+
* the row disconnected until the user acknowledges that exact incident, so the re-probe cannot
|
|
753
|
+
* talk cezar out of a rejection it actually observed.
|
|
754
|
+
*/
|
|
755
|
+
const providerActionError = async (required) => {
|
|
756
|
+
const known = await providerStatus();
|
|
757
|
+
const message = unavailableProviderMessage(required, known);
|
|
758
|
+
if (message === null)
|
|
759
|
+
return null;
|
|
760
|
+
// A DISABLED provider is a settings fact, not a probe result — re-probing it learns nothing and
|
|
761
|
+
// would spawn a CLI to re-read something the user typed.
|
|
762
|
+
const disabled = required.some((provider) => known.providers.find((row) => row.provider === provider)?.enabled === false);
|
|
763
|
+
if (disabled)
|
|
764
|
+
return message;
|
|
765
|
+
return unavailableProviderMessage(required, await providerStatus({ refresh: true }));
|
|
766
|
+
};
|
|
767
|
+
const openTerminal = deps.openTerminal ?? openInTerminal;
|
|
768
|
+
const openFile = deps.openFile ?? openFileInDefaultApp;
|
|
769
|
+
const skillsUpdate = deps.skillsUpdate ?? new SkillsUpdateService();
|
|
484
770
|
// ---- workspace boot-project identity (multi-project spec) ----------------
|
|
485
771
|
// The boot flow (`initWorkspace` in src/index.ts) registers the boot repo
|
|
486
772
|
// and plumbs its registry id in via `deps.bootProjectId`. Legacy callers and
|
|
@@ -551,6 +837,7 @@ export function createApp(deps) {
|
|
|
551
837
|
dataDir: bootDataDir,
|
|
552
838
|
store: deps.store,
|
|
553
839
|
manager: deps.manager,
|
|
840
|
+
automationStore: deps.automationStore ?? AutomationStore.open(bootDataDir),
|
|
554
841
|
launchKey: ensureLaunchKey(bootDataDir), // bookmarklet auto-start secret (spec 011)
|
|
555
842
|
};
|
|
556
843
|
// Non-boot projects build lazily on first scoped request; their managers
|
|
@@ -567,6 +854,25 @@ export function createApp(deps) {
|
|
|
567
854
|
// Workspace-level SSE bus (step 2.8) — the registry mutators and the
|
|
568
855
|
// checkout flow (Phase 4) emit here; /api/workspace/events relays.
|
|
569
856
|
const workspaceEvents = deps.workspaceEvents ?? new WorkspaceEventBus();
|
|
857
|
+
const emitAutomationChange = (project, automationId, revision, deleted = false) => workspaceEvents.emit('automation-change', {
|
|
858
|
+
project: project.id,
|
|
859
|
+
automationId,
|
|
860
|
+
revision,
|
|
861
|
+
...(deleted ? { deleted: true } : {}),
|
|
862
|
+
});
|
|
863
|
+
const automationsChanged = () => deps.automationsChanged?.();
|
|
864
|
+
const providerRuntimeAuth = deps.providerRuntimeAuth
|
|
865
|
+
?? new ProviderRuntimeAuthObserver(providerAuth, (status) => {
|
|
866
|
+
workspaceEvents.emit('provider-status', status);
|
|
867
|
+
});
|
|
868
|
+
providerRuntimeAuth.watch(bootContext.store);
|
|
869
|
+
for (const id of contexts.ids()) {
|
|
870
|
+
const ctx = contexts.peek(id);
|
|
871
|
+
if (ctx)
|
|
872
|
+
providerRuntimeAuth.watch(ctx.store);
|
|
873
|
+
}
|
|
874
|
+
contexts.onStoreCreated((store) => providerRuntimeAuth.watch(store));
|
|
875
|
+
contexts.onContextBuilt((ctx) => providerRuntimeAuth.watch(ctx.store));
|
|
570
876
|
const app = new Hono();
|
|
571
877
|
// Reject oversized request bodies before they reach any handler (#429). GETs
|
|
572
878
|
// and SSE carry no body, so this only ever gates the mutating routes.
|
|
@@ -577,7 +883,7 @@ export function createApp(deps) {
|
|
|
577
883
|
// own: any page the user visits can still POST to us (CSRF), and DNS
|
|
578
884
|
// rebinding can point a foreign domain at loopback and read our responses.
|
|
579
885
|
// Two zero-config checks close both holes on every /api route EXCEPT
|
|
580
|
-
// /api/health (the intentional cross-origin discovery endpoint, spec 011 —
|
|
886
|
+
// /api/v1/health (the intentional cross-origin discovery endpoint, spec 011 —
|
|
581
887
|
// it exposes nothing sensitive, see #431):
|
|
582
888
|
// 1. Host allowlist (loopback deployments only) — a request whose Host is
|
|
583
889
|
// not a loopback name did not really originate from this machine. A
|
|
@@ -600,7 +906,7 @@ export function createApp(deps) {
|
|
|
600
906
|
// Scope note: check 2 covers writes only. A cross-origin GET from any site
|
|
601
907
|
// still reaches the read routes — but its Host is ours, so it is a *forced
|
|
602
908
|
// request*, not a read: the same-origin policy stops the attacker seeing any
|
|
603
|
-
// response body (we send CORS headers on /api/health alone), and no GET
|
|
909
|
+
// response body (we send CORS headers on /api/v1/health alone), and no GET
|
|
604
910
|
// handler mutates state. Rebinding, which WOULD make those reads legible, is
|
|
605
911
|
// what check 1 stops.
|
|
606
912
|
const MUTATING_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
|
|
@@ -615,9 +921,12 @@ export function createApp(deps) {
|
|
|
615
921
|
error: 'forbidden: unexpected Host header — this request did not originate from this machine (see #426)',
|
|
616
922
|
}, 403);
|
|
617
923
|
}
|
|
618
|
-
// /api/health stays CORS-open for
|
|
619
|
-
// still checked above: cross-origin is legitimate, DNS rebinding is not.
|
|
620
|
-
|
|
924
|
+
// /api/v1/health stays CORS-open for cross-origin discovery, but its Host is
|
|
925
|
+
// still checked above: cross-origin is legitimate, DNS rebinding is not. The
|
|
926
|
+
// path is spelled through V1_PREFIX rather than inline — an unversioned
|
|
927
|
+
// literal here silently stopped matching when the API moved and left health
|
|
928
|
+
// relying on the mutating-methods gate below to let its GETs through.
|
|
929
|
+
if (c.req.path === `${V1_PREFIX}/health`)
|
|
621
930
|
return next();
|
|
622
931
|
if (MUTATING_METHODS.has(c.req.method)) {
|
|
623
932
|
const origin = c.req.header('origin');
|
|
@@ -661,15 +970,16 @@ export function createApp(deps) {
|
|
|
661
970
|
});
|
|
662
971
|
// The mirrored project-route table (spec "API Contracts → Project-scoped").
|
|
663
972
|
// Every route below registers ONCE on this sub-app; `createApp` mounts it
|
|
664
|
-
// twice — under `/api/p/:projectId` (scoped) and under `/api` (
|
|
665
|
-
//
|
|
666
|
-
//
|
|
667
|
-
// no `projectId` param (
|
|
973
|
+
// twice — under `/api/v1/p/:projectId` (scoped) and under `/api/v1` (bound to
|
|
974
|
+
// the boot project) — so both spellings share one handler and can never
|
|
975
|
+
// drift. The resolver middleware binds `c.get('project')`:
|
|
976
|
+
// no `projectId` param (unscoped mount) → the boot context, byte-identical to
|
|
668
977
|
// the pre-workspace closures; `default` or the boot project's own id → the
|
|
669
978
|
// boot context too; anything else → the lazy context map, with
|
|
670
979
|
// `ProjectContextError` mapped to 404 (unknown) / 409 (missing root).
|
|
671
|
-
|
|
672
|
-
|
|
980
|
+
// Named rather than inlined because both mounts share it — one function, so
|
|
981
|
+
// the two spellings can never disagree about what `default` means.
|
|
982
|
+
const resolveProjectScope = async (c, next) => {
|
|
673
983
|
const raw = c.req.param('projectId');
|
|
674
984
|
if (raw === undefined) {
|
|
675
985
|
c.set('project', bootContext);
|
|
@@ -694,15 +1004,23 @@ export function createApp(deps) {
|
|
|
694
1004
|
throw err;
|
|
695
1005
|
}
|
|
696
1006
|
return next();
|
|
697
|
-
}
|
|
1007
|
+
};
|
|
698
1008
|
// ---- static GUI ----------------------------------------------------------
|
|
699
1009
|
const webDir = resolveWebDir();
|
|
700
1010
|
const distDir = join(webDir, 'dist');
|
|
701
1011
|
const HTML_TYPE = 'text/html; charset=utf-8';
|
|
702
|
-
const staticFile = (name, type) => () => {
|
|
1012
|
+
const staticFile = (name, type) => (c) => {
|
|
703
1013
|
// Read per request — the files are tiny and this keeps dev iteration live.
|
|
704
|
-
|
|
705
|
-
|
|
1014
|
+
//
|
|
1015
|
+
// Served out of the Vite build: the file is a `public/` asset of the web package, which the
|
|
1016
|
+
// build copies verbatim into `web/dist`. One home, one URL — the same bytes this route
|
|
1017
|
+
// hands out are what the bundle's own `<img src="/open-mercato.svg">` asks for.
|
|
1018
|
+
// Without a build there is nothing to serve, which is a 404 rather than a crash (the shell
|
|
1019
|
+
// route answers the same dev-only state with its build hint).
|
|
1020
|
+
const path = join(distDir, name);
|
|
1021
|
+
if (!existsSync(path))
|
|
1022
|
+
return c.json({ error: 'not found' }, 404);
|
|
1023
|
+
return new Response(readFileSync(path), { headers: { 'content-type': type } });
|
|
706
1024
|
};
|
|
707
1025
|
let hintLogged = false;
|
|
708
1026
|
const serveShell = (c) => {
|
|
@@ -749,14 +1067,14 @@ export function createApp(deps) {
|
|
|
749
1067
|
},
|
|
750
1068
|
});
|
|
751
1069
|
});
|
|
752
|
-
// The favicon web/
|
|
1070
|
+
// The favicon packages/web/index.html points at (`/open-mercato.svg`).
|
|
753
1071
|
app.get('/open-mercato.svg', staticFile('open-mercato.svg', 'image/svg+xml'));
|
|
754
1072
|
// ---- meta ----------------------------------------------------------------
|
|
755
1073
|
// CORS — deliberately for /api/health ONLY (spec 011): the bookmarklets
|
|
756
1074
|
// fetch it cross-origin from github.com to discover which local ports run a
|
|
757
1075
|
// cockpit and which repo each serves. Health exposes no secrets beyond the
|
|
758
1076
|
// repo path/remote; every other endpoint stays same-origin.
|
|
759
|
-
|
|
1077
|
+
const healthCors = async (c, next) => {
|
|
760
1078
|
c.header('access-control-allow-origin', '*');
|
|
761
1079
|
if (c.req.method === 'OPTIONS') {
|
|
762
1080
|
// Preflight (e.g. Chrome Private Network Access) — allow the plain GET.
|
|
@@ -765,10 +1083,16 @@ export function createApp(deps) {
|
|
|
765
1083
|
return c.body(null, 204);
|
|
766
1084
|
}
|
|
767
1085
|
await next();
|
|
768
|
-
}
|
|
1086
|
+
};
|
|
1087
|
+
app.use(`${V1_PREFIX}/health`, healthCors);
|
|
769
1088
|
// One builder for both transports: `GET /api/health` (the authoritative,
|
|
770
|
-
// CORS-open discovery endpoint) and the `health` topic on `/api/ws` below
|
|
1089
|
+
// CORS-open discovery endpoint) and the `health` topic on `/api/v1/ws` below
|
|
771
1090
|
// push the byte-identical shape, so the two can never drift.
|
|
1091
|
+
// Deliberately UNANNOTATED: this literal is the source of the `/health` shape. Annotating it
|
|
1092
|
+
// with the api-client's `HealthResponse` made the contract circular — the DTO was declared by
|
|
1093
|
+
// hand, the handler was checked against it, and `AppType` then reported the hand-written type
|
|
1094
|
+
// back as if the server had proven it. Inferring here means the route says what it actually
|
|
1095
|
+
// sends, which is what lets the DTO be derived instead of maintained.
|
|
772
1096
|
const healthSnapshot = async () => {
|
|
773
1097
|
const [checks, repo, config, workspace] = await Promise.all([
|
|
774
1098
|
detectEnvironment(),
|
|
@@ -782,7 +1106,11 @@ export function createApp(deps) {
|
|
|
782
1106
|
const caps = capabilities();
|
|
783
1107
|
return {
|
|
784
1108
|
version,
|
|
785
|
-
latestVersion: update?.latest
|
|
1109
|
+
// Spread rather than `latestVersion: update?.latest`: an `undefined` VALUE is dropped by
|
|
1110
|
+
// JSON.stringify, so the key is absent on the wire — but writing it unconditionally types
|
|
1111
|
+
// the key as always-present, which is a shape no client ever receives. The contract schema
|
|
1112
|
+
// says `.optional()`, and contract-parity.test.ts holds the two together.
|
|
1113
|
+
...(update?.latest !== undefined ? { latestVersion: update.latest } : {}),
|
|
786
1114
|
// Health is CORS-open and, in hosted mode, reachable off the loopback —
|
|
787
1115
|
// so any site/host that reads it would learn the developer's absolute
|
|
788
1116
|
// checkout path and username (#431). Local mode keeps the full path (the
|
|
@@ -874,7 +1202,13 @@ export function createApp(deps) {
|
|
|
874
1202
|
void refreshHealth(); // stale: refresh, don't wait on it
|
|
875
1203
|
return healthCache.payload;
|
|
876
1204
|
};
|
|
877
|
-
|
|
1205
|
+
// ---- chained family: health (workspace-level) ----------------------------
|
|
1206
|
+
// Written as ONE chained expression rather than a loose `app.get(...)`
|
|
1207
|
+
// statement because Hono accumulates its route types through the chain: a
|
|
1208
|
+
// statement's return value is discarded, so `typeof app` would record nothing
|
|
1209
|
+
// and `hc<AppType>` would have no endpoint to offer. `createApp` mounts this
|
|
1210
|
+
// under both `/api` (the frozen legacy spelling) and `/api/v1`.
|
|
1211
|
+
const healthRoutes = new Hono().get('/health', async (c) => c.json(await readHealth()));
|
|
878
1212
|
// The push twin of the poll it replaced (#369): while at least one cockpit
|
|
879
1213
|
// holds the `health` topic the server re-reads the snapshot on the old 5 s
|
|
880
1214
|
// cadence and broadcasts ONLY when it changed — a `git checkout` in a
|
|
@@ -906,14 +1240,676 @@ export function createApp(deps) {
|
|
|
906
1240
|
// `GET /api/health` reads a warm value instead of the cold ~1 s compute.
|
|
907
1241
|
if (deps.socketHub)
|
|
908
1242
|
void refreshHealth();
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1243
|
+
/**
|
|
1244
|
+
* Warm the whole of cezar's agent knowledge — the three discovered defaults AND every extra
|
|
1245
|
+
* account — so no reader ever pays the first shell-out.
|
|
1246
|
+
*
|
|
1247
|
+
* Which login each agent is signed into is operating knowledge, not a settings-page detail: the
|
|
1248
|
+
* composer, the action gate, the accounts pane and every run resolution ask for it. So the server
|
|
1249
|
+
* learns it once, at boot, and keeps it (see the asymmetric cache lifetime in
|
|
1250
|
+
* `core/provider-auth.ts`); on-demand refresh rides on `?refresh=1` and on the explicit
|
|
1251
|
+
* invalidations — connect, repoint, remove, runtime rejection.
|
|
1252
|
+
*
|
|
1253
|
+
* Extra accounts are warmed ONE AT A TIME, after the defaults. Each is a CLI spawn, and a machine
|
|
1254
|
+
* with several accounts would otherwise fan out a spawn storm at exactly the moment the browser is
|
|
1255
|
+
* fetching the bundle; nothing is waiting on this, so sequential costs nothing that matters.
|
|
1256
|
+
*
|
|
1257
|
+
* Hosted mode warms only the defaults: the agent-profiles family is refused there, so there are
|
|
1258
|
+
* no accounts to learn about.
|
|
1259
|
+
*/
|
|
1260
|
+
const warmAgentKnowledge = async () => {
|
|
1261
|
+
await providerAuth.status().catch(() => { });
|
|
1262
|
+
if (!capabilities().localHandoff)
|
|
1263
|
+
return;
|
|
1264
|
+
const store = await loadAgentAccounts().catch(() => defaultAgentAccountStore());
|
|
1265
|
+
for (const account of listAgentProfiles(store, PROVIDER_IDS)) {
|
|
1266
|
+
if (account.isDefault)
|
|
1267
|
+
continue; // covered by `status()` above
|
|
1268
|
+
await providerAuth
|
|
1269
|
+
.profileStatus(account.provider, { id: account.id, configDir: account.path })
|
|
1270
|
+
.catch(() => { });
|
|
1271
|
+
}
|
|
1272
|
+
};
|
|
1273
|
+
// Same gate as `refreshHealth`, same reason (startServer injects the hub; a bare app in tests does
|
|
1274
|
+
// not, so tests never spawn probes here). Fire-and-forget: a probe that fails leaves that row
|
|
1275
|
+
// cold, which is exactly the state every reader already handles.
|
|
1276
|
+
if (deps.socketHub)
|
|
1277
|
+
void warmAgentKnowledge();
|
|
1278
|
+
// ---- chained family: host model catalog (workspace-level) ----
|
|
1279
|
+
const modelsRoutes = new Hono()
|
|
1280
|
+
.get('/models', queryZodValidator(z.object({ runner: z.union([z.string(), z.array(z.string()).transform((v) => v[0])]).pipe(z.literal('codex')) }), { message: 'runner must be codex' }), async (c) => {
|
|
1281
|
+
const query = { data: c.req.valid('query') };
|
|
915
1282
|
return c.json(await modelCatalog.get(query.data.runner));
|
|
916
1283
|
});
|
|
1284
|
+
/**
|
|
1285
|
+
* Resolve `profileId` (absent = the discovered default) into a concrete account for `provider`.
|
|
1286
|
+
*
|
|
1287
|
+
* A dangling id is an ERROR here rather than the silent fall-back to the default that run
|
|
1288
|
+
* resolution performs. The difference is who is asking: a run is replaying a stored reference
|
|
1289
|
+
* and the default is the only safe answer it can act on, whereas a route is answering a user
|
|
1290
|
+
* who just named an account — telling them "unknown account" is honest, and quietly connecting
|
|
1291
|
+
* or reporting on a different one is not.
|
|
1292
|
+
*/
|
|
1293
|
+
const resolveWorkspaceProfile = async (provider, profileId) => {
|
|
1294
|
+
if (profileId === undefined || profileId === DEFAULT_AGENT_ACCOUNT_ID) {
|
|
1295
|
+
return { profile: defaultAgentProfile(provider) };
|
|
1296
|
+
}
|
|
1297
|
+
let accounts;
|
|
1298
|
+
try {
|
|
1299
|
+
accounts = (await loadAgentAccounts()).accounts;
|
|
1300
|
+
}
|
|
1301
|
+
catch {
|
|
1302
|
+
return { error: `unknown ${provider} account: ${profileId}` };
|
|
1303
|
+
}
|
|
1304
|
+
const stored = accounts.find((a) => a.id === profileId && a.provider === provider);
|
|
1305
|
+
if (!stored)
|
|
1306
|
+
return { error: `unknown ${provider} account: ${profileId}` };
|
|
1307
|
+
return { profile: resolveStoredProfile(stored) };
|
|
1308
|
+
};
|
|
1309
|
+
/**
|
|
1310
|
+
* The environment a terminal handoff must carry so the CLI lands on the right account.
|
|
1311
|
+
*
|
|
1312
|
+
* `profileId` is the one RECORDED on the step that owns the session, never the project's
|
|
1313
|
+
* current selection: `claude --resume <id>` reads `<configDir>/sessions`, so a handoff for a
|
|
1314
|
+
* run started on the work account and resumed after the project was switched back would find
|
|
1315
|
+
* nothing and silently open a fresh conversation.
|
|
1316
|
+
*/
|
|
1317
|
+
const handoffEnv = async (provider, profileId) => {
|
|
1318
|
+
const resolved = await resolveWorkspaceProfile(provider, profileId);
|
|
1319
|
+
if ('error' in resolved) {
|
|
1320
|
+
return { error: `this session belongs to an account that no longer exists (${profileId})` };
|
|
1321
|
+
}
|
|
1322
|
+
const { profile } = resolved;
|
|
1323
|
+
return { env: profile.isDefault ? {} : profileEnv(provider, profile.path) };
|
|
1324
|
+
};
|
|
1325
|
+
/** The copy-paste fallback shown when no terminal could be opened — same account, spelled for
|
|
1326
|
+
* this platform's shell. `null` when the dir cannot be embedded safely, which is a refusal. */
|
|
1327
|
+
const handoffFallbackCommand = (cwd, command, env) => {
|
|
1328
|
+
const prefixed = withEnvPrefix(command, env, process.platform);
|
|
1329
|
+
return prefixed === null ? null : `cd '${cwd}' && ${prefixed}`;
|
|
1330
|
+
};
|
|
1331
|
+
/** A registered project's realpath'd root, or null when the id is unknown. */
|
|
1332
|
+
const projectRootFor = async (projectId) => {
|
|
1333
|
+
try {
|
|
1334
|
+
return (await loadWorkspaceConfig()).projects.find((p) => p.id === projectId)?.root ?? null;
|
|
1335
|
+
}
|
|
1336
|
+
catch {
|
|
1337
|
+
return null;
|
|
1338
|
+
}
|
|
1339
|
+
};
|
|
1340
|
+
// ---- chained family: agent providers (workspace-level) ----
|
|
1341
|
+
const providersRoutes = new Hono()
|
|
1342
|
+
.get('/providers/status', queryZodValidator(z.object({ refresh: queryValue.refine((v) => v === undefined || v === '1') }), { message: 'refresh must be 1 when provided' }), async (c) => {
|
|
1343
|
+
const query = { data: c.req.valid('query') };
|
|
1344
|
+
return c.json(await providerStatus({ refresh: query.data.refresh === '1' }));
|
|
1345
|
+
})
|
|
1346
|
+
.put('/providers/:provider/enabled', paramZodValidator(z.object({ provider: providerParamSchema }), { message: 'provider and enabled boolean are required' }), jsonZodValidator(providerEnabledSchema, { message: 'provider and enabled boolean are required' }), async (c) => {
|
|
1347
|
+
const provider = { data: c.req.valid('param').provider };
|
|
1348
|
+
const body = { data: c.req.valid('json') };
|
|
1349
|
+
let workspace;
|
|
1350
|
+
try {
|
|
1351
|
+
workspace = await workspaceConfig.mergeWrite((config) => {
|
|
1352
|
+
const disabled = new Set(config.disabledProviders);
|
|
1353
|
+
if (body.data.enabled)
|
|
1354
|
+
disabled.delete(provider.data);
|
|
1355
|
+
else
|
|
1356
|
+
disabled.add(provider.data);
|
|
1357
|
+
config.disabledProviders = PROVIDER_IDS.filter((id) => disabled.has(id));
|
|
1358
|
+
});
|
|
1359
|
+
}
|
|
1360
|
+
catch {
|
|
1361
|
+
return c.json({ error: 'Provider preference could not be saved.' }, 500);
|
|
1362
|
+
}
|
|
1363
|
+
const result = applyProviderEnablement(await providerAuth.status(), workspace.disabledProviders);
|
|
1364
|
+
const row = result.providers.find(({ provider: id }) => id === provider.data);
|
|
1365
|
+
if (row)
|
|
1366
|
+
workspaceEvents.emit('provider-status', row);
|
|
1367
|
+
return c.json(result);
|
|
1368
|
+
})
|
|
1369
|
+
.post('/providers/:provider/retry', paramZodValidator(z.object({ provider: providerParamSchema }), { message: 'provider and current authFailureId are required' }), jsonZodValidator(providerRetrySchema, { message: 'provider and current authFailureId are required' }), async (c) => {
|
|
1370
|
+
const provider = { data: c.req.valid('param').provider };
|
|
1371
|
+
const body = { data: c.req.valid('json') };
|
|
1372
|
+
if (!providerAuth.clearRuntimeAuthFailure(provider.data, body.data.authFailureId)) {
|
|
1373
|
+
return c.json({ error: 'Authentication incident changed. Refresh and try again.' }, 409);
|
|
1374
|
+
}
|
|
1375
|
+
const result = await providerStatus({ refresh: true });
|
|
1376
|
+
const row = result.providers.find(({ provider: id }) => id === provider.data);
|
|
1377
|
+
if (row)
|
|
1378
|
+
workspaceEvents.emit('provider-status', row);
|
|
1379
|
+
return c.json(result);
|
|
1380
|
+
})
|
|
1381
|
+
.post('/providers/connect', jsonZodValidator(providerConnectSchema, { message: 'provider must be claude, codex, or opencode' }), async (c) => {
|
|
1382
|
+
const body = { data: c.req.valid('json') };
|
|
1383
|
+
const provider = body.data.provider;
|
|
1384
|
+
// A NAMED account is refused in hosted mode before anything is resolved, exactly like every
|
|
1385
|
+
// sibling route in the agent-profiles family. Checking later would already have read
|
|
1386
|
+
// `~/.cezar/agent-accounts.json`, built a command carrying the account's absolute path (which
|
|
1387
|
+
// both the success body and the hosted 409 echo), and — for a stored account — spawned a
|
|
1388
|
+
// probe. It would also answer `unknown account: <id>` for a wrong id, which is an enumeration
|
|
1389
|
+
// oracle for the very ids the hosted listing withholds. The bare-provider spelling keeps its
|
|
1390
|
+
// existing behaviour: it names no host path and is how the Providers card has always worked.
|
|
1391
|
+
if (body.data.profileId !== undefined
|
|
1392
|
+
&& body.data.profileId !== DEFAULT_AGENT_ACCOUNT_ID
|
|
1393
|
+
&& !capabilities().localHandoff) {
|
|
1394
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1395
|
+
}
|
|
1396
|
+
// Resolve the account BEFORE anything else: both the command and the status probe below
|
|
1397
|
+
// must describe the same one, or the pane reports on the personal login while the terminal
|
|
1398
|
+
// signs into the work login.
|
|
1399
|
+
const resolved = await resolveWorkspaceProfile(provider, body.data.profileId);
|
|
1400
|
+
if ('error' in resolved)
|
|
1401
|
+
return c.json({ error: resolved.error }, 400);
|
|
1402
|
+
const { profile } = resolved;
|
|
1403
|
+
const command = providerAuth.loginCommand(provider, profile.isDefault ? null : profile.path);
|
|
1404
|
+
// Fail closed: a config dir that cannot be embedded safely in this platform's shell has no
|
|
1405
|
+
// safe degradation. Running the bare command would sign the user into a DIFFERENT account
|
|
1406
|
+
// than the one they clicked, and nothing in the terminal would say so.
|
|
1407
|
+
if (command === null) {
|
|
1408
|
+
return c.json({ error: `This account's folder cannot be used in a terminal command: ${profile.configDir}` }, 409);
|
|
1409
|
+
}
|
|
1410
|
+
// BOTH branches must mean "is this account signed in NOW". The default branch refreshes; the
|
|
1411
|
+
// account branch has to evict first, because `profileStatus` serves the per-account cache and
|
|
1412
|
+
// a connected answer there stands for CONNECTED_TTL_MS. Without this, Connect after a
|
|
1413
|
+
// `claude /logout` answers "already connected", opens nothing, and the user is stuck — and it
|
|
1414
|
+
// would contradict this module's own invariant that opening a login is one of the things
|
|
1415
|
+
// cezar CAN observe and therefore invalidates explicitly rather than waiting out a window.
|
|
1416
|
+
if (!profile.isDefault)
|
|
1417
|
+
providerAuth.forgetProfileStatus(provider, profile.id);
|
|
1418
|
+
const row = profile.isDefault
|
|
1419
|
+
? (await providerAuth.status({ refresh: true })).providers.find((candidate) => candidate.provider === provider)
|
|
1420
|
+
: await providerAuth.profileStatus(provider, { id: profile.id, configDir: profile.path });
|
|
1421
|
+
if (!row) {
|
|
1422
|
+
return c.json({ error: 'Authentication could not be verified. Try again.' }, 500);
|
|
1423
|
+
}
|
|
1424
|
+
if (row.status === 'connected') {
|
|
1425
|
+
return c.json({ opened: false, connected: true, command });
|
|
1426
|
+
}
|
|
1427
|
+
if (row.status === 'not-installed') {
|
|
1428
|
+
return c.json({ error: row.hint ?? providerAuth.installHint(provider), command }, 409);
|
|
1429
|
+
}
|
|
1430
|
+
if (row.status === 'unknown') {
|
|
1431
|
+
return c.json({ error: row.hint ?? 'Authentication could not be verified. Try again.', command }, 409);
|
|
1432
|
+
}
|
|
1433
|
+
if (!capabilities().localHandoff) {
|
|
1434
|
+
return c.json({ error: 'Run this command on the machine hosting cezar.', command }, 409);
|
|
1435
|
+
}
|
|
1436
|
+
let opened = false;
|
|
1437
|
+
try {
|
|
1438
|
+
// No `env` argument: `loginCommand` already rendered the account's config dir INTO the
|
|
1439
|
+
// command, because this string is also the copy-paste fallback the pane shows. Passing
|
|
1440
|
+
// it again here would set the variable twice.
|
|
1441
|
+
opened = await openTerminal(bootRoot, command);
|
|
1442
|
+
}
|
|
1443
|
+
catch {
|
|
1444
|
+
// Terminal handoff is best-effort; the exact command remains the safe fallback.
|
|
1445
|
+
}
|
|
1446
|
+
if (!opened) {
|
|
1447
|
+
return c.json({ error: 'No terminal emulator could be opened. Run this command manually.', command }, 409);
|
|
1448
|
+
}
|
|
1449
|
+
return c.json({ opened: true, command });
|
|
1450
|
+
});
|
|
1451
|
+
// ---- chained family: agent profiles / accounts (workspace-level) ----------
|
|
1452
|
+
// Extra config dirs for a SECOND login of the same agent CLI (spec
|
|
1453
|
+
// 2026-07-29-agent-profiles). Workspace-level and therefore SINGLE-MOUNT: an account belongs to
|
|
1454
|
+
// the person and the machine, never to a repo, and a project-scoped spelling would be a second
|
|
1455
|
+
// surface to protect with no consumer. Which account a project uses is a field on
|
|
1456
|
+
// `PATCH /api/v1/projects/:projectId` instead.
|
|
1457
|
+
//
|
|
1458
|
+
// Writing is a LOCAL-MACHINE capability, exactly like `PUT /api/v1/agent-config/:id`: a profile
|
|
1459
|
+
// points an agent at a directory on the host, and the listing echoes absolute paths carrying
|
|
1460
|
+
// the username — the same disclosure `/api/v1/health` trims in hosted mode (#431).
|
|
1461
|
+
/**
|
|
1462
|
+
* This agent's own USER-scope config files, resolved inside ONE account's folder.
|
|
1463
|
+
*
|
|
1464
|
+
* Straight from the catalog — the single home of config-file vendor knowledge — with an
|
|
1465
|
+
* `AgentHomePaths` whose slot for this provider is the account's dir. That is what makes a second
|
|
1466
|
+
* login's `settings.json` the file you open rather than the default account's, and it keeps the
|
|
1467
|
+
* ids opaque and stable so the open route below never takes a path from the client.
|
|
1468
|
+
*/
|
|
1469
|
+
const accountFiles = async (profile) => {
|
|
1470
|
+
const home = {
|
|
1471
|
+
...agentHomePaths(),
|
|
1472
|
+
...(profile.provider === 'claude' ? { claude: profile.path } : {}),
|
|
1473
|
+
...(profile.provider === 'codex' ? { codex: profile.path } : {}),
|
|
1474
|
+
...(profile.provider === 'opencode' ? { opencodeConfig: profile.path } : {}),
|
|
1475
|
+
};
|
|
1476
|
+
const defs = listConfigFiles().filter((def) => def.scope === 'user' && def.runners.includes(profile.provider));
|
|
1477
|
+
return Promise.all(defs.map(async (def) => {
|
|
1478
|
+
const path = def.resolve(bootRoot, home);
|
|
1479
|
+
return { id: def.id, label: basename(path), path, exists: (await statConfigPath(path)).exists };
|
|
1480
|
+
}));
|
|
1481
|
+
};
|
|
1482
|
+
/** Build the wire row for one resolved profile: its dir state plus whatever auth is cached. */
|
|
1483
|
+
const agentProfileBody = async (profile) => ({
|
|
1484
|
+
id: profile.id,
|
|
1485
|
+
provider: profile.provider,
|
|
1486
|
+
label: profile.label,
|
|
1487
|
+
configDir: profile.configDir,
|
|
1488
|
+
path: profile.path,
|
|
1489
|
+
...(await profileDirState(profile.provider, profile.path)),
|
|
1490
|
+
isDefault: profile.isDefault,
|
|
1491
|
+
// CACHED auth only — this listing must never pay a CLI spawn.
|
|
1492
|
+
//
|
|
1493
|
+
// Probing here cost a shell-out per provider PLUS one per extra account: ~0.7s with no extra
|
|
1494
|
+
// accounts and over 2s with a few, on every cold load, for a route whose real job (what
|
|
1495
|
+
// accounts exist) is a JSON read and a handful of stats. `GET /api/v1/health` already
|
|
1496
|
+
// established the rule — it serves whatever the cache holds and never pays a `gh` shell-out.
|
|
1497
|
+
// An absent `status` means "not determined yet", which the cockpit renders as Checking… and
|
|
1498
|
+
// then fills in from the per-account status route below.
|
|
1499
|
+
//
|
|
1500
|
+
// SPREAD, not `status: maybeUndefined`: hono would type the key as always-present while
|
|
1501
|
+
// `JSON.stringify` drops it, which is exactly the drift `contract-parity` catches (AGENTS.md
|
|
1502
|
+
// names this as one of the two recurring mismatches).
|
|
1503
|
+
...(() => {
|
|
1504
|
+
const cached = profile.isDefault
|
|
1505
|
+
? providerAuth.peekStatus()?.providers.find((row) => row.provider === profile.provider)
|
|
1506
|
+
: providerAuth.peekProfileStatus(profile.provider, profile.id);
|
|
1507
|
+
return cached ? { status: cached } : {};
|
|
1508
|
+
})(),
|
|
1509
|
+
files: await accountFiles(profile),
|
|
1510
|
+
});
|
|
1511
|
+
/**
|
|
1512
|
+
* Resolve `:id` to an account for the per-account reads below. Unlike `resolveWorkspaceProfile`
|
|
1513
|
+
* this accepts the reserved `default` for a NAMED provider, which these routes cannot infer — so
|
|
1514
|
+
* the id may be `default:<provider>` as well as a stored account id.
|
|
1515
|
+
*/
|
|
1516
|
+
const accountById = async (id) => {
|
|
1517
|
+
const [head, tail] = id.split(':');
|
|
1518
|
+
if (head === DEFAULT_AGENT_ACCOUNT_ID) {
|
|
1519
|
+
const provider = PROVIDER_IDS.find((p) => p === tail);
|
|
1520
|
+
return provider ? defaultAgentProfile(provider) : null;
|
|
1521
|
+
}
|
|
1522
|
+
try {
|
|
1523
|
+
const stored = (await loadAgentAccounts()).accounts.find((a) => a.id === id);
|
|
1524
|
+
return stored ? resolveStoredProfile(stored) : null;
|
|
1525
|
+
}
|
|
1526
|
+
catch {
|
|
1527
|
+
return null;
|
|
1528
|
+
}
|
|
1529
|
+
};
|
|
1530
|
+
/** Validate a client-supplied config dir. Returns the error text, or null when it is usable. */
|
|
1531
|
+
const checkProfileDir = (configDir) => {
|
|
1532
|
+
if (CONTROL_CHARS_RE.test(configDir))
|
|
1533
|
+
return 'folder must not contain control characters';
|
|
1534
|
+
const expanded = expandTilde(configDir);
|
|
1535
|
+
// Absolute after expansion: a relative dir would resolve against whatever cwd the agent
|
|
1536
|
+
// happens to be spawned in, which for a task is a throwaway worktree. Through
|
|
1537
|
+
// `isAbsoluteConfigDir`, never a leading-`/` test — see its note: a string test refuses every
|
|
1538
|
+
// real Windows path, and this is the only gate the Add-account dialog has.
|
|
1539
|
+
if (!isAbsoluteConfigDir(expanded))
|
|
1540
|
+
return `folder must be an absolute path: ${configDir}`;
|
|
1541
|
+
return null;
|
|
1542
|
+
};
|
|
1543
|
+
/** Refuse a dir that is already some other account's (or the default's), compared through
|
|
1544
|
+
* `realpath` — two spellings of one directory would be two accounts silently sharing one
|
|
1545
|
+
* session store, and "which one am I logged into?" would stop having an answer. */
|
|
1546
|
+
const conflictingProfile = async (profiles, provider, path, exceptId) => {
|
|
1547
|
+
if (await sameProfileDir(path, defaultAgentProfile(provider).path)) {
|
|
1548
|
+
return 'that is already this agent\'s default folder';
|
|
1549
|
+
}
|
|
1550
|
+
for (const candidate of profiles) {
|
|
1551
|
+
if (candidate.provider !== provider || candidate.id === exceptId)
|
|
1552
|
+
continue;
|
|
1553
|
+
if (await sameProfileDir(path, expandTilde(candidate.configDir))) {
|
|
1554
|
+
return `that folder is already used by "${candidate.label || candidate.id}"`;
|
|
1555
|
+
}
|
|
1556
|
+
}
|
|
1557
|
+
return null;
|
|
1558
|
+
};
|
|
1559
|
+
const agentProfilesRoutes = new Hono()
|
|
1560
|
+
.get('/workspace/agent-profiles', async (c) => {
|
|
1561
|
+
const editable = capabilities().localHandoff;
|
|
1562
|
+
// Hosted mode withholds the listing entirely rather than serving it read-only: the paths
|
|
1563
|
+
// are the host disclosure, so an empty list is the only honest hosted answer.
|
|
1564
|
+
//
|
|
1565
|
+
// ONE body object, never a hosted `return` and a local `return`: two returns let hono
|
|
1566
|
+
// narrow `editable` to the literal `false`/`true` of each branch, and the contract's
|
|
1567
|
+
// honest `z.boolean()` then reads as wider than the route. Same shape as
|
|
1568
|
+
// `listAgentConfig`, which carries the same flag for the same reason.
|
|
1569
|
+
let store = defaultAgentAccountStore();
|
|
1570
|
+
if (editable) {
|
|
1571
|
+
try {
|
|
1572
|
+
store = await loadAgentAccounts();
|
|
1573
|
+
}
|
|
1574
|
+
catch {
|
|
1575
|
+
// an unreadable home degrades to "no extra accounts", never a failed request
|
|
1576
|
+
}
|
|
1577
|
+
}
|
|
1578
|
+
const profiles = editable
|
|
1579
|
+
? await Promise.all(listAgentProfiles(store, PROVIDER_IDS).map(agentProfileBody))
|
|
1580
|
+
: [];
|
|
1581
|
+
return c.json({
|
|
1582
|
+
editable,
|
|
1583
|
+
profiles,
|
|
1584
|
+
profileCapableProviders: [...PROFILE_CAPABLE_PROVIDERS],
|
|
1585
|
+
// Which account each project uses, keyed by repo root. Served here rather than on the
|
|
1586
|
+
// project registry because it lives in the same file as the accounts it names.
|
|
1587
|
+
selections: editable ? store.selections : {},
|
|
1588
|
+
/** The machine-wide fallback, for repos that have chosen nothing. Withheld in hosted mode
|
|
1589
|
+
* on the same terms as the rest of this family. */
|
|
1590
|
+
defaults: editable ? store.defaults : {},
|
|
1591
|
+
});
|
|
1592
|
+
})
|
|
1593
|
+
.post('/workspace/agent-profiles', jsonZodValidator(() => createAgentProfileSchema), async (c) => {
|
|
1594
|
+
if (!capabilities().localHandoff)
|
|
1595
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1596
|
+
const { provider, configDir, label } = c.req.valid('json');
|
|
1597
|
+
if (!supportsProfiles(provider)) {
|
|
1598
|
+
return c.json({ error: `${provider} cannot carry more than one account` }, 400);
|
|
1599
|
+
}
|
|
1600
|
+
const dirError = checkProfileDir(configDir);
|
|
1601
|
+
if (dirError)
|
|
1602
|
+
return c.json({ error: dirError }, 400);
|
|
1603
|
+
// Read-first, exactly like `POST /projects`: the duplicate check needs `realpath`, and the
|
|
1604
|
+
// merge-write mutator is deliberately SYNCHRONOUS so the read→rename window stays as small
|
|
1605
|
+
// as it is for every other writer of this file. Two processes adding the same folder in
|
|
1606
|
+
// that window would both win — a cosmetic duplicate, not a correctness problem, since the
|
|
1607
|
+
// schema's id dedupe is what keeps resolution deterministic.
|
|
1608
|
+
let existing = [];
|
|
1609
|
+
try {
|
|
1610
|
+
existing = (await loadAgentAccounts()).accounts;
|
|
1611
|
+
}
|
|
1612
|
+
catch {
|
|
1613
|
+
// unreadable store — the merge-write below reports the real failure
|
|
1614
|
+
}
|
|
1615
|
+
const conflict = await conflictingProfile(existing, provider, expandTilde(configDir));
|
|
1616
|
+
if (conflict !== null)
|
|
1617
|
+
return c.json({ error: conflict }, 409);
|
|
1618
|
+
let created;
|
|
1619
|
+
try {
|
|
1620
|
+
await mergeWriteAgentAccounts((store) => {
|
|
1621
|
+
const id = allocateAgentProfileId(label ?? configDir, store.accounts.map((a) => a.id));
|
|
1622
|
+
created = {
|
|
1623
|
+
id,
|
|
1624
|
+
provider,
|
|
1625
|
+
configDir,
|
|
1626
|
+
label: label?.trim() || id,
|
|
1627
|
+
addedAt: new Date().toISOString(),
|
|
1628
|
+
};
|
|
1629
|
+
store.accounts.push(created);
|
|
1630
|
+
});
|
|
1631
|
+
}
|
|
1632
|
+
catch (err) {
|
|
1633
|
+
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
1634
|
+
}
|
|
1635
|
+
if (!created)
|
|
1636
|
+
return c.json({ error: 'account could not be saved' }, 500);
|
|
1637
|
+
// A brand-new account is the one thing the boot warm could not have known about, so learn it
|
|
1638
|
+
// now rather than only when something asks. Still off the response: the row is returned with
|
|
1639
|
+
// `status` absent (the listing's rule), the pane shows Checking…, and its follow-up request
|
|
1640
|
+
// joins this same in-flight probe.
|
|
1641
|
+
const account = resolveStoredProfile(created);
|
|
1642
|
+
const created201 = await agentProfileBody(account);
|
|
1643
|
+
void providerAuth
|
|
1644
|
+
.profileStatus(account.provider, { id: account.id, configDir: account.path })
|
|
1645
|
+
.catch(() => { });
|
|
1646
|
+
return c.json({ profile: created201 }, 201);
|
|
1647
|
+
})
|
|
1648
|
+
.patch('/workspace/agent-profiles/:id', paramZodValidator(z.object({ id: z.string() })), jsonZodValidator(() => updateAgentProfileSchema), async (c) => {
|
|
1649
|
+
if (!capabilities().localHandoff)
|
|
1650
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1651
|
+
const id = c.req.param('id');
|
|
1652
|
+
const { label, configDir } = c.req.valid('json');
|
|
1653
|
+
if (configDir !== undefined) {
|
|
1654
|
+
const dirError = checkProfileDir(configDir);
|
|
1655
|
+
if (dirError)
|
|
1656
|
+
return c.json({ error: dirError }, 400);
|
|
1657
|
+
}
|
|
1658
|
+
// Read-first (see POST above, and `PATCH /projects`): a well-formed but unknown id must
|
|
1659
|
+
// 404 WITHOUT rewriting the config, and the duplicate check needs async `realpath`.
|
|
1660
|
+
let existing = [];
|
|
1661
|
+
try {
|
|
1662
|
+
existing = (await loadAgentAccounts()).accounts;
|
|
1663
|
+
}
|
|
1664
|
+
catch {
|
|
1665
|
+
// unreadable store — treated as unknown, like DELETE and PATCH /projects
|
|
1666
|
+
}
|
|
1667
|
+
const current = existing.find((a) => a.id === id);
|
|
1668
|
+
if (!current)
|
|
1669
|
+
return c.json({ error: `unknown account: ${id}` }, 404);
|
|
1670
|
+
if (configDir !== undefined) {
|
|
1671
|
+
const conflict = await conflictingProfile(existing, current.provider, expandTilde(configDir), id);
|
|
1672
|
+
if (conflict !== null)
|
|
1673
|
+
return c.json({ error: conflict }, 409);
|
|
1674
|
+
}
|
|
1675
|
+
let updated;
|
|
1676
|
+
try {
|
|
1677
|
+
await mergeWriteAgentAccounts((store) => {
|
|
1678
|
+
const entry = store.accounts.find((a) => a.id === id);
|
|
1679
|
+
if (!entry)
|
|
1680
|
+
return; // lost a race with a concurrent delete — answered below
|
|
1681
|
+
// Mutated in place so `.passthrough()` keys on the row survive.
|
|
1682
|
+
if (label !== undefined)
|
|
1683
|
+
entry.label = label.trim() || entry.id;
|
|
1684
|
+
if (configDir !== undefined)
|
|
1685
|
+
entry.configDir = configDir;
|
|
1686
|
+
updated = entry;
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
catch (err) {
|
|
1690
|
+
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
1691
|
+
}
|
|
1692
|
+
if (!updated)
|
|
1693
|
+
return c.json({ error: `unknown account: ${id}` }, 404);
|
|
1694
|
+
// The dir may have moved under a cached probe — drop THIS account's answer so the response
|
|
1695
|
+
// reports the new folder's state rather than the old one's, and leave every other account's
|
|
1696
|
+
// warm answer alone (it is still true). Then re-learn it in the background, so the server's
|
|
1697
|
+
// knowledge is complete again whether or not a cockpit is open to ask; the pane's own
|
|
1698
|
+
// request for this row joins the same in-flight probe rather than spawning a second.
|
|
1699
|
+
const repointed = resolveStoredProfile(updated);
|
|
1700
|
+
providerAuth.forgetProfileStatus(repointed.provider, repointed.id);
|
|
1701
|
+
const body = await agentProfileBody(repointed);
|
|
1702
|
+
void providerAuth
|
|
1703
|
+
.profileStatus(repointed.provider, { id: repointed.id, configDir: repointed.path })
|
|
1704
|
+
.catch(() => { });
|
|
1705
|
+
return c.json({ profile: body });
|
|
1706
|
+
})
|
|
1707
|
+
/**
|
|
1708
|
+
* One account's authentication state, probed for real.
|
|
1709
|
+
*
|
|
1710
|
+
* Separate from the listing because a probe shells out to an agent CLI: keeping it here lets
|
|
1711
|
+
* the pane paint immediately and fill each row in as its answer lands, instead of every cold
|
|
1712
|
+
* load blocking on N spawns. `refresh=1` drops this account's cached answer and re-probes, for
|
|
1713
|
+
* the "Check again" affordance — the cache itself holds a connected answer for minutes and an
|
|
1714
|
+
* unsettled one for a minute (`cacheTtlFor` in `core/provider-auth.ts`).
|
|
1715
|
+
*/
|
|
1716
|
+
.get('/workspace/agent-profiles/:id/status', paramZodValidator(z.object({ id: z.string() })), queryZodValidator(z.object({ refresh: queryValue.refine((v) => v === undefined || v === '1') }), { message: 'refresh must be 1 when provided' }), async (c) => {
|
|
1717
|
+
if (!capabilities().localHandoff)
|
|
1718
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1719
|
+
const account = await accountById(c.req.param('id'));
|
|
1720
|
+
if (!account)
|
|
1721
|
+
return c.json({ error: `unknown account: ${c.req.param('id')}` }, 404);
|
|
1722
|
+
const refresh = c.req.valid('query').refresh === '1';
|
|
1723
|
+
// The discovered account's row is the one `GET /api/v1/providers/status` owns, so it comes
|
|
1724
|
+
// from there — enablement included, which a bare probe does not know about.
|
|
1725
|
+
if (account.isDefault) {
|
|
1726
|
+
const all = await providerStatus(refresh ? { refresh: true } : undefined);
|
|
1727
|
+
const row = all.providers.find((candidate) => candidate.provider === account.provider);
|
|
1728
|
+
return c.json({ status: row ?? { provider: account.provider, status: 'unknown' } });
|
|
1729
|
+
}
|
|
1730
|
+
// "Check again" re-probes THIS account only — the other accounts' warm answers are not
|
|
1731
|
+
// invalidated by asking about this one.
|
|
1732
|
+
if (refresh)
|
|
1733
|
+
providerAuth.forgetProfileStatus(account.provider, account.id);
|
|
1734
|
+
return c.json({
|
|
1735
|
+
status: await providerAuth.profileStatus(account.provider, {
|
|
1736
|
+
id: account.id,
|
|
1737
|
+
configDir: account.path,
|
|
1738
|
+
}),
|
|
1739
|
+
});
|
|
1740
|
+
})
|
|
1741
|
+
/**
|
|
1742
|
+
* Who this account is signed in AS — the pane's "Show details".
|
|
1743
|
+
*
|
|
1744
|
+
* A separate, on-demand route rather than a field on the listing, and that is what makes
|
|
1745
|
+
* "hidden by default" real: an email carried by the listing would already be in the response,
|
|
1746
|
+
* the query cache and devtools, whatever the UI chose to render. `provider-auth.ts` keeps
|
|
1747
|
+
* identity out of ITS boundary on purpose; this is the deliberate, local-only, opt-in
|
|
1748
|
+
* exception — not a widening of that rule. Never logged, never persisted.
|
|
1749
|
+
*/
|
|
1750
|
+
.get('/workspace/agent-profiles/:id/details', paramZodValidator(z.object({ id: z.string() })), async (c) => {
|
|
1751
|
+
if (!capabilities().localHandoff)
|
|
1752
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1753
|
+
const account = await accountById(c.req.param('id'));
|
|
1754
|
+
if (!account)
|
|
1755
|
+
return c.json({ error: `unknown account: ${c.req.param('id')}` }, 404);
|
|
1756
|
+
return c.json(await readAccountIdentity(account.provider, account.path));
|
|
1757
|
+
})
|
|
1758
|
+
/**
|
|
1759
|
+
* Open one of this account's own config files — or its folder — in a local app.
|
|
1760
|
+
*
|
|
1761
|
+
* `file` is a catalog ID from the account's own `files`, never a path: the client cannot name a
|
|
1762
|
+
* location, so there is no traversal surface here at all (the same rule
|
|
1763
|
+
* `/api/v1/agent-config/:id` follows). `folder` is the one extra keyword, and it resolves to
|
|
1764
|
+
* the account's dir rather than anything the caller spelled.
|
|
1765
|
+
*/
|
|
1766
|
+
.post('/workspace/agent-profiles/:id/open', paramZodValidator(z.object({ id: z.string() })), jsonZodValidator(() => openAgentAccountFileSchema), async (c) => {
|
|
1767
|
+
if (!capabilities().localHandoff)
|
|
1768
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1769
|
+
const account = await accountById(c.req.param('id'));
|
|
1770
|
+
if (!account)
|
|
1771
|
+
return c.json({ error: `unknown account: ${c.req.param('id')}` }, 404);
|
|
1772
|
+
const { file, target } = c.req.valid('json');
|
|
1773
|
+
let path;
|
|
1774
|
+
if (file === 'folder') {
|
|
1775
|
+
path = account.path;
|
|
1776
|
+
}
|
|
1777
|
+
else {
|
|
1778
|
+
const match = (await accountFiles(account)).find((f) => f.id === file);
|
|
1779
|
+
if (!match)
|
|
1780
|
+
return c.json({ error: `unknown file: ${file}` }, 404);
|
|
1781
|
+
path = match.path;
|
|
1782
|
+
}
|
|
1783
|
+
// A file the agent has not written yet has nothing to open; say so rather than hand the OS
|
|
1784
|
+
// a missing path and report success.
|
|
1785
|
+
if (!(await statConfigPath(path)).exists && file !== 'folder') {
|
|
1786
|
+
return c.json({ error: `this account has no ${basename(path)} yet` }, 409);
|
|
1787
|
+
}
|
|
1788
|
+
// `target` names a detected app; absent means the OS default handler. Either way the PATH
|
|
1789
|
+
// came from the catalog, so an editor is only ever pointed inside this account's folder.
|
|
1790
|
+
//
|
|
1791
|
+
// Which targets APPLY is checked here rather than left to the UI, because two of them are
|
|
1792
|
+
// actively wrong rather than merely useless: `terminal` runs `cd <path>`, which fails on a
|
|
1793
|
+
// file, and a `cli:<runner>` handoff would start an agent session inside the config folder.
|
|
1794
|
+
// A route is a surface of its own; it refuses what it cannot do correctly.
|
|
1795
|
+
if (target !== undefined) {
|
|
1796
|
+
if (agentCliRunner(target) !== null) {
|
|
1797
|
+
return c.json({ error: 'agent CLIs open a task worktree, not a config folder' }, 400);
|
|
1798
|
+
}
|
|
1799
|
+
if (target === 'terminal' && file !== 'folder') {
|
|
1800
|
+
return c.json({ error: 'a terminal opens a folder, not a file' }, 400);
|
|
1801
|
+
}
|
|
1802
|
+
if (!detectOpenTargets().some((candidate) => candidate.id === target)) {
|
|
1803
|
+
return c.json({ error: `no such app on this machine: ${target}` }, 400);
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
const opened = target === undefined
|
|
1807
|
+
? await openFile(path)
|
|
1808
|
+
: await openInApp(target, path);
|
|
1809
|
+
if (!opened)
|
|
1810
|
+
return c.json({ error: `could not open ${basename(path)}`, path }, 409);
|
|
1811
|
+
return c.json({ opened: true, path });
|
|
1812
|
+
})
|
|
1813
|
+
// Which account a PROJECT uses. On the accounts family rather than `PATCH /api/v1/projects`
|
|
1814
|
+
// because the selection is stored beside the accounts it names — one file, one atomic write,
|
|
1815
|
+
// and nothing about it can be dropped by a cezar version that never heard of accounts.
|
|
1816
|
+
.put('/workspace/agent-profiles/selection', jsonZodValidator(() => selectAgentProfileSchema), async (c) => {
|
|
1817
|
+
if (!capabilities().localHandoff)
|
|
1818
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1819
|
+
const { projectId, provider, profileId } = c.req.valid('json');
|
|
1820
|
+
// `null` writes the MACHINE-WIDE default instead of one repo's selection: the account any
|
|
1821
|
+
// repo that has chosen nothing uses, so a second login is set up once rather than per
|
|
1822
|
+
// checkout. No project to resolve, and therefore no 404 path.
|
|
1823
|
+
let root = null;
|
|
1824
|
+
if (projectId !== null) {
|
|
1825
|
+
const resolvedId = projectId === 'default' ? await resolveBootProject() : projectId;
|
|
1826
|
+
// Keyed by repo ROOT, so the selection survives the registry being rebuilt and needs no
|
|
1827
|
+
// cross-reference into config.json. An unknown project is a 404 rather than an orphan
|
|
1828
|
+
// entry nobody will ever read.
|
|
1829
|
+
root = await projectRootFor(resolvedId);
|
|
1830
|
+
if (root === null)
|
|
1831
|
+
return c.json({ error: `unknown project: ${projectId}` }, 404);
|
|
1832
|
+
}
|
|
1833
|
+
// A user naming an account that does not exist gets told so — the opposite of how RUN
|
|
1834
|
+
// resolution treats a dangling stored id, and deliberately: a run has no better answer
|
|
1835
|
+
// than the default, a person does.
|
|
1836
|
+
if (profileId !== null && profileId !== DEFAULT_AGENT_ACCOUNT_ID) {
|
|
1837
|
+
const account = await resolveWorkspaceProfile(provider, profileId);
|
|
1838
|
+
if ('error' in account)
|
|
1839
|
+
return c.json({ error: account.error }, 400);
|
|
1840
|
+
}
|
|
1841
|
+
let store;
|
|
1842
|
+
try {
|
|
1843
|
+
store = await mergeWriteAgentAccounts((current) => {
|
|
1844
|
+
// One rule, two targets: the machine default is the same per-provider shape as a repo's
|
|
1845
|
+
// selection, so it clears the same way rather than growing its own spelling.
|
|
1846
|
+
const selection = root === null ? current.defaults : current.selections[root] ?? {};
|
|
1847
|
+
// `null` and the reserved `default` both mean "back to the discovered account", which
|
|
1848
|
+
// is stored as ABSENCE — the default id is never written to the file.
|
|
1849
|
+
if (profileId === null || profileId === DEFAULT_AGENT_ACCOUNT_ID)
|
|
1850
|
+
delete selection[provider];
|
|
1851
|
+
else
|
|
1852
|
+
selection[provider] = profileId;
|
|
1853
|
+
// The machine default keeps an emptied object where a repo selection is deleted, and
|
|
1854
|
+
// that asymmetry is the schema's, not an oversight: `defaults` is one FIXED field with
|
|
1855
|
+
// `.default(() => ({}))`, so `mergeWriteAgentAccounts` re-materializes it on the next
|
|
1856
|
+
// write no matter what this one omits (verified). `selections` is a growing MAP, where
|
|
1857
|
+
// an emptied entry is a row per repo ever touched that says nothing. The rule stated
|
|
1858
|
+
// for `agentDefaults.models` — "absence is the same answer" — applies there because
|
|
1859
|
+
// that key is `.optional()`, so deleting it actually sticks.
|
|
1860
|
+
if (root === null)
|
|
1861
|
+
current.defaults = selection;
|
|
1862
|
+
else if (Object.keys(selection).length === 0)
|
|
1863
|
+
delete current.selections[root];
|
|
1864
|
+
else
|
|
1865
|
+
current.selections[root] = selection;
|
|
1866
|
+
});
|
|
1867
|
+
}
|
|
1868
|
+
catch (err) {
|
|
1869
|
+
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
1870
|
+
}
|
|
1871
|
+
return c.json({ selections: store.selections, defaults: store.defaults });
|
|
1872
|
+
})
|
|
1873
|
+
.delete('/workspace/agent-profiles/:id', paramZodValidator(z.object({ id: z.string() })), async (c) => {
|
|
1874
|
+
if (!capabilities().localHandoff)
|
|
1875
|
+
return c.json(hostedProfileRefusal, 409);
|
|
1876
|
+
const id = c.req.param('id');
|
|
1877
|
+
let removed = false;
|
|
1878
|
+
// Captured inside the mutator, because after the write there is nothing left to ask which
|
|
1879
|
+
// provider this account belonged to — and the eviction below is keyed by it.
|
|
1880
|
+
let removedProvider;
|
|
1881
|
+
try {
|
|
1882
|
+
await mergeWriteAgentAccounts((store) => {
|
|
1883
|
+
const before = store.accounts.length;
|
|
1884
|
+
removedProvider = store.accounts.find((a) => a.id === id)?.provider;
|
|
1885
|
+
store.accounts = store.accounts.filter((a) => a.id !== id);
|
|
1886
|
+
removed = store.accounts.length < before;
|
|
1887
|
+
if (!removed)
|
|
1888
|
+
return;
|
|
1889
|
+
// Scrub every reference IN THE SAME MUTATOR — the reason selections share this file.
|
|
1890
|
+
// A two-call delete-then-scrub can be observed mid-way by another cezar process on
|
|
1891
|
+
// this machine, which would then resolve a dangling id; harmless today (it degrades
|
|
1892
|
+
// to the default) but only by luck.
|
|
1893
|
+
for (const [root, selection] of Object.entries(store.selections)) {
|
|
1894
|
+
for (const key of Object.keys(selection)) {
|
|
1895
|
+
if (selection[key] === id)
|
|
1896
|
+
delete selection[key];
|
|
1897
|
+
}
|
|
1898
|
+
if (Object.keys(selection).length === 0)
|
|
1899
|
+
delete store.selections[root];
|
|
1900
|
+
}
|
|
1901
|
+
});
|
|
1902
|
+
}
|
|
1903
|
+
catch (err) {
|
|
1904
|
+
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
1905
|
+
}
|
|
1906
|
+
if (!removed)
|
|
1907
|
+
return c.json({ error: `unknown account: ${id}` }, 404);
|
|
1908
|
+
// Only this account's answer: it is about to stop existing, and holding it would let a
|
|
1909
|
+
// re-added account with the same id read the deleted one's state.
|
|
1910
|
+
providerAuth.forgetProfileStatus(removedProvider, id);
|
|
1911
|
+
return c.json({ removed: true, id });
|
|
1912
|
+
});
|
|
917
1913
|
// ---- workspace projects (multi-project spec) -----------------------------
|
|
918
1914
|
// The registered-project list for the cockpit sidebar. Same-origin (unlike
|
|
919
1915
|
// health), so absolute `root`s are fine here. `listProjects()` TTL-caches
|
|
@@ -939,7 +1935,9 @@ export function createApp(deps) {
|
|
|
939
1935
|
return defaultWorkspaceConfig().browseRoot;
|
|
940
1936
|
}
|
|
941
1937
|
};
|
|
942
|
-
|
|
1938
|
+
// ---- chained family: project registry (workspace-level) ----
|
|
1939
|
+
const projectsRoutes = new Hono()
|
|
1940
|
+
.get('/projects', async (c) => {
|
|
943
1941
|
let projects = [];
|
|
944
1942
|
let projectsDir = defaultWorkspaceConfig().projectsDir;
|
|
945
1943
|
try {
|
|
@@ -958,38 +1956,196 @@ export function createApp(deps) {
|
|
|
958
1956
|
projectsDir,
|
|
959
1957
|
};
|
|
960
1958
|
return c.json(body);
|
|
961
|
-
})
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
})
|
|
969
|
-
|
|
970
|
-
* The register-a-folder half of `POST /api/projects`, factored out so the
|
|
971
|
-
* checkout route (step 4.3) commits its fresh clone through the SAME guards
|
|
972
|
-
* and the same `project-added` emission rather than a second copy of them.
|
|
973
|
-
* Returns the status + body for the caller to answer with.
|
|
974
|
-
*/
|
|
975
|
-
const registerFolder = async (spelled, source) => {
|
|
1959
|
+
})
|
|
1960
|
+
.post('/projects', jsonZodValidator(() => registerProjectSchema, { message: 'root must be a non-empty path' }), async (c) => {
|
|
1961
|
+
const parsed = { data: c.req.valid('json') };
|
|
1962
|
+
const registered = await registerFolder(parsed.data.root, 'local');
|
|
1963
|
+
if (registered.status !== 200)
|
|
1964
|
+
return c.json(registered.body, registered.status);
|
|
1965
|
+
return c.json(registered.body, 200);
|
|
1966
|
+
})
|
|
1967
|
+
.delete('/projects/:projectId', async (c) => {
|
|
976
1968
|
if (capabilities().singleProject) {
|
|
977
|
-
return
|
|
1969
|
+
return c.json(singleProjectRefusal('removing projects'), 409);
|
|
978
1970
|
}
|
|
979
|
-
|
|
980
|
-
//
|
|
981
|
-
//
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
return {
|
|
985
|
-
status: 400,
|
|
986
|
-
body: { error: `not a folder: ${spelled} is not an absolute path` },
|
|
987
|
-
};
|
|
1971
|
+
const raw = c.req.param('projectId');
|
|
1972
|
+
// Same gate the scoped-route resolver applies, and the same 404 wording —
|
|
1973
|
+
// a malformed id is an unknown project, not a validation essay.
|
|
1974
|
+
if (!projectIdSchema.safeParse(raw).success) {
|
|
1975
|
+
return c.json({ error: `unknown project: ${raw}` }, 404);
|
|
988
1976
|
}
|
|
989
|
-
|
|
990
|
-
// `
|
|
991
|
-
//
|
|
992
|
-
|
|
1977
|
+
const bootId = await resolveBootProject();
|
|
1978
|
+
// `default` is the boot alias everywhere else in the API; honour it here
|
|
1979
|
+
// too rather than 404ing a spelling the cockpit is allowed to use.
|
|
1980
|
+
const id = raw === 'default' ? bootId : raw;
|
|
1981
|
+
let entry;
|
|
1982
|
+
try {
|
|
1983
|
+
entry = (await loadWorkspaceConfig()).projects.find((p) => p.id === id);
|
|
1984
|
+
}
|
|
1985
|
+
catch {
|
|
1986
|
+
// unreadable workspace — there is nothing to remove, and saying so is
|
|
1987
|
+
// more useful than a 500 the user cannot act on
|
|
1988
|
+
}
|
|
1989
|
+
if (!entry)
|
|
1990
|
+
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
1991
|
+
// The boot project is refused, not removed: `cezar serve` re-registers the
|
|
1992
|
+
// repo it was started in on every boot, so "removing" it would undo itself
|
|
1993
|
+
// at the next restart while breaking this session's sidebar in the
|
|
1994
|
+
// meantime. The pane disables the button and says the same thing.
|
|
1995
|
+
if (id === bootId) {
|
|
1996
|
+
return c.json({
|
|
1997
|
+
error: `cezar is serving ${entry.name} right now — it re-registers itself at every start, so it cannot be removed from here`,
|
|
1998
|
+
}, 409);
|
|
1999
|
+
}
|
|
2000
|
+
const active = activeRunCount(id);
|
|
2001
|
+
if (active > 0) {
|
|
2002
|
+
return c.json({
|
|
2003
|
+
error: `${entry.name} has ${active} running task${active === 1 ? '' : 's'} — cancel or finish ${active === 1 ? 'it' : 'them'} before removing the project`,
|
|
2004
|
+
runningTasks: active,
|
|
2005
|
+
}, 409);
|
|
2006
|
+
}
|
|
2007
|
+
let removed;
|
|
2008
|
+
try {
|
|
2009
|
+
removed = await removeProject(id);
|
|
2010
|
+
}
|
|
2011
|
+
catch (err) {
|
|
2012
|
+
// e.g. a read-only home — nothing was persisted (atomic tmp+rename).
|
|
2013
|
+
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
2014
|
+
}
|
|
2015
|
+
// Lost a race with another writer (or another cezar process): the entry is
|
|
2016
|
+
// gone, which is what the caller wanted, but say it honestly.
|
|
2017
|
+
if (!removed)
|
|
2018
|
+
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
2019
|
+
// In-process handles for a project no route can reach any more: store
|
|
2020
|
+
// closed (index flushed), manager's timers and usage subscription dropped.
|
|
2021
|
+
contexts.dispose(id);
|
|
2022
|
+
workspaceEvents.emit('project-removed', { id });
|
|
2023
|
+
const body = { removed: true, id };
|
|
2024
|
+
return c.json(body);
|
|
2025
|
+
})
|
|
2026
|
+
.patch('/projects/:projectId', jsonZodValidator(() => updateProjectSchema), async (c) => {
|
|
2027
|
+
if (capabilities().singleProject) {
|
|
2028
|
+
return c.json(singleProjectRefusal('editing projects'), 409);
|
|
2029
|
+
}
|
|
2030
|
+
const raw = c.req.param('projectId');
|
|
2031
|
+
// Same gate + 404 wording as DELETE: a malformed id is an unknown project.
|
|
2032
|
+
if (!projectIdSchema.safeParse(raw).success) {
|
|
2033
|
+
return c.json({ error: `unknown project: ${raw}` }, 404);
|
|
2034
|
+
}
|
|
2035
|
+
const parsed = { data: c.req.valid('json') };
|
|
2036
|
+
// `default` is the boot alias the cockpit is allowed to use everywhere else.
|
|
2037
|
+
const id = raw === 'default' ? await resolveBootProject() : raw;
|
|
2038
|
+
const { maxParallel } = parsed.data;
|
|
2039
|
+
// Read-first (mirroring DELETE, server.ts:1252-1258): a well-formed but
|
|
2040
|
+
// unknown id must 404 WITHOUT rewriting the config — otherwise it would both
|
|
2041
|
+
// do a needless full-config tmp+rename and, on a read-only home, surface the
|
|
2042
|
+
// write failure as a 500 where the honest answer is 404.
|
|
2043
|
+
let known = false;
|
|
2044
|
+
try {
|
|
2045
|
+
known = (await loadWorkspaceConfig()).projects.some((p) => p.id === id);
|
|
2046
|
+
}
|
|
2047
|
+
catch {
|
|
2048
|
+
// unreadable workspace — treat as unknown; the read-only case answers 404,
|
|
2049
|
+
// not a 500 the caller cannot act on (same reasoning as DELETE).
|
|
2050
|
+
}
|
|
2051
|
+
if (!known)
|
|
2052
|
+
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
2053
|
+
let updated;
|
|
2054
|
+
try {
|
|
2055
|
+
await mergeWriteWorkspaceConfig((config) => {
|
|
2056
|
+
const entry = config.projects.find((p) => p.id === id);
|
|
2057
|
+
if (!entry)
|
|
2058
|
+
return; // lost a race with a concurrent remove — answered below
|
|
2059
|
+
// null clears the override; a number sets it. Mutated in place so
|
|
2060
|
+
// `.passthrough()` keys on the entry survive.
|
|
2061
|
+
if (maxParallel === null)
|
|
2062
|
+
delete entry.maxParallel;
|
|
2063
|
+
else
|
|
2064
|
+
entry.maxParallel = maxParallel;
|
|
2065
|
+
updated = entry;
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
catch (err) {
|
|
2069
|
+
// e.g. a read-only home — nothing was persisted (atomic tmp+rename).
|
|
2070
|
+
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
2071
|
+
}
|
|
2072
|
+
// Raced with a concurrent removal between the read and the write.
|
|
2073
|
+
if (!updated)
|
|
2074
|
+
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
2075
|
+
// The new ceiling takes effect WITHOUT a restart: refresh the shared
|
|
2076
|
+
// semaphore's snapshot and pump every manager — the same live-apply hook
|
|
2077
|
+
// `PUT /api/workspace/config` fires for a workspace-cap change.
|
|
2078
|
+
await deps.semaphore?.refresh();
|
|
2079
|
+
const body = {
|
|
2080
|
+
project: { ...updated, ...(await probeProjectStatus(updated.root)) },
|
|
2081
|
+
};
|
|
2082
|
+
return c.json(body);
|
|
2083
|
+
})
|
|
2084
|
+
.post('/projects/checkout', jsonZodValidator(() => checkoutSchema, { message: 'url must be a GitHub repository' }), async (c) => {
|
|
2085
|
+
if (capabilities().singleProject) {
|
|
2086
|
+
return c.json(singleProjectRefusal('adding projects'), 409);
|
|
2087
|
+
}
|
|
2088
|
+
const parsed = { data: c.req.valid('json') };
|
|
2089
|
+
const { url, name, checkoutId } = parsed.data;
|
|
2090
|
+
const result = await checkoutRepo({
|
|
2091
|
+
url,
|
|
2092
|
+
name,
|
|
2093
|
+
checkoutId,
|
|
2094
|
+
projectsDir: expandTilde(await workspaceProjectsDir()),
|
|
2095
|
+
onProgress: (event) => workspaceEvents.emit('checkout-progress', event),
|
|
2096
|
+
// A closed dialog / navigated-away tab aborts the request; the clone is
|
|
2097
|
+
// killed and its partial directory removed rather than left running.
|
|
2098
|
+
signal: c.req.raw.signal,
|
|
2099
|
+
...(deps.cloneRunner ? { run: deps.cloneRunner } : {}),
|
|
2100
|
+
});
|
|
2101
|
+
if (!result.ok) {
|
|
2102
|
+
// `reason` rides along on the 503 (`gh` unavailable) — the spec's
|
|
2103
|
+
// `{ error, reason }` degradation, mirroring the GitHub pane.
|
|
2104
|
+
return c.json('reason' in result ? { error: result.error, reason: result.reason } : { error: result.error }, result.status);
|
|
2105
|
+
}
|
|
2106
|
+
const registered = await registerFolder(result.target, 'checkout');
|
|
2107
|
+
if (registered.status !== 200) {
|
|
2108
|
+
// The clone SUCCEEDED and its files are legitimately the user's, so this
|
|
2109
|
+
// path deliberately does NOT clean up — an unregisterable checkout is a
|
|
2110
|
+
// registry problem, not a reason to delete a repo we just fetched. Say
|
|
2111
|
+
// where it is so they can register it by hand.
|
|
2112
|
+
const { body } = registered;
|
|
2113
|
+
const error = 'error' in body && body.error ? body.error : 'could not register the checkout';
|
|
2114
|
+
return c.json({ error: `${error} (the clone is at ${result.target})` }, registered.status);
|
|
2115
|
+
}
|
|
2116
|
+
return c.json(registered.body, 200);
|
|
2117
|
+
});
|
|
2118
|
+
// Register an existing folder (multi-project spec, "Add project" — the
|
|
2119
|
+
// folder-browser dialog's commit step, step 4.2). Workspace-level like its
|
|
2120
|
+
// GET twin. Everything here is a guard; the registry write itself is one
|
|
2121
|
+
// idempotent `registerProject` call.
|
|
2122
|
+
const registerProjectSchema = z.object({
|
|
2123
|
+
root: z.string().trim().min(1).max(4096),
|
|
2124
|
+
});
|
|
2125
|
+
/**
|
|
2126
|
+
* The register-a-folder half of `POST /api/projects`, factored out so the
|
|
2127
|
+
* checkout route (step 4.3) commits its fresh clone through the SAME guards
|
|
2128
|
+
* and the same `project-added` emission rather than a second copy of them.
|
|
2129
|
+
* Returns the status + body for the caller to answer with.
|
|
2130
|
+
*/
|
|
2131
|
+
const registerFolder = async (spelled, source) => {
|
|
2132
|
+
if (capabilities().singleProject) {
|
|
2133
|
+
return { status: 409, body: singleProjectRefusal('adding projects') };
|
|
2134
|
+
}
|
|
2135
|
+
// `~` is expanded for the same reason `/api/fs/browse` expands it: the
|
|
2136
|
+
// dialog hands back absolute paths, but a hand-written body (curl, a
|
|
2137
|
+
// future CLI) spells home the way a shell does.
|
|
2138
|
+
const requested = expandTilde(spelled);
|
|
2139
|
+
if (!requested.startsWith('/')) {
|
|
2140
|
+
return {
|
|
2141
|
+
status: 400,
|
|
2142
|
+
body: { error: `not a folder: ${spelled} is not an absolute path` },
|
|
2143
|
+
};
|
|
2144
|
+
}
|
|
2145
|
+
// Hosted mode: the same root the picker is narrowed to, re-checked — see
|
|
2146
|
+
// `isInsideBrowseRoot`. Local mode deliberately has NO containment: a
|
|
2147
|
+
// project under `/srv/code` is a normal local setup and `cezar serve`
|
|
2148
|
+
// registers it today.
|
|
993
2149
|
//
|
|
994
2150
|
// Containment is asked in two halves, around the stat, and the split is
|
|
995
2151
|
// deliberate.
|
|
@@ -1079,13 +2235,6 @@ export function createApp(deps) {
|
|
|
1079
2235
|
workspaceEvents.emit('project-added', { project });
|
|
1080
2236
|
return { status: 200, body: { project } };
|
|
1081
2237
|
};
|
|
1082
|
-
app.post('/api/projects', async (c) => {
|
|
1083
|
-
const parsed = registerProjectSchema.safeParse(await c.req.json().catch(() => null));
|
|
1084
|
-
if (!parsed.success)
|
|
1085
|
-
return c.json({ error: 'root must be a non-empty path' }, 400);
|
|
1086
|
-
const { status, body } = await registerFolder(parsed.data.root, 'local');
|
|
1087
|
-
return c.json(body, status);
|
|
1088
|
-
});
|
|
1089
2238
|
// Deregister a project (multi-project spec, step 4.4 — Settings → Projects,
|
|
1090
2239
|
// the per-row "Remove"). READ THIS BEFORE TOUCHING THE HANDLER: the ONLY
|
|
1091
2240
|
// durable effect allowed here is dropping one entry from
|
|
@@ -1120,136 +2269,74 @@ export function createApp(deps) {
|
|
|
1120
2269
|
return 0;
|
|
1121
2270
|
return ctx.store.listRuns().filter((run) => ACTIVE_RUN_STATUSES.has(run.status)).length;
|
|
1122
2271
|
};
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
// a malformed id is an unknown project, not a validation essay.
|
|
1130
|
-
if (!projectIdSchema.safeParse(raw).success) {
|
|
1131
|
-
return c.json({ error: `unknown project: ${raw}` }, 404);
|
|
1132
|
-
}
|
|
2272
|
+
// Workspace-level by design: update state spans project and global installs,
|
|
2273
|
+
// but the selected registered project supplies the safe, server-owned cwd.
|
|
2274
|
+
const skillsUpdateInputSchema = z.object({ projectId: projectIdSchema }).strict();
|
|
2275
|
+
const resolveSkillsUpdateRoot = async (raw) => {
|
|
2276
|
+
if (!projectIdSchema.safeParse(raw).success)
|
|
2277
|
+
return { status: 404, error: `unknown project: ${raw}` };
|
|
1133
2278
|
const bootId = await resolveBootProject();
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
const
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
catch {
|
|
1142
|
-
// unreadable workspace — there is nothing to remove, and saying so is
|
|
1143
|
-
// more useful than a 500 the user cannot act on
|
|
1144
|
-
}
|
|
1145
|
-
if (!entry)
|
|
1146
|
-
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
1147
|
-
// The boot project is refused, not removed: `cezar serve` re-registers the
|
|
1148
|
-
// repo it was started in on every boot, so "removing" it would undo itself
|
|
1149
|
-
// at the next restart while breaking this session's sidebar in the
|
|
1150
|
-
// meantime. The pane disables the button and says the same thing.
|
|
1151
|
-
if (id === bootId) {
|
|
1152
|
-
return c.json({
|
|
1153
|
-
error: `cezar is serving ${entry.name} right now — it re-registers itself at every start, so it cannot be removed from here`,
|
|
1154
|
-
}, 409);
|
|
1155
|
-
}
|
|
1156
|
-
const active = activeRunCount(id);
|
|
1157
|
-
if (active > 0) {
|
|
1158
|
-
return c.json({
|
|
1159
|
-
error: `${entry.name} has ${active} running task${active === 1 ? '' : 's'} — cancel or finish ${active === 1 ? 'it' : 'them'} before removing the project`,
|
|
1160
|
-
runningTasks: active,
|
|
1161
|
-
}, 409);
|
|
2279
|
+
if (raw === 'default' || raw === bootId)
|
|
2280
|
+
return { root: bootRoot };
|
|
2281
|
+
const project = (await loadWorkspaceConfig()).projects.find((entry) => entry.id === raw);
|
|
2282
|
+
if (!project)
|
|
2283
|
+
return { status: 404, error: `unknown project: ${raw}` };
|
|
2284
|
+
if ((await probeProjectStatus(project.root)).status === 'missing') {
|
|
2285
|
+
return { status: 409, error: `project folder not found: ${raw}` };
|
|
1162
2286
|
}
|
|
1163
|
-
|
|
2287
|
+
return { root: project.root };
|
|
2288
|
+
};
|
|
2289
|
+
const skillsUpdateResponse = async (state) => {
|
|
2290
|
+
const config = await loadWorkspaceConfig();
|
|
2291
|
+
return { ...state, autoUpdateEnabled: effectiveSkillsAutoUpdate(config), inherited: config.skillsAutoUpdate === undefined };
|
|
2292
|
+
};
|
|
2293
|
+
// ---- chained family: skills updates (workspace-level) ----
|
|
2294
|
+
const skillsUpdateRoutes = new Hono()
|
|
2295
|
+
.get('/workspace/skills-update', queryZodValidator(skillsUpdateInputSchema, { message: 'projectId is required' }), async (c) => {
|
|
2296
|
+
const parsed = { data: c.req.valid('query') };
|
|
2297
|
+
const resolved = await resolveSkillsUpdateRoot(parsed.data.projectId);
|
|
2298
|
+
if ('error' in resolved)
|
|
2299
|
+
return c.json({ error: resolved.error }, resolved.status);
|
|
2300
|
+
const state = skillsUpdate.snapshot(resolved.root);
|
|
2301
|
+
void skillsUpdate.check(resolved.root).catch(() => { });
|
|
2302
|
+
return c.json(await skillsUpdateResponse(state));
|
|
2303
|
+
})
|
|
2304
|
+
.post('/workspace/skills-update/check', jsonZodValidator(skillsUpdateInputSchema, { message: 'body must contain only projectId' }), async (c) => {
|
|
2305
|
+
const parsed = { data: c.req.valid('json') };
|
|
2306
|
+
const resolved = await resolveSkillsUpdateRoot(parsed.data.projectId);
|
|
2307
|
+
if ('error' in resolved)
|
|
2308
|
+
return c.json({ error: resolved.error }, resolved.status);
|
|
2309
|
+
return c.json(await skillsUpdateResponse(await skillsUpdate.check(resolved.root, true)));
|
|
2310
|
+
})
|
|
2311
|
+
.post('/workspace/skills-update/apply', jsonZodValidator(skillsUpdateInputSchema, { message: 'body must contain only projectId' }), async (c) => {
|
|
2312
|
+
const parsed = { data: c.req.valid('json') };
|
|
2313
|
+
const resolved = await resolveSkillsUpdateRoot(parsed.data.projectId);
|
|
2314
|
+
if ('error' in resolved)
|
|
2315
|
+
return c.json({ error: resolved.error }, resolved.status);
|
|
1164
2316
|
try {
|
|
1165
|
-
|
|
2317
|
+
return c.json(await skillsUpdateResponse(await skillsUpdate.update(resolved.root, true)));
|
|
1166
2318
|
}
|
|
1167
|
-
catch (
|
|
1168
|
-
|
|
1169
|
-
|
|
2319
|
+
catch (error) {
|
|
2320
|
+
if (error instanceof SkillsUpdateConflictError) {
|
|
2321
|
+
return c.json({ error: 'another skills update operation is running', state: await skillsUpdateResponse(skillsUpdate.snapshot(resolved.root)) }, 409);
|
|
2322
|
+
}
|
|
2323
|
+
throw error;
|
|
1170
2324
|
}
|
|
1171
|
-
// Lost a race with another writer (or another cezar process): the entry is
|
|
1172
|
-
// gone, which is what the caller wanted, but say it honestly.
|
|
1173
|
-
if (!removed)
|
|
1174
|
-
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
1175
|
-
// In-process handles for a project no route can reach any more: store
|
|
1176
|
-
// closed (index flushed), manager's timers and usage subscription dropped.
|
|
1177
|
-
contexts.dispose(id);
|
|
1178
|
-
workspaceEvents.emit('project-removed', { id });
|
|
1179
|
-
const body = { removed: true, id };
|
|
1180
|
-
return c.json(body);
|
|
1181
2325
|
});
|
|
1182
2326
|
// Edit one field of an existing registry entry (spec
|
|
1183
2327
|
// 2026-07-22-per-project-concurrency): the per-project concurrency ceiling.
|
|
1184
2328
|
// A PATCH (not PUT) because it touches a single field, and a distinct route
|
|
1185
|
-
// from POST (register-a-folder) to keep register vs. edit semantics clear.
|
|
1186
|
-
// `maxParallel: null` clears the override back to "inherit the workspace
|
|
1187
|
-
// cap". Bounds mirror `workspaceProjectSchema` (config.ts) exactly, so a
|
|
1188
|
-
// value this route accepts can never be degraded away by the next load's
|
|
1189
|
-
// `.catch`.
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
}
|
|
1197
|
-
const raw = c.req.param('projectId');
|
|
1198
|
-
// Same gate + 404 wording as DELETE: a malformed id is an unknown project.
|
|
1199
|
-
if (!projectIdSchema.safeParse(raw).success) {
|
|
1200
|
-
return c.json({ error: `unknown project: ${raw}` }, 404);
|
|
1201
|
-
}
|
|
1202
|
-
const parsed = updateProjectSchema.safeParse(await c.req.json().catch(() => null));
|
|
1203
|
-
if (!parsed.success) {
|
|
1204
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1205
|
-
}
|
|
1206
|
-
// `default` is the boot alias the cockpit is allowed to use everywhere else.
|
|
1207
|
-
const id = raw === 'default' ? await resolveBootProject() : raw;
|
|
1208
|
-
const { maxParallel } = parsed.data;
|
|
1209
|
-
// Read-first (mirroring DELETE, server.ts:1252-1258): a well-formed but
|
|
1210
|
-
// unknown id must 404 WITHOUT rewriting the config — otherwise it would both
|
|
1211
|
-
// do a needless full-config tmp+rename and, on a read-only home, surface the
|
|
1212
|
-
// write failure as a 500 where the honest answer is 404.
|
|
1213
|
-
let known = false;
|
|
1214
|
-
try {
|
|
1215
|
-
known = (await loadWorkspaceConfig()).projects.some((p) => p.id === id);
|
|
1216
|
-
}
|
|
1217
|
-
catch {
|
|
1218
|
-
// unreadable workspace — treat as unknown; the read-only case answers 404,
|
|
1219
|
-
// not a 500 the caller cannot act on (same reasoning as DELETE).
|
|
1220
|
-
}
|
|
1221
|
-
if (!known)
|
|
1222
|
-
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
1223
|
-
let updated;
|
|
1224
|
-
try {
|
|
1225
|
-
await mergeWriteWorkspaceConfig((config) => {
|
|
1226
|
-
const entry = config.projects.find((p) => p.id === id);
|
|
1227
|
-
if (!entry)
|
|
1228
|
-
return; // lost a race with a concurrent remove — answered below
|
|
1229
|
-
// null clears the override; a number sets it. Mutated in place so
|
|
1230
|
-
// `.passthrough()` keys on the entry survive.
|
|
1231
|
-
if (maxParallel === null)
|
|
1232
|
-
delete entry.maxParallel;
|
|
1233
|
-
else
|
|
1234
|
-
entry.maxParallel = maxParallel;
|
|
1235
|
-
updated = entry;
|
|
1236
|
-
});
|
|
1237
|
-
}
|
|
1238
|
-
catch (err) {
|
|
1239
|
-
// e.g. a read-only home — nothing was persisted (atomic tmp+rename).
|
|
1240
|
-
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
1241
|
-
}
|
|
1242
|
-
// Raced with a concurrent removal between the read and the write.
|
|
1243
|
-
if (!updated)
|
|
1244
|
-
return c.json({ error: `unknown project: ${id}` }, 404);
|
|
1245
|
-
// The new ceiling takes effect WITHOUT a restart: refresh the shared
|
|
1246
|
-
// semaphore's snapshot and pump every manager — the same live-apply hook
|
|
1247
|
-
// `PUT /api/workspace/config` fires for a workspace-cap change.
|
|
1248
|
-
await deps.semaphore?.refresh();
|
|
1249
|
-
const body = {
|
|
1250
|
-
project: { ...updated, ...(await probeProjectStatus(updated.root)) },
|
|
1251
|
-
};
|
|
1252
|
-
return c.json(body);
|
|
2329
|
+
// from POST (register-a-folder) to keep register vs. edit semantics clear.
|
|
2330
|
+
// `maxParallel: null` clears the override back to "inherit the workspace
|
|
2331
|
+
// cap". Bounds mirror `workspaceProjectSchema` (config.ts) exactly, so a
|
|
2332
|
+
// value this route accepts can never be degraded away by the next load's
|
|
2333
|
+
// `.catch`.
|
|
2334
|
+
//
|
|
2335
|
+
// Deliberately NOT the home of the agent-account selection: that lives in
|
|
2336
|
+
// `~/.cezar/agent-accounts.json` beside the accounts it names, so a cezar version that has
|
|
2337
|
+
// never heard of accounts cannot drop it (see workspace/agent-accounts.ts).
|
|
2338
|
+
const updateProjectSchema = z.object({
|
|
2339
|
+
maxParallel: z.number().int().min(1).max(16).nullable(),
|
|
1253
2340
|
});
|
|
1254
2341
|
// ---- GUI clone (multi-project spec, step 4.3) ----------------------------
|
|
1255
2342
|
// "Add project → Clone from GitHub": clone into the checkout root, then
|
|
@@ -1267,41 +2354,6 @@ export function createApp(deps) {
|
|
|
1267
2354
|
name: z.string().trim().max(128).optional(),
|
|
1268
2355
|
checkoutId: z.string().trim().max(128).optional(),
|
|
1269
2356
|
});
|
|
1270
|
-
app.post('/api/projects/checkout', async (c) => {
|
|
1271
|
-
if (capabilities().singleProject) {
|
|
1272
|
-
return c.json(singleProjectRefusal('adding projects'), 409);
|
|
1273
|
-
}
|
|
1274
|
-
const parsed = checkoutSchema.safeParse(await c.req.json().catch(() => null));
|
|
1275
|
-
if (!parsed.success)
|
|
1276
|
-
return c.json({ error: 'url must be a GitHub repository' }, 400);
|
|
1277
|
-
const { url, name, checkoutId } = parsed.data;
|
|
1278
|
-
const result = await checkoutRepo({
|
|
1279
|
-
url,
|
|
1280
|
-
name,
|
|
1281
|
-
checkoutId,
|
|
1282
|
-
projectsDir: expandTilde(await workspaceProjectsDir()),
|
|
1283
|
-
onProgress: (event) => workspaceEvents.emit('checkout-progress', event),
|
|
1284
|
-
// A closed dialog / navigated-away tab aborts the request; the clone is
|
|
1285
|
-
// killed and its partial directory removed rather than left running.
|
|
1286
|
-
signal: c.req.raw.signal,
|
|
1287
|
-
...(deps.cloneRunner ? { run: deps.cloneRunner } : {}),
|
|
1288
|
-
});
|
|
1289
|
-
if (!result.ok) {
|
|
1290
|
-
// `reason` rides along on the 503 (`gh` unavailable) — the spec's
|
|
1291
|
-
// `{ error, reason }` degradation, mirroring the GitHub pane.
|
|
1292
|
-
return c.json('reason' in result ? { error: result.error, reason: result.reason } : { error: result.error }, result.status);
|
|
1293
|
-
}
|
|
1294
|
-
const { status, body } = await registerFolder(result.target, 'checkout');
|
|
1295
|
-
if (status !== 200) {
|
|
1296
|
-
// The clone SUCCEEDED and its files are legitimately the user's, so this
|
|
1297
|
-
// path deliberately does NOT clean up — an unregisterable checkout is a
|
|
1298
|
-
// registry problem, not a reason to delete a repo we just fetched. Say
|
|
1299
|
-
// where it is so they can register it by hand.
|
|
1300
|
-
const error = 'error' in body && body.error ? body.error : 'could not register the checkout';
|
|
1301
|
-
return c.json({ error: `${error} (the clone is at ${result.target})` }, status);
|
|
1302
|
-
}
|
|
1303
|
-
return c.json(body, 200);
|
|
1304
|
-
});
|
|
1305
2357
|
// ---- workspace settings (multi-project spec, step 2.7) -------------------
|
|
1306
2358
|
// WORKSPACE-level routes: single-mount (never mirrored under /api/p/),
|
|
1307
2359
|
// same-origin. The config routes carry the settings UI's slice of
|
|
@@ -1311,33 +2363,39 @@ export function createApp(deps) {
|
|
|
1311
2363
|
const workspaceConfigBody = (config) => ({
|
|
1312
2364
|
browseRoot: config.browseRoot,
|
|
1313
2365
|
projectsDir: config.projectsDir,
|
|
2366
|
+
skillsAutoUpdate: config.skillsAutoUpdate ?? null,
|
|
2367
|
+
effectiveSkillsAutoUpdate: effectiveSkillsAutoUpdate(config),
|
|
2368
|
+
composerDefaults: {
|
|
2369
|
+
autonomous: config.composerDefaults.autonomous ?? null,
|
|
2370
|
+
worktree: config.composerDefaults.worktree ?? null,
|
|
2371
|
+
inheritedAutonomous: process.env.CEZ_AUTONOMOUS_DEFAULT === '0'
|
|
2372
|
+
? false
|
|
2373
|
+
: process.env.CEZ_AUTONOMOUS_DEFAULT === '1'
|
|
2374
|
+
? true
|
|
2375
|
+
: 'source-dependent',
|
|
2376
|
+
inheritedWorktree: effectiveComposerDefault(undefined, process.env.CEZ_WORKTREE_DEFAULT, true),
|
|
2377
|
+
},
|
|
1314
2378
|
resources: {
|
|
1315
2379
|
maxParallel: config.resources.maxParallel,
|
|
2380
|
+
maxMonitoringSessions: config.resources.maxMonitoringSessions,
|
|
2381
|
+
monitoringWakeIntervalMinutes: config.resources.monitoringWakeIntervalMinutes,
|
|
1316
2382
|
memoryLimitMb: config.resources.memoryLimitMb,
|
|
1317
2383
|
worktreeRetentionDefault: config.resources.worktreeRetentionDefault,
|
|
1318
2384
|
},
|
|
2385
|
+
// SPREAD, never `runner: maybeUndefined`: hono would type the key as always-present while
|
|
2386
|
+
// `JSON.stringify` drops it, which is the exact drift `contract-parity` catches. And absent has
|
|
2387
|
+
// to keep meaning "no opinion" here, or the fallback collapses into "always claude".
|
|
2388
|
+
agentDefaults: {
|
|
2389
|
+
...(config.agentDefaults.runner !== undefined ? { runner: config.agentDefaults.runner } : {}),
|
|
2390
|
+
...(config.agentDefaults.models !== undefined ? { models: config.agentDefaults.models } : {}),
|
|
2391
|
+
},
|
|
1319
2392
|
});
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
browseRoot
|
|
1326
|
-
projectsDir: z.string().trim().min(1).max(4096).optional(),
|
|
1327
|
-
resources: z
|
|
1328
|
-
.object({
|
|
1329
|
-
maxParallel: z.number().int().min(1).max(16).optional(),
|
|
1330
|
-
memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
|
|
1331
|
-
worktreeRetentionDefault: z.number().int().min(0).max(1000).optional(),
|
|
1332
|
-
})
|
|
1333
|
-
.optional(),
|
|
1334
|
-
});
|
|
1335
|
-
app.put('/api/workspace/config', async (c) => {
|
|
1336
|
-
const parsed = workspaceConfigUpdateSchema.safeParse(await c.req.json().catch(() => null));
|
|
1337
|
-
if (!parsed.success) {
|
|
1338
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1339
|
-
}
|
|
1340
|
-
const { browseRoot, projectsDir, resources } = parsed.data;
|
|
2393
|
+
// ---- chained family: workspace settings + GUI prefs (workspace-level) ----
|
|
2394
|
+
const workspaceConfigRoutes = new Hono()
|
|
2395
|
+
.get('/workspace/config', async (c) => c.json(workspaceConfigBody(await loadWorkspaceConfig())))
|
|
2396
|
+
.put('/workspace/config', jsonZodValidator(() => workspaceConfigUpdateSchema), async (c) => {
|
|
2397
|
+
const parsed = { data: c.req.valid('json') };
|
|
2398
|
+
const { browseRoot, projectsDir, skillsAutoUpdate, composerDefaults, resources, agentDefaults } = parsed.data;
|
|
1341
2399
|
for (const [configuredRoot, create] of [
|
|
1342
2400
|
[browseRoot, false],
|
|
1343
2401
|
[projectsDir, true],
|
|
@@ -1376,13 +2434,54 @@ export function createApp(deps) {
|
|
|
1376
2434
|
config.browseRoot = browseRoot;
|
|
1377
2435
|
if (projectsDir !== undefined)
|
|
1378
2436
|
config.projectsDir = projectsDir;
|
|
2437
|
+
if (skillsAutoUpdate === null)
|
|
2438
|
+
delete config.skillsAutoUpdate;
|
|
2439
|
+
else if (skillsAutoUpdate !== undefined)
|
|
2440
|
+
config.skillsAutoUpdate = skillsAutoUpdate;
|
|
2441
|
+
if (composerDefaults?.autonomous === null)
|
|
2442
|
+
delete config.composerDefaults.autonomous;
|
|
2443
|
+
else if (composerDefaults?.autonomous !== undefined) {
|
|
2444
|
+
config.composerDefaults.autonomous = composerDefaults.autonomous;
|
|
2445
|
+
}
|
|
2446
|
+
if (composerDefaults?.worktree === null)
|
|
2447
|
+
delete config.composerDefaults.worktree;
|
|
2448
|
+
else if (composerDefaults?.worktree !== undefined) {
|
|
2449
|
+
config.composerDefaults.worktree = composerDefaults.worktree;
|
|
2450
|
+
}
|
|
1379
2451
|
if (resources?.maxParallel !== undefined)
|
|
1380
2452
|
config.resources.maxParallel = resources.maxParallel;
|
|
2453
|
+
if (resources?.maxMonitoringSessions !== undefined) {
|
|
2454
|
+
config.resources.maxMonitoringSessions = resources.maxMonitoringSessions;
|
|
2455
|
+
}
|
|
2456
|
+
if (resources?.monitoringWakeIntervalMinutes !== undefined) {
|
|
2457
|
+
config.resources.monitoringWakeIntervalMinutes = resources.monitoringWakeIntervalMinutes;
|
|
2458
|
+
}
|
|
1381
2459
|
if (resources?.memoryLimitMb !== undefined)
|
|
1382
2460
|
config.resources.memoryLimitMb = resources.memoryLimitMb;
|
|
1383
2461
|
if (resources?.worktreeRetentionDefault !== undefined) {
|
|
1384
2462
|
config.resources.worktreeRetentionDefault = resources.worktreeRetentionDefault;
|
|
1385
2463
|
}
|
|
2464
|
+
// `null` CLEARS back to "no opinion" — a partial patch cannot say that by omission,
|
|
2465
|
+
// and leaving a stale runner behind would keep overriding repos that never chose.
|
|
2466
|
+
if (agentDefaults?.runner === null)
|
|
2467
|
+
delete config.agentDefaults.runner;
|
|
2468
|
+
else if (agentDefaults?.runner !== undefined)
|
|
2469
|
+
config.agentDefaults.runner = agentDefaults.runner;
|
|
2470
|
+
for (const runner of PROVIDER_IDS) {
|
|
2471
|
+
const model = agentDefaults?.models?.[runner];
|
|
2472
|
+
if (model === undefined)
|
|
2473
|
+
continue;
|
|
2474
|
+
const models = config.agentDefaults.models ?? {};
|
|
2475
|
+
if (model === null)
|
|
2476
|
+
delete models[runner];
|
|
2477
|
+
else
|
|
2478
|
+
models[runner] = model;
|
|
2479
|
+
// An empty object would persist a key that says nothing; absence is the same answer.
|
|
2480
|
+
if (Object.keys(models).length === 0)
|
|
2481
|
+
delete config.agentDefaults.models;
|
|
2482
|
+
else
|
|
2483
|
+
config.agentDefaults.models = models;
|
|
2484
|
+
}
|
|
1386
2485
|
});
|
|
1387
2486
|
}
|
|
1388
2487
|
catch (err) {
|
|
@@ -1394,15 +2493,19 @@ export function createApp(deps) {
|
|
|
1394
2493
|
if (resources !== undefined)
|
|
1395
2494
|
await deps.semaphore?.refresh();
|
|
1396
2495
|
return c.json(workspaceConfigBody(written));
|
|
1397
|
-
})
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
2496
|
+
})
|
|
2497
|
+
// Global GUI state (`~/.cezar/ui-state.json`) — same parse/key-cap/shallow-
|
|
2498
|
+
// merge semantics as the per-repo /api/v1/ui-state route below (the shared half
|
|
2499
|
+
// is `uiStateBodySchema`), but backed by the workspace file.
|
|
2500
|
+
.get('/workspace/ui-state', async (c) => c.json(await readWorkspaceUiState()))
|
|
2501
|
+
// The tighter body cap rides on `use` rather than inline on the route: `bodyLimit` is typed
|
|
2502
|
+
// as a bare MiddlewareHandler, and passing one to `.put()` collapses the route's schema, so
|
|
2503
|
+
// the PUT went missing from `AppType` and `hc` could not see its body at all. `use` runs at
|
|
2504
|
+
// the same point (before the handler, so the cap still precedes any read) and leaves the
|
|
2505
|
+
// chain's type accumulation alone. Method-agnostic here, which the GET does not mind.
|
|
2506
|
+
.use('/workspace/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
|
|
2507
|
+
.put('/workspace/ui-state', jsonZodValidator(workspaceUiStateBody), async (c) => {
|
|
2508
|
+
const parsed = { data: c.req.valid('json') };
|
|
1406
2509
|
try {
|
|
1407
2510
|
return c.json(await mergeWriteWorkspaceUiState((state) => ({
|
|
1408
2511
|
...state,
|
|
@@ -1414,67 +2517,117 @@ export function createApp(deps) {
|
|
|
1414
2517
|
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
1415
2518
|
}
|
|
1416
2519
|
});
|
|
1417
|
-
//
|
|
1418
|
-
//
|
|
1419
|
-
//
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
2520
|
+
// Partial updates only — absent keys stay untouched. Bounds mirror the
|
|
2521
|
+
// workspace schema (src/workspace/config.ts, step 1.2) exactly, so a value
|
|
2522
|
+
// this route accepts can never be degraded away by the next load's `.catch`.
|
|
2523
|
+
const workspaceConfigUpdateSchema = z.object({
|
|
2524
|
+
browseRoot: z.string().trim().min(1).max(4096).optional(),
|
|
2525
|
+
projectsDir: z.string().trim().min(1).max(4096).optional(),
|
|
2526
|
+
skillsAutoUpdate: z.boolean().nullable().optional(),
|
|
2527
|
+
composerDefaults: z
|
|
2528
|
+
.object({
|
|
2529
|
+
autonomous: z.boolean().nullable().optional(),
|
|
2530
|
+
worktree: z.boolean().nullable().optional(),
|
|
2531
|
+
})
|
|
2532
|
+
.optional(),
|
|
2533
|
+
resources: z
|
|
2534
|
+
.object({
|
|
2535
|
+
maxParallel: z.number().int().min(1).max(16).optional(),
|
|
2536
|
+
maxMonitoringSessions: z.number().int().min(0).max(16).optional(),
|
|
2537
|
+
monitoringWakeIntervalMinutes: z.number().int().min(1).max(60).nullable().optional(),
|
|
2538
|
+
memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
|
|
2539
|
+
worktreeRetentionDefault: z.number().int().min(0).max(1000).optional(),
|
|
2540
|
+
})
|
|
2541
|
+
.optional(),
|
|
2542
|
+
// Bounds mirror `src/workspace/config.ts`, so a value this accepts is never degraded away by
|
|
2543
|
+
// the next load's `.catch`. `null` clears a key back to "no opinion".
|
|
2544
|
+
agentDefaults: z
|
|
2545
|
+
.object({
|
|
2546
|
+
runner: z.enum(PROVIDER_IDS).nullable().optional(),
|
|
2547
|
+
models: z
|
|
2548
|
+
.object({
|
|
2549
|
+
claude: z.string().trim().min(1).max(200).nullable().optional(),
|
|
2550
|
+
codex: z.string().trim().min(1).max(200).nullable().optional(),
|
|
2551
|
+
opencode: z.string().trim().min(1).max(200).nullable().optional(),
|
|
2552
|
+
})
|
|
2553
|
+
.optional(),
|
|
2554
|
+
})
|
|
2555
|
+
.optional(),
|
|
2556
|
+
});
|
|
2557
|
+
// ---- chained family: filesystem browse (workspace-level) ----
|
|
2558
|
+
const fsBrowseRoutes = new Hono()
|
|
2559
|
+
.get('/fs/browse', queryZodValidator(z.object({ path: queryValue, showHidden: queryValue })), async (c) => {
|
|
1424
2560
|
if (capabilities().singleProject) {
|
|
1425
2561
|
return c.json(singleProjectRefusal('folder browsing'), 409);
|
|
1426
2562
|
}
|
|
2563
|
+
const query = c.req.valid('query');
|
|
1427
2564
|
const root = resolveBrowseRoot(await workspaceBrowseRoot());
|
|
1428
2565
|
const result = await browseDirectory({
|
|
1429
2566
|
root,
|
|
1430
|
-
path:
|
|
1431
|
-
showHidden:
|
|
2567
|
+
path: query.path,
|
|
2568
|
+
showHidden: query.showHidden === '1',
|
|
1432
2569
|
});
|
|
1433
2570
|
if (!result.ok)
|
|
1434
2571
|
return c.json({ error: result.error }, result.status);
|
|
1435
2572
|
return c.json(result.body);
|
|
1436
2573
|
});
|
|
1437
|
-
//
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
2574
|
+
// ---- chained family: launch-key (project-scoped) ----
|
|
2575
|
+
const launchKeyRoutes = new Hono()
|
|
2576
|
+
.get('/launch-key', (c) => c.json({ key: c.get('project').launchKey }));
|
|
2577
|
+
// ---- chained family: skills (project-scoped) ----
|
|
2578
|
+
const skillsRoutes = new Hono()
|
|
2579
|
+
.get('/skills', queryZodValidator(waitQuery), async (c) => {
|
|
1441
2580
|
const repoRoot = c.get('project').root;
|
|
1442
2581
|
// The default read stays fast and starts the team load in the background.
|
|
1443
2582
|
// The cockpit follows it with `wait=1`, off the render path, so a cold
|
|
1444
2583
|
// cache converges without polling or a manual reload (spec 005 / #555).
|
|
1445
|
-
if (c.req.
|
|
2584
|
+
if (c.req.valid('query').wait === '1')
|
|
1446
2585
|
await waitForTeamSkills(repoRoot);
|
|
1447
2586
|
return c.json(await discoverSkills(repoRoot));
|
|
1448
|
-
})
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
2587
|
+
})
|
|
2588
|
+
// The opt-in catalog for the "Import skills" panel: every skill a default
|
|
2589
|
+
// (vendor) repo offers — `open-mercato/skills` — regardless of import state,
|
|
2590
|
+
// so the panel can present them all with a per-skill toggle. Empty once a repo
|
|
2591
|
+
// configures its own `skillsRepos` (nothing is gated then). `wait=1` lets the
|
|
2592
|
+
// panel wait out a cold team-skill cache, same as `GET /skills` (spec 005).
|
|
2593
|
+
.get('/skills/importable', queryZodValidator(waitQuery), async (c) => {
|
|
1455
2594
|
const repoRoot = c.get('project').root;
|
|
1456
2595
|
const gated = await gatedSkillsRepos(repoRoot);
|
|
1457
2596
|
if (gated.size === 0)
|
|
1458
2597
|
return c.json([]);
|
|
1459
|
-
if (c.req.
|
|
2598
|
+
if (c.req.valid('query').wait === '1')
|
|
1460
2599
|
await waitForTeamSkills(repoRoot);
|
|
1461
2600
|
const importable = getTeamSkillsCached(repoRoot)
|
|
1462
2601
|
.filter((skill) => skill.team && gated.has(skill.team.repo))
|
|
1463
|
-
|
|
2602
|
+
// Spread `description` rather than writing it unconditionally: an undefined VALUE is
|
|
2603
|
+
// dropped by JSON.stringify, so the key is absent on the wire, and writing it always
|
|
2604
|
+
// typed the route as sending a key it does not. contract/skills.ts says `.optional()`,
|
|
2605
|
+
// which is what the client actually receives.
|
|
2606
|
+
.map((skill) => ({
|
|
2607
|
+
name: skill.name,
|
|
2608
|
+
...(skill.description !== undefined ? { description: skill.description } : {}),
|
|
2609
|
+
}));
|
|
1464
2610
|
return c.json(importable);
|
|
2611
|
+
})
|
|
2612
|
+
// Refresh team skills (spec 005): clone/fetch the configured skills repos,
|
|
2613
|
+
// then return the merged catalog. Degrades quietly — offline just means the
|
|
2614
|
+
// team entries stay as they were (or absent).
|
|
2615
|
+
.post('/skills/refresh', async (c) => {
|
|
2616
|
+
const { root: repoRoot } = c.get('project');
|
|
2617
|
+
await refreshTeamSkills(repoRoot);
|
|
2618
|
+
return c.json(await discoverSkills(repoRoot));
|
|
1465
2619
|
});
|
|
1466
|
-
// ---- GUI prefs
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
2620
|
+
// ---- chained family: GUI prefs / ui-state (project-scoped) ----
|
|
2621
|
+
const uiStateRoutes = new Hono()
|
|
2622
|
+
.get('/ui-state', async (c) => c.json(await readUiState(c.get('project').root)))
|
|
2623
|
+
// On `use`, not inline on the route — see the workspace ui-state PUT above.
|
|
2624
|
+
.use('/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
|
|
2625
|
+
.put('/ui-state', jsonZodValidator(uiStateBody), async (c) => {
|
|
1471
2626
|
const { root: repoRoot, dataDir } = c.get('project');
|
|
1472
2627
|
// `.passthrough()` keeps unknown prefs (BACKWARD_COMPATIBILITY §3), but a
|
|
1473
2628
|
// single request may not stuff an unbounded key set (#429) — the shared
|
|
1474
|
-
//
|
|
1475
|
-
const parsed =
|
|
1476
|
-
if ('error' in parsed)
|
|
1477
|
-
return c.json({ error: parsed.error }, 400);
|
|
2629
|
+
// schema+cap half of both ui-state routes lives in `uiStateBody`.
|
|
2630
|
+
const parsed = { data: c.req.valid('json') };
|
|
1478
2631
|
const merged = { ...(await readUiState(repoRoot)), ...parsed.data };
|
|
1479
2632
|
try {
|
|
1480
2633
|
await mkdir(dataDir, { recursive: true });
|
|
@@ -1485,24 +2638,18 @@ export function createApp(deps) {
|
|
|
1485
2638
|
}
|
|
1486
2639
|
return c.json(merged);
|
|
1487
2640
|
});
|
|
1488
|
-
//
|
|
1489
|
-
//
|
|
1490
|
-
//
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
await
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
// `.ai/cezar/workflows/<slug>.yaml` — from then on it's in the dropdown
|
|
1499
|
-
// like any other workflow.
|
|
1500
|
-
api.post('/workflows', async (c) => {
|
|
2641
|
+
// ---- chained family: workflows (project-scoped) --------------------------
|
|
2642
|
+
// One chained expression, mounted by `createApp` into BOTH the legacy `api`
|
|
2643
|
+
// table and the versioned `v1` one — see `healthRoutes` for why the chain
|
|
2644
|
+
// shape (not the statement shape) is what carries the types.
|
|
2645
|
+
const workflowsRoutes = new Hono()
|
|
2646
|
+
.get('/workflows', async (c) => c.json(await loadWorkflows(c.get('project').root)))
|
|
2647
|
+
// Save an approved plan as a reusable chain (spec 008): YAML in
|
|
2648
|
+
// `.ai/cezar/workflows/<slug>.yaml` — from then on it's in the dropdown
|
|
2649
|
+
// like any other workflow.
|
|
2650
|
+
.post('/workflows', jsonZodValidator(saveWorkflowSchema), async (c) => {
|
|
1501
2651
|
const { root: repoRoot } = c.get('project');
|
|
1502
|
-
const parsed =
|
|
1503
|
-
if (!parsed.success) {
|
|
1504
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1505
|
-
}
|
|
2652
|
+
const parsed = { data: c.req.valid('json') };
|
|
1506
2653
|
const steps = parsed.data.steps ?? skillsToSteps(parsed.data.skills ?? []);
|
|
1507
2654
|
const issue = stepsIssue(steps);
|
|
1508
2655
|
if (issue)
|
|
@@ -1534,10 +2681,10 @@ export function createApp(deps) {
|
|
|
1534
2681
|
return c.json({ error: message }, 500);
|
|
1535
2682
|
}
|
|
1536
2683
|
return c.json({ path, name: parsed.data.name }, 201);
|
|
1537
|
-
})
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
2684
|
+
})
|
|
2685
|
+
// Delete a saved workflow (spec 012 follow-up): file workflows only —
|
|
2686
|
+
// built-ins have no file and always come back.
|
|
2687
|
+
.delete('/workflows/:name', async (c) => {
|
|
1541
2688
|
const { root: repoRoot } = c.get('project');
|
|
1542
2689
|
const name = c.req.param('name');
|
|
1543
2690
|
const { workflows } = await loadWorkflows(repoRoot);
|
|
@@ -1559,15 +2706,12 @@ export function createApp(deps) {
|
|
|
1559
2706
|
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
1560
2707
|
}
|
|
1561
2708
|
return c.json({ ok: true, path: target });
|
|
1562
|
-
})
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
const parsed =
|
|
1568
|
-
if (!parsed.success) {
|
|
1569
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1570
|
-
}
|
|
2709
|
+
})
|
|
2710
|
+
// Import support for the builder (spec 012): parse + validate a pasted
|
|
2711
|
+
// workflow YAML (either form) and hand back the normalized definition. The
|
|
2712
|
+
// server owns YAML parsing — the GUI stays dependency-free.
|
|
2713
|
+
.post('/workflows/parse', jsonZodValidator(parseWorkflowSchema), async (c) => {
|
|
2714
|
+
const parsed = { data: c.req.valid('json') };
|
|
1571
2715
|
let raw;
|
|
1572
2716
|
try {
|
|
1573
2717
|
raw = parseYaml(parsed.data.yaml);
|
|
@@ -1586,17 +2730,250 @@ export function createApp(deps) {
|
|
|
1586
2730
|
return c.json({ error: issue }, 400);
|
|
1587
2731
|
return c.json(normalized);
|
|
1588
2732
|
});
|
|
1589
|
-
//
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
api.post('/plan', async (c) => {
|
|
2733
|
+
// ---- chained family: plan (project-scoped) ----
|
|
2734
|
+
const planRoutes = new Hono()
|
|
2735
|
+
.post('/plan', jsonZodValidator(planSchema), async (c) => {
|
|
1593
2736
|
const { root: repoRoot } = c.get('project');
|
|
1594
|
-
const parsed =
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
2737
|
+
const parsed = { data: c.req.valid('json') };
|
|
2738
|
+
const blocked = await providerActionError([(await loadConfig(repoRoot)).defaultRunner]);
|
|
2739
|
+
if (blocked)
|
|
2740
|
+
return c.json({ error: blocked }, 409);
|
|
1598
2741
|
return c.json(await planChain(repoRoot, parsed.data.task));
|
|
1599
2742
|
});
|
|
2743
|
+
const manualChecks = new Map();
|
|
2744
|
+
// ---- chained family: GitHub automations (project-scoped) ----
|
|
2745
|
+
// Every handler below reads `c.get('project')` — the definitions, their runtime state and the
|
|
2746
|
+
// execution log are per-project files — so the family is project-scoped and mounted with the
|
|
2747
|
+
// rest of the mirrored table. The one exception is the manual-check read, which touches no
|
|
2748
|
+
// project at all; it is its own workspace-level family below.
|
|
2749
|
+
const automationsRoutes = new Hono()
|
|
2750
|
+
.get('/automations', async (c) => {
|
|
2751
|
+
const { root, automationStore } = c.get('project');
|
|
2752
|
+
const forge = resolveForge(await getRepoInfo(root));
|
|
2753
|
+
// Annotated, so the two branches are ONE shape rather than a union of two: the fallback
|
|
2754
|
+
// literal always carries `reason`, the cached answer only sometimes does, and the route
|
|
2755
|
+
// type is what `contract/src/automations.ts` has to describe.
|
|
2756
|
+
const availability = forge?.detectCached() ?? {
|
|
2757
|
+
available: false,
|
|
2758
|
+
reason: forge ? 'GitHub availability is still being checked' : 'No GitHub remote is configured',
|
|
2759
|
+
};
|
|
2760
|
+
const automations = automationStore.list().map((automation) => {
|
|
2761
|
+
const logs = automationStore.logs({ automationId: automation.id, limit: 100 });
|
|
2762
|
+
const state = automationStore.state(automation.id);
|
|
2763
|
+
const latestLog = logs[0];
|
|
2764
|
+
return {
|
|
2765
|
+
...automation,
|
|
2766
|
+
// Spread conditionally, never `state: maybeUndefined`: the latter types the key as
|
|
2767
|
+
// always-present while `JSON.stringify` drops it from the wire, so the contract would
|
|
2768
|
+
// have to describe a key consumers never receive.
|
|
2769
|
+
...(state ? { state } : {}),
|
|
2770
|
+
...(latestLog ? { latestLog } : {}),
|
|
2771
|
+
counts: {
|
|
2772
|
+
matches: logs.filter((row) => row.result === 'launched' || row.result === 'duplicate').length,
|
|
2773
|
+
launched: logs.filter((row) => row.result === 'launched').length,
|
|
2774
|
+
duplicates: logs.filter((row) => row.result === 'duplicate').length,
|
|
2775
|
+
errors: logs.filter((row) => row.result === 'error' || row.result === 'rate-limited').length,
|
|
2776
|
+
},
|
|
2777
|
+
};
|
|
2778
|
+
});
|
|
2779
|
+
const nextDue = automations.map((item) => item.state?.nextCheckAt).filter(Boolean).sort()[0];
|
|
2780
|
+
return c.json({
|
|
2781
|
+
...availability,
|
|
2782
|
+
scheduler: {
|
|
2783
|
+
// `as const` on both arms: in an object literal a conditional of two string literals
|
|
2784
|
+
// widens to `string`, which would erase the two states this key can hold.
|
|
2785
|
+
state: automations.some((item) => item.enabled) ? 'scheduled' : 'idle',
|
|
2786
|
+
...(nextDue ? { nextDue } : {}),
|
|
2787
|
+
},
|
|
2788
|
+
automations,
|
|
2789
|
+
});
|
|
2790
|
+
})
|
|
2791
|
+
.post('/automations', jsonZodValidator(() => automationCreateSchema), async (c) => {
|
|
2792
|
+
const { automationStore } = c.get('project');
|
|
2793
|
+
const parsed = { data: c.req.valid('json') };
|
|
2794
|
+
const promptIssue = validateAutomationPrompt(parsed.data.task.prompt);
|
|
2795
|
+
if (promptIssue)
|
|
2796
|
+
return c.json({ error: promptIssue }, 400);
|
|
2797
|
+
const { enable, ...input } = parsed.data;
|
|
2798
|
+
try {
|
|
2799
|
+
const automation = automationStore.create({ ...input, enabled: enable === true });
|
|
2800
|
+
if (enable) {
|
|
2801
|
+
const baselineAt = new Date().toISOString();
|
|
2802
|
+
automationStore.setState(automation.id, {
|
|
2803
|
+
revision: automation.revision,
|
|
2804
|
+
baselineAt,
|
|
2805
|
+
cursor: { timestamp: baselineAt },
|
|
2806
|
+
nextCheckAt: new Date(Date.now() + automation.intervalSeconds * 1_000).toISOString(),
|
|
2807
|
+
});
|
|
2808
|
+
}
|
|
2809
|
+
emitAutomationChange(c.get('project'), automation.id, automation.revision);
|
|
2810
|
+
automationsChanged();
|
|
2811
|
+
return c.json({ automation }, 201);
|
|
2812
|
+
}
|
|
2813
|
+
catch (error) {
|
|
2814
|
+
return c.json({ error: error instanceof Error ? error.message : String(error) }, 400);
|
|
2815
|
+
}
|
|
2816
|
+
})
|
|
2817
|
+
.get('/automations/:id', (c) => {
|
|
2818
|
+
const { automationStore } = c.get('project');
|
|
2819
|
+
const automation = automationStore.get(c.req.param('id'));
|
|
2820
|
+
if (!automation)
|
|
2821
|
+
return c.json({ error: 'not found' }, 404);
|
|
2822
|
+
const state = automationStore.state(automation.id);
|
|
2823
|
+
const latestLog = automationStore.logs({ automationId: automation.id, limit: 1 })[0];
|
|
2824
|
+
return c.json({
|
|
2825
|
+
automation,
|
|
2826
|
+
...(state ? { state } : {}),
|
|
2827
|
+
...(latestLog ? { latestLog } : {}),
|
|
2828
|
+
});
|
|
2829
|
+
})
|
|
2830
|
+
.put('/automations/:id', jsonZodValidator(() => automationUpdateSchema), async (c) => {
|
|
2831
|
+
const { automationStore } = c.get('project');
|
|
2832
|
+
const parsed = { data: c.req.valid('json') };
|
|
2833
|
+
const promptIssue = validateAutomationPrompt(parsed.data.task.prompt);
|
|
2834
|
+
if (promptIssue)
|
|
2835
|
+
return c.json({ error: promptIssue }, 400);
|
|
2836
|
+
const { expectedRevision, ...input } = parsed.data;
|
|
2837
|
+
if (!automationStore.get(c.req.param('id')))
|
|
2838
|
+
return c.json({ error: 'not found' }, 404);
|
|
2839
|
+
try {
|
|
2840
|
+
const automation = automationStore.update(c.req.param('id'), expectedRevision, { ...input, enabled: input.enabled ?? false });
|
|
2841
|
+
emitAutomationChange(c.get('project'), automation.id, automation.revision);
|
|
2842
|
+
automationsChanged();
|
|
2843
|
+
return c.json({ automation });
|
|
2844
|
+
}
|
|
2845
|
+
catch (error) {
|
|
2846
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2847
|
+
return c.json({ error: message }, message.includes('conflict') ? 409 : 400);
|
|
2848
|
+
}
|
|
2849
|
+
})
|
|
2850
|
+
.delete('/automations/:id', (c) => {
|
|
2851
|
+
const id = c.req.param('id');
|
|
2852
|
+
const store = c.get('project').automationStore;
|
|
2853
|
+
const current = store.get(id);
|
|
2854
|
+
if (!current || !store.delete(id))
|
|
2855
|
+
return c.json({ error: 'not found' }, 404);
|
|
2856
|
+
emitAutomationChange(c.get('project'), id, current.revision, true);
|
|
2857
|
+
automationsChanged();
|
|
2858
|
+
return c.body(null, 204);
|
|
2859
|
+
})
|
|
2860
|
+
.post('/automations/:id/enable', (c) => {
|
|
2861
|
+
const store = c.get('project').automationStore;
|
|
2862
|
+
const current = store.get(c.req.param('id'));
|
|
2863
|
+
if (!current)
|
|
2864
|
+
return c.json({ error: 'not found' }, 404);
|
|
2865
|
+
const automation = store.update(current.id, current.revision, { ...editableAutomation(current), enabled: true });
|
|
2866
|
+
const baselineAt = new Date().toISOString();
|
|
2867
|
+
store.setState(automation.id, {
|
|
2868
|
+
...store.state(automation.id),
|
|
2869
|
+
revision: automation.revision,
|
|
2870
|
+
baselineAt,
|
|
2871
|
+
cursor: { timestamp: baselineAt },
|
|
2872
|
+
nextCheckAt: new Date(Date.now() + automation.intervalSeconds * 1_000).toISOString(),
|
|
2873
|
+
});
|
|
2874
|
+
store.appendLog({ automationId: automation.id, revision: automation.revision, result: 'baseline', reason: 'Enabled from a current-time baseline; existing records were not launched.' });
|
|
2875
|
+
emitAutomationChange(c.get('project'), automation.id, automation.revision);
|
|
2876
|
+
automationsChanged();
|
|
2877
|
+
return c.json({ automation });
|
|
2878
|
+
})
|
|
2879
|
+
.post('/automations/:id/pause', (c) => {
|
|
2880
|
+
const store = c.get('project').automationStore;
|
|
2881
|
+
const current = store.get(c.req.param('id'));
|
|
2882
|
+
if (!current)
|
|
2883
|
+
return c.json({ error: 'not found' }, 404);
|
|
2884
|
+
const automation = store.update(current.id, current.revision, { ...editableAutomation(current), enabled: false });
|
|
2885
|
+
emitAutomationChange(c.get('project'), automation.id, automation.revision);
|
|
2886
|
+
automationsChanged();
|
|
2887
|
+
return c.json({ automation });
|
|
2888
|
+
})
|
|
2889
|
+
// The body is validated as MIDDLEWARE, which is what puts it in the route type — and moves
|
|
2890
|
+
// the 400 ahead of this route's 404: `POST /automations/<unknown>/check` with a malformed
|
|
2891
|
+
// body now answers 400 rather than 404. Nothing else about either answer changed.
|
|
2892
|
+
.post('/automations/:id/check', jsonZodValidator(() => automationCheckRequestSchema), async (c) => {
|
|
2893
|
+
const project = c.get('project');
|
|
2894
|
+
const store = project.automationStore;
|
|
2895
|
+
const automation = store.get(c.req.param('id'));
|
|
2896
|
+
if (!automation)
|
|
2897
|
+
return c.json({ error: 'not found' }, 404);
|
|
2898
|
+
const parsed = { data: c.req.valid('json') };
|
|
2899
|
+
// `string`, not `randomUUID`'s template-literal type: the wire carries an opaque id, and
|
|
2900
|
+
// leaking `${string}-${string}-…` into the route type would make the contract describe the
|
|
2901
|
+
// generator rather than the answer.
|
|
2902
|
+
const id = randomUUID();
|
|
2903
|
+
const check = { id, automationId: automation.id, mode: parsed.data.mode, status: 'queued', createdAt: new Date().toISOString() };
|
|
2904
|
+
if (manualChecks.size >= 200)
|
|
2905
|
+
manualChecks.delete(manualChecks.keys().next().value);
|
|
2906
|
+
manualChecks.set(id, check);
|
|
2907
|
+
void (async () => {
|
|
2908
|
+
check.status = 'running';
|
|
2909
|
+
try {
|
|
2910
|
+
const remote = parseRemote((await getRepoInfo(project.root))?.remote ?? '');
|
|
2911
|
+
if (!remote || remote.host !== 'github.com')
|
|
2912
|
+
throw new Error('No GitHub remote is configured');
|
|
2913
|
+
const scheduler = new ProjectAutomationScheduler({
|
|
2914
|
+
projectId: project.id,
|
|
2915
|
+
owner: remote.owner,
|
|
2916
|
+
repo: remote.repo,
|
|
2917
|
+
store,
|
|
2918
|
+
poller: new GithubPoller(),
|
|
2919
|
+
launch: parsed.data.mode === 'execute'
|
|
2920
|
+
? (definition, candidate, receiptId) => launchAutomationRun({ root: project.root, manager: project.manager, store: project.store, definition, candidate, receiptId })
|
|
2921
|
+
: undefined,
|
|
2922
|
+
onChange: (automationId, revision) => emitAutomationChange(project, automationId, revision),
|
|
2923
|
+
});
|
|
2924
|
+
const result = await scheduler.check(automation, parsed.data.mode);
|
|
2925
|
+
Object.assign(check, { status: 'complete', completedAt: new Date().toISOString(), matches: result.candidates.length, truncated: result.truncated });
|
|
2926
|
+
}
|
|
2927
|
+
catch (error) {
|
|
2928
|
+
Object.assign(check, { status: 'error', completedAt: new Date().toISOString(), error: error instanceof Error ? error.message : String(error) });
|
|
2929
|
+
}
|
|
2930
|
+
})();
|
|
2931
|
+
return c.json({ checkId: id }, 202);
|
|
2932
|
+
})
|
|
2933
|
+
.get('/automation-log', queryZodValidator(automationLogQuerySchema), (c) => {
|
|
2934
|
+
return c.json({ records: c.get('project').automationStore.logs(c.req.valid('query')) });
|
|
2935
|
+
})
|
|
2936
|
+
.post('/automation-log/:receiptId/retry', async (c) => {
|
|
2937
|
+
const project = c.get('project');
|
|
2938
|
+
const store = project.automationStore;
|
|
2939
|
+
const receipt = [...store.latestReceipts().values()].find((row) => row.receiptId === c.req.param('receiptId'));
|
|
2940
|
+
if (!receipt)
|
|
2941
|
+
return c.json({ error: 'not found' }, 404);
|
|
2942
|
+
if (receipt.status !== 'launch-error' || receipt.runId)
|
|
2943
|
+
return c.json({ error: 'receipt is not retryable' }, 409);
|
|
2944
|
+
if (!receipt.candidate)
|
|
2945
|
+
return c.json({ error: 'receipt predates retry context and cannot be retried safely' }, 409);
|
|
2946
|
+
const definition = store.get(receipt.automationId);
|
|
2947
|
+
if (!definition)
|
|
2948
|
+
return c.json({ error: 'automation not found' }, 404);
|
|
2949
|
+
const lease = store.acquireLease();
|
|
2950
|
+
if (!lease)
|
|
2951
|
+
return c.json({ error: 'automation polling lease is held by another process' }, 409);
|
|
2952
|
+
const reserved = { ...receipt, status: 'reserved', error: undefined, updatedAt: new Date().toISOString() };
|
|
2953
|
+
store.appendReceipt(reserved);
|
|
2954
|
+
try {
|
|
2955
|
+
const launched = await launchAutomationRun({ root: project.root, manager: project.manager, store: project.store, definition, candidate: receipt.candidate, receiptId: receipt.receiptId });
|
|
2956
|
+
store.appendReceipt({ ...reserved, status: 'launched', runId: launched.runId, updatedAt: new Date().toISOString() });
|
|
2957
|
+
emitAutomationChange(project, definition.id, definition.revision);
|
|
2958
|
+
return c.json({ receiptId: receipt.receiptId, runId: launched.runId }, 202);
|
|
2959
|
+
}
|
|
2960
|
+
catch (error) {
|
|
2961
|
+
store.appendReceipt({ ...reserved, status: 'launch-error', error: error instanceof Error ? error.message : String(error), updatedAt: new Date().toISOString() });
|
|
2962
|
+
return c.json({ error: error instanceof Error ? error.message : String(error) }, 409);
|
|
2963
|
+
}
|
|
2964
|
+
finally {
|
|
2965
|
+
lease.release();
|
|
2966
|
+
}
|
|
2967
|
+
});
|
|
2968
|
+
// ---- chained family: manual automation checks (workspace-level) ----
|
|
2969
|
+
// Workspace-level because the handler reads no project: a check lives in the server-memory map
|
|
2970
|
+
// above, keyed by an unguessable id that the project-scoped POST hands back. Mounting it under
|
|
2971
|
+
// `/api/v1/p/:projectId` too would be a second spelling of a lookup that consults no project.
|
|
2972
|
+
const automationChecksRoutes = new Hono()
|
|
2973
|
+
.get('/automation-checks/:checkId', (c) => {
|
|
2974
|
+
const check = manualChecks.get(c.req.param('checkId'));
|
|
2975
|
+
return check ? c.json(check) : c.json({ error: 'not found' }, 404);
|
|
2976
|
+
});
|
|
1600
2977
|
// ---- runs ----------------------------------------------------------------
|
|
1601
2978
|
// Additive `usage` field (#348): the latest CPU/RSS/proc-count sample of the
|
|
1602
2979
|
// run's live process tree — absent for finished runs and when `ps` yields
|
|
@@ -1625,27 +3002,35 @@ export function createApp(deps) {
|
|
|
1625
3002
|
console.warn(`[cezar] could not mark inbox entry ${todoId} started: ${String(err)}`);
|
|
1626
3003
|
}
|
|
1627
3004
|
};
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
3005
|
+
// ---- chained family: runs lifecycle + artifacts (project-scoped) ----
|
|
3006
|
+
const runsRoutes = new Hono()
|
|
3007
|
+
.get('/runs', (c) => c.json(c.get('project').store.listRuns().map(withUsage)))
|
|
3008
|
+
// Registered before the `/:id/...` routes so "archive-finished" and "read-all"
|
|
3009
|
+
// never match as a run id.
|
|
3010
|
+
.post('/runs/archive-finished', (c) => c.json({ archived: c.get('project').store.archiveFinished() }))
|
|
3011
|
+
// The read-receipt sweep (#unread-done-items) — the mark-read twin of the archive
|
|
3012
|
+
// sweep above, and under the same registration-order guard.
|
|
3013
|
+
.post('/runs/read-all', (c) => c.json({ read: c.get('project').store.markAllRead() }))
|
|
3014
|
+
.post('/runs/:id/archive', jsonZodValidator(archiveSchema, { absent: ({}) }), async (c) => {
|
|
1633
3015
|
const { store } = c.get('project');
|
|
1634
3016
|
const id = c.req.param('id');
|
|
1635
3017
|
// An empty/absent body archives (the common case); a malformed body degrades
|
|
1636
3018
|
// to `{}` just as before, but a wrong-typed `archived` is now a 400 (#429).
|
|
1637
|
-
const parsed =
|
|
1638
|
-
if (!parsed.success) {
|
|
1639
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1640
|
-
}
|
|
3019
|
+
const parsed = { data: c.req.valid('json') };
|
|
1641
3020
|
const run = store.setArchived(id, parsed.data.archived !== false);
|
|
1642
3021
|
return run ? c.json(run) : c.json({ error: 'not found' }, 404);
|
|
1643
|
-
})
|
|
1644
|
-
|
|
3022
|
+
})
|
|
3023
|
+
.post('/runs/:id/read', (c) => {
|
|
3024
|
+
// No body: opening a thread marks it read, full stop. Stamps `seenAt = now` and
|
|
3025
|
+
// returns the updated record (which also rides the `run` SSE via `touch`).
|
|
3026
|
+
const run = c.get('project').store.setRead(c.req.param('id'));
|
|
3027
|
+
return run ? c.json(run) : c.json({ error: 'not found' }, 404);
|
|
3028
|
+
})
|
|
3029
|
+
.post('/runs', jsonZodValidator(startRunSchema), async (c) => {
|
|
1645
3030
|
const { root: repoRoot, dataDir, manager } = c.get('project');
|
|
1646
|
-
const parsed =
|
|
1647
|
-
if (
|
|
1648
|
-
return c.json({ error:
|
|
3031
|
+
const parsed = { data: c.req.valid('json') };
|
|
3032
|
+
if (agentModelsLocked(repoRoot) && parsed.data.model?.trim()) {
|
|
3033
|
+
return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
|
|
1649
3034
|
}
|
|
1650
3035
|
let workflow;
|
|
1651
3036
|
if (parsed.data.steps) {
|
|
@@ -1653,166 +3038,91 @@ export function createApp(deps) {
|
|
|
1653
3038
|
const issue = stepsIssue(parsed.data.steps);
|
|
1654
3039
|
if (issue)
|
|
1655
3040
|
return c.json({ error: issue }, 400);
|
|
1656
|
-
workflow = {
|
|
1657
|
-
name: '(planned)',
|
|
1658
|
-
source: 'built-in',
|
|
1659
|
-
steps: parsed.data.steps,
|
|
1660
|
-
};
|
|
1661
|
-
}
|
|
1662
|
-
else {
|
|
1663
|
-
const { workflows } = await loadWorkflows(repoRoot);
|
|
1664
|
-
workflow = workflows.find((w) => w.name === parsed.data.workflow);
|
|
1665
|
-
if (!workflow)
|
|
1666
|
-
return c.json({ error: `unknown workflow: ${parsed.data.workflow}` }, 404);
|
|
1667
|
-
}
|
|
1668
|
-
const images = parsed.data.images?.map((img) => ({
|
|
1669
|
-
type: 'image',
|
|
1670
|
-
source: { type: 'base64', media_type: img.mediaType, data: img.data },
|
|
1671
|
-
}));
|
|
1672
|
-
const input = {
|
|
1673
|
-
task: parsed.data.task,
|
|
1674
|
-
model: parsed.data.model,
|
|
1675
|
-
runner: parsed.data.runner,
|
|
1676
|
-
images,
|
|
1677
|
-
systemPrompt: parsed.data.systemPrompt,
|
|
1678
|
-
worktree: parsed.data.worktree,
|
|
1679
|
-
autonomous: parsed.data.autonomous,
|
|
1680
|
-
// Opt-in inbox (#471): the capability is the ceiling, so a client asking
|
|
1681
|
-
// for follow-ups on a server that has them off gets a plain `false`
|
|
1682
|
-
// rather than an error — the run is still perfectly valid without them.
|
|
1683
|
-
// One decision here feeds the run record, the system prompt and
|
|
1684
|
-
// CEZ_TODOS_FILE alike (RunManager.agentEnv).
|
|
1685
|
-
generateFollowups: capabilities().followups ? parsed.data.generateFollowups : false,
|
|
1686
|
-
};
|
|
1687
|
-
const variants = parsed.data.variants ?? 1;
|
|
1688
|
-
if (variants > 1) {
|
|
1689
|
-
// Variants live in worktrees — without git there's nothing to isolate
|
|
1690
|
-
// them with, so this degrades to a clear 400 instead of stepping on
|
|
1691
|
-
// one shared working tree.
|
|
1692
|
-
const repo = await getRepoInfo(repoRoot);
|
|
1693
|
-
if (!repo) {
|
|
1694
|
-
return c.json({
|
|
1695
|
-
error: 'parallel variants need a git repository (each variant runs in its own worktree) — run ×1 here, or start cezar inside a git repo',
|
|
1696
|
-
}, 400);
|
|
1697
|
-
}
|
|
1698
|
-
const runs = manager.startVariants(workflow, input, variants);
|
|
1699
|
-
// The entry points at the first variant — the thread the composer navigates to.
|
|
1700
|
-
const first = runs[0];
|
|
1701
|
-
if (parsed.data.todoId && first)
|
|
1702
|
-
await noteTodoStarted(dataDir, parsed.data.todoId, first.id);
|
|
1703
|
-
return c.json({ runs }, 201);
|
|
1704
|
-
}
|
|
1705
|
-
const run = manager.startRun(workflow, input);
|
|
1706
|
-
if (parsed.data.todoId)
|
|
1707
|
-
await noteTodoStarted(dataDir, parsed.data.todoId, run.id);
|
|
1708
|
-
return c.json(run, 201);
|
|
1709
|
-
});
|
|
1710
|
-
// ---- parallel variants (spec 010) -----------------------------------------
|
|
1711
|
-
const groupRuns = (store, groupId) => store
|
|
1712
|
-
.listRuns()
|
|
1713
|
-
.filter((r) => r.groupId === groupId)
|
|
1714
|
-
.sort((a, b) => (a.variant ?? '').localeCompare(b.variant ?? ''));
|
|
1715
|
-
// Comparison data: per variant the status, cost, `git diff --stat` and the
|
|
1716
|
-
// first Progress-log lines from the handoff. The full diff is fetched per
|
|
1717
|
-
// variant via the existing GET /api/runs/:id/diff.
|
|
1718
|
-
api.get('/groups/:groupId', async (c) => {
|
|
1719
|
-
const { dataDir, store } = c.get('project');
|
|
1720
|
-
const runs = groupRuns(store, c.req.param('groupId'));
|
|
1721
|
-
if (runs.length === 0)
|
|
1722
|
-
return c.json({ error: 'not found' }, 404);
|
|
1723
|
-
const detailed = await Promise.all(runs.map(async (r) => ({
|
|
1724
|
-
id: r.id,
|
|
1725
|
-
variant: r.variant ?? '?',
|
|
1726
|
-
title: r.title,
|
|
1727
|
-
status: r.status,
|
|
1728
|
-
archived: r.archived,
|
|
1729
|
-
tokensUsed: r.tokensUsed,
|
|
1730
|
-
costUsd: r.costUsd,
|
|
1731
|
-
diffStat: r.worktreePath && existsSync(r.worktreePath)
|
|
1732
|
-
? await worktreeDiffStat(r.worktreePath, r.baseBranch ?? 'HEAD')
|
|
1733
|
-
: '',
|
|
1734
|
-
handoffExcerpt: handoffProgressExcerpt(readHandoff(dataDir, r.id)),
|
|
1735
|
-
})));
|
|
1736
|
-
return c.json({
|
|
1737
|
-
groupId: c.req.param('groupId'),
|
|
1738
|
-
runs: detailed,
|
|
1739
|
-
});
|
|
1740
|
-
});
|
|
1741
|
-
// "Pick this one": the winner rests at `review` (spec 009 takes it from
|
|
1742
|
-
// there — send back / draft PR / finish); the losers are cancelled if
|
|
1743
|
-
// alive, archived, and their worktrees + branches removed.
|
|
1744
|
-
api.post('/groups/:groupId/pick', async (c) => {
|
|
1745
|
-
const { root: repoRoot, dataDir, store, manager } = c.get('project');
|
|
1746
|
-
const runs = groupRuns(store, c.req.param('groupId'));
|
|
1747
|
-
if (runs.length === 0)
|
|
1748
|
-
return c.json({ error: 'not found' }, 404);
|
|
1749
|
-
const parsed = pickSchema.safeParse(await c.req.json().catch(() => null));
|
|
1750
|
-
if (!parsed.success) {
|
|
1751
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1752
|
-
}
|
|
1753
|
-
const winner = runs.find((r) => r.id === parsed.data.runId);
|
|
1754
|
-
if (!winner)
|
|
1755
|
-
return c.json({ error: 'runId is not part of this group' }, 404);
|
|
1756
|
-
if (manager.isActive(winner.id)) {
|
|
1757
|
-
return c.json({ error: 'this variant is still active — wait for it to finish first' }, 409);
|
|
1758
|
-
}
|
|
1759
|
-
// Winner: a non-review terminal state with a non-empty diff flips to
|
|
1760
|
-
// `review` (the settleSuccess rule) — but only when the review gate applies
|
|
1761
|
-
// (#489): it is enabled (`reviewGateEnabled`, default off) AND the winner is
|
|
1762
|
-
// not autonomous. An autonomous / gate-off winner keeps its `done` state with
|
|
1763
|
-
// the diff left in the worktree; an empty diff (or no worktree) stays too.
|
|
1764
|
-
if (winner.status !== 'review' &&
|
|
1765
|
-
winner.worktreePath &&
|
|
1766
|
-
existsSync(winner.worktreePath) &&
|
|
1767
|
-
winner.autonomous !== true &&
|
|
1768
|
-
reviewGateEnabled(await loadConfig(repoRoot))) {
|
|
1769
|
-
const diff = await worktreeDiff(winner.worktreePath, winner.baseBranch ?? 'HEAD');
|
|
1770
|
-
if (diff.trim().length > 0 && !diff.startsWith('(diff failed')) {
|
|
1771
|
-
store.updateRun(winner.id, { status: 'review' });
|
|
1772
|
-
}
|
|
3041
|
+
workflow = {
|
|
3042
|
+
name: '(planned)',
|
|
3043
|
+
source: 'built-in',
|
|
3044
|
+
steps: parsed.data.steps,
|
|
3045
|
+
};
|
|
1773
3046
|
}
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
appendHandoffHeartbeat(dataDir, winner.id, `picked from ${runs.length} variants`);
|
|
1780
|
-
for (const loser of losers) {
|
|
1781
|
-
if (manager.isActive(loser.id))
|
|
1782
|
-
manager.cancel(loser.id);
|
|
1783
|
-
if (loser.worktreePath)
|
|
1784
|
-
await removeWorktree(repoRoot, loser.worktreePath, loser.branch);
|
|
1785
|
-
store.updateRun(loser.id, { worktreePath: undefined, branch: undefined });
|
|
1786
|
-
store.setArchived(loser.id, true);
|
|
1787
|
-
store.appendEvent(loser.id, {
|
|
1788
|
-
type: 'lifecycle',
|
|
1789
|
-
message: `variant ${winner.variant ?? '?'} was picked — this variant is archived, its worktree removed`,
|
|
1790
|
-
});
|
|
3047
|
+
else {
|
|
3048
|
+
const { workflows } = await loadWorkflows(repoRoot);
|
|
3049
|
+
workflow = workflows.find((w) => w.name === parsed.data.workflow);
|
|
3050
|
+
if (!workflow)
|
|
3051
|
+
return c.json({ error: `unknown workflow: ${parsed.data.workflow}` }, 404);
|
|
1791
3052
|
}
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
3053
|
+
const fallback = parsed.data.runner ?? (await loadConfig(repoRoot)).defaultRunner;
|
|
3054
|
+
const blocked = await providerActionError(providersRequiredByWorkflow(workflow, fallback));
|
|
3055
|
+
if (blocked)
|
|
3056
|
+
return c.json({ error: blocked }, 409);
|
|
3057
|
+
// A composer override names an account the user just picked, so a stale id (deleted since
|
|
3058
|
+
// the page loaded) is answered honestly instead of quietly running on the default — the
|
|
3059
|
+
// opposite of how RESOLUTION treats a dangling reference, and deliberately so: a run
|
|
3060
|
+
// replaying a stored id has no better answer than the default, a user does.
|
|
3061
|
+
if (parsed.data.agentProfile !== undefined) {
|
|
3062
|
+
const account = await resolveWorkspaceProfile(fallback, parsed.data.agentProfile);
|
|
3063
|
+
if ('error' in account)
|
|
3064
|
+
return c.json({ error: account.error }, 400);
|
|
3065
|
+
}
|
|
3066
|
+
const images = parsed.data.images?.map((img) => ({
|
|
3067
|
+
type: 'image',
|
|
3068
|
+
source: { type: 'base64', media_type: img.mediaType, data: img.data },
|
|
3069
|
+
}));
|
|
3070
|
+
const input = {
|
|
3071
|
+
task: parsed.data.task,
|
|
3072
|
+
model: parsed.data.model,
|
|
3073
|
+
runner: parsed.data.runner,
|
|
3074
|
+
agentProfile: parsed.data.agentProfile,
|
|
3075
|
+
images,
|
|
3076
|
+
systemPrompt: parsed.data.systemPrompt,
|
|
3077
|
+
worktree: parsed.data.worktree,
|
|
3078
|
+
autonomous: parsed.data.autonomous,
|
|
3079
|
+
// Opt-in inbox (#471): the capability is the ceiling, so a client asking
|
|
3080
|
+
// for follow-ups on a server that has them off gets a plain `false`
|
|
3081
|
+
// rather than an error — the run is still perfectly valid without them.
|
|
3082
|
+
// One decision here feeds the run record, the system prompt and
|
|
3083
|
+
// CEZ_TODOS_FILE alike (RunManager.agentEnv).
|
|
3084
|
+
generateFollowups: capabilities().followups ? parsed.data.generateFollowups : false,
|
|
3085
|
+
};
|
|
3086
|
+
const variants = parsed.data.variants ?? 1;
|
|
3087
|
+
if (variants > 1) {
|
|
3088
|
+
// Variants live in worktrees — without git there's nothing to isolate
|
|
3089
|
+
// them with, so this degrades to a clear 400 instead of stepping on
|
|
3090
|
+
// one shared working tree.
|
|
3091
|
+
const repo = await getRepoInfo(repoRoot);
|
|
3092
|
+
if (!repo) {
|
|
3093
|
+
return c.json({
|
|
3094
|
+
error: 'parallel variants need a git repository (each variant runs in its own worktree) — run ×1 here, or start cezar inside a git repo',
|
|
3095
|
+
}, 400);
|
|
3096
|
+
}
|
|
3097
|
+
const runs = manager.startVariants(workflow, input, variants);
|
|
3098
|
+
// The entry points at the first variant — the thread the composer navigates to.
|
|
3099
|
+
const first = runs[0];
|
|
3100
|
+
if (parsed.data.todoId && first)
|
|
3101
|
+
await noteTodoStarted(dataDir, parsed.data.todoId, first.id);
|
|
3102
|
+
return c.json({ runs }, 201);
|
|
3103
|
+
}
|
|
3104
|
+
const run = manager.startRun(workflow, input);
|
|
3105
|
+
if (parsed.data.todoId)
|
|
3106
|
+
await noteTodoStarted(dataDir, parsed.data.todoId, run.id);
|
|
3107
|
+
return c.json(run, 201);
|
|
3108
|
+
})
|
|
3109
|
+
.get('/runs/:id', (c) => {
|
|
1797
3110
|
const { store } = c.get('project');
|
|
1798
3111
|
const run = store.getRun(c.req.param('id'));
|
|
1799
3112
|
return run ? c.json(withUsage(run)) : c.json({ error: 'not found' }, 404);
|
|
1800
|
-
})
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
3113
|
+
})
|
|
3114
|
+
// Editable titles (#389). The UI displays `titleSummary ?? title`, so a
|
|
3115
|
+
// user edit sets BOTH: `title` (the record's own name — the raw task stops
|
|
3116
|
+
// being it the moment the user renames the run) and `titleSummary` (what
|
|
3117
|
+
// actually displays). The auto-summarizer only ever fills an *unset*
|
|
3118
|
+
// titleSummary (RunManager.recordTurnEnd), so an edit wins over any past or
|
|
3119
|
+
// future auto-summary. Answers the updated record.
|
|
3120
|
+
.patch('/runs/:id', jsonZodValidator(patchRunSchema), async (c) => {
|
|
1808
3121
|
const { store, manager } = c.get('project');
|
|
1809
3122
|
const id = c.req.param('id');
|
|
1810
3123
|
if (!store.getRun(id))
|
|
1811
3124
|
return c.json({ error: 'not found' }, 404);
|
|
1812
|
-
const parsed =
|
|
1813
|
-
if (!parsed.success) {
|
|
1814
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1815
|
-
}
|
|
3125
|
+
const parsed = { data: c.req.valid('json') };
|
|
1816
3126
|
// The prompt is editable only while the run is still queued (#472). Checked
|
|
1817
3127
|
// BEFORE the title write so a rejected PATCH is a no-op rather than a partial
|
|
1818
3128
|
// one. `title` itself keeps working on any status — no regression to #389.
|
|
@@ -1837,25 +3147,33 @@ export function createApp(deps) {
|
|
|
1837
3147
|
});
|
|
1838
3148
|
}
|
|
1839
3149
|
return c.json(store.getRun(id));
|
|
1840
|
-
})
|
|
1841
|
-
|
|
3150
|
+
})
|
|
3151
|
+
.post('/runs/:id/cancel', (c) => {
|
|
1842
3152
|
const { store, manager } = c.get('project');
|
|
1843
3153
|
const id = c.req.param('id');
|
|
1844
3154
|
if (!store.getRun(id))
|
|
1845
3155
|
return c.json({ error: 'not found' }, 404);
|
|
1846
3156
|
const cancelled = manager.cancel(id);
|
|
1847
3157
|
return c.json({ cancelled });
|
|
1848
|
-
})
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
3158
|
+
})
|
|
3159
|
+
// Live-session participation (spec 002): deliver a user message (text +
|
|
3160
|
+
// pasted screenshots) into the run's open claude session.
|
|
3161
|
+
.post('/runs/:id/messages', jsonZodValidator(messageSchema), async (c) => {
|
|
1852
3162
|
const { store, manager } = c.get('project');
|
|
1853
3163
|
const id = c.req.param('id');
|
|
1854
|
-
|
|
3164
|
+
const run = store.getRun(id);
|
|
3165
|
+
if (!run)
|
|
1855
3166
|
return c.json({ error: 'not found' }, 404);
|
|
1856
|
-
const parsed =
|
|
1857
|
-
|
|
1858
|
-
|
|
3167
|
+
const parsed = { data: c.req.valid('json') };
|
|
3168
|
+
// Stacking onto a queued prompt mutates an existing task and invokes no provider.
|
|
3169
|
+
// Provider availability still gates live delivery after the record leaves `queued`, but
|
|
3170
|
+
// must not strand prompt authoring just because an unrelated fallback provider is
|
|
3171
|
+
// disconnected (provider-auth spec: disabling never blocks existing-task mutations).
|
|
3172
|
+
// In the dequeue race, the ladder below safely turns this into a starting-state buffer.
|
|
3173
|
+
if (run.status !== 'queued') {
|
|
3174
|
+
const blocked = await providerActionError([providerForActiveRun(run)]);
|
|
3175
|
+
if (blocked)
|
|
3176
|
+
return c.json({ error: blocked }, 409);
|
|
1859
3177
|
}
|
|
1860
3178
|
const content = [
|
|
1861
3179
|
...parsed.data.images.map((img) => ({
|
|
@@ -1871,14 +3189,14 @@ export function createApp(deps) {
|
|
|
1871
3189
|
// starting up → buffered · anything else → 409, exactly as before
|
|
1872
3190
|
if (manager.sendMessage(id, content))
|
|
1873
3191
|
return c.json({ delivered: true });
|
|
1874
|
-
const
|
|
1875
|
-
const stack =
|
|
3192
|
+
const currentRun = store.getRun(id);
|
|
3193
|
+
const stack = currentRun?.queuedMessages ?? [];
|
|
1876
3194
|
// Bounds apply only to a message that is actually about to be stacked. Without this
|
|
1877
3195
|
// gate an over-long message posted to a *finished* run would answer `400 prompt too
|
|
1878
3196
|
// long` when the truthful answer is `409 session closed`. The status read is safe
|
|
1879
3197
|
// here because it only decides whether to reject EARLY — `enqueueMessage` still
|
|
1880
3198
|
// re-checks against the engine's own queue before writing anything.
|
|
1881
|
-
if (
|
|
3199
|
+
if (currentRun?.status === 'queued') {
|
|
1882
3200
|
if (stack.length >= MAX_QUEUED_MESSAGES) {
|
|
1883
3201
|
return c.json({ error: `too many queued messages — ${MAX_QUEUED_MESSAGES} message limit` }, 400);
|
|
1884
3202
|
}
|
|
@@ -1886,7 +3204,7 @@ export function createApp(deps) {
|
|
|
1886
3204
|
if (stackedImages + parsed.data.images.length > MAX_QUEUED_IMAGES) {
|
|
1887
3205
|
return c.json({ error: `too many queued images — ${MAX_QUEUED_IMAGES} image limit across the stack` }, 400);
|
|
1888
3206
|
}
|
|
1889
|
-
const prospective = foldedLength(
|
|
3207
|
+
const prospective = foldedLength(currentRun.task, [...stack, { text: parsed.data.text }]);
|
|
1890
3208
|
if (prospective > MAX_FOLDED_TASK_CHARS) {
|
|
1891
3209
|
return c.json({
|
|
1892
3210
|
error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
|
|
@@ -1899,19 +3217,16 @@ export function createApp(deps) {
|
|
|
1899
3217
|
if (manager.deferMessage(id, content))
|
|
1900
3218
|
return c.json({ deferred: true });
|
|
1901
3219
|
return c.json({ error: 'session closed' }, 409);
|
|
1902
|
-
})
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
3220
|
+
})
|
|
3221
|
+
// Edit / remove a stacked message (#472). Registered before any conflicting
|
|
3222
|
+
// `/:id` route so `queued-messages` never matches as a run id.
|
|
3223
|
+
.patch('/runs/:id/queued-messages/:msgId', jsonZodValidator(queuedMessagePatchSchema), async (c) => {
|
|
1906
3224
|
const { store, manager } = c.get('project');
|
|
1907
3225
|
const id = c.req.param('id');
|
|
1908
3226
|
const run = store.getRun(id);
|
|
1909
3227
|
if (!run)
|
|
1910
3228
|
return c.json({ error: 'not found' }, 404);
|
|
1911
|
-
const parsed =
|
|
1912
|
-
if (!parsed.success) {
|
|
1913
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
1914
|
-
}
|
|
3229
|
+
const parsed = { data: c.req.valid('json') };
|
|
1915
3230
|
const msgId = c.req.param('msgId');
|
|
1916
3231
|
const stack = run.queuedMessages ?? [];
|
|
1917
3232
|
const existing = stack.find((m) => m.id === msgId);
|
|
@@ -1944,8 +3259,8 @@ export function createApp(deps) {
|
|
|
1944
3259
|
if (!message)
|
|
1945
3260
|
return c.json({ error: 'run already started' }, 409);
|
|
1946
3261
|
return c.json({ message });
|
|
1947
|
-
})
|
|
1948
|
-
|
|
3262
|
+
})
|
|
3263
|
+
.delete('/runs/:id/queued-messages/:msgId', (c) => {
|
|
1949
3264
|
const { store, manager } = c.get('project');
|
|
1950
3265
|
const id = c.req.param('id');
|
|
1951
3266
|
const run = store.getRun(id);
|
|
@@ -1958,9 +3273,9 @@ export function createApp(deps) {
|
|
|
1958
3273
|
if (!manager.removeQueuedMessage(id, msgId))
|
|
1959
3274
|
return c.json({ error: 'run already started' }, 409);
|
|
1960
3275
|
return c.json({ removed: true });
|
|
1961
|
-
})
|
|
1962
|
-
|
|
1963
|
-
|
|
3276
|
+
})
|
|
3277
|
+
// "Finish": gracefully close a waiting session — the run completes as done.
|
|
3278
|
+
.post('/runs/:id/finish', (c) => {
|
|
1964
3279
|
const { store, manager } = c.get('project');
|
|
1965
3280
|
const id = c.req.param('id');
|
|
1966
3281
|
if (!store.getRun(id))
|
|
@@ -1969,19 +3284,23 @@ export function createApp(deps) {
|
|
|
1969
3284
|
if (!finished)
|
|
1970
3285
|
return c.json({ error: 'no open session' }, 409);
|
|
1971
3286
|
return c.json({ finished: true });
|
|
1972
|
-
})
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
const { store, manager } = c.get('project');
|
|
3287
|
+
})
|
|
3288
|
+
// "Continue" (spec 003): reopen a finished run's session in-process.
|
|
3289
|
+
.post('/runs/:id/continue', jsonZodValidator(continueSchema, { absent: ({}) }), async (c) => {
|
|
3290
|
+
const { root: repoRoot, store, manager } = c.get('project');
|
|
1976
3291
|
const id = c.req.param('id');
|
|
1977
|
-
|
|
3292
|
+
const run = store.getRun(id);
|
|
3293
|
+
if (!run)
|
|
1978
3294
|
return c.json({ error: 'not found' }, 404);
|
|
1979
3295
|
// Bounded resume text (#429); an empty/absent body still just re-runs on the
|
|
1980
3296
|
// run's current backend, and a runner/model override reopens on that engine (#401).
|
|
1981
|
-
const parsed =
|
|
1982
|
-
if (
|
|
1983
|
-
return c.json({ error:
|
|
3297
|
+
const parsed = { data: c.req.valid('json') };
|
|
3298
|
+
if (agentModelsLocked(repoRoot) && parsed.data.model?.trim()) {
|
|
3299
|
+
return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
|
|
1984
3300
|
}
|
|
3301
|
+
const blocked = await providerActionError([providerForExistingRun(run, parsed.data.runner)]);
|
|
3302
|
+
if (blocked)
|
|
3303
|
+
return c.json({ error: blocked }, 409);
|
|
1985
3304
|
const result = manager.continueRun(id, {
|
|
1986
3305
|
text: parsed.data.text,
|
|
1987
3306
|
images: parsed.data.images?.map((img) => ({
|
|
@@ -1994,10 +3313,10 @@ export function createApp(deps) {
|
|
|
1994
3313
|
if (!result.ok)
|
|
1995
3314
|
return c.json({ error: result.error }, 409);
|
|
1996
3315
|
return c.json({ continued: true });
|
|
1997
|
-
})
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
3316
|
+
})
|
|
3317
|
+
// "Open in terminal" (spec 003): hand the session off to a real terminal —
|
|
3318
|
+
// in the task's worktree when it still exists (spec 006).
|
|
3319
|
+
.post('/runs/:id/open-in-cli', async (c) => {
|
|
2001
3320
|
const { root: repoRoot, store } = c.get('project');
|
|
2002
3321
|
const id = c.req.param('id');
|
|
2003
3322
|
const run = store.getRun(id);
|
|
@@ -2010,28 +3329,36 @@ export function createApp(deps) {
|
|
|
2010
3329
|
error: 'local handoff is disabled — this cockpit runs in hosted mode (CEZ_REMOTE); resume the session from a machine that has the checkout',
|
|
2011
3330
|
}, 409);
|
|
2012
3331
|
}
|
|
2013
|
-
const
|
|
3332
|
+
const sessionStep = [...run.steps].reverse().find((s) => s.sessionId);
|
|
3333
|
+
const sessionId = sessionStep?.sessionId;
|
|
2014
3334
|
if (!sessionId)
|
|
2015
3335
|
return c.json({ error: 'no agent session to resume' }, 409);
|
|
3336
|
+
const blocked = await providerActionError([providerForExistingRun(run)]);
|
|
3337
|
+
if (blocked)
|
|
3338
|
+
return c.json({ error: blocked }, 409);
|
|
2016
3339
|
const cwd = run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : repoRoot;
|
|
2017
3340
|
const command = resumeCommand(run.runner, sessionId);
|
|
2018
3341
|
// Fails closed on an id we do not recognise — see resumeCommand (#431).
|
|
2019
3342
|
if (!command)
|
|
2020
3343
|
return c.json({ error: 'the recorded session id has an unexpected shape' }, 409);
|
|
2021
|
-
|
|
3344
|
+
// The account that OWNS this session, not the project's current one (spec 2026-07-29).
|
|
3345
|
+
const account = await handoffEnv(run.runner ?? 'claude', sessionStep?.profileId);
|
|
3346
|
+
if ('error' in account)
|
|
3347
|
+
return c.json({ error: account.error }, 409);
|
|
3348
|
+
const fallback = handoffFallbackCommand(cwd, command, account.env);
|
|
3349
|
+
// Fail closed for the same reason as the session id: a terminal opened without the
|
|
3350
|
+
// account's config dir resumes nothing and says nothing about why.
|
|
3351
|
+
if (fallback === null) {
|
|
3352
|
+
return c.json({ error: 'this account\'s folder cannot be used in a terminal command' }, 409);
|
|
3353
|
+
}
|
|
3354
|
+
const opened = await openInTerminal(cwd, command, account.env);
|
|
2022
3355
|
if (!opened) {
|
|
2023
|
-
return c.json({
|
|
2024
|
-
error: 'no terminal emulator found',
|
|
2025
|
-
command: `cd '${cwd}' && ${command}`,
|
|
2026
|
-
}, 409);
|
|
3356
|
+
return c.json({ error: 'no terminal emulator found', command: fallback }, 409);
|
|
2027
3357
|
}
|
|
2028
3358
|
return c.json({ opened: true, command });
|
|
2029
|
-
})
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
api.get('/open-targets', (c) => c.json({ targets: capabilities().localHandoff ? detectOpenTargets() : [] }));
|
|
2033
|
-
// Open a run's worktree (or the repo root) in the chosen local app.
|
|
2034
|
-
api.post('/runs/:id/open-in', async (c) => {
|
|
3359
|
+
})
|
|
3360
|
+
// Open a run's worktree (or the repo root) in the chosen local app.
|
|
3361
|
+
.post('/runs/:id/open-in', jsonZodValidator(openInSchema), async (c) => {
|
|
2035
3362
|
const { root: repoRoot, store } = c.get('project');
|
|
2036
3363
|
const id = c.req.param('id');
|
|
2037
3364
|
const run = store.getRun(id);
|
|
@@ -2044,10 +3371,7 @@ export function createApp(deps) {
|
|
|
2044
3371
|
}
|
|
2045
3372
|
// Follows the safeParse convention (#429); the downstream allowlist match is the real
|
|
2046
3373
|
// injection guard, this just validates the shape.
|
|
2047
|
-
const parsedBody =
|
|
2048
|
-
if (!parsedBody.success) {
|
|
2049
|
-
return c.json({ error: parsedBody.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
2050
|
-
}
|
|
3374
|
+
const parsedBody = { data: c.req.valid('json') };
|
|
2051
3375
|
const { target, path: relPath } = parsedBody.data;
|
|
2052
3376
|
const dir = run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : repoRoot;
|
|
2053
3377
|
// Diff pane "open in OS default app" (#365): one worktree file, opened with the platform's
|
|
@@ -2105,18 +3429,32 @@ export function createApp(deps) {
|
|
|
2105
3429
|
// and what the client's cliTargetResumes now labels. Resume-after-finish is untouched.
|
|
2106
3430
|
const cliRunner = agentCliRunner(target);
|
|
2107
3431
|
if (cliRunner) {
|
|
3432
|
+
const blocked = await providerActionError([cliRunner]);
|
|
3433
|
+
if (blocked)
|
|
3434
|
+
return c.json({ error: blocked }, 409);
|
|
2108
3435
|
const engineOwnsSession = run.status === 'running' || run.status === 'queued' || run.status === 'waiting';
|
|
2109
|
-
const
|
|
3436
|
+
const sessionStep = engineOwnsSession ? undefined : [...run.steps].reverse().find((s) => s.sessionId);
|
|
3437
|
+
const sessionId = sessionStep?.sessionId;
|
|
2110
3438
|
// An id resumeCommand refuses (#431) degrades to a fresh CLI in the worktree,
|
|
2111
3439
|
// exactly like a run that never recorded a session.
|
|
2112
3440
|
const resume = sessionId && cliRunner === (run.runner ?? 'claude') ? resumeCommand(cliRunner, sessionId) : null;
|
|
2113
3441
|
const command = resume ?? cliRunner;
|
|
2114
|
-
|
|
3442
|
+
// BOTH branches carry the account (spec 2026-07-29-agent-profiles): a resume needs the
|
|
3443
|
+
// config dir that holds its session, and a FRESH CLI in this worktree should still open
|
|
3444
|
+
// on the account the project works under — otherwise "Open in → Claude CLI" quietly
|
|
3445
|
+
// hands the user a different subscription than every task in the same project uses.
|
|
3446
|
+
const account = resume
|
|
3447
|
+
? await handoffEnv(cliRunner, sessionStep?.profileId)
|
|
3448
|
+
: { env: (await resolveProfileEnvForRoot(repoRoot, cliRunner)).env };
|
|
3449
|
+
if ('error' in account)
|
|
3450
|
+
return c.json({ error: account.error }, 409);
|
|
3451
|
+
const fallback = handoffFallbackCommand(dir, command, account.env);
|
|
3452
|
+
if (fallback === null) {
|
|
3453
|
+
return c.json({ error: 'this account\'s folder cannot be used in a terminal command' }, 409);
|
|
3454
|
+
}
|
|
3455
|
+
const opened = await openInTerminal(dir, command, account.env);
|
|
2115
3456
|
if (!opened) {
|
|
2116
|
-
return c.json({
|
|
2117
|
-
error: 'no terminal emulator found',
|
|
2118
|
-
command: `cd '${dir}' && ${command}`,
|
|
2119
|
-
}, 409);
|
|
3457
|
+
return c.json({ error: 'no terminal emulator found', command: fallback }, 409);
|
|
2120
3458
|
}
|
|
2121
3459
|
return c.json({ opened: true, path: dir, command });
|
|
2122
3460
|
}
|
|
@@ -2124,10 +3462,10 @@ export function createApp(deps) {
|
|
|
2124
3462
|
if (!opened)
|
|
2125
3463
|
return c.json({ error: `could not open ${target}`, path: dir }, 409);
|
|
2126
3464
|
return c.json({ opened: true, path: dir });
|
|
2127
|
-
})
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
3465
|
+
})
|
|
3466
|
+
// Handoff journal (spec 007): the per-task handoff.md as markdown. 404 only
|
|
3467
|
+
// when the task is unknown; a task without a (yet) seeded file returns ''.
|
|
3468
|
+
.get('/runs/:id/handoff', (c) => {
|
|
2131
3469
|
const { dataDir, store } = c.get('project');
|
|
2132
3470
|
const run = store.getRun(c.req.param('id'));
|
|
2133
3471
|
if (!run)
|
|
@@ -2135,16 +3473,8 @@ export function createApp(deps) {
|
|
|
2135
3473
|
return c.text(readHandoff(dataDir, run.id), 200, {
|
|
2136
3474
|
'content-type': 'text/markdown; charset=utf-8',
|
|
2137
3475
|
});
|
|
2138
|
-
})
|
|
2139
|
-
|
|
2140
|
-
// results (persistImage). `basename` pins reads inside the run's own dir.
|
|
2141
|
-
const IMAGE_TYPES = {
|
|
2142
|
-
png: 'image/png',
|
|
2143
|
-
jpg: 'image/jpeg',
|
|
2144
|
-
webp: 'image/webp',
|
|
2145
|
-
gif: 'image/gif',
|
|
2146
|
-
};
|
|
2147
|
-
api.get('/runs/:id/images/:file', (c) => {
|
|
3476
|
+
})
|
|
3477
|
+
.get('/runs/:id/images/:file', (c) => {
|
|
2148
3478
|
const { dataDir, store } = c.get('project');
|
|
2149
3479
|
const run = store.getRun(c.req.param('id'));
|
|
2150
3480
|
if (!run)
|
|
@@ -2160,9 +3490,9 @@ export function createApp(deps) {
|
|
|
2160
3490
|
'cache-control': 'private, max-age=31536000, immutable',
|
|
2161
3491
|
},
|
|
2162
3492
|
});
|
|
2163
|
-
})
|
|
2164
|
-
|
|
2165
|
-
|
|
3493
|
+
})
|
|
3494
|
+
// Task diff (spec 006): what this run changed — its worktree vs its base.
|
|
3495
|
+
.get('/runs/:id/diff', async (c) => {
|
|
2166
3496
|
const { store } = c.get('project');
|
|
2167
3497
|
const run = store.getRun(c.req.param('id'));
|
|
2168
3498
|
if (!run)
|
|
@@ -2171,94 +3501,111 @@ export function createApp(deps) {
|
|
|
2171
3501
|
return c.text('(no worktree — this task ran directly in the repo working tree)');
|
|
2172
3502
|
}
|
|
2173
3503
|
return c.text(await worktreeDiff(run.worktreePath, run.baseBranch ?? 'HEAD'));
|
|
2174
|
-
})
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
// protected surface). Same worktree/base resolution; every predictable git
|
|
2178
|
-
// failure degrades to 409 + human-readable reason, 404 only for unknown ids.
|
|
2179
|
-
const worktreeOf = (run) => run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : null;
|
|
2180
|
-
const NO_WORKTREE = 'no worktree — this task ran directly in the repo working tree';
|
|
2181
|
-
api.get('/runs/:id/changes', async (c) => {
|
|
2182
|
-
const { store } = c.get('project');
|
|
3504
|
+
})
|
|
3505
|
+
.get('/runs/:id/changes', async (c) => {
|
|
3506
|
+
const { root: repoRoot, store } = c.get('project');
|
|
2183
3507
|
const run = store.getRun(c.req.param('id'));
|
|
2184
3508
|
if (!run)
|
|
2185
3509
|
return c.json({ error: 'not found' }, 404);
|
|
2186
|
-
const
|
|
2187
|
-
if (!
|
|
3510
|
+
const workingDirectory = workingDirectoryOf(run, repoRoot);
|
|
3511
|
+
if (!workingDirectory)
|
|
2188
3512
|
return c.json({ error: NO_WORKTREE }, 409);
|
|
2189
|
-
const result = await collectChanges(
|
|
3513
|
+
const result = await collectChanges(workingDirectory, run.baseBranch ?? 'HEAD', {
|
|
3514
|
+
taskBranch: run.branch,
|
|
3515
|
+
// A read-only GET against the user's real checkout must never modify its index.
|
|
3516
|
+
intentToAdd: run.worktreePath ? undefined : false,
|
|
3517
|
+
});
|
|
2190
3518
|
if (!result.ok)
|
|
2191
3519
|
return c.json({ error: result.error }, 409);
|
|
2192
3520
|
return c.json(result.changes);
|
|
2193
|
-
})
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
const { store } = c.get('project');
|
|
3521
|
+
})
|
|
3522
|
+
// The run's own commits (<base>..HEAD on the worktree branch) — the Commits tab.
|
|
3523
|
+
.get('/runs/:id/commits', async (c) => {
|
|
3524
|
+
const { root: repoRoot, store } = c.get('project');
|
|
2197
3525
|
const run = store.getRun(c.req.param('id'));
|
|
2198
3526
|
if (!run)
|
|
2199
3527
|
return c.json({ error: 'not found' }, 404);
|
|
2200
|
-
const
|
|
2201
|
-
if (!
|
|
3528
|
+
const workingDirectory = workingDirectoryOf(run, repoRoot);
|
|
3529
|
+
if (!workingDirectory)
|
|
2202
3530
|
return c.json({ error: NO_WORKTREE }, 409);
|
|
2203
|
-
const result = await collectRunCommits(
|
|
3531
|
+
const result = await collectRunCommits(workingDirectory, run.baseBranch ?? 'HEAD');
|
|
2204
3532
|
if (!result.ok)
|
|
2205
3533
|
return c.json({ error: result.error }, 409);
|
|
2206
3534
|
return c.json({ commits: result.commits });
|
|
2207
|
-
})
|
|
2208
|
-
|
|
2209
|
-
|
|
2210
|
-
const { store } = c.get('project');
|
|
3535
|
+
})
|
|
3536
|
+
// One of the run's commits, structured like the Changes tab (reuses collectCommitChanges).
|
|
3537
|
+
.get('/runs/:id/commit/:sha', async (c) => {
|
|
3538
|
+
const { root: repoRoot, store } = c.get('project');
|
|
2211
3539
|
const run = store.getRun(c.req.param('id'));
|
|
2212
3540
|
if (!run)
|
|
2213
3541
|
return c.json({ error: 'not found' }, 404);
|
|
2214
|
-
const
|
|
2215
|
-
if (!
|
|
3542
|
+
const workingDirectory = workingDirectoryOf(run, repoRoot);
|
|
3543
|
+
if (!workingDirectory)
|
|
2216
3544
|
return c.json({ error: NO_WORKTREE }, 409);
|
|
2217
|
-
const result = await collectCommitChanges(
|
|
3545
|
+
const result = await collectCommitChanges(workingDirectory, c.req.param('sha'));
|
|
2218
3546
|
if (!result.ok)
|
|
2219
3547
|
return c.json({ error: result.error }, 409);
|
|
2220
3548
|
return c.json(result.commit);
|
|
2221
|
-
})
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
3549
|
+
})
|
|
3550
|
+
// Files tab: directory listing (path omitted or a dir) or file content
|
|
3551
|
+
// (size-capped, binary flagged). Traversal-safe — readWorktreePath rejects
|
|
3552
|
+
// anything escaping the worktree. `raw=1` (R5 Step 1.6) serves the BYTES of
|
|
3553
|
+
// image files only, for the preview's inline <img> — never HTML/JS/etc., so
|
|
3554
|
+
// no worktree file can become a same-origin document, and never past the
|
|
3555
|
+
// size cap. The no-script CSP neutralizes SVG opened as a top-level URL.
|
|
3556
|
+
//
|
|
3557
|
+
// An `Accept` that asks for images reaches the same raw branch without the flag — which is
|
|
3558
|
+
// what an `<img>` sends — while the flag still wins whenever it is present and `*<slash>*`
|
|
3559
|
+
// (every `fetch`) still gets the JSON listing. See `negotiate`.
|
|
3560
|
+
.get('/runs/:id/files', queryZodValidator(z.object({ path: queryValue, raw: queryValue })), async (c) => {
|
|
3561
|
+
const { root: repoRoot, store } = c.get('project');
|
|
3562
|
+
const query = c.req.valid('query');
|
|
3563
|
+
c.header('vary', 'Accept');
|
|
3564
|
+
const wantsRaw = query.raw !== undefined
|
|
3565
|
+
? query.raw === '1'
|
|
3566
|
+
: negotiate(c.req.header('accept'), FILE_FORMATS) === 'image/*';
|
|
2230
3567
|
const run = store.getRun(c.req.param('id'));
|
|
2231
3568
|
if (!run)
|
|
2232
3569
|
return c.json({ error: 'not found' }, 404);
|
|
2233
|
-
const
|
|
2234
|
-
if (!
|
|
3570
|
+
const workingDirectory = workingDirectoryOf(run, repoRoot);
|
|
3571
|
+
if (!workingDirectory)
|
|
2235
3572
|
return c.json({ error: NO_WORKTREE }, 409);
|
|
2236
|
-
const result = await readWorktreePath(
|
|
3573
|
+
const result = await readWorktreePath(workingDirectory, query.path ?? '');
|
|
2237
3574
|
if (result.kind === 'invalid' || result.kind === 'missing') {
|
|
2238
3575
|
return c.json({ error: result.error }, 409);
|
|
2239
3576
|
}
|
|
2240
3577
|
if (result.kind === 'dir') {
|
|
2241
3578
|
return c.json({
|
|
3579
|
+
// `as const` or the literal widens to `string` during Hono's route-type inference,
|
|
3580
|
+
// which erases the discriminant a consumer narrows on — `entry.type === 'dir'` then
|
|
3581
|
+
// leaves `never` and every field access on it fails. The wire was always 'dir'.
|
|
2242
3582
|
type: 'dir',
|
|
2243
3583
|
path: result.path,
|
|
2244
3584
|
entries: result.entries,
|
|
2245
3585
|
});
|
|
2246
3586
|
}
|
|
2247
|
-
if (
|
|
3587
|
+
if (wantsRaw) {
|
|
2248
3588
|
const mime = imageMimeType(result.path);
|
|
2249
|
-
if (
|
|
2250
|
-
|
|
2251
|
-
|
|
2252
|
-
|
|
2253
|
-
|
|
2254
|
-
|
|
3589
|
+
if (mime === null || result.tooLarge) {
|
|
3590
|
+
// `?raw=1` ASKED for bytes, so it hears why it cannot have them — that 409 and its
|
|
3591
|
+
// wording are the protected surface (§2). An `Accept` is only a preference, so a
|
|
3592
|
+
// resource with no image representation falls THROUGH to the JSON answer below rather
|
|
3593
|
+
// than turning a browser's navigation to a text file into an error.
|
|
3594
|
+
if (query.raw !== undefined) {
|
|
3595
|
+
const error = mime === null
|
|
3596
|
+
? `raw serving is limited to images: ${result.path}`
|
|
3597
|
+
: `file too large to serve raw (${result.size} bytes): ${result.path}`;
|
|
3598
|
+
return c.json({ error }, 409);
|
|
3599
|
+
}
|
|
3600
|
+
}
|
|
3601
|
+
else {
|
|
3602
|
+
const bytes = await readFile(join(workingDirectory, result.path));
|
|
3603
|
+
return c.body(new Uint8Array(bytes).buffer, 200, {
|
|
3604
|
+
'content-type': mime,
|
|
3605
|
+
'x-content-type-options': 'nosniff',
|
|
3606
|
+
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
|
3607
|
+
});
|
|
2255
3608
|
}
|
|
2256
|
-
const bytes = await readFile(join(worktree, result.path));
|
|
2257
|
-
return c.body(new Uint8Array(bytes).buffer, 200, {
|
|
2258
|
-
'content-type': mime,
|
|
2259
|
-
'x-content-type-options': 'nosniff',
|
|
2260
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
|
2261
|
-
});
|
|
2262
3609
|
}
|
|
2263
3610
|
return c.json({
|
|
2264
3611
|
type: 'file',
|
|
@@ -2268,8 +3615,8 @@ export function createApp(deps) {
|
|
|
2268
3615
|
tooLarge: result.tooLarge,
|
|
2269
3616
|
...(result.content !== undefined ? { content: result.content } : {}),
|
|
2270
3617
|
});
|
|
2271
|
-
})
|
|
2272
|
-
|
|
3618
|
+
})
|
|
3619
|
+
.post('/runs/:id/git/commit', jsonZodValidator(gitCommitSchema), async (c) => {
|
|
2273
3620
|
const { store } = c.get('project');
|
|
2274
3621
|
const run = store.getRun(c.req.param('id'));
|
|
2275
3622
|
if (!run)
|
|
@@ -2277,16 +3624,13 @@ export function createApp(deps) {
|
|
|
2277
3624
|
const worktree = worktreeOf(run);
|
|
2278
3625
|
if (!worktree)
|
|
2279
3626
|
return c.json({ error: NO_WORKTREE }, 409);
|
|
2280
|
-
const parsed =
|
|
2281
|
-
if (!parsed.success) {
|
|
2282
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
2283
|
-
}
|
|
3627
|
+
const parsed = { data: c.req.valid('json') };
|
|
2284
3628
|
const result = await commitAll(worktree, parsed.data.message);
|
|
2285
3629
|
if (!result.ok)
|
|
2286
3630
|
return c.json({ error: result.error }, 409);
|
|
2287
3631
|
return c.json({ committed: true, sha: result.sha });
|
|
2288
|
-
})
|
|
2289
|
-
|
|
3632
|
+
})
|
|
3633
|
+
.post('/runs/:id/git/push', async (c) => {
|
|
2290
3634
|
const { store } = c.get('project');
|
|
2291
3635
|
const run = store.getRun(c.req.param('id'));
|
|
2292
3636
|
if (!run)
|
|
@@ -2303,12 +3647,12 @@ export function createApp(deps) {
|
|
|
2303
3647
|
remote: result.remote,
|
|
2304
3648
|
upstreamSet: result.upstreamSet,
|
|
2305
3649
|
});
|
|
2306
|
-
})
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
3650
|
+
})
|
|
3651
|
+
// Draft PR from the review gate (spec 009): final autosave → push →
|
|
3652
|
+
// `gh pr create --draft`; on success the run completes as done with the PR
|
|
3653
|
+
// badge. Failures come back as 409 with a `manual` merge command the GUI
|
|
3654
|
+
// shows next to the toast. CEZ_DRY_RUN=1 fakes the URL (no push, no gh).
|
|
3655
|
+
.post('/runs/:id/pr', async (c) => {
|
|
2312
3656
|
const { root: repoRoot, dataDir, store, manager } = c.get('project');
|
|
2313
3657
|
const id = c.req.param('id');
|
|
2314
3658
|
const run = store.getRun(id);
|
|
@@ -2339,10 +3683,10 @@ export function createApp(deps) {
|
|
|
2339
3683
|
message: `draft PR created: ${outcome.url}${outcome.dryRun ? ' (dry run — no real PR)' : ''}`,
|
|
2340
3684
|
});
|
|
2341
3685
|
return c.json({ url: outcome.url, dryRun: outcome.dryRun }, 201);
|
|
2342
|
-
})
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
|
|
3686
|
+
})
|
|
3687
|
+
// Archived tasks keep their worktree for inspection; this is the explicit
|
|
3688
|
+
// "🧹 Remove worktree" cleanup (spec 006).
|
|
3689
|
+
.post('/runs/:id/remove-worktree', async (c) => {
|
|
2346
3690
|
const { root: repoRoot, store, manager } = c.get('project');
|
|
2347
3691
|
const id = c.req.param('id');
|
|
2348
3692
|
const run = store.getRun(id);
|
|
@@ -2354,8 +3698,8 @@ export function createApp(deps) {
|
|
|
2354
3698
|
await removeWorktree(repoRoot, run.worktreePath, run.branch);
|
|
2355
3699
|
store.updateRun(id, { worktreePath: undefined, branch: undefined });
|
|
2356
3700
|
return c.json({ removed: true });
|
|
2357
|
-
})
|
|
2358
|
-
|
|
3701
|
+
})
|
|
3702
|
+
.delete('/runs/:id', async (c) => {
|
|
2359
3703
|
const { root: repoRoot, store, manager } = c.get('project');
|
|
2360
3704
|
const id = c.req.param('id');
|
|
2361
3705
|
if (manager.isActive(id))
|
|
@@ -2368,11 +3712,116 @@ export function createApp(deps) {
|
|
|
2368
3712
|
await removeWorktree(repoRoot, run.worktreePath, run.branch);
|
|
2369
3713
|
return store.deleteRun(id) ? c.json({ deleted: true }) : c.json({ error: 'not found' }, 404);
|
|
2370
3714
|
});
|
|
2371
|
-
// ----
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
3715
|
+
// ---- parallel variants (spec 010) -----------------------------------------
|
|
3716
|
+
const groupRuns = (store, groupId) => store
|
|
3717
|
+
.listRuns()
|
|
3718
|
+
.filter((r) => r.groupId === groupId)
|
|
3719
|
+
.sort((a, b) => (a.variant ?? '').localeCompare(b.variant ?? ''));
|
|
3720
|
+
// ---- chained family: variant groups (project-scoped) ----
|
|
3721
|
+
const groupsRoutes = new Hono()
|
|
3722
|
+
.get('/groups/:groupId', async (c) => {
|
|
3723
|
+
const { dataDir, store } = c.get('project');
|
|
3724
|
+
const runs = groupRuns(store, c.req.param('groupId'));
|
|
3725
|
+
if (runs.length === 0)
|
|
3726
|
+
return c.json({ error: 'not found' }, 404);
|
|
3727
|
+
const detailed = await Promise.all(runs.map(async (r) => ({
|
|
3728
|
+
id: r.id,
|
|
3729
|
+
variant: r.variant ?? '?',
|
|
3730
|
+
title: r.title,
|
|
3731
|
+
status: r.status,
|
|
3732
|
+
archived: r.archived,
|
|
3733
|
+
tokensUsed: r.tokensUsed,
|
|
3734
|
+
...(r.inputTokens !== undefined ? { inputTokens: r.inputTokens } : {}),
|
|
3735
|
+
...(r.outputTokens !== undefined ? { outputTokens: r.outputTokens } : {}),
|
|
3736
|
+
...(r.costUsd !== undefined ? { costUsd: r.costUsd } : {}),
|
|
3737
|
+
diffStat: r.worktreePath && existsSync(r.worktreePath)
|
|
3738
|
+
? await worktreeDiffStat(r.worktreePath, r.baseBranch ?? 'HEAD')
|
|
3739
|
+
: '',
|
|
3740
|
+
handoffExcerpt: handoffProgressExcerpt(readHandoff(dataDir, r.id)),
|
|
3741
|
+
})));
|
|
3742
|
+
return c.json({
|
|
3743
|
+
groupId: c.req.param('groupId'),
|
|
3744
|
+
runs: detailed,
|
|
3745
|
+
});
|
|
3746
|
+
})
|
|
3747
|
+
// "Pick this one": the winner rests at `review` (spec 009 takes it from
|
|
3748
|
+
// there — send back / draft PR / finish); the losers are cancelled if
|
|
3749
|
+
// alive, archived, and their worktrees + branches removed.
|
|
3750
|
+
.post('/groups/:groupId/pick', jsonZodValidator(pickSchema), async (c) => {
|
|
3751
|
+
const { root: repoRoot, dataDir, store, manager } = c.get('project');
|
|
3752
|
+
const runs = groupRuns(store, c.req.param('groupId'));
|
|
3753
|
+
if (runs.length === 0)
|
|
3754
|
+
return c.json({ error: 'not found' }, 404);
|
|
3755
|
+
const parsed = { data: c.req.valid('json') };
|
|
3756
|
+
const winner = runs.find((r) => r.id === parsed.data.runId);
|
|
3757
|
+
if (!winner)
|
|
3758
|
+
return c.json({ error: 'runId is not part of this group' }, 404);
|
|
3759
|
+
if (manager.isActive(winner.id)) {
|
|
3760
|
+
return c.json({ error: 'this variant is still active — wait for it to finish first' }, 409);
|
|
3761
|
+
}
|
|
3762
|
+
// Winner: a non-review terminal state with a non-empty diff flips to
|
|
3763
|
+
// `review` (the settleSuccess rule) — but only when the review gate applies
|
|
3764
|
+
// (#489): it is enabled (`reviewGateEnabled`, default off) AND the winner is
|
|
3765
|
+
// not autonomous. An autonomous / gate-off winner keeps its `done` state with
|
|
3766
|
+
// the diff left in the worktree; an empty diff (or no worktree) stays too.
|
|
3767
|
+
if (winner.status !== 'review' &&
|
|
3768
|
+
winner.worktreePath &&
|
|
3769
|
+
existsSync(winner.worktreePath) &&
|
|
3770
|
+
winner.autonomous !== true &&
|
|
3771
|
+
reviewGateEnabled(await loadConfig(repoRoot))) {
|
|
3772
|
+
const diff = await worktreeDiff(winner.worktreePath, winner.baseBranch ?? 'HEAD');
|
|
3773
|
+
if (diff.trim().length > 0 && !diff.startsWith('(diff failed')) {
|
|
3774
|
+
store.updateRun(winner.id, { status: 'review' });
|
|
3775
|
+
}
|
|
3776
|
+
}
|
|
3777
|
+
const losers = runs.filter((r) => r.id !== winner.id);
|
|
3778
|
+
store.appendEvent(winner.id, {
|
|
3779
|
+
type: 'lifecycle',
|
|
3780
|
+
message: `picked from ${runs.length} variants — ${losers.length} other variant(s) archived`,
|
|
3781
|
+
});
|
|
3782
|
+
appendHandoffHeartbeat(dataDir, winner.id, `picked from ${runs.length} variants`);
|
|
3783
|
+
for (const loser of losers) {
|
|
3784
|
+
if (manager.isActive(loser.id))
|
|
3785
|
+
manager.cancel(loser.id);
|
|
3786
|
+
if (loser.worktreePath)
|
|
3787
|
+
await removeWorktree(repoRoot, loser.worktreePath, loser.branch);
|
|
3788
|
+
store.updateRun(loser.id, { worktreePath: undefined, branch: undefined });
|
|
3789
|
+
store.setArchived(loser.id, true);
|
|
3790
|
+
store.appendEvent(loser.id, {
|
|
3791
|
+
type: 'lifecycle',
|
|
3792
|
+
message: `variant ${winner.variant ?? '?'} was picked — this variant is archived, its worktree removed`,
|
|
3793
|
+
});
|
|
3794
|
+
}
|
|
3795
|
+
// Spread: `getRun` may answer undefined, and an undefined VALUE is dropped by
|
|
3796
|
+
// JSON.stringify — so writing the key unconditionally typed the route as sending a key it
|
|
3797
|
+
// does not. contract/workflows.ts says `.optional()`, which is what a client receives.
|
|
3798
|
+
const picked = store.getRun(winner.id);
|
|
3799
|
+
return c.json({ ...(picked !== undefined ? { winner: picked } : {}) });
|
|
3800
|
+
});
|
|
3801
|
+
// ---- chained family: open-targets (project-scoped) ----
|
|
3802
|
+
const openTargetsRoutes = new Hono()
|
|
3803
|
+
.get('/open-targets', (c) => c.json({ targets: capabilities().localHandoff ? detectOpenTargets() : [] }));
|
|
3804
|
+
// Agent screenshots — image blocks the run manager persisted out of tool
|
|
3805
|
+
// results (persistImage). `basename` pins reads inside the run's own dir.
|
|
3806
|
+
const IMAGE_TYPES = {
|
|
3807
|
+
png: 'image/png',
|
|
3808
|
+
jpg: 'image/jpeg',
|
|
3809
|
+
webp: 'image/webp',
|
|
3810
|
+
gif: 'image/gif',
|
|
3811
|
+
};
|
|
3812
|
+
// ---- session git view (redesign R5 Step 1.2 — §"Git/session API additions").
|
|
3813
|
+
// Structured sibling of the text-blob /diff above (which stays untouched —
|
|
3814
|
+
// protected surface). Isolated runs read their worktree; worktree-off runs
|
|
3815
|
+
// read the repo checkout they executed in. Every predictable git failure
|
|
3816
|
+
// degrades to 409 + human-readable reason, 404 only for unknown ids.
|
|
3817
|
+
const worktreeOf = (run) => run.worktreePath && existsSync(run.worktreePath) ? run.worktreePath : null;
|
|
3818
|
+
const workingDirectoryOf = (run, repoRoot) => run.worktree === false
|
|
3819
|
+
? repoRoot
|
|
3820
|
+
: worktreeOf(run);
|
|
3821
|
+
const NO_WORKTREE = 'no worktree — this task ran directly in the repo working tree';
|
|
3822
|
+
// ---- chained family: worktrees (project-scoped) ----
|
|
3823
|
+
const worktreesRoutes = new Hono()
|
|
3824
|
+
.get('/worktrees', async (c) => {
|
|
2376
3825
|
const { root: repoRoot, store } = c.get('project');
|
|
2377
3826
|
// The keep-limit the panel reports is the one the enforcer will actually
|
|
2378
3827
|
// apply — inherited from the workspace default when this repo sets none.
|
|
@@ -2392,61 +3841,69 @@ export function createApp(deps) {
|
|
|
2392
3841
|
const totalBytes = worktrees.some((w) => w.sizeBytes === null)
|
|
2393
3842
|
? null
|
|
2394
3843
|
: worktrees.reduce((sum, w) => sum + (w.sizeBytes ?? 0), 0);
|
|
2395
|
-
return c.json({ worktrees, totalBytes, keep });
|
|
2396
|
-
})
|
|
2397
|
-
|
|
2398
|
-
api.post('/worktrees/reclaim', async (c) => {
|
|
3844
|
+
return c.json({ worktrees, totalBytes, keep });
|
|
3845
|
+
})
|
|
3846
|
+
.post('/worktrees/reclaim', jsonZodValidator(() => reclaimBodySchema, { absent: ({}), message: 'invalid body' }), async (c) => {
|
|
2399
3847
|
const { root: repoRoot, store } = c.get('project');
|
|
2400
|
-
//
|
|
2401
|
-
|
|
2402
|
-
if (!parsed.success)
|
|
2403
|
-
return c.json({ error: 'invalid body' }, 400);
|
|
3848
|
+
// The body is validated (an empty or `{}` one is accepted) but carries nothing this
|
|
3849
|
+
// handler reads; retention is best-effort, so 200 always.
|
|
2404
3850
|
const reclaimed = await reclaimWorktrees(repoRoot, store, await resolveWorktreeRetention(repoRoot));
|
|
2405
3851
|
return c.json({ reclaimed });
|
|
2406
3852
|
});
|
|
2407
|
-
|
|
2408
|
-
|
|
2409
|
-
|
|
2410
|
-
|
|
2411
|
-
|
|
2412
|
-
|
|
2413
|
-
|
|
2414
|
-
|
|
2415
|
-
|
|
3853
|
+
const reclaimBodySchema = z.object({}).passthrough();
|
|
3854
|
+
/**
|
|
3855
|
+
* "The inbox is on and this entry exists" — the 409/404 half of `POST /todos/:id/start`, lifted
|
|
3856
|
+
* out of the handler and in FRONT of the body validator.
|
|
3857
|
+
*
|
|
3858
|
+
* That position is the whole point. The route's contract is that an unknown id 404s before the
|
|
3859
|
+
* body is looked at, and Hono only records a body in the route type when it is validated as
|
|
3860
|
+
* MIDDLEWARE — which necessarily runs before the handler. Registering this guard first satisfies
|
|
3861
|
+
* both: the documented status order is unchanged, and `startTodoSchema` becomes visible to
|
|
3862
|
+
* `AppType` (and so to `hc`) instead of being parsed invisibly inside the handler.
|
|
3863
|
+
*
|
|
3864
|
+
* Deliberately NOT annotated with a return type: the inferred one carries the two typed
|
|
3865
|
+
* responses, which is what keeps the 409 and 404 branches in the route's schema for the client.
|
|
3866
|
+
*/
|
|
3867
|
+
const todoMustExist = async (c, next) => {
|
|
3868
|
+
if (!capabilities().followups)
|
|
3869
|
+
return c.json({ error: FOLLOWUPS_OFF }, 409);
|
|
3870
|
+
const todo = (await readTodos(c.get('project').dataDir)).find((t) => t.id === c.req.param('id'));
|
|
3871
|
+
if (!todo)
|
|
3872
|
+
return c.json({ error: 'not found' }, 404);
|
|
3873
|
+
c.set('todo', todo);
|
|
3874
|
+
await next();
|
|
3875
|
+
};
|
|
3876
|
+
// ---- chained family: follow-up inbox / todos (project-scoped) ----
|
|
3877
|
+
const todosRoutes = new Hono()
|
|
3878
|
+
.get('/todos', async (c) => c.json(capabilities().followups ? await readTodos(c.get('project').dataDir) : []))
|
|
3879
|
+
// Check off = delete the entry.
|
|
3880
|
+
.delete('/todos/:id', async (c) => {
|
|
2416
3881
|
const { dataDir } = c.get('project');
|
|
2417
3882
|
if (!capabilities().followups)
|
|
2418
3883
|
return c.json({ error: FOLLOWUPS_OFF }, 409);
|
|
2419
3884
|
const removed = await removeTodo(dataDir, c.req.param('id'));
|
|
2420
3885
|
return removed ? c.json({ removed: true }) : c.json({ error: 'not found' }, 404);
|
|
2421
|
-
})
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
3886
|
+
})
|
|
3887
|
+
// "▶ Run": turn an inbox entry into a task — a one-off single-step workflow
|
|
3888
|
+
// around the suggested skill when it exists, plain quick-task otherwise.
|
|
3889
|
+
//
|
|
3890
|
+
// TWO middlewares, and their ORDER is the contract. This route's documented status order
|
|
3891
|
+
// (pinned by todos-start.test.ts) is that a disabled inbox 409s and an unknown id 404s BEFORE
|
|
3892
|
+
// the body is looked at — which is why the body used to be parsed inline, invisible to `hc`.
|
|
3893
|
+
// Hono runs route middleware in registration order, so `todoMustExist` FIRST keeps that order
|
|
3894
|
+
// exactly while `jsonZodValidator` second is what records the body in the route type.
|
|
3895
|
+
//
|
|
3896
|
+
// The two no-body cases the old inline parse distinguished are carried by the validator's
|
|
3897
|
+
// `absent`/`malformed` options: no body at all is `undefined` (the pre-#401 bodyless POST,
|
|
3898
|
+
// which the optional schema accepts → 201), a truncated payload is `null` (which it rejects
|
|
3899
|
+
// → 400, rather than passing as "no body" and silently starting a run).
|
|
3900
|
+
.post('/todos/:id/start', todoMustExist, jsonZodValidator(startTodoSchema, { absent: undefined, malformed: null }), async (c) => {
|
|
2425
3901
|
const { root: repoRoot, dataDir, manager } = c.get('project');
|
|
2426
|
-
if (!capabilities().followups)
|
|
2427
|
-
return c.json({ error: FOLLOWUPS_OFF }, 409);
|
|
2428
3902
|
const id = c.req.param('id');
|
|
2429
|
-
const todo =
|
|
2430
|
-
|
|
2431
|
-
|
|
2432
|
-
|
|
2433
|
-
// request with none at all (the pre-pills/pre-composer client) stays `undefined`, same as an
|
|
2434
|
-
// empty `{}`. A body that IS present but is not valid JSON becomes `null`, which the schema
|
|
2435
|
-
// rejects → 400 (the `.catch(() => null)` pattern every other mutating route uses); mapping
|
|
2436
|
-
// it to `undefined` too would let a broken payload pass as "no body" and silently 201.
|
|
2437
|
-
const rawBody = await c.req.text().catch(() => '');
|
|
2438
|
-
let body;
|
|
2439
|
-
if (rawBody.trim().length > 0) {
|
|
2440
|
-
try {
|
|
2441
|
-
body = JSON.parse(rawBody);
|
|
2442
|
-
}
|
|
2443
|
-
catch {
|
|
2444
|
-
body = null;
|
|
2445
|
-
}
|
|
2446
|
-
}
|
|
2447
|
-
const parsed = startTodoSchema.safeParse(body);
|
|
2448
|
-
if (!parsed.success) {
|
|
2449
|
-
return c.json({ error: parsed.error.issues.map((i) => i.message).join('; ') }, 400);
|
|
3903
|
+
const todo = c.get('todo');
|
|
3904
|
+
const parsed = { data: c.req.valid('json') };
|
|
3905
|
+
if (agentModelsLocked(repoRoot) && parsed.data?.model?.trim()) {
|
|
3906
|
+
return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
|
|
2450
3907
|
}
|
|
2451
3908
|
if (todo.startedTaskId)
|
|
2452
3909
|
return c.json({ error: 'already started' }, 409);
|
|
@@ -2476,6 +3933,10 @@ export function createApp(deps) {
|
|
|
2476
3933
|
const { workflows } = await loadWorkflows(repoRoot);
|
|
2477
3934
|
workflow = workflows.find((w) => w.name === 'quick-task') ?? QUICK_TASK_WORKFLOW;
|
|
2478
3935
|
}
|
|
3936
|
+
const fallback = parsed.data?.runner ?? (await loadConfig(repoRoot)).defaultRunner;
|
|
3937
|
+
const blocked = await providerActionError(providersRequiredByWorkflow(workflow, fallback));
|
|
3938
|
+
if (blocked)
|
|
3939
|
+
return c.json({ error: blocked }, 409);
|
|
2479
3940
|
const run = manager.startRun(workflow, {
|
|
2480
3941
|
task,
|
|
2481
3942
|
runner: parsed.data?.runner,
|
|
@@ -2484,10 +3945,9 @@ export function createApp(deps) {
|
|
|
2484
3945
|
await markStarted(dataDir, id, run.id);
|
|
2485
3946
|
return c.json({ run }, 201);
|
|
2486
3947
|
});
|
|
2487
|
-
//
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
api.get('/runs/:id/events', (c) => {
|
|
3948
|
+
// ---- chained family: SSE streams (project-scoped) ----
|
|
3949
|
+
const sseRoutes = new Hono()
|
|
3950
|
+
.get('/runs/:id/events', (c) => {
|
|
2491
3951
|
const { store } = c.get('project');
|
|
2492
3952
|
const id = c.req.param('id');
|
|
2493
3953
|
if (!store.getRun(id))
|
|
@@ -2543,13 +4003,13 @@ export function createApp(deps) {
|
|
|
2543
4003
|
await stream.sleep(15_000);
|
|
2544
4004
|
}
|
|
2545
4005
|
});
|
|
2546
|
-
})
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
4006
|
+
})
|
|
4007
|
+
// Global SSE: run-summary updates for the list view + inbox changes.
|
|
4008
|
+
// Scoped `/p/:projectId/events` carries that project's stream in today's
|
|
4009
|
+
// shape; the legacy unprefixed alias stays bound to the boot project ONLY
|
|
4010
|
+
// (spec "Legacy aliases" — widening it would be a silent behavioral break;
|
|
4011
|
+
// the all-project stream arrives as `/api/workspace/events` in step 2.8).
|
|
4012
|
+
.get('/events', (c) => {
|
|
2553
4013
|
const { dataDir, store } = c.get('project');
|
|
2554
4014
|
return streamSSENoBuffer(c, async (stream) => {
|
|
2555
4015
|
const onRun = (run) => void stream.writeSSE({ event: 'run', data: JSON.stringify(run) });
|
|
@@ -2595,22 +4055,9 @@ export function createApp(deps) {
|
|
|
2595
4055
|
}
|
|
2596
4056
|
});
|
|
2597
4057
|
});
|
|
2598
|
-
// ---- workspace SSE (
|
|
2599
|
-
|
|
2600
|
-
|
|
2601
|
-
// Same event names as the per-project stream, but every payload is stamped
|
|
2602
|
-
// with the owning `project` id — additively where the legacy payload is an
|
|
2603
|
-
// object (`run` grows a `project` key, `run-deleted` becomes
|
|
2604
|
-
// `{id, project}`), wrapped where it is not (`todos` → `{project, items}`,
|
|
2605
|
-
// `usage` → `{project, usage}` — a bare array/record has nowhere to carry a
|
|
2606
|
-
// stamp). The legacy `/api/events` alias above keeps its UN-stamped,
|
|
2607
|
-
// boot-filtered shape — that stream is a protected surface.
|
|
2608
|
-
//
|
|
2609
|
-
// Subscribing NEVER force-instantiates a project: only the boot context
|
|
2610
|
-
// (always live) and already-built lazy contexts are attached at connect;
|
|
2611
|
-
// contexts built later join via the `onContextBuilt` hook, so a project's
|
|
2612
|
-
// first API touch makes its events flow to streams already open.
|
|
2613
|
-
app.get('/api/workspace/events', (c) => {
|
|
4058
|
+
// ---- chained family: workspace SSE stream (workspace-level) ----
|
|
4059
|
+
const workspaceEventsRoutes = new Hono()
|
|
4060
|
+
.get('/workspace/events', (c) => {
|
|
2614
4061
|
return streamSSENoBuffer(c, async (stream) => {
|
|
2615
4062
|
// One detach bundle per attached project — the id guard makes a double
|
|
2616
4063
|
// attach (connect-time snapshot vs. the built hook) impossible.
|
|
@@ -2682,11 +4129,12 @@ export function createApp(deps) {
|
|
|
2682
4129
|
}
|
|
2683
4130
|
});
|
|
2684
4131
|
// Workspace-level events (project-added / project-removed /
|
|
2685
|
-
// checkout-progress
|
|
2686
|
-
// removal also drops the project's
|
|
2687
|
-
// `attach` would otherwise pin the
|
|
2688
|
-
// project removed and re-added on the
|
|
2689
|
-
// context whose events never reach this
|
|
4132
|
+
// checkout-progress plus host-wide unstamped provider-status) — relayed
|
|
4133
|
+
// verbatim under their own names. A removal also drops the project's
|
|
4134
|
+
// attach entry: the id guard in `attach` would otherwise pin the
|
|
4135
|
+
// DISPOSED context forever, so a project removed and re-added on the
|
|
4136
|
+
// same slug would rebuild a fresh context whose events never reach this
|
|
4137
|
+
// already-open stream.
|
|
2690
4138
|
const offWorkspace = workspaceEvents.on((event, data) => {
|
|
2691
4139
|
if (event === 'project-removed') {
|
|
2692
4140
|
const removed = data.id;
|
|
@@ -2711,23 +4159,25 @@ export function createApp(deps) {
|
|
|
2711
4159
|
}
|
|
2712
4160
|
});
|
|
2713
4161
|
});
|
|
2714
|
-
// ---- GitHub
|
|
2715
|
-
//
|
|
2716
|
-
//
|
|
2717
|
-
//
|
|
2718
|
-
|
|
4162
|
+
// ---- chained family: GitHub (project-scoped) ----
|
|
4163
|
+
// These sit ABOVE the routes rather than with the family's other schemas below it, because a
|
|
4164
|
+
// validator argument is evaluated when the route is REGISTERED — a schema declared further down
|
|
4165
|
+
// would be in its temporal dead zone. (The schemas below are all read inside a handler, or
|
|
4166
|
+
// passed as a thunk, which defers them past that point.)
|
|
4167
|
+
const mergeNumberParams = z.object({ number: z.coerce.number().int().positive() });
|
|
4168
|
+
const prChangesParams = z.object({ number: z.coerce.number().int().positive().safe() });
|
|
4169
|
+
const prChangesQuery = z.object({ refresh: queryValue.refine((v) => v === undefined || v === '1') });
|
|
4170
|
+
const githubRoutes = new Hono()
|
|
4171
|
+
.get('/github',
|
|
4172
|
+
// `limit` stays a bare string: the handler's `Number.parseInt`/`Number.isFinite` fallback to
|
|
4173
|
+
// 30 already accepts `?limit=banana`, and a numeric schema would 400 it instead.
|
|
4174
|
+
queryZodValidator(z.object({ limit: queryValue, refresh: queryValue })), async (c) => {
|
|
2719
4175
|
const { root: repoRoot } = c.get('project');
|
|
2720
|
-
const
|
|
2721
|
-
|
|
2722
|
-
|
|
2723
|
-
|
|
2724
|
-
|
|
2725
|
-
// same in-payload availability degrade (gh missing / offline / 404 all render as a hint).
|
|
2726
|
-
const commentsParams = z.object({
|
|
2727
|
-
kind: z.enum(['issue', 'pr']),
|
|
2728
|
-
number: z.coerce.number().int().positive(),
|
|
2729
|
-
});
|
|
2730
|
-
api.get('/github/comments/:kind/:number', async (c) => {
|
|
4176
|
+
const query = c.req.valid('query');
|
|
4177
|
+
const limit = Number.parseInt(query.limit ?? '', 10);
|
|
4178
|
+
return c.json(await fetchGithub(repoRoot, query.refresh === '1', Number.isFinite(limit) ? limit : 30));
|
|
4179
|
+
})
|
|
4180
|
+
.get('/github/comments/:kind/:number', queryZodValidator(refreshQuery), async (c) => {
|
|
2731
4181
|
const { root: repoRoot } = c.get('project');
|
|
2732
4182
|
const parsed = commentsParams.safeParse({
|
|
2733
4183
|
kind: c.req.param('kind'),
|
|
@@ -2735,10 +4185,86 @@ export function createApp(deps) {
|
|
|
2735
4185
|
});
|
|
2736
4186
|
if (!parsed.success)
|
|
2737
4187
|
return c.json({ error: 'invalid kind or number' }, 400);
|
|
2738
|
-
return c.json(await fetchGithubComments(repoRoot, parsed.data.kind, parsed.data.number, c.req.
|
|
4188
|
+
return c.json(await fetchGithubComments(repoRoot, parsed.data.kind, parsed.data.number, c.req.valid('query').refresh === '1'));
|
|
4189
|
+
})
|
|
4190
|
+
// Lazy checks glyphs for on-screen PR rows (#664). Additive sibling of /api/github — the list
|
|
4191
|
+
// call dropped `statusCheckRollup` (the dominant cost), so the glyph is hydrated here per
|
|
4192
|
+
// visible row. `prs` is a comma-separated list of positive integers, capped at GH_CHECKS_MAX;
|
|
4193
|
+
// anything malformed is a 400. Same in-payload availability degrade as the list (never a 5xx).
|
|
4194
|
+
// `prs` is the one genuinely REQUIRED query key on this server, so it is the one validated
|
|
4195
|
+
// strictly — `.min(1)` because `?prs=` answered `missing prs query` before it answered
|
|
4196
|
+
// `invalid prs query`, and both spellings must keep their own words.
|
|
4197
|
+
.get('/github/checks', queryZodValidator(z.object({ prs: z.string().min(1) }), { message: 'missing prs query' }), async (c) => {
|
|
4198
|
+
const { root: repoRoot } = c.get('project');
|
|
4199
|
+
const raw = c.req.valid('query').prs;
|
|
4200
|
+
const parts = raw.split(',').map((p) => p.trim()).filter(Boolean);
|
|
4201
|
+
if (parts.length === 0 || parts.length > GH_CHECKS_MAX)
|
|
4202
|
+
return c.json({ error: 'invalid prs query' }, 400);
|
|
4203
|
+
const numbers = [];
|
|
4204
|
+
for (const part of parts) {
|
|
4205
|
+
const n = Number(part);
|
|
4206
|
+
if (!Number.isInteger(n) || n <= 0 || String(n) !== part)
|
|
4207
|
+
return c.json({ error: 'invalid prs query' }, 400);
|
|
4208
|
+
numbers.push(n);
|
|
4209
|
+
}
|
|
4210
|
+
return c.json(await fetchGithubChecks(repoRoot, numbers));
|
|
4211
|
+
})
|
|
4212
|
+
.get('/github/prs/:number/merge-state', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), queryZodValidator(refreshQuery), async (c) => {
|
|
4213
|
+
const { root: repoRoot } = c.get('project');
|
|
4214
|
+
const parsed = { data: c.req.valid('param') };
|
|
4215
|
+
const forge = resolveForge(await getRepoInfo(repoRoot));
|
|
4216
|
+
if (!forge?.prMergeState)
|
|
4217
|
+
return c.json({ available: false, reason: 'GitHub merge state is unavailable' });
|
|
4218
|
+
return c.json(await forge.prMergeState(parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
|
|
4219
|
+
})
|
|
4220
|
+
.post('/github/prs/:number/merge', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), jsonZodValidator(() => mergeBodySchema, { message: 'invalid merge request' }), async (c) => {
|
|
4221
|
+
const { root: repoRoot } = c.get('project');
|
|
4222
|
+
const parsedNumber = { data: c.req.valid('param') };
|
|
4223
|
+
const body = { data: c.req.valid('json') };
|
|
4224
|
+
const forge = resolveForge(await getRepoInfo(repoRoot));
|
|
4225
|
+
if (!forge?.mergePR)
|
|
4226
|
+
return c.json({ error: 'GitHub merge is unavailable' }, 409);
|
|
4227
|
+
const result = await forge.mergePR(parsedNumber.data.number, body.data);
|
|
4228
|
+
if (result.merged)
|
|
4229
|
+
return c.json(result);
|
|
4230
|
+
return c.json({
|
|
4231
|
+
error: result.error,
|
|
4232
|
+
...(result.code ? { code: result.code } : {}),
|
|
4233
|
+
...(result.current ? { current: result.current } : {}),
|
|
4234
|
+
}, result.status);
|
|
4235
|
+
})
|
|
4236
|
+
.get('/github/prs/:number/changes',
|
|
4237
|
+
// Split out of one `safeParse` over both inputs, because a path param and the query string
|
|
4238
|
+
// are separate validation targets to Hono and only a split makes each visible to the route
|
|
4239
|
+
// type. Both keep the single 400 sentence the combined parse answered. `refresh` stays
|
|
4240
|
+
// STRICT here (`?refresh=true` is a 400 today, unlike everywhere else on this server).
|
|
4241
|
+
paramZodValidator(prChangesParams, { message: 'invalid pull request number or refresh flag' }), queryZodValidator(prChangesQuery, { message: 'invalid pull request number or refresh flag' }), async (c) => {
|
|
4242
|
+
const { root: repoRoot } = c.get('project');
|
|
4243
|
+
const parsed = { data: c.req.valid('param') };
|
|
4244
|
+
try {
|
|
4245
|
+
return c.json(await fetchGithubPrDiff(repoRoot, parsed.data.number, c.req.valid('query').refresh === '1'));
|
|
4246
|
+
}
|
|
4247
|
+
catch (err) {
|
|
4248
|
+
if (err instanceof GithubPrNotFoundError)
|
|
4249
|
+
return c.json({ error: err.message }, 404);
|
|
4250
|
+
throw err;
|
|
4251
|
+
}
|
|
4252
|
+
});
|
|
4253
|
+
// The full comment thread for one issue/PR (#499). Additive sibling of /api/github — lazy
|
|
4254
|
+
// (fetched only while a detail view is open), zod-validated params, 400 on garbage, and the
|
|
4255
|
+
// same in-payload availability degrade (gh missing / offline / 404 all render as a hint).
|
|
4256
|
+
const commentsParams = z.object({
|
|
4257
|
+
kind: z.enum(['issue', 'pr']),
|
|
4258
|
+
number: z.coerce.number().int().positive(),
|
|
2739
4259
|
});
|
|
2740
|
-
|
|
2741
|
-
|
|
4260
|
+
const mergeBodySchema = z.object({
|
|
4261
|
+
method: z.enum(['merge', 'squash', 'rebase']),
|
|
4262
|
+
expectedHeadSha: z.string().regex(/^[0-9a-f]{40}$/),
|
|
4263
|
+
overrideRules: z.boolean().optional().default(false),
|
|
4264
|
+
}).strict();
|
|
4265
|
+
// ---- chained family: repo / git (project-scoped) ----
|
|
4266
|
+
const repoRoutes = new Hono()
|
|
4267
|
+
.get('/repo', async (c) => {
|
|
2742
4268
|
const { root: repoRoot } = c.get('project');
|
|
2743
4269
|
const info = await getRepoInfo(repoRoot);
|
|
2744
4270
|
if (!info)
|
|
@@ -2762,64 +4288,115 @@ export function createApp(deps) {
|
|
|
2762
4288
|
branches,
|
|
2763
4289
|
baseBranch: config.baseBranch ?? null,
|
|
2764
4290
|
});
|
|
4291
|
+
})
|
|
4292
|
+
.get('/repo/diff', async (c) => {
|
|
4293
|
+
const { root: repoRoot } = c.get('project');
|
|
4294
|
+
const info = await getRepoInfo(repoRoot);
|
|
4295
|
+
if (!info)
|
|
4296
|
+
return c.text('not a git repository');
|
|
4297
|
+
return c.text(await getDiff(info.root));
|
|
4298
|
+
})
|
|
4299
|
+
// One commit's message + stat + patch — the Repo view expands it inline.
|
|
4300
|
+
// `?structured=1` is the ADDITIVE sibling (R5 Step 1.7): the new repo view's commit-diff
|
|
4301
|
+
// shape `{sha, subject, author, when, files, stat}` with 409 + reason on failure. The
|
|
4302
|
+
// legacy text answer below is a protected surface (BACKWARD_COMPATIBILITY.md §2) — its
|
|
4303
|
+
// shape, including the in-band failure sentences, stays exactly as it was.
|
|
4304
|
+
//
|
|
4305
|
+
// `Accept: application/json` reaches the same structured answer without the flag, and
|
|
4306
|
+
// `Accept: text/plain` asks for the blob; the flag still wins whenever it is present, and a
|
|
4307
|
+
// request with no opinion still gets the blob. See `negotiate`.
|
|
4308
|
+
.get('/repo/commit/:sha', queryZodValidator(z.object({ structured: queryValue })), async (c) => {
|
|
4309
|
+
const { root: repoRoot } = c.get('project');
|
|
4310
|
+
c.header('vary', 'Accept');
|
|
4311
|
+
const { structured } = c.req.valid('query');
|
|
4312
|
+
const wantsJson = structured !== undefined
|
|
4313
|
+
? structured === '1'
|
|
4314
|
+
: negotiate(c.req.header('accept'), COMMIT_FORMATS) === 'application/json';
|
|
4315
|
+
const info = await getRepoInfo(repoRoot);
|
|
4316
|
+
if (wantsJson) {
|
|
4317
|
+
if (!info)
|
|
4318
|
+
return c.json({ error: 'not a git repository' }, 409);
|
|
4319
|
+
const result = await collectCommitChanges(info.root, c.req.param('sha'));
|
|
4320
|
+
if (!result.ok)
|
|
4321
|
+
return c.json({ error: result.error }, 409);
|
|
4322
|
+
return c.json(result.commit);
|
|
4323
|
+
}
|
|
4324
|
+
if (!info)
|
|
4325
|
+
return c.text('not a git repository');
|
|
4326
|
+
try {
|
|
4327
|
+
return c.text(await getCommit(info.root, c.req.param('sha')));
|
|
4328
|
+
}
|
|
4329
|
+
catch (err) {
|
|
4330
|
+
return c.text(`(git show failed: ${err instanceof Error ? err.message : String(err)})`);
|
|
4331
|
+
}
|
|
4332
|
+
})
|
|
4333
|
+
// Structured sibling of the text-blob /api/repo/diff above (protected
|
|
4334
|
+
// surface, untouched): the same {files, stat} shape the session /changes
|
|
4335
|
+
// route serves, here for the MAIN working tree's uncommitted changes vs
|
|
4336
|
+
// HEAD (redesign R5 Step 1.3 — §"Git/session API additions").
|
|
4337
|
+
.get('/repo/changes', async (c) => {
|
|
4338
|
+
const { root: repoRoot } = c.get('project');
|
|
4339
|
+
const info = await getRepoInfo(repoRoot);
|
|
4340
|
+
if (!info)
|
|
4341
|
+
return c.json({ error: 'not a git repository' }, 409);
|
|
4342
|
+
// The user's REAL working tree — never stage into their index (a GET must not write).
|
|
4343
|
+
const result = await collectChanges(info.root, 'HEAD', {
|
|
4344
|
+
intentToAdd: false,
|
|
4345
|
+
});
|
|
4346
|
+
if (!result.ok)
|
|
4347
|
+
return c.json({ error: result.error }, 409);
|
|
4348
|
+
return c.json(result.changes);
|
|
4349
|
+
})
|
|
4350
|
+
.post('/repo/branch', jsonZodValidator(() => repoBranchSchema), async (c) => {
|
|
4351
|
+
const { root: repoRoot } = c.get('project');
|
|
4352
|
+
const info = await getRepoInfo(repoRoot);
|
|
4353
|
+
if (!info)
|
|
4354
|
+
return c.json({ error: 'not a git repository' }, 409);
|
|
4355
|
+
const parsed = { data: c.req.valid('json') };
|
|
4356
|
+
const result = await createOrSwitchBranch(info.root, parsed.data.name, parsed.data.from);
|
|
4357
|
+
if (!result.ok)
|
|
4358
|
+
return c.json({ error: result.error }, 409);
|
|
4359
|
+
return c.json({ branch: result.branch, created: result.created });
|
|
2765
4360
|
});
|
|
2766
4361
|
// The Settings → Agents knobs in one read (R6 Step 1.5) — an ADDITIVE
|
|
2767
4362
|
// sibling of PUT /api/config below; /api/health keeps its protected shape.
|
|
2768
|
-
const configAnswer = (config) =>
|
|
2769
|
-
|
|
2770
|
-
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
|
|
2777
|
-
|
|
2778
|
-
|
|
2779
|
-
|
|
2780
|
-
|
|
2781
|
-
|
|
2782
|
-
|
|
2783
|
-
|
|
2784
|
-
|
|
2785
|
-
|
|
2786
|
-
|
|
2787
|
-
|
|
2788
|
-
|
|
2789
|
-
|
|
2790
|
-
|
|
2791
|
-
|
|
2792
|
-
|
|
2793
|
-
|
|
2794
|
-
|
|
2795
|
-
|
|
2796
|
-
|
|
2797
|
-
|
|
2798
|
-
|
|
2799
|
-
|
|
2800
|
-
|
|
2801
|
-
})
|
|
2802
|
-
.optional(),
|
|
2803
|
-
// Concurrency + memory guard (Settings → Resources). maxParallel clamps to
|
|
2804
|
-
// the schema's 1–16; memoryLimitMb null/0 clears the ceiling.
|
|
2805
|
-
maxParallel: z.number().int().min(1).max(16).optional(),
|
|
2806
|
-
memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
|
|
2807
|
-
// Worktree retention count (Settings → Resources, #483). 0 = unlimited;
|
|
2808
|
-
// null clears the key back to the schema default (10). Unlike memoryLimitMb,
|
|
2809
|
-
// 0 is a meaningful value (unlimited), so it is stored, not treated as clear.
|
|
2810
|
-
worktreeRetention: z.number().int().min(0).max(1000).nullable().optional(),
|
|
2811
|
-
// Live title updates toggle (Settings → Agents): null clears the key back
|
|
2812
|
-
// to the env-default behavior.
|
|
2813
|
-
liveTitleUpdates: z.boolean().nullable().optional(),
|
|
2814
|
-
// Optional review gate toggle (Settings → Agents, #489): null clears the key
|
|
2815
|
-
// back to the env-default behavior (OFF).
|
|
2816
|
-
reviewGate: z.boolean().nullable().optional(),
|
|
2817
|
-
});
|
|
2818
|
-
api.put('/config', async (c) => {
|
|
4363
|
+
const configAnswer = async (repoRoot, config) => {
|
|
4364
|
+
const nativeModels = await readAgentModelDefaults(repoRoot);
|
|
4365
|
+
const modelsLocked = agentModelsLocked(repoRoot);
|
|
4366
|
+
return {
|
|
4367
|
+
baseBranch: config.baseBranch ?? null,
|
|
4368
|
+
defaultRunner: config.defaultRunner,
|
|
4369
|
+
systemPrompt: config.systemPrompt ?? null,
|
|
4370
|
+
// Native defaults seed each runner independently. A Cezar preset remains
|
|
4371
|
+
// selectable unless the operator opts into the fixed-model policy.
|
|
4372
|
+
defaultModels: modelsLocked
|
|
4373
|
+
? nativeModels
|
|
4374
|
+
: { ...nativeModels, ...(config.defaultModels ?? {}) },
|
|
4375
|
+
modelsLocked,
|
|
4376
|
+
maxParallel: config.maxParallel,
|
|
4377
|
+
memoryLimitMb: config.memoryLimitMb ?? null,
|
|
4378
|
+
// Count-based worktree retention (#483): keep the last N finished worktrees
|
|
4379
|
+
// on disk. 0 = unlimited. Always materialized (schema default 10).
|
|
4380
|
+
worktreeRetention: config.worktreeRetention,
|
|
4381
|
+
// Live title updates (task auto-naming spec): tri-state — null means "no
|
|
4382
|
+
// config key, the CEZ_TITLE_UPDATES env default (ON) decides".
|
|
4383
|
+
liveTitleUpdates: config.liveTitleUpdates ?? null,
|
|
4384
|
+
// Optional review gate (#489): tri-state — null means "no config key, the
|
|
4385
|
+
// CEZ_REVIEW_GATE env default (OFF) decides".
|
|
4386
|
+
reviewGate: config.reviewGate ?? null,
|
|
4387
|
+
};
|
|
4388
|
+
};
|
|
4389
|
+
// ---- chained family: per-repo config (project-scoped) ----
|
|
4390
|
+
const configRoutes = new Hono()
|
|
4391
|
+
.get('/config', async (c) => {
|
|
4392
|
+
const repoRoot = c.get('project').root;
|
|
4393
|
+
return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot)));
|
|
4394
|
+
})
|
|
4395
|
+
.put('/config', jsonZodValidator(() => setConfigSchema), async (c) => {
|
|
2819
4396
|
const { root: repoRoot, dataDir } = c.get('project');
|
|
2820
|
-
const parsed =
|
|
2821
|
-
if (
|
|
2822
|
-
return c.json({ error:
|
|
4397
|
+
const parsed = { data: c.req.valid('json') };
|
|
4398
|
+
if (agentModelsLocked(repoRoot) && parsed.data.defaultModels !== undefined) {
|
|
4399
|
+
return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
|
|
2823
4400
|
}
|
|
2824
4401
|
const configPath = join(dataDir, 'config.json');
|
|
2825
4402
|
let raw = {};
|
|
@@ -2905,16 +4482,55 @@ export function createApp(deps) {
|
|
|
2905
4482
|
return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
2906
4483
|
}
|
|
2907
4484
|
// Pre-R6 answer shape ({baseBranch, defaultRunner}) + additive R6 fields.
|
|
2908
|
-
return c.json(configAnswer(await loadConfig(repoRoot)));
|
|
4485
|
+
return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot)));
|
|
4486
|
+
});
|
|
4487
|
+
// Set/clear the agents' config knobs (Settings → Agents; the Repo tab's
|
|
4488
|
+
// base-branch picker). Merges into the RAW config.json so user keys
|
|
4489
|
+
// (skillsRepos…) survive and schema defaults are never materialized into
|
|
4490
|
+
// the file. All fields optional + additive: `null` (and `''` for the
|
|
4491
|
+
// R6 keys) clears a knob back to its default.
|
|
4492
|
+
const modelPresetSchema = z.string().trim().max(200).nullable().optional();
|
|
4493
|
+
const setConfigSchema = z.object({
|
|
4494
|
+
baseBranch: z.string().trim().min(1).max(200).nullable().optional(),
|
|
4495
|
+
defaultRunner: z.enum(['claude', 'codex', 'opencode']).optional(),
|
|
4496
|
+
systemPrompt: z.string().trim().max(20_000, 'must be at most 20000 characters').nullable().optional(),
|
|
4497
|
+
defaultModels: z
|
|
4498
|
+
.object({
|
|
4499
|
+
claude: modelPresetSchema,
|
|
4500
|
+
codex: modelPresetSchema,
|
|
4501
|
+
opencode: modelPresetSchema,
|
|
4502
|
+
})
|
|
4503
|
+
.optional(),
|
|
4504
|
+
// Concurrency + memory guard (Settings → Resources). maxParallel clamps to
|
|
4505
|
+
// the schema's 1–16; memoryLimitMb null/0 clears the ceiling.
|
|
4506
|
+
maxParallel: z.number().int().min(1).max(16).optional(),
|
|
4507
|
+
memoryLimitMb: z.number().int().min(0).max(1_048_576).nullable().optional(),
|
|
4508
|
+
// Worktree retention count (Settings → Resources, #483). 0 = unlimited;
|
|
4509
|
+
// null clears the key back to the schema default (10). Unlike memoryLimitMb,
|
|
4510
|
+
// 0 is a meaningful value (unlimited), so it is stored, not treated as clear.
|
|
4511
|
+
worktreeRetention: z.number().int().min(0).max(1000).nullable().optional(),
|
|
4512
|
+
// Live title updates toggle (Settings → Agents): null clears the key back
|
|
4513
|
+
// to the env-default behavior.
|
|
4514
|
+
liveTitleUpdates: z.boolean().nullable().optional(),
|
|
4515
|
+
// Optional review gate toggle (Settings → Agents, #489): null clears the key
|
|
4516
|
+
// back to the env-default behavior (OFF).
|
|
4517
|
+
reviewGate: z.boolean().nullable().optional(),
|
|
4518
|
+
});
|
|
4519
|
+
const setAgentConfigSchema = z.object({
|
|
4520
|
+
content: z.string().max(2_000_000),
|
|
4521
|
+
version: z.string().nullable(),
|
|
2909
4522
|
});
|
|
4523
|
+
// ---- chained family: agent-config (project-scoped) -----------------------
|
|
2910
4524
|
// Agent config is project-scoped (spec #404, adapted to the multi-project
|
|
2911
4525
|
// route seam from #521): handlers resolve the selected repo through the
|
|
2912
|
-
// same ProjectContext as every other mirrored route.
|
|
2913
|
-
|
|
4526
|
+
// same ProjectContext as every other mirrored route. Chained (not statements)
|
|
4527
|
+
// so `AppType` carries it — see `healthRoutes`.
|
|
4528
|
+
const agentConfigRoutes = new Hono()
|
|
4529
|
+
.get('/agent-config', async (c) => {
|
|
2914
4530
|
const editable = capabilities().localHandoff;
|
|
2915
4531
|
return c.json(await listAgentConfig(c.get('project').root, process.env, editable));
|
|
2916
|
-
})
|
|
2917
|
-
|
|
4532
|
+
})
|
|
4533
|
+
.get('/agent-config/:id', async (c) => {
|
|
2918
4534
|
const id = c.req.param('id');
|
|
2919
4535
|
const def = findConfigFile(id);
|
|
2920
4536
|
if (!def)
|
|
@@ -2930,12 +4546,8 @@ export function createApp(deps) {
|
|
|
2930
4546
|
if ('error' in read)
|
|
2931
4547
|
return c.json({ error: read.error }, 500);
|
|
2932
4548
|
return c.json(read);
|
|
2933
|
-
})
|
|
2934
|
-
|
|
2935
|
-
content: z.string().max(2_000_000),
|
|
2936
|
-
version: z.string().nullable(),
|
|
2937
|
-
});
|
|
2938
|
-
api.put('/agent-config/:id', async (c) => {
|
|
4549
|
+
})
|
|
4550
|
+
.put('/agent-config/:id', jsonZodValidator(setAgentConfigSchema), async (c) => {
|
|
2939
4551
|
// Config files may define hooks and MCP commands, so writes remain a
|
|
2940
4552
|
// local-machine capability and are re-gated on every request.
|
|
2941
4553
|
if (!capabilities().localHandoff) {
|
|
@@ -2943,10 +4555,7 @@ export function createApp(deps) {
|
|
|
2943
4555
|
error: 'editing agent config is disabled in hosted mode (CEZ_REMOTE) — edit it from the machine that owns the checkout',
|
|
2944
4556
|
}, 409);
|
|
2945
4557
|
}
|
|
2946
|
-
const parsed =
|
|
2947
|
-
if (!parsed.success) {
|
|
2948
|
-
return c.json({ error: parsed.error.issues.map((issue) => issue.message).join('; ') }, 400);
|
|
2949
|
-
}
|
|
4558
|
+
const parsed = { data: c.req.valid('json') };
|
|
2950
4559
|
const out = await writeConfigFile(c.req.param('id'), parsed.data.content, parsed.data.version, c.get('project').root);
|
|
2951
4560
|
if (out === null)
|
|
2952
4561
|
return c.json({ error: 'unknown config file' }, 404);
|
|
@@ -2954,55 +4563,6 @@ export function createApp(deps) {
|
|
|
2954
4563
|
return c.json({ error: out.error }, out.status);
|
|
2955
4564
|
return c.json(out.read);
|
|
2956
4565
|
});
|
|
2957
|
-
api.get('/repo/diff', async (c) => {
|
|
2958
|
-
const { root: repoRoot } = c.get('project');
|
|
2959
|
-
const info = await getRepoInfo(repoRoot);
|
|
2960
|
-
if (!info)
|
|
2961
|
-
return c.text('not a git repository');
|
|
2962
|
-
return c.text(await getDiff(info.root));
|
|
2963
|
-
});
|
|
2964
|
-
// One commit's message + stat + patch — the Repo view expands it inline.
|
|
2965
|
-
// `?structured=1` is the ADDITIVE sibling (R5 Step 1.7): the new repo view's commit-diff
|
|
2966
|
-
// shape `{sha, subject, author, when, files, stat}` with 409 + reason on failure. The
|
|
2967
|
-
// legacy text answer below is a protected surface (BACKWARD_COMPATIBILITY.md §2) — its
|
|
2968
|
-
// shape, including the in-band failure sentences, stays exactly as it was.
|
|
2969
|
-
api.get('/repo/commit/:sha', async (c) => {
|
|
2970
|
-
const { root: repoRoot } = c.get('project');
|
|
2971
|
-
const info = await getRepoInfo(repoRoot);
|
|
2972
|
-
if (c.req.query('structured') === '1') {
|
|
2973
|
-
if (!info)
|
|
2974
|
-
return c.json({ error: 'not a git repository' }, 409);
|
|
2975
|
-
const result = await collectCommitChanges(info.root, c.req.param('sha'));
|
|
2976
|
-
if (!result.ok)
|
|
2977
|
-
return c.json({ error: result.error }, 409);
|
|
2978
|
-
return c.json(result.commit);
|
|
2979
|
-
}
|
|
2980
|
-
if (!info)
|
|
2981
|
-
return c.text('not a git repository');
|
|
2982
|
-
try {
|
|
2983
|
-
return c.text(await getCommit(info.root, c.req.param('sha')));
|
|
2984
|
-
}
|
|
2985
|
-
catch (err) {
|
|
2986
|
-
return c.text(`(git show failed: ${err instanceof Error ? err.message : String(err)})`);
|
|
2987
|
-
}
|
|
2988
|
-
});
|
|
2989
|
-
// Structured sibling of the text-blob /api/repo/diff above (protected
|
|
2990
|
-
// surface, untouched): the same {files, stat} shape the session /changes
|
|
2991
|
-
// route serves, here for the MAIN working tree's uncommitted changes vs
|
|
2992
|
-
// HEAD (redesign R5 Step 1.3 — §"Git/session API additions").
|
|
2993
|
-
api.get('/repo/changes', async (c) => {
|
|
2994
|
-
const { root: repoRoot } = c.get('project');
|
|
2995
|
-
const info = await getRepoInfo(repoRoot);
|
|
2996
|
-
if (!info)
|
|
2997
|
-
return c.json({ error: 'not a git repository' }, 409);
|
|
2998
|
-
// The user's REAL working tree — never stage into their index (a GET must not write).
|
|
2999
|
-
const result = await collectChanges(info.root, 'HEAD', {
|
|
3000
|
-
intentToAdd: false,
|
|
3001
|
-
});
|
|
3002
|
-
if (!result.ok)
|
|
3003
|
-
return c.json({ error: result.error }, 409);
|
|
3004
|
-
return c.json(result.changes);
|
|
3005
|
-
});
|
|
3006
4566
|
// Repo view branch actions: switch to an existing branch, or create one
|
|
3007
4567
|
// (from `from` or HEAD) and switch. Predictable git failures — invalid
|
|
3008
4568
|
// name, unknown `from`, dirty-tree checkout conflict — are 409 + reason.
|
|
@@ -3010,28 +4570,62 @@ export function createApp(deps) {
|
|
|
3010
4570
|
name: z.string().trim().min(1).max(200),
|
|
3011
4571
|
from: z.string().trim().min(1).max(200).optional(),
|
|
3012
4572
|
});
|
|
3013
|
-
|
|
3014
|
-
|
|
3015
|
-
|
|
3016
|
-
|
|
3017
|
-
|
|
3018
|
-
|
|
3019
|
-
|
|
3020
|
-
|
|
3021
|
-
|
|
3022
|
-
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
|
|
3026
|
-
|
|
3027
|
-
|
|
3028
|
-
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
3032
|
-
|
|
3033
|
-
|
|
3034
|
-
|
|
4573
|
+
// ---- assemble the chained families --------------------------------------
|
|
4574
|
+
// Every chained family is registered ONCE and mounted into the versioned table. There is no
|
|
4575
|
+
// second, unversioned spelling: `/api/*` was removed once the whole API was reachable under
|
|
4576
|
+
// `/api/v1` (BACKWARD_COMPATIBILITY.md §2). One surface means one thing to keep working, and
|
|
4577
|
+
// it is the one the typed client describes.
|
|
4578
|
+
//
|
|
4579
|
+
// MOUNT ORDER IS REGISTRATION ORDER. Hono matches in the order routes were added, so each
|
|
4580
|
+
// family keeps its internal order and the families keep theirs relative to each other.
|
|
4581
|
+
//
|
|
4582
|
+
// Written as ONE chained expression because that is the only shape Hono can infer route types
|
|
4583
|
+
// from — it is what puts these routes in `AppType`, and so in the typed client.
|
|
4584
|
+
const v1 = new Hono()
|
|
4585
|
+
.use('*', resolveProjectScope)
|
|
4586
|
+
.route('/', launchKeyRoutes)
|
|
4587
|
+
.route('/', skillsRoutes)
|
|
4588
|
+
.route('/', uiStateRoutes)
|
|
4589
|
+
.route('/', workflowsRoutes)
|
|
4590
|
+
.route('/', planRoutes)
|
|
4591
|
+
.route('/', automationsRoutes)
|
|
4592
|
+
.route('/', runsRoutes)
|
|
4593
|
+
.route('/', groupsRoutes)
|
|
4594
|
+
.route('/', openTargetsRoutes)
|
|
4595
|
+
.route('/', worktreesRoutes)
|
|
4596
|
+
.route('/', todosRoutes)
|
|
4597
|
+
.route('/', sseRoutes)
|
|
4598
|
+
.route('/', githubRoutes)
|
|
4599
|
+
.route('/', repoRoutes)
|
|
4600
|
+
.route('/', configRoutes)
|
|
4601
|
+
.route('/', agentConfigRoutes);
|
|
4602
|
+
// Workspace-level families answer for the whole workspace, so they are single-mount: never a
|
|
4603
|
+
// project-scoped spelling, which would be a second surface to protect with no consumer.
|
|
4604
|
+
const workspaceV1 = new Hono()
|
|
4605
|
+
.route('/', healthRoutes)
|
|
4606
|
+
.route('/', modelsRoutes)
|
|
4607
|
+
.route('/', providersRoutes)
|
|
4608
|
+
.route('/', projectsRoutes)
|
|
4609
|
+
.route('/', agentProfilesRoutes)
|
|
4610
|
+
.route('/', skillsUpdateRoutes)
|
|
4611
|
+
.route('/', workspaceConfigRoutes)
|
|
4612
|
+
.route('/', fsBrowseRoutes)
|
|
4613
|
+
.route('/', automationChecksRoutes)
|
|
4614
|
+
.route('/', workspaceEventsRoutes);
|
|
4615
|
+
// ---- mount ---------------------------------------------------------------
|
|
4616
|
+
// Scoped first, then the unscoped alias bound to the boot project. The paths are disjoint (no
|
|
4617
|
+
// route starts with `/p/`), so order between the two never decides a match — but the SPA
|
|
4618
|
+
// catch-all below must still come last. `route()` re-registers the sub-app's routes under
|
|
4619
|
+
// each prefix, handlers shared, internal order preserved.
|
|
4620
|
+
//
|
|
4621
|
+
// Workspace families mount LAST and that is load-bearing: mounting the project table also
|
|
4622
|
+
// mounts its `use('*')` scope resolver over the whole prefix, and Hono runs matched middleware
|
|
4623
|
+
// in registration order. `/health` in particular answers for the workspace, has no project to
|
|
4624
|
+
// resolve, and is the CORS-open discovery route — it must not sit behind the resolver.
|
|
4625
|
+
const routed = app
|
|
4626
|
+
.route(V1_SCOPED_PREFIX, v1)
|
|
4627
|
+
.route(V1_PREFIX, v1)
|
|
4628
|
+
.route(V1_PREFIX, workspaceV1);
|
|
3035
4629
|
// ---- SPA catch-all -------------------------------------------------------
|
|
3036
4630
|
// Last, so every route above still wins. Any other GET gets the cockpit shell:
|
|
3037
4631
|
// react-router owns the route map, including the 404, so `/tasks/:id/changes`
|
|
@@ -3040,14 +4634,33 @@ export function createApp(deps) {
|
|
|
3040
4634
|
// an unknown API path must never answer with HTML.
|
|
3041
4635
|
// Without a web/dist build this serves the built-in build-hint page (dev-only
|
|
3042
4636
|
// state — the published tarball ships web/dist), never a 404.
|
|
3043
|
-
|
|
3044
|
-
return
|
|
4637
|
+
routed.get('*', (c) => serveShell(c) ?? c.notFound());
|
|
4638
|
+
return routed;
|
|
3045
4639
|
}
|
|
3046
4640
|
export function startServer(deps, port) {
|
|
4641
|
+
const workspaceEvents = deps.workspaceEvents ?? new WorkspaceEventBus();
|
|
4642
|
+
const skillsUpdate = deps.skillsUpdate ?? new SkillsUpdateService({ invalidateCatalog: refreshTeamSkills });
|
|
3047
4643
|
// The subscription hub rides the same HTTP server (one port, zero config):
|
|
3048
4644
|
// createApp registers the topics, the `upgrade` hook below owns the socket.
|
|
3049
4645
|
const socketHub = deps.socketHub ?? createSocketHub();
|
|
3050
|
-
const
|
|
4646
|
+
const automationCoordinator = new AutomationCoordinator({ listProjects });
|
|
4647
|
+
const bootProjectId = deps.bootProjectId ?? 'default';
|
|
4648
|
+
const bootAutomationStore = automationCoordinator.store(bootProjectId, deps.repoRoot);
|
|
4649
|
+
const sharedContexts = deps.contexts ?? new ProjectContexts({
|
|
4650
|
+
listProjects,
|
|
4651
|
+
semaphore: deps.semaphore,
|
|
4652
|
+
automationStore: (projectId, root) => automationCoordinator.store(projectId, root),
|
|
4653
|
+
});
|
|
4654
|
+
let rescheduleAutomations = () => { };
|
|
4655
|
+
const app = createApp({
|
|
4656
|
+
...deps,
|
|
4657
|
+
contexts: sharedContexts,
|
|
4658
|
+
automationStore: bootAutomationStore,
|
|
4659
|
+
workspaceEvents,
|
|
4660
|
+
skillsUpdate,
|
|
4661
|
+
socketHub,
|
|
4662
|
+
automationsChanged: () => rescheduleAutomations(),
|
|
4663
|
+
});
|
|
3051
4664
|
// SECURITY: default to loopback. This server executes agents locally and its endpoints are
|
|
3052
4665
|
// same-origin-trusted (only /api/health is CORS-open); binding to a non-loopback host would
|
|
3053
4666
|
// expose an agent-executing box to the network. `bindHost` exists only for a deliberate
|
|
@@ -3058,13 +4671,89 @@ export function startServer(deps, port) {
|
|
|
3058
4671
|
port,
|
|
3059
4672
|
hostname: deps.bindHost ?? '127.0.0.1',
|
|
3060
4673
|
});
|
|
4674
|
+
const coordinator = new SkillsUpdateCoordinator(skillsUpdate, async () => effectiveSkillsAutoUpdate(await loadWorkspaceConfig()));
|
|
4675
|
+
const automationProjects = new Map();
|
|
4676
|
+
const automationScheduler = new WorkspaceAutomationScheduler({
|
|
4677
|
+
coordinator: automationCoordinator,
|
|
4678
|
+
handle: (projectId, store) => {
|
|
4679
|
+
const project = automationProjects.get(projectId);
|
|
4680
|
+
if (!project)
|
|
4681
|
+
return undefined;
|
|
4682
|
+
return {
|
|
4683
|
+
projectId,
|
|
4684
|
+
owner: project.owner,
|
|
4685
|
+
repo: project.repo,
|
|
4686
|
+
store,
|
|
4687
|
+
poller: new GithubPoller(),
|
|
4688
|
+
onChange: (automationId, revision) => workspaceEvents.emit('automation-change', { project: projectId, automationId, revision }),
|
|
4689
|
+
launch: async (definition, candidate, receiptId) => {
|
|
4690
|
+
const bootId = deps.bootProjectId ?? 'default';
|
|
4691
|
+
const context = projectId === bootId
|
|
4692
|
+
? { root: deps.repoRoot, manager: deps.manager, store: deps.store }
|
|
4693
|
+
: await sharedContexts.context(projectId);
|
|
4694
|
+
return launchAutomationRun({
|
|
4695
|
+
root: context.root,
|
|
4696
|
+
manager: context.manager,
|
|
4697
|
+
store: context.store,
|
|
4698
|
+
definition,
|
|
4699
|
+
candidate,
|
|
4700
|
+
receiptId,
|
|
4701
|
+
});
|
|
4702
|
+
},
|
|
4703
|
+
};
|
|
4704
|
+
},
|
|
4705
|
+
});
|
|
4706
|
+
rescheduleAutomations = () => { void automationScheduler.reschedule(); };
|
|
4707
|
+
const unsubscribe = workspaceEvents.on((event, data) => {
|
|
4708
|
+
if (event === 'project-added') {
|
|
4709
|
+
const project = data.project;
|
|
4710
|
+
if (project && typeof project.id === 'string' && typeof project.root === 'string' && project.status !== 'missing') {
|
|
4711
|
+
coordinator.add(project.id, project.root);
|
|
4712
|
+
void getRepoInfo(project.root).then((info) => {
|
|
4713
|
+
const parsed = parseRemote(info?.remote ?? '');
|
|
4714
|
+
if (parsed?.host === 'github.com')
|
|
4715
|
+
automationProjects.set(project.id, { root: project.root, owner: parsed.owner, repo: parsed.repo });
|
|
4716
|
+
return automationScheduler.reschedule();
|
|
4717
|
+
});
|
|
4718
|
+
}
|
|
4719
|
+
}
|
|
4720
|
+
else if (event === 'project-removed') {
|
|
4721
|
+
const id = data.id;
|
|
4722
|
+
if (typeof id === 'string')
|
|
4723
|
+
coordinator.remove(id);
|
|
4724
|
+
if (typeof id === 'string') {
|
|
4725
|
+
automationCoordinator.remove(id);
|
|
4726
|
+
automationProjects.delete(id);
|
|
4727
|
+
void automationScheduler.reschedule();
|
|
4728
|
+
}
|
|
4729
|
+
}
|
|
4730
|
+
});
|
|
4731
|
+
server.once('listening', () => {
|
|
4732
|
+
void listProjects().then((projects) => {
|
|
4733
|
+
const all = projects.some((project) => project.root === deps.repoRoot)
|
|
4734
|
+
? projects : [{ id: deps.bootProjectId ?? 'default', root: deps.repoRoot, status: 'ok' }, ...projects];
|
|
4735
|
+
coordinator.start(all);
|
|
4736
|
+
void Promise.all(all.map(async (project) => {
|
|
4737
|
+
const parsed = parseRemote((await getRepoInfo(project.root))?.remote ?? '');
|
|
4738
|
+
if (parsed?.host === 'github.com')
|
|
4739
|
+
automationProjects.set(project.id, { root: project.root, owner: parsed.owner, repo: parsed.repo });
|
|
4740
|
+
const automationStore = automationCoordinator.store(project.id, project.root);
|
|
4741
|
+
const runStore = project.id === (deps.bootProjectId ?? 'default')
|
|
4742
|
+
? deps.store
|
|
4743
|
+
: sharedContexts.peek(project.id)?.store;
|
|
4744
|
+
if (automationStore && runStore)
|
|
4745
|
+
reconcileAutomationReceipts(automationStore, runStore);
|
|
4746
|
+
})).then(() => automationScheduler.start()).catch(() => undefined);
|
|
4747
|
+
}).catch(() => undefined);
|
|
4748
|
+
});
|
|
4749
|
+
server.once('close', () => { unsubscribe(); coordinator.stop(); automationScheduler.stop(); });
|
|
3061
4750
|
socketHub.attach(server, (req) => verifyWsUpgrade(req, deps.bindHost));
|
|
3062
4751
|
return server;
|
|
3063
4752
|
}
|
|
3064
4753
|
/**
|
|
3065
4754
|
* The WebSocket twin of the `/api/*` request-origin guard (#426), applied
|
|
3066
|
-
* before the `/api/ws` handshake. WebSocket is NOT subject to CORS — any web
|
|
3067
|
-
* page may open `ws://127.0.0.1:<port>/api/ws` and, unlike a forced HTTP GET,
|
|
4755
|
+
* before the `/api/v1/ws` handshake. WebSocket is NOT subject to CORS — any web
|
|
4756
|
+
* page may open `ws://127.0.0.1:<port>/api/v1/ws` and, unlike a forced HTTP GET,
|
|
3068
4757
|
* would get to READ what comes back — so this guard is load-bearing:
|
|
3069
4758
|
*
|
|
3070
4759
|
* 1. Host allowlist (local mode): a non-loopback Host is a DNS-rebound
|