@hearsay-tools/squawk 0.18.0-pr4287.8317 → 0.18.0-pr4289.8319

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/automations/tools.d.ts +8 -8
  2. package/dist/core/session-process.d.ts +0 -10
  3. package/dist/core/session-process.js +22 -109
  4. package/dist/core/session-process.js.map +1 -1
  5. package/dist/delegation/routes.d.ts +10 -10
  6. package/dist/delegation/transport.d.ts +79 -79
  7. package/dist/jobs/cli.js +2 -6
  8. package/dist/jobs/cli.js.map +1 -1
  9. package/dist/jobs/job.d.ts +0 -6
  10. package/dist/jobs/job.js +2 -80
  11. package/dist/jobs/job.js.map +1 -1
  12. package/dist/plugin/runtime.d.ts +1 -1
  13. package/dist/plugin/runtime.js +1 -1
  14. package/dist/plugin/runtime.js.map +1 -1
  15. package/dist/runners/opencode/opencode-http.d.ts +0 -1
  16. package/dist/runners/opencode/opencode-http.js +0 -7
  17. package/dist/runners/opencode/opencode-http.js.map +1 -1
  18. package/dist/runners/opencode/opencode-server-runner.js +9 -3
  19. package/dist/runners/opencode/opencode-server-runner.js.map +1 -1
  20. package/dist/runs/run-decode.d.ts +72 -72
  21. package/dist/server/automations-routes.d.ts +1435 -0
  22. package/dist/server/automations-routes.js +192 -0
  23. package/dist/server/automations-routes.js.map +1 -0
  24. package/dist/server/github-routes.d.ts +733 -0
  25. package/dist/server/github-routes.js +140 -0
  26. package/dist/server/github-routes.js.map +1 -0
  27. package/dist/server/project-settings-routes.d.ts +999 -0
  28. package/dist/server/project-settings-routes.js +347 -0
  29. package/dist/server/project-settings-routes.js.map +1 -0
  30. package/dist/server/projects-routes.d.ts +833 -0
  31. package/dist/server/projects-routes.js +423 -0
  32. package/dist/server/projects-routes.js.map +1 -0
  33. package/dist/server/providers-routes.d.ts +683 -0
  34. package/dist/server/providers-routes.js +359 -0
  35. package/dist/server/providers-routes.js.map +1 -0
  36. package/dist/server/repo-routes.d.ts +509 -0
  37. package/dist/server/repo-routes.js +243 -0
  38. package/dist/server/repo-routes.js.map +1 -0
  39. package/dist/server/reports-api.d.ts +2 -2
  40. package/dist/server/runner-install-routes.d.ts +10 -10
  41. package/dist/server/runners-routes.d.ts +10 -10
  42. package/dist/server/server-types.d.ts +40 -0
  43. package/dist/server/server-types.js +31 -0
  44. package/dist/server/server-types.js.map +1 -0
  45. package/dist/server/server.d.ts +1706 -1732
  46. package/dist/server/server.js +108 -2500
  47. package/dist/server/server.js.map +1 -1
  48. package/dist/server/workspace-live-routes.d.ts +6 -6
  49. package/dist/server/workspace-routes.d.ts +713 -0
  50. package/dist/server/workspace-routes.js +262 -0
  51. package/dist/server/workspace-routes.js.map +1 -0
  52. package/dist/worker-scope/cgroup.d.ts +36 -2
  53. package/dist/worker-scope/cgroup.js +161 -5
  54. package/dist/worker-scope/cgroup.js.map +1 -1
  55. package/dist/worker-scope/job.d.ts +22 -1
  56. package/dist/worker-scope/job.js +56 -1
  57. package/dist/worker-scope/job.js.map +1 -1
  58. package/dist/worker-scope/scope.d.ts +1 -5
  59. package/dist/worker-scope/worker-scopes.js +18 -36
  60. package/dist/worker-scope/worker-scopes.js.map +1 -1
  61. package/dist/workflows/input-acknowledgement.d.ts +24 -24
  62. package/dist/workflows/run/wait-engine.d.ts +72 -72
  63. package/package.json +4 -4
  64. package/scripts/windows-worker-job.cs +32 -67
  65. package/scripts/windows-worker-job.ps1 +4 -11
  66. package/dist/core/os-cgroup.d.ts +0 -43
  67. package/dist/core/os-cgroup.js +0 -220
  68. package/dist/core/os-cgroup.js.map +0 -1
  69. package/dist/core/os-win-job.d.ts +0 -30
  70. package/dist/core/os-win-job.js +0 -80
  71. package/dist/core/os-win-job.js.map +0 -1
  72. package/dist/core/session-containment.d.ts +0 -78
  73. package/dist/core/session-containment.js +0 -247
  74. package/dist/core/session-containment.js.map +0 -1
@@ -1,113 +1,52 @@
1
- import { memoizeRead } from './bounded-read-cache.js';
2
- import { cachedWorktreeSizeBytes } from './worktree-size-cache.js';
3
- import { readRepoRefs, forgetRepoRead } from './repo-read-cache.js';
4
- import { allocateAgentProfileId } from './agent-profile-id.js';
5
- import { runnerSkillsQuerySchema } from '../contract/index.js';
6
- import { readRunnerSkills } from './runner-skills.js';
7
- import { runCheckout, preparePublishCheckout, reclaimCheckoutError } from './run-checkout.js';
1
+ import { runCheckout, preparePublishCheckout } from './run-checkout.js';
8
2
  import { adoptFallbackControl, protectFallbackRun, runArtifactDirectory } from './project-run-files.js';
9
- import { deleteSavedWorkflow } from './workflow-files.js';
10
3
  import { projectPaths, fallbackProjectWriteError } from '../project-paths.js';
11
- import { productIdentity } from '../home/identity.js';
12
- import { productEnv } from '../core/product-env.js';
13
4
  import { reportsRoutes } from './reports-api.js';
14
- import { writeMergedConfig } from './config-merge.js';
15
- import { applyWorkspaceConfigPatch } from './workspace-config-patch.js';
16
- import { retryAutomationLogReceipt } from './automation-log-retry.js';
17
- import { automationCreateSchema, automationUpdateSchema, automationCheckRequestSchema, automationLogQuerySchema } from '../contract/index.js';
18
- import { providerConnectSchema, createAgentProfileSchema, updateAgentProfileSchema, selectAgentProfileSchema, providerEnabledSchema, providerRetrySchema, providerRouteParamsSchema, agentProfileRouteParamsSchema } from '../contract/index.js';
19
- import { planSchema, parseWorkflowSchema } from '../contract/index.js';
20
- import { uiStateBody } from '../contract/index.js';
21
5
  import { queuedMessagePatchSchema, continueSchema, archiveSchema, openInSchema } from '../contract/index.js';
22
- import { refreshQuery, strictRefreshQuerySchema, browseQuerySchema, worktreeFilesQuerySchema } from '../contract/index.js';
23
- import { mergeNumberParams, prChangesParams, prChangesQuery, mergeBodySchema } from '../contract/index.js';
24
- import { gitCommitSchema, reclaimBodySchema, repoBranchSchema } from '../contract/index.js';
25
- import { setConfigSchema, setAgentConfigSchema } from '../contract/index.js';
26
- import { saveWorkflowInputSchema as saveWorkflowSchema } from '../contract/index.js';
6
+ import { worktreeFilesQuerySchema } from '../contract/index.js';
7
+ import { gitCommitSchema } from '../contract/index.js';
27
8
  import { patchRunInputSchema as patchRunSchema, messageInputSchema as messageSchema } from '../contract/index.js';
28
- import { checkoutProjectInputSchema as checkoutSchema, registerProjectInputSchema as registerProjectSchema } from '../contract/index.js';
29
- import { setWorkspaceConfigInputSchema as workspaceConfigUpdateSchema } from '../contract/index.js';
30
- import { reclaimRunParamsSchema } from '../contract/index.js';
31
- import { githubChecksQuerySchema } from '../contract/index.js';
32
- import { githubRefsQuerySchema } from '../contract/index.js';
33
- import { commitQuerySchema } from '../contract/index.js';
34
9
  import { imageMimeType } from '../contract/index.js';
35
10
  import { providerForActiveRun } from '../contract/index.js';
36
11
  import { removedRunnerMessage } from '../contract/index.js';
37
- import { defined } from '../core/defined.js';
38
- import { isAbsoluteHostPath } from '../core/host-path.js';
39
- import { resolveArchiveOnMerge, resolveGlobalArchiveOnMerge } from '../archive-on-merge-setting.js';
40
12
  import { permissionDecisionSchema } from '../contract/index.js';
41
13
  import { runIdParamSchema as permissionRunIdParamSchema } from '../contract/index.js';
42
14
  import { CheckoutProgressCache } from './checkout-progress.js';
43
- import { checkoutProgressParamsSchema, createProjectInputSchema } from '../contract/index.js';
44
15
  import { createWorkspaceLiveRoutes } from './workspace-live-routes.js';
45
16
  import { createActivityRoutes } from './activity-routes.js';
46
17
  import { createRunnersRoutes } from './runners-routes.js';
47
18
  import { createWorkspaceProjects, createWorkspaceProjectContexts, createTaskWebhooks } from './workspace-projects.js';
48
- import { subscribeRunFeed } from './run-event-feed.js';
49
19
  import { latestSession } from '../contract/index.js';
50
- import { probeWritableDir } from './probe-writable-dir.js';
51
20
  import { ARCHIVED_RUNS_PAGE_DEFAULT } from '../contract/index.js';
52
- import { RUNS_SEARCH_PER_PROJECT_MAX, archivedRunsQuerySchema, createRunInputSchema, runSummariesQuerySchema, runsSearchQuerySchema } from '../contract/index.js';
53
- import { workspaceEventsQuerySchema } from '../contract/index.js';
54
- import { automationListQuerySchema } from '../contract/index.js';
55
- import { localTimeZone } from '../contract/index.js';
21
+ import { archivedRunsQuerySchema, createRunInputSchema, runSummariesQuerySchema } from '../contract/index.js';
56
22
  import { DelegationService } from '../delegation/service.js';
57
23
  import { runRelationships } from './run-relationships.js';
58
24
  import { delegationFailure } from '../delegation/routes.js';
59
- import { githubItemParamsSchema } from '../contract/index.js';
60
25
  import { workerDestroyRequestSchema, workerEmptyRequestSchema, runRelationshipsSchema } from '../contract/index.js';
61
- import { existsSync } from 'node:fs';
62
26
  import { randomUUID } from 'node:crypto';
63
- import { createAutomationService, onceCreateAnswer } from '../automations/service.js';
64
- import { createAutomationToolService } from '../automations/tool-adapter.js';
65
- import { GithubPoller } from '../automations/github-poller.js';
66
- import { githubRepository } from '../automations/github-repository.js';
67
- import { ProjectAutomationScheduler } from '../automations/scheduler.js';
68
- import { launchAutomationRun, launchScheduledRun, reconcileAutomationReceipts } from '../automations/task-template.js';
69
- import { isGithubAutomation, } from '../automations/types.js';
70
- import { mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
27
+ import { readFile } from 'node:fs/promises';
71
28
  import { basename, dirname, join } from 'node:path';
72
29
  import { fileURLToPath } from 'node:url';
73
30
  import { Hono } from 'hono';
74
31
  import { bodyLimit } from 'hono/body-limit';
75
- import { streamSSE } from 'hono/streaming';
76
32
  import { matchedRoutes } from 'hono/route';
77
33
  import { jsonZodValidator, paramZodValidator, queryZodValidator } from './validators.js';
78
- import { deliverOnce, registryEntry, sendAgentReport } from '../runs/webhook.js';
79
- import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
80
- import { z } from 'zod';
81
- import { repoPullInputSchema, deleteBranchesInputSchema } from '../contract/index.js';
82
- import { pinRunInputSchema, archiveFinishedRequestSchema, markAllReadRequestSchema, notifyRunInputSchema, } from '../contract/index.js';
83
- import { githubSearchQuerySchema, githubProjectsQuerySchema, githubListQuerySchema, githubCommentCountsQuerySchema, } from '../contract/index.js';
84
- import { setWorkspaceUiStateInputSchema } from '../contract/index.js';
34
+ import { pinRunInputSchema, archiveFinishedRequestSchema, markAllReadRequestSchema, notifyRunInputSchema } from '../contract/index.js';
85
35
  // A contract VALUE, like `workspaceUiStateSchema` in workspace/migrations.ts — the request
86
36
  // schema this route validates with is the same one the client compiles against.
87
- import { openProjectInSchema } from '../contract/index.js';
88
- import { isRegisteredRunner, knownRunnerIds, registeredRunnerId, registeredRunners, resolveRunnerId, runnerDefinition } from '../core/runner-registry.js';
89
- import { REMOVED_RUNNER_IDS } from '../runs/legacy-run-rows.js';
37
+ import { registeredRunnerId, registeredRunners, resolveRunnerId, runnerDefinition } from '../core/runner-registry.js';
90
38
  import { attachmentFileParamSchema, } from '../contract/index.js';
91
- import { agentWebhookParamsSchema, createProjectWebhookInputSchema, projectWebhookParamsSchema, sendAgentReportInputSchema, updateProjectInputSchema, updateProjectWebhookInputSchema, } from '../contract/index.js';
92
- import { PROJECT_WEBHOOKS_MAX } from '../contract/index.js';
93
- import { agentWebhook, agentWebhooks, applyTaskWebhookInput, createdWebhook, editedWebhook, nameTaken, projectWebhooks, redactWebhook, setProjectWebhooks, taskWebhooks as taskWebhookList, } from '../workspace/webhooks.js';
39
+ import { taskWebhooks as taskWebhookList } from '../workspace/webhooks.js';
94
40
  import { environmentStamp } from '../core/backend-detect.js';
95
41
  import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
96
- import { applyProviderEnablement } from '../core/provider-availability.js';
97
42
  import { createModelsRoutes } from './models-routes.js';
98
43
  import { createProviderSignInRoutes } from './provider-sign-in-routes.js';
99
44
  import { allUsage, currentUsage, onUsage } from '../core/process-usage.js';
100
- import { loadWorkflows } from '../workflows/load.js';
101
- import { normalizeWorkflowDoc, skillStackOf, skillsToSteps, stepsIssue, workflowFileSchema, } from '../workflows/types.js';
102
- import { planChain, slugify } from '../planner.js';
103
45
  import { readHandoff, renderHandoffRecords } from '../handoff.js';
104
- import { HistoryCursorError, deriveRunContextEvents, readRunHistoryPage, validateLiveCursor, } from '../runs/event-history.js';
105
- import { ARCHIVED_WINDOW, readRunIndexFromDisk, searchRunIndexFromDisk } from '../runs/run-index.js';
106
- import { searchTokens } from '../contract/index.js';
46
+ import { HistoryCursorError, deriveRunContextEvents, readRunHistoryPage } from '../runs/event-history.js';
47
+ import { ARCHIVED_WINDOW } from '../runs/run-index.js';
107
48
  import { ownPullRequestNumbers } from '../runs/pull-requests.js';
108
- import { ColdRepoHandles } from './cold-repo-handles.js';
109
- import { isV2WireEventType } from '../runs/ui-event-sink.js';
110
- import { runEventsQuerySchema, runHistoryQuerySchema, runIdParamSchema, } from '../contract/index.js';
49
+ import { runHistoryQuerySchema, runIdParamSchema } from '../contract/index.js';
111
50
  import { resolveAttachmentPathAsync } from '../workflows/attachment-path.js';
112
51
  import { artifactParamsSchema, fileLinkQuerySchema } from '../contract/index.js';
113
52
  import { listArtifacts, readArtifact, readArtifactMetadata } from '../artifacts/store.js';
@@ -116,57 +55,44 @@ import { toPastedContent } from '../workflows/pasted-content.js';
116
55
  import { isUntouchedCancelledRun } from '../workflows/run/run-guards.js';
117
56
  import { worktreeDiff } from '../git-worktree.js';
118
57
  import { releaseThenRemoveWorktree } from '../git-worktree-release.js';
119
- import { isReclaimable, reclaimWorktree, reclaimWorktrees, selectReclaimableWorktrees } from '../runs/retention.js';
120
- import { getCommit, getDiff, getRepoInfo, getStatus } from './git.js';
58
+ import { getRepoInfo } from './git.js';
121
59
  import { createHealthCache, HEALTH_TTL_MS } from './health-cache.js';
122
- import { COMMIT_FORMATS, FILE_FORMATS, negotiate } from './accept-negotiation.js';
60
+ import { FILE_FORMATS, negotiate } from './accept-negotiation.js';
123
61
  import { authorityOfHost, authorityOfOrigin, hostnameOfHost, hostnameOfOrigin } from './host-authority.js';
124
62
  import { pluginHealth, pluginLoadReport } from '../plugin/loader.js';
125
63
  import { createBackendChecks } from './backend-checks.js';
126
- import { createGithubBranchForge } from './repo-branch-forge.js';
127
- import { classifyInputFor, deleteBranches, forgetRepoBranches, readRepoBranchCounts, readRepoBranches } from './repo-branches.js';
128
- import { claimRepoGitMutation, localPullBranches, pullRepoCheckout } from './repo-pull.js';
129
- import { collectChanges, collectCommitChanges, collectRunCommits, commitAll, createOrSwitchBranch, pushCurrentBranch, readWorktreePath, } from './git-changes.js';
130
- import { healthConfig, loadConfig, resolveWorktreeRetention } from '../config.js';
131
- import { reportWorktreeCommands } from '../worktree-setup.js';
132
- import { readConfigFile, writeConfigFile } from '../agent-config/files.js';
133
- import { readAgentModelDefaults } from '../agent-config/models.js';
134
- import { listAgentConfig } from '../agent-config/service.js';
135
- import { findConfigFile } from '../agent-config/catalog.js';
136
- import { defaultWorkspaceConfig, loadWorkspaceConfig, mergeWriteWorkspaceConfig, preservedDisabledProviders, effectiveComposerDefault, } from '../workspace/config.js';
137
- import { CONTROL_CHARS_RE, DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, isAbsoluteConfigDir, loadAgentAccounts, mergeWriteAgentAccounts, removeAgentAccount, } from '../workspace/agent-accounts.js';
138
- import { defaultAgentProfile, listAgentProfiles, profileDirState, resolveStoredProfile, sameProfileDir, } from '../workspace/agent-profiles.js';
139
- import { profileCapableProviders, profileEnv, supportsProfiles } from '../core/agent-profiles.js';
64
+ import { collectChanges, collectCommitChanges, collectRunCommits, commitAll, pushCurrentBranch, readWorktreePath } from './git-changes.js';
65
+ import { healthConfig, loadConfig } from '../config.js';
66
+ import { defaultWorkspaceConfig, loadWorkspaceConfig } from '../workspace/config.js';
67
+ import { DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, loadAgentAccounts } from '../workspace/agent-accounts.js';
68
+ import { defaultAgentProfile, listAgentProfiles, resolveStoredProfile } from '../workspace/agent-profiles.js';
69
+ import { profileEnv } from '../core/agent-profiles.js';
140
70
  import { shellQuote, withEnvPrefix } from '../core/shell-env.js';
141
71
  import { resumeCommand } from '../core/runner-cli.js';
142
- import { normalizeProjectTags, probeProjectStatus, toProjectListEntry, registerProject, removeProject, shouldRegisterProject, } from '../workspace/projects.js';
143
- import { mergeWriteWorkspaceUiState, readWorkspaceUiState } from '../workspace/ui-state.js';
144
- import { checkoutRepo } from './checkout.js';
145
- import { createProject, listGithubOwners } from './create-project.js';
146
- import { createWorkspaceRunFeed, currentRecord } from './workspace-run-feed.js';
147
- import { mergeWriteProjectUiState, readUiState } from '../ui-state.js';
148
- import { expandTilde } from '../paths.js';
72
+ import { createWorkspaceRunFeed } from './workspace-run-feed.js';
149
73
  import { isLoopbackHostHeader, resolveCapabilities } from './capabilities.js';
150
- import { browseDirectory, isInsideBrowseRoot, isLexicallyInsideBrowseRoot, resolveBrowseRoot } from './fs-browse.js';
151
- import { resolveForge, forgeWebRoot, resolveForgeRoot, GithubPrNotFoundError, GH_CHECKS_MAX, GH_REF_STATUS_MAX } from './forge/index.js';
152
- import { refNumberFromUrl } from '../contract/index.js';
153
- import { projectAdmissionRefusal, withProjectAdmission } from './cockpit-ownership.js';
74
+ import { resolveForge, forgeWebRoot, resolveForgeRoot } from './forge/index.js';
75
+ import { withProjectAdmission } from './cockpit-ownership.js';
154
76
  import { prepareProjects } from '../project-migration/auto.js';
155
77
  import { freshCliHandoff, openRunApp, openRunCli, openRunDefaultApp } from './open-in-targets.js';
156
- import { agentCliRunner, detectOpenTargets } from './open-in-app.js';
78
+ import { agentCliRunner } from './open-in-app.js';
157
79
  import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
158
80
  import { continueRunProviders } from './provider-action-gate.js';
159
- import { attachProjectWebhooks, createBootContext, createProviderStatus, emitProviderRow, resolveServerDeps, watchProviderRuntimeAuth, } from './server-deps.js';
81
+ import { attachProjectWebhooks, createBootContext, createProviderStatus, resolveServerDeps, watchProviderRuntimeAuth } from './server-deps.js';
160
82
  import { NO_WEBHOOK_ERROR, agentProfileRefusal, clientRequestOf, launchRun, modelLockRefusal, notifyRefusal, providerGateRefusal, replayedRun, resolveStartWorkflow, startRunInput, } from './start-run-options.js';
161
83
  import { ASSET_CACHE_CONTROL, BUILD_HINT_HTML, assetContentType, isSafeAssetFilename, resolveGetRequest, } from './static-ui.js';
162
84
  import { compression, createStaticAssets, isFile } from './static-assets.js';
163
85
  import { registerBrandFileRoutes } from './brand-file-routes.js';
164
- /** The hosted-mode refusal, worded like the agent-config one it mirrors. */
165
- const HOSTED_GITHUB_CREATE_REFUSAL = 'Creating GitHub repositories is available from a local cockpit only';
166
- const HOSTED_GITHUB_OWNERS_REASON = 'GitHub repositories can be created from a local cockpit only';
167
- const hostedProfileRefusal = {
168
- error: 'agent accounts are managed from the machine that owns the checkout (this cockpit runs in hosted mode)',
169
- };
86
+ import { createProjectsRoutes } from './projects-routes.js';
87
+ import { createAgentProfilesRoutes, createProvidersRoutes } from './providers-routes.js';
88
+ import { hostedProfileRefusal, WorkspaceEventBus } from './server-types.js';
89
+ import { createAutomationsRouteBundles } from './automations-routes.js';
90
+ import { createGithubRoutes } from './github-routes.js';
91
+ import { createOpenTargetsRoutes, createRepoRoutes, createWorktreesRoutes } from './repo-routes.js';
92
+ import { createFsBrowseRoutes, createRunsIndexRoutes, createWorkspaceConfigRoutes, createWorkspaceEventsRoutes } from './workspace-routes.js';
93
+ import { createAgentConfigRoutes, createAgentWebhooksRoutes, createConfigRoutes, createPlanRoutes, createSkillsRoutes, createSseRoutes, createUiStateRoutes, createWorkflowsRoutes } from './project-settings-routes.js';
94
+ // ---- project-scoped routing (multi-project spec, step 2.2) -----------------
95
+ export { WorkspaceEventBus } from './server-types.js';
170
96
  /**
171
97
  * The public API surface (spec 2026-07-23-independent-server-web-packages).
172
98
  *
@@ -202,43 +128,9 @@ export function projectRouteManifest(app) {
202
128
  return manifest;
203
129
  }
204
130
  /** 409 body for every automations route while GitHub automations are off (#801). */
205
- const AUTOMATIONS_OFF = 'Automations are disabled — unset CEZ_AUTOMATIONS or set it to 1 and restart to enable them';
206
131
  /** 404 body for a run whose row is in runs.db but whose record this Squawk cannot decode (#779). */
207
132
  const UNREADABLE_RUN_ERROR = `this run could not be read by this Squawk: its record in runs.db does not fit this version (a newer Squawk may have written it). It is left in the database untouched.`;
208
- /**
209
- * The in-process bus for workspace-level SSE events. The registry-mutating
210
- * routes (`POST /api/projects` — step 4.2, emits `project-added` for a
211
- * genuinely new entry; `DELETE /api/projects/:projectId` — step 4.4) and the
212
- * checkout flow (step 4.3) call `emit()`; runtime provider auth observation
213
- * emits host-wide `provider-status`; every open `/api/workspace/events` stream
214
- * relays the event verbatim under its name. Injectable via
215
- * `ServerDeps.workspaceEvents` so tests (and any out-of-createApp emitter) can
216
- * drive the stream.
217
- */
218
- export class WorkspaceEventBus {
219
- listeners = new Set();
220
- emit(event, data) {
221
- for (const listener of [...this.listeners])
222
- listener(event, data);
223
- }
224
- /** Subscribe; returns an unsubscribe. */
225
- on(listener) {
226
- this.listeners.add(listener);
227
- return () => this.listeners.delete(listener);
228
- }
229
- }
230
- /** streamSSE with the anti-buffering contract (#424): hono's own header is a
231
- * bare `no-cache`, which lets an intermediary (reverse proxy, compression
232
- * middleware, corporate MITM) transform-buffer the stream — the client then
233
- * sees a silently frozen transcript while the server keeps writing. Headers
234
- * are set on the returned Response because hono's helper overwrites
235
- * `Cache-Control` set via `c.header()` before it. */
236
- const streamSSENoBuffer = (c, cb, onError) => {
237
- const res = streamSSE(c, cb, onError);
238
- res.headers.set('Cache-Control', 'no-cache, no-transform');
239
- res.headers.set('X-Accel-Buffering', 'no');
240
- return res;
241
- };
133
+ // ---- workspace SSE (multi-project spec, step 2.8) --------------------------
242
134
  // Queued prompt stack bounds (#472). The per-message bounds mirror `messageSchema`
243
135
  // above; the one that actually matters is the FOLDED total, because 20 messages of
244
136
  // 100 000 chars each would otherwise compose a ~2 M-character {{task}}.
@@ -260,8 +152,6 @@ function foldedLength(task, stack) {
260
152
  // images at ~7 MB base64 each); the ui-state PUT gets a much tighter cap since
261
153
  // it only ever carries small GUI prefs.
262
154
  const GLOBAL_BODY_LIMIT = 32 * 1024 * 1024; // 32 MiB
263
- const UI_STATE_BODY_LIMIT = 128 * 1024; // 128 KiB
264
- function writeErrorMessage(error) { return error instanceof Error ? error.message : String(error); }
265
155
  // The return type is INFERRED on purpose: it is the chained app type built at the bottom of
266
156
  // this function, and `AppType` (src/server/app-type.ts) is `ReturnType<typeof createApp>`.
267
157
  // Annotating it `Hono` here would erase every route from the type and leave the typed client
@@ -327,12 +217,6 @@ export function createApp(deps) {
327
217
  const serverGeneration = randomUUID();
328
218
  const checkoutProgress = new CheckoutProgressCache();
329
219
  const workspaceEvents = deps.workspaceEvents ?? new WorkspaceEventBus();
330
- const emitAutomationChange = (project, automationId, revision, deleted = false) => workspaceEvents.emit('automation-change', {
331
- project: project.id,
332
- automationId,
333
- revision,
334
- ...(deleted ? { deleted: true } : {}),
335
- });
336
220
  const automationsChanged = () => deps.automationsChanged?.();
337
221
  const providerRuntimeAuth = deps.providerRuntimeAuth
338
222
  ?? new ProviderRuntimeAuthObserver(providerAuth, (status) => {
@@ -354,65 +238,6 @@ export function createApp(deps) {
354
238
  contexts.onContextBuilt((ctx) => workspaceEvents.emit('project-ready', { project: ctx.id }));
355
239
  const projectRegistryEntry = workspaceProjects.registryEntry;
356
240
  workspaceProjects.bindContexts(bootContext, contexts);
357
- /** One `task.test` POST to `webhook`, or a dry run under `CEZ_DRY_RUN=1`. */
358
- const sendTestDelivery = async (projectId, webhook) => {
359
- if (productEnv('DRY_RUN') === '1')
360
- return { ok: true, dryRun: true };
361
- const payload = {
362
- event: 'task.test',
363
- deliveryId: randomUUID(),
364
- projectId,
365
- webhook: { id: webhook.id, name: webhook.name },
366
- occurredAt: new Date().toISOString(),
367
- };
368
- const result = await deliverOnce(webhook, payload, { fetch: deps.taskWebhookFetch });
369
- return {
370
- ok: result.ok,
371
- ...(result.status === undefined ? {} : { status: result.status }),
372
- ...(result.error === undefined ? {} : { error: result.error }),
373
- };
374
- };
375
- /**
376
- * Read-modify-write one project's webhook list (hearsay-tools/cezarion#1576), with the PATCH
377
- * route's guards: an unknown project 404s without a write, and a
378
- * failed write (a read-only home) answers 500 having persisted nothing.
379
- */
380
- const editProjectWebhooks = async (raw, edit) => {
381
- const resolved = await workspaceProjects.resolveProjectId(raw);
382
- if ('error' in resolved)
383
- return { ...resolved, status: 404 };
384
- const { id } = resolved;
385
- const known = await loadWorkspaceConfig(deps.home.workspaceConfig).then((config) => config.projects.some((p) => p.id === id), () => false);
386
- if (!known)
387
- return { error: `unknown project: ${id}`, status: 404 };
388
- let updated;
389
- let outcome;
390
- try {
391
- await mergeWriteWorkspaceConfig((config) => {
392
- const entry = config.projects.find((p) => p.id === id);
393
- if (!entry)
394
- return;
395
- outcome = edit([...projectWebhooks(entry)]);
396
- if ('error' in outcome)
397
- return;
398
- setProjectWebhooks(entry, outcome.webhooks);
399
- updated = entry;
400
- }, deps.home);
401
- }
402
- catch (err) {
403
- return { error: err instanceof Error ? err.message : String(err), status: 500 };
404
- }
405
- if (outcome && 'error' in outcome)
406
- return outcome;
407
- if (!updated || !outcome)
408
- return { error: `unknown project: ${id}`, status: 404 };
409
- return {
410
- body: {
411
- project: toProjectListEntry(updated, await probeProjectStatus(updated.root)),
412
- webhook: redactWebhook(outcome.webhook),
413
- },
414
- };
415
- };
416
241
  const app = new Hono();
417
242
  app.use('*', compression);
418
243
  // One cache per app: immutable bundle bytes and their negotiated encodings share a cap.
@@ -809,475 +634,28 @@ export function createApp(deps) {
809
634
  return null;
810
635
  }
811
636
  };
812
- // ---- chained family: agent providers (workspace-level) ----
813
- const providersRoutes = new Hono()
814
- .get('/providers/status', queryZodValidator(strictRefreshQuerySchema, { message: 'refresh must be 1 when provided' }), async (c) => {
815
- const query = { data: c.req.valid('query') };
816
- const refresh = query.data.refresh === '1';
817
- if (refresh) {
818
- for (const { id } of registeredRunners())
819
- modelCatalog.invalidate(id);
820
- }
821
- return c.json(await providerStatus({ refresh }));
822
- })
823
- .put('/providers/:provider/enabled', paramZodValidator(providerRouteParamsSchema, { message: 'provider and enabled boolean are required', runners: { ids: ['provider'] } }), jsonZodValidator(providerEnabledSchema, { message: 'provider and enabled boolean are required' }), async (c) => {
824
- const provider = { data: registeredRunnerId(c.req.valid('param').provider) };
825
- const body = { data: c.req.valid('json') };
826
- let workspace;
827
- try {
828
- workspace = await workspaceConfig.mergeWrite((config) => {
829
- const disabled = new Set(config.disabledProviders);
830
- if (body.data.enabled)
831
- disabled.delete(provider.data);
832
- else
833
- disabled.add(provider.data);
834
- config.disabledProviders = preservedDisabledProviders(registeredRunners().map(({ id }) => id), disabled, config.disabledProviders);
835
- });
836
- }
837
- catch {
838
- return c.json({ error: 'Provider preference could not be saved.' }, 500);
839
- }
840
- const result = applyProviderEnablement(await providerAuth.status(), workspace.disabledProviders);
841
- emitProviderRow(workspaceEvents, result.providers, provider.data);
842
- return c.json(result);
843
- })
844
- .post('/providers/:provider/retry', paramZodValidator(providerRouteParamsSchema, { message: 'provider and current authFailureId are required', runners: { ids: ['provider'] } }), jsonZodValidator(providerRetrySchema, { message: 'provider and current authFailureId are required' }), async (c) => {
845
- const provider = { data: registeredRunnerId(c.req.valid('param').provider) };
846
- const body = { data: c.req.valid('json') };
847
- if (!providerAuth.clearRuntimeAuthFailure(provider.data, body.data.authFailureId)) {
848
- return c.json({ error: 'Authentication incident changed. Refresh and try again.' }, 409);
849
- }
850
- invalidateHostModels(provider.data);
851
- const result = await providerStatus({ refresh: true });
852
- emitProviderRow(workspaceEvents, result.providers, provider.data);
853
- return c.json(result);
854
- })
855
- .post('/providers/connect', jsonZodValidator(providerConnectSchema, { message: `provider must be ${knownRunnerIds().slice(0, -1).join(', ')}, or ${knownRunnerIds().at(-1)}`, runners: { ids: ['provider'] } }), async (c) => {
856
- const body = { data: c.req.valid('json') };
857
- const provider = body.data.provider;
858
- // A NAMED account is refused in hosted mode before anything is resolved, exactly like every
859
- // sibling route in the agent-profiles family. Checking later would already have read
860
- // `~/.cezar/agent-accounts.json`, built a command carrying the account's absolute path (which
861
- // both the success body and the hosted 409 echo), and — for a stored account — spawned a
862
- // probe. It would also answer `unknown account: <id>` for a wrong id, which is an enumeration
863
- // oracle for the very ids the hosted listing withholds. The bare-provider spelling keeps its
864
- // existing behaviour: it names no host path and is how the Providers card has always worked.
865
- if (body.data.profileId !== undefined
866
- && body.data.profileId !== DEFAULT_AGENT_ACCOUNT_ID
867
- && !capabilities().localHandoff) {
868
- return c.json(hostedProfileRefusal, 409);
869
- }
870
- // Resolve the account BEFORE anything else: both the command and the status probe below
871
- // must describe the same one, or the pane reports on the personal login while the terminal
872
- // signs into the work login.
873
- const resolved = await resolveWorkspaceProfile(provider, body.data.profileId);
874
- if ('error' in resolved)
875
- return c.json({ error: resolved.error }, 400);
876
- const { profile } = resolved;
877
- const command = providerAuth.loginCommand(provider, profile.isDefault ? null : profile.path);
878
- // Fail closed: a config dir that cannot be embedded safely in this platform's shell has no
879
- // safe degradation. Running the bare command would sign the user into a DIFFERENT account
880
- // than the one they clicked, and nothing in the terminal would say so.
881
- if (command === null) {
882
- return c.json({ error: providerAuth.loginRefusalHint(provider, profile.configDir) }, 409);
883
- }
884
- // BOTH branches must mean "is this account signed in NOW". The default branch refreshes; the
885
- // account branch has to evict first, because `profileStatus` serves the per-account cache and
886
- // a connected answer there stands for CONNECTED_TTL_MS. Without this, Connect after a
887
- // `claude /logout` answers "already connected", opens nothing, and the user is stuck — and it
888
- // would contradict this module's own invariant that opening a login is one of the things
889
- // Squawk CAN observe and therefore invalidates explicitly rather than waiting out a window.
890
- if (!profile.isDefault)
891
- providerAuth.forgetProfileStatus(provider, profile.id);
892
- const row = profile.isDefault
893
- ? (await providerAuth.status({ refresh: true })).providers.find((candidate) => candidate.provider === provider)
894
- : await providerAuth.profileStatus(provider, { id: profile.id, configDir: profile.path });
895
- if (!row) {
896
- return c.json({ error: 'Authentication could not be verified. Try again.' }, 500);
897
- }
898
- if (row.status === 'connected') {
899
- invalidateHostModels(provider);
900
- return c.json({ opened: false, connected: true, command });
901
- }
902
- if (row.status === 'not-installed') {
903
- return c.json({ error: row.hint ?? providerAuth.installHint(provider), command }, 409);
904
- }
905
- if (row.status === 'unknown') {
906
- return c.json({ error: row.hint ?? 'Authentication could not be verified. Try again.', command }, 409);
907
- }
908
- if (!capabilities().localHandoff) {
909
- return c.json({ error: `Run this command on the machine hosting Squawk.`, command }, 409);
910
- }
911
- let opened = false;
912
- try {
913
- // No `env` argument: `loginCommand` already rendered the account's config dir INTO the
914
- // command, because this string is also the copy-paste fallback the pane shows. Passing
915
- // it again here would set the variable twice.
916
- opened = await openTerminal(bootRoot, command);
917
- }
918
- catch {
919
- // Terminal handoff is best-effort; the exact command remains the safe fallback.
920
- }
921
- if (!opened) {
922
- return c.json({ error: 'No terminal emulator could be opened. Run this command manually.', command }, 409);
923
- }
924
- invalidateHostModels(provider);
925
- return c.json({ opened: true, command });
637
+ const providersRoutes = createProvidersRoutes({
638
+ bootRoot,
639
+ capabilities,
640
+ modelCatalog,
641
+ providerAuth,
642
+ providerStatus,
643
+ invalidateHostModels,
644
+ workspaceConfig,
645
+ workspaceEvents,
646
+ openTerminal,
647
+ resolveWorkspaceProfile,
926
648
  });
927
- // ---- chained family: agent profiles / accounts (workspace-level) ----------
928
- // Extra config dirs for a SECOND login of the same agent CLI (spec
929
- // 2026-07-29-agent-profiles). Workspace-level and therefore SINGLE-MOUNT: an account belongs to
930
- // the person and the machine, never to a repo, and a project-scoped spelling would be a second
931
- // surface to protect with no consumer. Which account a project uses is a field on
932
- // `PATCH /api/v1/projects/:projectId` instead.
933
- //
934
- // Writing is a LOCAL-MACHINE capability, exactly like `PUT /api/v1/agent-config/:id`: a profile
935
- // points an agent at a directory on the host, and the listing echoes absolute paths carrying
936
- // the username — the same disclosure `/api/v1/health` trims in hosted mode (#431).
937
- /** Build the wire row for one resolved profile: its dir state plus whatever auth is cached. */
938
- const agentProfileBody = async (profile) => ({
939
- id: profile.id,
940
- provider: profile.provider,
941
- label: profile.label,
942
- configDir: profile.configDir,
943
- path: profile.path,
944
- ...(await profileDirState(profile.provider, profile.path)),
945
- isDefault: profile.isDefault,
946
- // CACHED auth only — this listing must never pay a CLI spawn.
947
- //
948
- // Probing here cost a shell-out per provider PLUS one per extra account: ~0.7s with no extra
949
- // accounts and over 2s with a few, on every cold load, for a route whose real job (what
950
- // accounts exist) is a JSON read and a handful of stats. `GET /api/v1/health` already
951
- // established the rule — it serves whatever the cache holds and never pays a `gh` shell-out.
952
- // An absent `status` means "not determined yet", which the cockpit renders as Checking… and
953
- // then fills in from the per-account status route below.
954
- //
955
- // SPREAD, not `status: maybeUndefined`: hono would type the key as always-present while
956
- // `JSON.stringify` drops it, which is exactly the drift `contract-parity` catches (AGENTS.md
957
- // names this as one of the two recurring mismatches).
958
- ...(() => {
959
- const cached = profile.isDefault
960
- ? providerAuth.peekStatus()?.providers.find((row) => row.provider === profile.provider)
961
- : providerAuth.peekProfileStatus(profile.provider, profile.id);
962
- return cached ? { status: cached } : {};
963
- })(),
649
+ const agentProfilesRoutes = createAgentProfilesRoutes({
650
+ home: deps.home,
651
+ capabilities,
652
+ providerAuth,
653
+ providerStatus,
654
+ invalidateHostModels,
655
+ workspaceProjects,
656
+ resolveWorkspaceProfile,
657
+ projectRootFor,
964
658
  });
965
- /**
966
- * Resolve `:id` to an account for the per-account reads below. Unlike `resolveWorkspaceProfile`
967
- * this accepts the reserved `default` for a NAMED provider, which these routes cannot infer — so
968
- * the id may be `default:<provider>` as well as a stored account id.
969
- */
970
- const accountById = async (id) => {
971
- const [head, tail] = id.split(':');
972
- if (head === DEFAULT_AGENT_ACCOUNT_ID) {
973
- const provider = registeredRunners().find(({ id }) => id === tail)?.id;
974
- return provider ? defaultAgentProfile(provider) : null;
975
- }
976
- try {
977
- const stored = (await loadAgentAccounts(deps.home)).accounts.find((a) => a.id === id);
978
- return stored && isRegisteredRunner(stored.provider) ? resolveStoredProfile(stored) : null;
979
- }
980
- catch {
981
- return null;
982
- }
983
- };
984
- /** The per-account routes' gate: refuse hosted mode before resolving the id, then 404 an unknown id. */
985
- const localAccount = async (c) => {
986
- if (!capabilities().localHandoff)
987
- return c.json(hostedProfileRefusal, 409);
988
- const id = c.req.param('id');
989
- return (await accountById(id)) ?? c.json({ error: `unknown account: ${id}` }, 404);
990
- };
991
- /** Validate a client-supplied config dir. Returns the error text, or null when it is usable. */
992
- const checkProfileDir = (configDir) => {
993
- if (CONTROL_CHARS_RE.test(configDir))
994
- return 'folder must not contain control characters';
995
- const expanded = expandTilde(configDir);
996
- // Absolute after expansion: a relative dir would resolve against whatever cwd the agent
997
- // happens to be spawned in, which for a task is a throwaway worktree. Through
998
- // `isAbsoluteConfigDir`, never a leading-`/` test — see its note: a string test refuses every
999
- // real Windows path, and this is the only gate the Add-account dialog has.
1000
- return isAbsoluteConfigDir(expanded) ? null : `folder must be an absolute path: ${configDir}`;
1001
- };
1002
- /** Refuse a dir that is already some other account's (or the default's), compared through
1003
- * `realpath` — two spellings of one directory would be two accounts silently sharing one
1004
- * session store, and "which one am I logged into?" would stop having an answer. */
1005
- const conflictingProfile = async (profiles, provider, path, exceptId) => {
1006
- if (await sameProfileDir(path, defaultAgentProfile(provider).path)) {
1007
- return 'that is already this agent\'s default folder';
1008
- }
1009
- for (const candidate of profiles) {
1010
- if (candidate.provider !== provider || candidate.id === exceptId)
1011
- continue;
1012
- if (await sameProfileDir(path, expandTilde(candidate.configDir))) {
1013
- return `that folder is already used by "${candidate.label || candidate.id}"`;
1014
- }
1015
- }
1016
- return null;
1017
- };
1018
- const agentProfilesRoutes = new Hono()
1019
- .get('/workspace/agent-profiles', async (c) => {
1020
- const editable = capabilities().localHandoff;
1021
- // Hosted mode withholds the listing entirely rather than serving it read-only: the paths
1022
- // are the host disclosure, so an empty list is the only honest hosted answer.
1023
- //
1024
- // ONE body object, never a hosted `return` and a local `return`: two returns let hono
1025
- // narrow `editable` to the literal `false`/`true` of each branch, and the contract's
1026
- // honest `z.boolean()` then reads as wider than the route. Same shape as
1027
- // `listAgentConfig`, which carries the same flag for the same reason.
1028
- let store = defaultAgentAccountStore();
1029
- if (editable) {
1030
- try {
1031
- store = await loadAgentAccounts(deps.home);
1032
- }
1033
- catch {
1034
- // an unreadable home degrades to "no extra accounts", never a failed request
1035
- }
1036
- }
1037
- const profiles = editable
1038
- ? await Promise.all(listAgentProfiles(store, registeredRunners().map(({ id }) => id)).map(agentProfileBody))
1039
- : [];
1040
- return c.json({
1041
- editable,
1042
- profiles,
1043
- profileCapableProviders: profileCapableProviders(),
1044
- // Which account each project uses, keyed by repo root. Served here rather than on the
1045
- // project registry because it lives in the same file as the accounts it names.
1046
- selections: editable ? store.selections : {},
1047
- });
1048
- })
1049
- .post('/workspace/agent-profiles', jsonZodValidator(() => createAgentProfileSchema, { runners: { ids: ['provider'] } }), async (c) => {
1050
- if (!capabilities().localHandoff)
1051
- return c.json(hostedProfileRefusal, 409);
1052
- const { configDir, label } = c.req.valid('json'), provider = registeredRunnerId(c.req.valid('json').provider);
1053
- if (!supportsProfiles(provider)) {
1054
- return c.json({ error: `${provider} cannot carry more than one account` }, 400);
1055
- }
1056
- const dirError = checkProfileDir(configDir);
1057
- if (dirError)
1058
- return c.json({ error: dirError }, 400);
1059
- // Read-first, exactly like `POST /projects`: the duplicate check needs `realpath`, and the
1060
- // merge-write mutator is deliberately SYNCHRONOUS so the read→rename window stays as small
1061
- // as it is for every other writer of this file. Two processes adding the same folder in
1062
- // that window would both win — a cosmetic duplicate, not a correctness problem, since the
1063
- // schema's id dedupe is what keeps resolution deterministic.
1064
- let existing = [];
1065
- try {
1066
- existing = (await loadAgentAccounts(deps.home)).accounts;
1067
- }
1068
- catch {
1069
- // unreadable store — the merge-write below reports the real failure
1070
- }
1071
- const conflict = await conflictingProfile(existing, provider, expandTilde(configDir));
1072
- if (conflict !== null)
1073
- return c.json({ error: conflict }, 409);
1074
- let created;
1075
- try {
1076
- await mergeWriteAgentAccounts((store) => {
1077
- const id = allocateAgentProfileId(label ?? configDir, store.accounts.map((a) => a.id));
1078
- created = {
1079
- id,
1080
- provider,
1081
- configDir,
1082
- label: label?.trim() || id,
1083
- addedAt: new Date().toISOString(),
1084
- };
1085
- store.accounts.push(created);
1086
- }, deps.home);
1087
- }
1088
- catch (err) {
1089
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1090
- }
1091
- if (!created)
1092
- return c.json({ error: 'account could not be saved' }, 500);
1093
- // A brand-new account is the one thing the boot warm could not have known about, so learn it
1094
- // now rather than only when something asks. Still off the response: the row is returned with
1095
- // `status` absent (the listing's rule), the pane shows Checking…, and its follow-up request
1096
- // joins this same in-flight probe.
1097
- const account = resolveStoredProfile(created);
1098
- const created201 = await agentProfileBody(account);
1099
- void providerAuth
1100
- .profileStatus(account.provider, { id: account.id, configDir: account.path })
1101
- .catch(() => { });
1102
- return c.json({ profile: created201 }, 201);
1103
- })
1104
- .patch('/workspace/agent-profiles/:id', paramZodValidator(agentProfileRouteParamsSchema), jsonZodValidator(() => updateAgentProfileSchema), async (c) => {
1105
- if (!capabilities().localHandoff)
1106
- return c.json(hostedProfileRefusal, 409);
1107
- const id = c.req.param('id');
1108
- const { label, configDir } = c.req.valid('json');
1109
- if (configDir !== undefined) {
1110
- const dirError = checkProfileDir(configDir);
1111
- if (dirError)
1112
- return c.json({ error: dirError }, 400);
1113
- }
1114
- // Read-first (see POST above, and `PATCH /projects`): a well-formed but unknown id must
1115
- // 404 WITHOUT rewriting the config, and the duplicate check needs async `realpath`.
1116
- let existing = [];
1117
- try {
1118
- existing = (await loadAgentAccounts(deps.home)).accounts;
1119
- }
1120
- catch {
1121
- // unreadable store — treated as unknown, like DELETE and PATCH /projects
1122
- }
1123
- const current = existing.find((a) => a.id === id);
1124
- if (!current || !isRegisteredRunner(current.provider))
1125
- return c.json({ error: `unknown account: ${id}` }, 404);
1126
- if (configDir !== undefined) {
1127
- const conflict = await conflictingProfile(existing, current.provider, expandTilde(configDir), id);
1128
- if (conflict !== null)
1129
- return c.json({ error: conflict }, 409);
1130
- }
1131
- let updated;
1132
- try {
1133
- await mergeWriteAgentAccounts((store) => {
1134
- const entry = store.accounts.find((a) => a.id === id);
1135
- if (!entry)
1136
- return; // lost a race with a concurrent delete — answered below
1137
- // Mutated in place so `.passthrough()` keys on the row survive.
1138
- if (label !== undefined)
1139
- entry.label = label.trim() || entry.id;
1140
- if (configDir !== undefined)
1141
- entry.configDir = configDir;
1142
- updated = entry;
1143
- }, deps.home);
1144
- }
1145
- catch (err) {
1146
- return c.json({ error: writeErrorMessage(err) }, 500);
1147
- }
1148
- if (!updated)
1149
- return c.json({ error: `unknown account: ${id}` }, 404);
1150
- // The dir may have moved under a cached probe — drop THIS account's answer so the response
1151
- // reports the new folder's state rather than the old one's, and leave every other account's
1152
- // warm answer alone (it is still true). Then re-learn it in the background, so the server's
1153
- // knowledge is complete again whether or not a cockpit is open to ask; the pane's own
1154
- // request for this row joins the same in-flight probe rather than spawning a second.
1155
- const repointed = resolveStoredProfile(updated);
1156
- providerAuth.forgetProfileStatus(repointed.provider, repointed.id);
1157
- const body = await agentProfileBody(repointed);
1158
- void providerAuth
1159
- .profileStatus(repointed.provider, { id: repointed.id, configDir: repointed.path })
1160
- .catch(() => { });
1161
- return c.json({ profile: body });
1162
- })
1163
- /**
1164
- * One account's authentication state, probed for real.
1165
- *
1166
- * Separate from the listing because a probe shells out to an agent CLI: keeping it here lets
1167
- * the pane paint immediately and fill each row in as its answer lands, instead of every cold
1168
- * load blocking on N spawns. `refresh=1` drops this account's cached answer and re-probes, for
1169
- * the "Check again" affordance — the cache itself holds a connected answer for minutes and an
1170
- * unsettled one for a minute (`cacheTtlFor` in `core/provider-auth.ts`).
1171
- */
1172
- .get('/workspace/agent-profiles/:id/status', paramZodValidator(agentProfileRouteParamsSchema), queryZodValidator(strictRefreshQuerySchema, { message: 'refresh must be 1 when provided' }), async (c) => {
1173
- const account = await localAccount(c);
1174
- if (account instanceof Response)
1175
- return account;
1176
- const refresh = c.req.valid('query').refresh === '1';
1177
- if (refresh)
1178
- invalidateHostModels(account.provider);
1179
- // The discovered account's row is the one `GET /api/v1/providers/status` owns, so it comes
1180
- // from there — enablement included, which a bare probe does not know about.
1181
- if (account.isDefault) {
1182
- const all = await providerStatus(refresh ? { refresh: true } : undefined);
1183
- const row = all.providers.find((candidate) => candidate.provider === account.provider);
1184
- return c.json({ status: row ?? { provider: account.provider, status: 'unknown' } });
1185
- }
1186
- // "Check again" re-probes THIS account only — the other accounts' warm answers are not
1187
- // invalidated by asking about this one.
1188
- if (refresh)
1189
- providerAuth.forgetProfileStatus(account.provider, account.id);
1190
- return c.json({
1191
- status: await providerAuth.profileStatus(account.provider, {
1192
- id: account.id,
1193
- configDir: account.path,
1194
- }),
1195
- });
1196
- })
1197
- // Which account a PROJECT uses. On the accounts family rather than `PATCH /api/v1/projects`
1198
- // because the selection is stored beside the accounts it names — one file, one atomic write,
1199
- // and nothing about it can be dropped by a Squawk version that never heard of accounts.
1200
- .put('/workspace/agent-profiles/selection', jsonZodValidator(() => selectAgentProfileSchema, { runners: { ids: ['provider'] } }), async (c) => {
1201
- if (!capabilities().localHandoff)
1202
- return c.json(hostedProfileRefusal, 409);
1203
- const { projectId, profileId } = c.req.valid('json'), provider = registeredRunnerId(c.req.valid('json').provider);
1204
- const resolvedId = await workspaceProjects.canonicalProjectId(projectId);
1205
- // Keyed by repo ROOT, so the selection survives the registry being rebuilt and needs no
1206
- // cross-reference into config.json. An unknown project is a 404 rather than an orphan
1207
- // entry nobody will ever read.
1208
- const root = await projectRootFor(resolvedId);
1209
- if (root === null)
1210
- return c.json({ error: `unknown project: ${projectId}` }, 404);
1211
- // A user naming an account that does not exist gets told so — the opposite of how RUN
1212
- // resolution treats a dangling stored id, and deliberately: a run has no better answer
1213
- // than the default, a person does.
1214
- if (profileId !== null && profileId !== DEFAULT_AGENT_ACCOUNT_ID) {
1215
- const account = await resolveWorkspaceProfile(provider, profileId);
1216
- if ('error' in account)
1217
- return c.json({ error: account.error }, 400);
1218
- }
1219
- let store;
1220
- try {
1221
- store = await mergeWriteAgentAccounts((current) => {
1222
- const selection = current.selections[root] ?? {};
1223
- // `null` and the reserved `default` both mean "back to the discovered account", which
1224
- // is stored as ABSENCE — the default id is never written to the file.
1225
- if (profileId === null || profileId === DEFAULT_AGENT_ACCOUNT_ID)
1226
- delete selection[provider];
1227
- else
1228
- selection[provider] = profileId;
1229
- if (Object.keys(selection).length === 0)
1230
- delete current.selections[root];
1231
- else
1232
- current.selections[root] = selection;
1233
- }, deps.home);
1234
- }
1235
- catch (err) {
1236
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1237
- }
1238
- return c.json({ selections: store.selections });
1239
- })
1240
- .delete('/workspace/agent-profiles/:id', paramZodValidator(agentProfileRouteParamsSchema), async (c) => {
1241
- if (!capabilities().localHandoff)
1242
- return c.json(hostedProfileRefusal, 409);
1243
- const id = c.req.param('id');
1244
- let removed = false;
1245
- // Captured inside the mutator, because after the write there is nothing left to ask which
1246
- // provider this account belonged to — and the eviction below is keyed by it.
1247
- let removedProvider;
1248
- try {
1249
- await mergeWriteAgentAccounts((store) => {
1250
- removedProvider = removeAgentAccount(store, id);
1251
- removed = removedProvider !== undefined;
1252
- }, deps.home);
1253
- }
1254
- catch (err) {
1255
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1256
- }
1257
- if (!removed)
1258
- return c.json({ error: `unknown account: ${id}` }, 404);
1259
- // Only this account's answer: it is about to stop existing, and holding it would let a
1260
- // re-added account with the same id read the deleted one's state.
1261
- providerAuth.forgetProfileStatus(removedProvider, id);
1262
- return c.json({ removed: true, id });
1263
- });
1264
- // ---- workspace projects (multi-project spec) -----------------------------
1265
- // The registered-project list for the cockpit sidebar. Same-origin (unlike
1266
- // health), so absolute `root`s are fine here. `listProjects()` TTL-caches
1267
- // its per-root status/branch probes, so a burst of renders never shells git
1268
- // N times. Never 404s: empty or unreadable registry → `projects: []`.
1269
- /** The configured checkout root, as WRITTEN (`~` kept — callers that touch
1270
- * the filesystem expand it). An unreadable workspace degrades to the
1271
- * default rather than failing the request: every caller here is a route
1272
- * that must keep answering. */
1273
- const workspaceProjectsDir = async () => {
1274
- try {
1275
- return (await loadWorkspaceConfig(deps.home.workspaceConfig)).projectsDir;
1276
- }
1277
- catch {
1278
- return defaultWorkspaceConfig().projectsDir;
1279
- }
1280
- };
1281
659
  const workspaceBrowseRoot = async () => {
1282
660
  try {
1283
661
  return (await loadWorkspaceConfig(deps.home.workspaceConfig)).browseRoot;
@@ -1286,510 +664,19 @@ export function createApp(deps) {
1286
664
  return defaultWorkspaceConfig().browseRoot;
1287
665
  }
1288
666
  };
1289
- // ---- chained family: project registry (workspace-level) ----
1290
- const projectsRoutes = new Hono()
1291
- .get('/projects', async (c) => {
1292
- let projects = [];
1293
- let projectsDir = defaultWorkspaceConfig().projectsDir;
1294
- try {
1295
- projectsDir = (await loadWorkspaceConfig(deps.home.workspaceConfig)).projectsDir;
1296
- projects = await workspaceProjects.listProjects();
1297
- }
1298
- catch {
1299
- // unreadable workspace — degrade to the empty registry + defaults
1300
- }
1301
- const body = {
1302
- projects,
1303
- bootProject: await resolveBootProject(projects),
1304
- projectsDir,
1305
- };
1306
- return c.json(body);
1307
- })
1308
- .post('/projects', jsonZodValidator(() => registerProjectSchema, { message: 'root must be a non-empty path' }), async (c) => {
1309
- const parsed = { data: c.req.valid('json') };
1310
- const registered = await registerFolder(parsed.data.root, 'local');
1311
- if (registered.status !== 200)
1312
- return c.json(registered.body, registered.status);
1313
- if (registered.existing) {
1314
- // 409 with the EXISTING entry (spec): the dialog treats it as "you already have this one"
1315
- // and navigates there rather than dead-ending.
1316
- const { project } = registered.body;
1317
- return c.json({ project, error: `already registered as ${project.id}` }, 409);
1318
- }
1319
- return c.json(registered.body, 200);
1320
- })
1321
- .delete('/projects/:projectId', async (c) => {
1322
- const raw = c.req.param('projectId');
1323
- // Same gate the scoped-route resolver applies, and the same 404 wording —
1324
- // a malformed id is an unknown project, not a validation essay.
1325
- const resolved = await workspaceProjects.resolveProjectId(raw, true);
1326
- if ('error' in resolved)
1327
- return c.json(resolved, 404);
1328
- // `default` is the boot alias everywhere else in the API; honour it here
1329
- // too rather than 404ing a spelling the cockpit is allowed to use.
1330
- const { id, bootId } = resolved;
1331
- let entry;
1332
- try {
1333
- entry = (await loadWorkspaceConfig(deps.home.workspaceConfig)).projects.find((p) => p.id === id);
1334
- }
1335
- catch {
1336
- // unreadable workspace — there is nothing to remove, and saying so is
1337
- // more useful than a 500 the user cannot act on
1338
- }
1339
- if (!entry)
1340
- return c.json({ error: `unknown project: ${id}` }, 404);
1341
- // The boot project is refused, not removed: `hsq serve` re-registers the
1342
- // repo it was started in on every boot, so "removing" it would undo itself
1343
- // at the next restart while breaking this session's sidebar in the
1344
- // meantime. The pane disables the button and says the same thing.
1345
- if (id === bootId) {
1346
- return c.json({
1347
- error: `Squawk is serving ${entry.name} right now — it re-registers itself at every start, so it cannot be removed from here`,
1348
- }, 409);
1349
- }
1350
- // A background warm-up may be building this project right now: count its runs, and dispose
1351
- // it, only once that build has landed (#667).
1352
- await contexts.settle(id);
1353
- const active = activeRunCount(id);
1354
- if (active > 0) {
1355
- return c.json({
1356
- error: `${entry.name} has ${active} running task${active === 1 ? '' : 's'} — cancel or finish ${active === 1 ? 'it' : 'them'} before removing the project`,
1357
- runningTasks: active,
1358
- }, 409);
1359
- }
1360
- let removed;
1361
- try {
1362
- removed = await removeProject(id, deps.home);
1363
- }
1364
- catch (err) {
1365
- // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
1366
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1367
- }
1368
- // Lost a race with another writer (or another Squawk process): the entry is
1369
- // gone, which is what the caller wanted, but say it honestly.
1370
- if (!removed)
1371
- return c.json({ error: `unknown project: ${id}` }, 404);
1372
- // In-process handles for a project no route can reach any more: store
1373
- // closed (index flushed), manager's timers and usage subscription dropped.
1374
- contexts.dispose(id);
1375
- workspaceEvents.emit('project-removed', { id });
1376
- const body = { removed: true, id };
1377
- return c.json(body);
1378
- })
1379
- // Edit the per-project registry fields the cockpit owns: the concurrency ceiling (spec
1380
- // 2026-07-22-per-project-concurrency) and the grouping tags (spec
1381
- // 2026-08-10-global-tasks-and-project-tags). A PATCH (not PUT) because it touches named
1382
- // fields and leaves the rest of the entry alone, and a distinct route from POST
1383
- // (register-a-folder) to keep register vs. edit semantics clear.
1384
- //
1385
- // The body schema is the CONTRACT's, passed directly rather than restated behind a thunk:
1386
- // it is already in scope, and a second copy is a second thing to keep in step. Its bounds
1387
- // mirror `workspaceProjectSchema` (config.ts) exactly, so a value this route accepts can
1388
- // never be degraded away by the next load's `.catch`.
1389
- //
1390
- // Deliberately NOT the home of the agent-account selection: that lives in
1391
- // `~/.cezar/agent-accounts.json` beside the accounts it names, so a Squawk version that has
1392
- // never heard of accounts cannot drop it (see workspace/agent-accounts.ts).
1393
- .patch('/projects/:projectId', jsonZodValidator(updateProjectInputSchema), async (c) => {
1394
- const raw = c.req.param('projectId');
1395
- // Same gate + 404 wording as DELETE: a malformed id is an unknown project.
1396
- const resolved = await workspaceProjects.resolveProjectId(raw);
1397
- if ('error' in resolved)
1398
- return c.json(resolved, 404);
1399
- const parsed = { data: c.req.valid('json') };
1400
- // `default` is the boot alias the cockpit is allowed to use everywhere else.
1401
- const { id } = resolved;
1402
- const { maxParallel, tags, webhook } = parsed.data;
1403
- // Read-first (mirroring DELETE, server.ts:1252-1258): a well-formed but
1404
- // unknown id must 404 WITHOUT rewriting the config — otherwise it would both
1405
- // do a needless full-config tmp+rename and, on a read-only home, surface the
1406
- // write failure as a 500 where the honest answer is 404.
1407
- let known = false;
1408
- try {
1409
- known = (await loadWorkspaceConfig(deps.home.workspaceConfig)).projects.some((p) => p.id === id);
1410
- }
1411
- catch {
1412
- // unreadable workspace — treat as unknown; the read-only case answers 404,
1413
- // not a 500 the caller cannot act on (same reasoning as DELETE).
1414
- }
1415
- if (!known)
1416
- return c.json({ error: `unknown project: ${id}` }, 404);
1417
- let updated;
1418
- try {
1419
- await mergeWriteWorkspaceConfig((config) => {
1420
- const entry = config.projects.find((p) => p.id === id);
1421
- if (!entry)
1422
- return; // lost a race with a concurrent remove — answered below
1423
- // Each key is applied only when the body NAMED it: a PATCH that says
1424
- // nothing about a field must leave it exactly as it was, which is what
1425
- // keeps the tags editor from clearing a concurrency ceiling (and the
1426
- // pre-tags `{ maxParallel }` body from clearing tags). null clears;
1427
- // a value sets. Mutated in place so `.passthrough()` keys survive.
1428
- if (maxParallel !== undefined) {
1429
- if (maxParallel === null)
1430
- delete entry.maxParallel;
1431
- else
1432
- entry.maxParallel = maxParallel;
1433
- }
1434
- if (tags !== undefined) {
1435
- // Normalized on the way IN, so every reader — this API, the CLI, the
1436
- // global Tasks page — sees one spelling per tag and never has to
1437
- // fold case itself.
1438
- const normalized = normalizeProjectTags(tags);
1439
- if (normalized === undefined)
1440
- delete entry.tags;
1441
- else
1442
- entry.tags = normalized;
1443
- }
1444
- if (webhook !== undefined) {
1445
- // The token is write-only (#589): the form never has it back, so an omitted token
1446
- // keeps the stored one and only `''` clears it. An omitted `triggers` keeps the stored
1447
- // selection the same way, so a URL or token edit never resets it (#1356).
1448
- // Since #1576 this edits the first webhook with task notifications on.
1449
- applyTaskWebhookInput(entry, webhook);
1450
- }
1451
- updated = entry;
1452
- }, deps.home);
1453
- }
1454
- catch (err) {
1455
- // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
1456
- return c.json({ error: writeErrorMessage(err) }, 500);
1457
- }
1458
- // Raced with a concurrent removal between the read and the write.
1459
- if (!updated)
1460
- return c.json({ error: `unknown project: ${id}` }, 404);
1461
- // The new ceiling takes effect WITHOUT a restart: refresh the shared
1462
- // semaphore's snapshot and pump every manager — the same live-apply hook
1463
- // `PUT /api/workspace/config` fires for a workspace-cap change.
1464
- await deps.semaphore?.refresh();
1465
- const body = {
1466
- project: toProjectListEntry(updated, await probeProjectStatus(updated.root)),
1467
- };
1468
- return c.json(body);
1469
- })
1470
- // "Send test" (#589): one `task.test` delivery to the STORED webhook, now, with the timeout
1471
- // the real deliveries use and no retries — the settings page wants the answer, not a queue.
1472
- .post('/projects/:projectId/webhook/test', async (c) => {
1473
- const raw = c.req.param('projectId');
1474
- const entry = await workspaceProjects.resolveRegistryEntry(raw);
1475
- if (!entry)
1476
- return c.json({ error: `unknown project: ${raw}` }, 404);
1477
- // Since #1576: the first webhook with task notifications on.
1478
- const webhook = taskWebhookList(entry)[0];
1479
- if (!webhook)
1480
- return c.json({ error: NO_WEBHOOK_ERROR }, 400);
1481
- const body = await sendTestDelivery(entry.id, webhook);
1482
- return c.json(body);
1483
- })
1484
- // ---- project webhooks (hearsay-tools/cezarion#1576) ----
1485
- // Several webhooks per project, each with its own task-state selection and an explicit
1486
- // "Expose to agents" switch. Registry edits like the PATCH above:
1487
- // 404 on an unknown project or webhook, and a write that names nothing else leaves the
1488
- // rest of the entry alone. The first write stores `webhooks` and drops the old `webhook` key.
1489
- .post('/projects/:projectId/webhooks', jsonZodValidator(createProjectWebhookInputSchema), async (c) => {
1490
- const input = c.req.valid('json');
1491
- const answer = await editProjectWebhooks(c.req.param('projectId'), (webhooks) => {
1492
- if (webhooks.length >= PROJECT_WEBHOOKS_MAX)
1493
- return { error: `a project holds at most ${PROJECT_WEBHOOKS_MAX} webhooks`, status: 409 };
1494
- if (nameTaken(webhooks, input.name))
1495
- return { error: webhookNameTakenError(input.name), status: 409 };
1496
- const webhook = createdWebhook(webhooks, input);
1497
- return { webhooks: [...webhooks, webhook], webhook };
1498
- });
1499
- if ('error' in answer)
1500
- return c.json({ error: answer.error }, answer.status);
1501
- const body = answer.body;
1502
- return c.json(body, 201);
1503
- })
1504
- .patch('/projects/:projectId/webhooks/:webhookId', paramZodValidator(projectWebhookParamsSchema), jsonZodValidator(updateProjectWebhookInputSchema), async (c) => {
1505
- const { projectId, webhookId } = c.req.valid('param');
1506
- const input = c.req.valid('json');
1507
- const answer = await editProjectWebhooks(projectId, (webhooks) => {
1508
- const index = webhooks.findIndex((webhook) => webhook.id === webhookId);
1509
- if (index < 0)
1510
- return { error: `unknown webhook: ${webhookId}`, status: 404 };
1511
- if (input.name !== undefined && nameTaken(webhooks, input.name, webhookId))
1512
- return { error: webhookNameTakenError(input.name), status: 409 };
1513
- const webhook = editedWebhook(webhooks[index], input);
1514
- return { webhooks: webhooks.map((entry, at) => (at === index ? webhook : entry)), webhook };
1515
- });
1516
- if ('error' in answer)
1517
- return c.json({ error: answer.error }, answer.status);
1518
- const body = answer.body;
1519
- return c.json(body);
1520
- })
1521
- .delete('/projects/:projectId/webhooks/:webhookId', paramZodValidator(projectWebhookParamsSchema), async (c) => {
1522
- const { projectId, webhookId } = c.req.valid('param');
1523
- const answer = await editProjectWebhooks(projectId, (webhooks) => {
1524
- const webhook = webhooks.find((entry) => entry.id === webhookId);
1525
- if (!webhook)
1526
- return { error: `unknown webhook: ${webhookId}`, status: 404 };
1527
- return { webhooks: webhooks.filter((entry) => entry !== webhook), webhook };
1528
- });
1529
- if ('error' in answer)
1530
- return c.json({ error: answer.error }, answer.status);
1531
- const project = answer.body.project;
1532
- const body = { project: defined({ ...project, webhook: project.webhook && defined(project.webhook) }) };
1533
- return c.json(body);
1534
- })
1535
- // "Send test" for one webhook: one `task.test` delivery, now, no retries.
1536
- .post('/projects/:projectId/webhooks/:webhookId/test', paramZodValidator(projectWebhookParamsSchema), async (c) => {
1537
- const { projectId, webhookId } = c.req.valid('param');
1538
- const entry = await workspaceProjects.resolveRegistryEntry(projectId);
1539
- if (!entry)
1540
- return c.json({ error: `unknown project: ${projectId}` }, 404);
1541
- const webhook = projectWebhooks(entry).find((candidate) => candidate.id === webhookId);
1542
- if (!webhook)
1543
- return c.json({ error: `unknown webhook: ${webhookId}` }, 404);
1544
- const body = await sendTestDelivery(entry.id, webhook);
1545
- return c.json(body);
1546
- })
1547
- .get('/projects/checkout/:checkoutId/progress', paramZodValidator(checkoutProgressParamsSchema), c => c.json({ progress: checkoutProgress.get(c.req.valid('param').checkoutId) }))
1548
- .post('/projects/checkout', jsonZodValidator(() => checkoutSchema, { message: 'url must be a GitHub repository' }), async (c) => {
1549
- const parsed = { data: c.req.valid('json') };
1550
- const { url, name, checkoutId } = parsed.data;
1551
- const result = await checkoutRepo({
1552
- url,
1553
- name,
1554
- checkoutId,
1555
- projectsDir: expandTilde(await workspaceProjectsDir()),
1556
- onProgress: (event) => { checkoutProgress.record(event); workspaceEvents.emit('checkout-progress', event); },
1557
- // A closed dialog / navigated-away tab aborts the request; the clone is
1558
- // killed and its partial directory removed rather than left running.
1559
- signal: c.req.raw.signal,
1560
- ...(deps.cloneRunner ? { run: deps.cloneRunner } : {}),
1561
- });
1562
- if (!result.ok) {
1563
- // `reason` rides along on the 503 (`gh` unavailable) — the spec's
1564
- // `{ error, reason }` degradation, mirroring the GitHub pane.
1565
- return c.json('reason' in result ? { error: result.error, reason: result.reason } : { error: result.error }, result.status);
1566
- }
1567
- // An existing entry for the same root (its folder had been deleted) is a success too: the
1568
- // project the user asked for is there (hearsay-tools/squawk#1086).
1569
- const registered = await registerFolder(result.target, 'checkout');
1570
- if (registered.status !== 200) {
1571
- // The clone SUCCEEDED and its files are legitimately the user's, so this
1572
- // path deliberately does NOT clean up — an unregisterable checkout is a
1573
- // registry problem, not a reason to delete a repo we just fetched. Say
1574
- // where it is so they can register it by hand.
1575
- return c.json({ error: `${registered.body.error} (the clone is at ${result.target})` }, registered.status);
1576
- }
1577
- return c.json(registered.body, 200);
1578
- })
1579
- // ---- new project (spec 2026-10-15-create-new-project) ------------------
1580
- // "Add project → New project": a fresh git repo at `<projectsDir>/<name>`,
1581
- // optionally backed by a new PRIVATE GitHub repository (never public — the
1582
- // body has no visibility field to set), optionally from a template. Same
1583
- // progress stream and cache, same `registerFolder` commit, same
1584
- // `{ error, reason }` degradation as the clone route above.
1585
- //
1586
- // A hosted cockpit creates LOCAL projects only: GitHub creation would act
1587
- // with the host's `gh` account on a remote viewer's behalf, and the owner
1588
- // list would show that viewer the host's login and organisations.
1589
- .get('/projects/github-owners', async (c) => {
1590
- if (!capabilities().localHandoff) {
1591
- const body = { available: false, reason: HOSTED_GITHUB_OWNERS_REASON };
1592
- return c.json(body);
1593
- }
1594
- return c.json(await listGithubOwners(deps.projectCommandRunner));
1595
- })
1596
- .post('/projects/create', jsonZodValidator(() => createProjectInputSchema, { message: 'project name must be a valid GitHub repository name — letters, digits, ".", "-" and "_" only, no spaces' }), async (c) => {
1597
- const { name, github, checkoutId } = c.req.valid('json');
1598
- if (github && !capabilities().localHandoff) {
1599
- return c.json({ error: HOSTED_GITHUB_CREATE_REFUSAL }, 409);
1600
- }
1601
- const projectsDir = expandTilde(await workspaceProjectsDir());
1602
- // `registerFolder` re-checks hosted containment, but only AFTER the
1603
- // repository exists; asked here first, an out-of-root checkout root
1604
- // refuses before anything is created.
1605
- if (!capabilities().localHandoff && !(await isInsideHostedBrowseRoot(join(projectsDir, name)))) {
1606
- return c.json({ error: 'folder is outside the browsable root' }, 400);
1607
- }
1608
- const result = await createProject({
1609
- name,
1610
- github,
1611
- checkoutId,
1612
- projectsDir,
1613
- onProgress: (event) => { checkoutProgress.record(event); workspaceEvents.emit('checkout-progress', event); },
1614
- // Cancels only the steps before `gh repo create` (create-project.ts).
1615
- signal: c.req.raw.signal,
1616
- ...(deps.projectCommandRunner ? { run: deps.projectCommandRunner } : {}),
1617
- });
1618
- if (!result.ok) {
1619
- return c.json('reason' in result ? { error: result.error, reason: result.reason } : { error: result.error }, result.status);
1620
- }
1621
- // GitHub-backed projects register as `checkout` (they have an origin the
1622
- // clone flow would also produce); a local-only repo is `local`.
1623
- // A new entry, or the existing one for the same root — what creating a registered project
1624
- // whose folder had been deleted produces. Both are a success.
1625
- const registered = await registerFolder(result.target, result.slug ? 'checkout' : 'local');
1626
- if (registered.status !== 200) {
1627
- // As with a clone: the repository is the user's now, so it stays — and a GitHub warning
1628
- // rides along, since its finishing commands are the only record of what is left to do.
1629
- const warning = result.warning ? `\n${result.warning}` : '';
1630
- return c.json({ error: `${registered.body.error} (the project is at ${result.target})${warning}` }, registered.status);
1631
- }
1632
- const body = { project: registered.body.project, ...(result.warning ? { warning: result.warning } : {}) };
1633
- return c.json(body, 200);
667
+ const projectsRoutes = createProjectsRoutes({
668
+ home: deps.home,
669
+ capabilities,
670
+ contexts,
671
+ workspaceProjects,
672
+ workspaceEvents,
673
+ checkoutProgress,
674
+ semaphore: deps.semaphore,
675
+ taskWebhookFetch: deps.taskWebhookFetch,
676
+ cloneRunner: deps.cloneRunner,
677
+ projectCommandRunner: deps.projectCommandRunner,
678
+ workspaceBrowseRoot,
1634
679
  });
1635
- /** Hosted containment for a path that may not exist yet: lexical for the
1636
- * path itself, realpath for its nearest existing ancestor (a symlink inside
1637
- * the browse root may point out of it). Same rule as `registerFolder`. */
1638
- const isInsideHostedBrowseRoot = async (candidate) => {
1639
- const browseRoot = resolveBrowseRoot(await workspaceBrowseRoot());
1640
- if (!(await isLexicallyInsideBrowseRoot(browseRoot, candidate)))
1641
- return false;
1642
- let existing = candidate;
1643
- while (!(await stat(existing).then(() => true, () => false))) {
1644
- const parent = dirname(existing);
1645
- if (parent === existing)
1646
- return false;
1647
- existing = parent;
1648
- }
1649
- return isInsideBrowseRoot(browseRoot, existing);
1650
- };
1651
- // Register an existing folder (multi-project spec, "Add project" — the
1652
- // folder-browser dialog's commit step, step 4.2). Workspace-level like its
1653
- // GET twin. Everything here is a guard; the registry write itself is one
1654
- // idempotent `registerProject` call.
1655
- /**
1656
- * The register-a-folder half of `POST /api/projects`, factored out so the
1657
- * checkout route (step 4.3) commits its fresh clone through the SAME guards
1658
- * and the same `project-added` emission rather than a second copy of them.
1659
- * A root the registry already holds is a success with `existing: true`; each
1660
- * route decides how to answer it.
1661
- */
1662
- const registerFolder = async (spelled, source) => {
1663
- // `~` is expanded for the same reason `/api/fs/browse` expands it: the
1664
- // dialog hands back absolute paths, but a hand-written body (curl, a
1665
- // future CLI) spells home the way a shell does.
1666
- const requested = expandTilde(spelled);
1667
- if (!isAbsoluteHostPath(requested)) {
1668
- return {
1669
- status: 400,
1670
- body: { error: `not a folder: ${spelled} is not an absolute path` },
1671
- };
1672
- }
1673
- // Hosted mode: the same root the picker is narrowed to, re-checked — see
1674
- // `isInsideBrowseRoot`. Local mode deliberately has NO containment: a
1675
- // project under `/srv/code` is a normal local setup and `hsq serve`
1676
- // registers it today.
1677
- //
1678
- // Containment is asked in two halves, around the stat, and the split is
1679
- // deliberate.
1680
- //
1681
- // The LEXICAL half runs BEFORE the stat, and that order is the security
1682
- // property: an out-of-root path must answer the SAME way whether or not it
1683
- // exists, or the route becomes the existence oracle fs-browse narrows the
1684
- // tree to prevent. Lexical, not realpath, because a realpath check answers
1685
- // `false` for a path that IS inside the root and merely absent — which
1686
- // would tell a hosted user who typo'd a folder under their own checkout
1687
- // root that it is "outside the browsable root".
1688
- const hostedBrowseRoot = capabilities().localHandoff
1689
- ? null
1690
- : resolveBrowseRoot(await workspaceBrowseRoot());
1691
- if (hostedBrowseRoot !== null) {
1692
- if (!(await isLexicallyInsideBrowseRoot(hostedBrowseRoot, requested))) {
1693
- // No resolved path in the message (fs-browse's rule): saying where the
1694
- // root is would hand a remote viewer the layout the narrowing hides.
1695
- return {
1696
- status: 400,
1697
- body: { error: 'folder is outside the browsable root' },
1698
- };
1699
- }
1700
- }
1701
- // Existence is checked HERE rather than left to `registerProject` (which
1702
- // degrades a failed realpath to a plain resolve): a registry full of
1703
- // `missing` rows the user never had is worse than a 400 they can act on.
1704
- const info = await stat(requested).catch(() => null);
1705
- if (!info?.isDirectory())
1706
- return { status: 400, body: { error: `no such folder: ${spelled}` } };
1707
- // The REALPATH half, now that the path is known to exist: a symlink inside
1708
- // the root pointing out of it spells as contained and is not. Same message
1709
- // as the lexical rejection, so the two halves stay indistinguishable from
1710
- // outside.
1711
- if (hostedBrowseRoot !== null && !(await isInsideBrowseRoot(hostedBrowseRoot, requested))) {
1712
- return {
1713
- status: 400,
1714
- body: { error: 'folder is outside the browsable root' },
1715
- };
1716
- }
1717
- // The boot-time auto-registration guard, applied to the manual gesture
1718
- // too: `$HOME` and Squawk's own task worktrees are exactly as wrong a
1719
- // project root when a human clicks "Add project" as when `hsq serve`
1720
- // would have registered them. Reachable from the dialog, which starts at
1721
- // `~` and can add the folder it is showing.
1722
- if (!(await shouldRegisterProject(requested))) {
1723
- return {
1724
- status: 400,
1725
- body: {
1726
- error: `not a project folder: ${spelled} is your home directory or a Squawk task worktree`,
1727
- },
1728
- };
1729
- }
1730
- // Asked BEFORE the write, because `registerProject` is idempotent and
1731
- // cannot tell us afterwards whether it appended or just bumped
1732
- // `lastOpenedAt`. Same realpath key the registry dedupes on.
1733
- const real = await realpath(requested).catch(() => requested);
1734
- let known = false;
1735
- try {
1736
- known = (await loadWorkspaceConfig(deps.home.workspaceConfig)).projects.some((p) => p.root === real);
1737
- }
1738
- catch {
1739
- // unreadable workspace — treat as unknown; the write below will fail loudly
1740
- }
1741
- let project;
1742
- try {
1743
- const entry = await registerProject(requested, source, deps.home);
1744
- project = toProjectListEntry(entry, await probeProjectStatus(entry.root));
1745
- }
1746
- catch (err) {
1747
- // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
1748
- return {
1749
- status: 500,
1750
- body: { error: err instanceof Error ? err.message : String(err) },
1751
- };
1752
- }
1753
- // Only a genuinely new project is an event — a re-add is a no-op for every
1754
- // open cockpit's sidebar.
1755
- if (!known)
1756
- workspaceEvents.emit('project-added', { project });
1757
- return { status: 200, body: { project }, existing: known };
1758
- };
1759
- // Deregister a project (multi-project spec, step 4.4 — Settings → Projects,
1760
- // the per-row "Remove"). READ THIS BEFORE TOUCHING THE HANDLER: the ONLY
1761
- // durable effect allowed here is dropping one entry from
1762
- // `~/.cezar/config.json`. There is deliberately no `rm`, no `rmdir`, no
1763
- // `RunStore.open` (which would `mkdir` `<root>/.ai/cezar/runs` and therefore
1764
- // WRITE into a folder the user just asked us to forget) anywhere below —
1765
- // `removeProject` is a registry filter and `contexts.dispose` only tears down
1766
- // in-process handles. Re-registering the same root later finds every task,
1767
- // worktree and transcript exactly where it was. The confirmation copy in the
1768
- // cockpit promises precisely this; the promise is kept here.
1769
- //
1770
- // A run this server is responsible for blocks the removal with a 409 (spec):
1771
- // deregistering mid-run would strand a live agent process under a root no
1772
- // route can resolve any more — the run would keep burning tokens with no
1773
- // cockpit able to show, message or cancel it.
1774
- const ACTIVE_RUN_STATUSES = new Set(['queued', 'running', 'waiting']);
1775
- /**
1776
- * How many of `projectId`'s runs this process is actively responsible for.
1777
- *
1778
- * Counted from the ALREADY-BUILT context only (`peek`, never `context()`):
1779
- * a project with no context in this process has no manager, therefore no
1780
- * agent to strand — and building one to answer the question would recover
1781
- * and resume runs on a project being deleted, which is the exact opposite of
1782
- * what the caller asked for. Reading the run index off disk instead was
1783
- * rejected for the same reason as the `rm` above: `RunStore.open` creates
1784
- * directories, and a stale `running` row left by a crashed process would
1785
- * become a 409 the user could never clear.
1786
- */
1787
- const activeRunCount = (projectId) => {
1788
- const ctx = contexts.peek(projectId);
1789
- if (!ctx)
1790
- return 0;
1791
- return ctx.store.queries.listRuns().filter((run) => ACTIVE_RUN_STATUSES.has(run.status)).length;
1792
- };
1793
680
  // ---- GUI clone (multi-project spec, step 4.3) ----------------------------
1794
681
  // "Add project → Clone from GitHub": clone into the checkout root, then
1795
682
  // register the result through `registerFolder` above (same guards, same
@@ -1801,454 +688,26 @@ export function createApp(deps) {
1801
688
  // events on the workspace stream. `checkoutId` is the cockpit's own
1802
689
  // correlation token, echoed on every event so two tabs cloning at once never
1803
690
  // render each other's progress.
1804
- // ---- workspace settings (multi-project spec, step 2.7) -------------------
1805
- // WORKSPACE-level routes: single-mount (never mirrored under /api/p/),
1806
- // same-origin. The config routes carry the settings UI's slice of
1807
- // `~/.cezar/config.json` — global knobs only; the registry stays on
1808
- // /api/projects above, and schemaVersion (a migration cursor, not a
1809
- // setting) is deliberately omitted.
1810
- const workspaceConfigBody = (config) => ({
1811
- browseRoot: config.browseRoot,
1812
- projectsDir: config.projectsDir,
1813
- archiveOnMerge: config.archiveOnMerge ?? null,
1814
- effectiveArchiveOnMerge: resolveGlobalArchiveOnMerge(config).enabled,
1815
- archiveOnMergeSource: resolveGlobalArchiveOnMerge(config).source,
1816
- composerDefaults: {
1817
- autonomous: config.composerDefaults.autonomous ?? null,
1818
- worktree: config.composerDefaults.worktree ?? null,
1819
- inheritedAutonomous: productEnv('AUTONOMOUS_DEFAULT') === '0'
1820
- ? false
1821
- : productEnv('AUTONOMOUS_DEFAULT') === '1'
1822
- ? true
1823
- : 'source-dependent',
1824
- inheritedWorktree: effectiveComposerDefault(undefined, productEnv('WORKTREE_DEFAULT'), true),
1825
- },
1826
- resources: {
1827
- maxParallel: config.resources.maxParallel,
1828
- maxMonitoringSessions: config.resources.maxMonitoringSessions,
1829
- monitoringWakeIntervalMinutes: config.resources.monitoringWakeIntervalMinutes,
1830
- autoResumeOnUsageLimit: config.resources.autoResumeOnUsageLimit,
1831
- memoryLimitMb: config.resources.memoryLimitMb,
1832
- worktreeRetentionDefault: config.resources.worktreeRetentionDefault,
1833
- },
1834
- // SPREAD, never `runner: maybeUndefined`: hono would type the key as always-present while
1835
- // `JSON.stringify` drops it, which is the exact drift `contract-parity` catches. And absent has
1836
- // to keep meaning "no opinion" here, or the fallback collapses into "always claude".
1837
- agentDefaults: {
1838
- ...(config.agentDefaults.runner !== undefined ? { runner: config.agentDefaults.runner } : {}),
1839
- ...(config.agentDefaults.models !== undefined ? { models: config.agentDefaults.models } : {}),
1840
- },
691
+ const workspaceConfigRoutes = createWorkspaceConfigRoutes({
692
+ home: deps.home,
693
+ semaphore: deps.semaphore,
694
+ archiveOnMergeChanged: deps.archiveOnMergeChanged,
1841
695
  });
1842
- // ---- chained family: workspace settings + GUI prefs (workspace-level) ----
1843
- const workspaceConfigRoutes = new Hono()
1844
- .get('/workspace/config', async (c) => c.json(workspaceConfigBody(await loadWorkspaceConfig(deps.home.workspaceConfig))))
1845
- .put('/workspace/config', jsonZodValidator(() => workspaceConfigUpdateSchema, { runners: { ids: ['agentDefaults.runner'], keys: ['agentDefaults.models'] } }), async (c) => {
1846
- const parsed = { data: c.req.valid('json') };
1847
- const { browseRoot, projectsDir, archiveOnMerge, resources } = parsed.data;
1848
- for (const [configuredRoot, create] of [
1849
- [browseRoot, false],
1850
- [projectsDir, true],
1851
- ]) {
1852
- if (configuredRoot === undefined)
1853
- continue;
1854
- // Validated ON CHANGE, never at load (spec): browse roots must already
1855
- // exist; checkout roots use `mkdir -p`. Both get a real write probe.
1856
- // Any failure → 400 and NO change persisted.
1857
- const expanded = expandTilde(configuredRoot);
1858
- if (!isAbsoluteHostPath(expanded))
1859
- return c.json({ error: `not writable: ${configuredRoot} is not an absolute path` }, 400);
1860
- if (!create) {
1861
- try {
1862
- if (!(await stat(expanded)).isDirectory()) {
1863
- return c.json({ error: `browse folder is not a directory: ${configuredRoot}` }, 400);
1864
- }
1865
- }
1866
- catch (err) {
1867
- if (err.code === 'ENOENT') {
1868
- return c.json({ error: `browse folder does not exist: ${configuredRoot}` }, 400);
1869
- }
1870
- return c.json({ error: `browse folder unavailable: ${err instanceof Error ? err.message : String(err)}` }, 400);
1871
- }
1872
- }
1873
- const probeError = await probeWritableDir(expanded, create);
1874
- if (probeError !== null)
1875
- return c.json({ error: `not writable: ${probeError}` }, 400);
1876
- }
1877
- let written;
1878
- try {
1879
- written = await mergeWriteWorkspaceConfig((config) => {
1880
- applyWorkspaceConfigPatch(config, parsed.data);
1881
- }, deps.home);
1882
- }
1883
- catch (err) {
1884
- // e.g. a read-only home — nothing was persisted (atomic tmp+rename).
1885
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1886
- }
1887
- if (archiveOnMerge !== undefined)
1888
- deps.archiveOnMergeChanged?.();
1889
- // A resource change takes effect WITHOUT a restart: refresh the shared
1890
- // semaphore's in-memory snapshot and pump every manager (step 2.5's hook).
1891
- if (resources !== undefined)
1892
- await deps.semaphore?.refresh();
1893
- return c.json(workspaceConfigBody(written));
1894
- })
1895
- // Global GUI state (`~/.cezar/ui-state.json`) — same parse/key-cap/shallow-
1896
- // merge semantics as the per-repo /api/v1/ui-state route below (the shared half
1897
- // is `uiStateBodySchema`), but backed by the workspace file.
1898
- .get('/workspace/ui-state', async (c) => c.json(await readWorkspaceUiState(deps.home.workspaceUiState, deps.home)))
1899
- // The tighter body cap rides on `use` rather than inline on the route: `bodyLimit` is typed
1900
- // as a bare MiddlewareHandler, and passing one to `.put()` collapses the route's schema, so
1901
- // the PUT went missing from `AppType` and `hc` could not see its body at all. `use` runs at
1902
- // the same point (before the handler, so the cap still precedes any read) and leaves the
1903
- // chain's type accumulation alone. Method-agnostic here, which the GET does not mind.
1904
- .use('/workspace/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
1905
- .put('/workspace/ui-state', jsonZodValidator(setWorkspaceUiStateInputSchema, { runners: { strictKeys: { path: 'dismissedProviderAuthFailures', also: REMOVED_RUNNER_IDS } } }), async (c) => {
1906
- const parsed = { data: c.req.valid('json') };
1907
- try {
1908
- return c.json(await mergeWriteWorkspaceUiState((state) => ({
1909
- ...state,
1910
- ...parsed.data,
1911
- }), deps.home));
1912
- }
1913
- catch (err) {
1914
- // A read-only home degrades to an unsaved pref, never a crash.
1915
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1916
- }
1917
- });
1918
- // Partial updates only — absent keys stay untouched. Bounds mirror the
1919
- // workspace schema (src/workspace/config.ts, step 1.2) exactly, so a value
1920
- // this route accepts can never be degraded away by the next load's `.catch`.
1921
- // ---- chained family: filesystem browse (workspace-level) ----
1922
- const fsBrowseRoutes = new Hono()
1923
- .get('/fs/browse', queryZodValidator(browseQuerySchema), async (c) => {
1924
- const query = c.req.valid('query');
1925
- const root = resolveBrowseRoot(await workspaceBrowseRoot());
1926
- const result = await browseDirectory({
1927
- root,
1928
- path: query.path,
1929
- showHidden: query.showHidden === '1',
1930
- });
1931
- if (!result.ok)
1932
- return c.json({ error: result.error }, result.status);
1933
- return c.json(result.body);
1934
- });
1935
- // ---- chained family: skills (project-scoped) ----
1936
- const skillsRoutes = new Hono()
1937
- .get('/runner-skills', queryZodValidator(runnerSkillsQuerySchema, { runners: { ids: ['runner'] } }), async (c) => {
1938
- if (c.req.valid('query').account !== undefined && !capabilities().localHandoff)
1939
- return c.json(hostedProfileRefusal, 409);
1940
- const result = await readRunnerSkills(c.req.valid('query'), c.get('project').root, deps.home, skillCatalog, resolveWorkspaceProfile);
1941
- if ('error' in result)
1942
- return c.json(result, 400);
1943
- return c.json(result);
1944
- });
1945
- // ---- chained family: GUI prefs / ui-state (project-scoped) ----
1946
- const uiStateRoutes = new Hono()
1947
- .get('/ui-state', async (c) => c.json(await readUiState(c.get('project').root)))
1948
- // On `use`, not inline on the route — see the workspace ui-state PUT above.
1949
- .use('/ui-state', bodyLimit({ maxSize: UI_STATE_BODY_LIMIT }))
1950
- .put('/ui-state', jsonZodValidator(uiStateBody), async (c) => {
1951
- // `.passthrough()` keeps unknown prefs, but a
1952
- // single request may not stuff an unbounded key set (#429) — the shared
1953
- // schema+cap half of both ui-state routes lives in `uiStateBody`.
1954
- const patch = c.req.valid('json');
1955
- try {
1956
- return c.json(await mergeWriteProjectUiState(c.get('project').root, (current) => ({ ...current, ...patch })));
1957
- }
1958
- catch (err) {
1959
- return c.json({ error: err instanceof Error ? err.message : String(err) }, 500);
1960
- }
1961
- });
1962
- // ---- chained family: workflows (project-scoped) --------------------------
1963
- // One chained expression, mounted by `createApp` into BOTH the legacy `api`
1964
- // table and the versioned `v1` one — see `healthRoutes` for why the chain
1965
- // shape (not the statement shape) is what carries the types.
1966
- const workflowsRoutes = new Hono()
1967
- .get('/workflows', async (c) => c.json(await loadWorkflows(c.get('project').root)))
1968
- // Save an approved plan as a reusable chain (spec 008): YAML in
1969
- // `.ai/cezar/workflows/<slug>.yaml` — from then on it's in the dropdown
1970
- // like any other workflow.
1971
- .post('/workflows', jsonZodValidator(saveWorkflowSchema, { runners: { ids: ['steps.*.runner'] } }), async (c) => {
1972
- const { root: repoRoot } = c.get('project');
1973
- const parsed = { data: c.req.valid('json') };
1974
- const steps = parsed.data.steps ?? skillsToSteps(parsed.data.skills ?? []);
1975
- const issue = stepsIssue(steps);
1976
- if (issue)
1977
- return c.json({ error: issue }, 400);
1978
- const slug = slugify(parsed.data.name) || 'chain';
1979
- const dir = join(projectPaths(repoRoot).write, 'workflows');
1980
- const path = join(dir, `${slug}.yaml`);
1981
- // Pure skill stacks are written in the portable compact form (spec 012) —
1982
- // `name` + `skills:` — so the file imports cleanly in any repo.
1983
- const stack = skillStackOf(steps);
1984
- const doc = {
1985
- name: parsed.data.name,
1986
- ...(parsed.data.description ? { description: parsed.data.description } : {}),
1987
- ...(stack ? { skills: stack } : { steps }),
1988
- };
1989
- try {
1990
- await mkdir(dir, { recursive: true });
1991
- // `wx` = fail if the file exists — no silent overwrite of a chain.
1992
- await writeFile(path, stringifyYaml(doc), {
1993
- encoding: 'utf8',
1994
- flag: parsed.data.overwrite ? 'w' : 'wx',
1995
- });
1996
- }
1997
- catch (err) {
1998
- if (err instanceof Error && 'code' in err && err.code === 'EEXIST') {
1999
- return c.json({ error: `workflow file already exists: ${path}`, exists: true }, 409);
2000
- }
2001
- const message = err instanceof Error ? err.message : String(err);
2002
- return c.json({ error: message }, 500);
2003
- }
2004
- return c.json({ path, name: parsed.data.name }, 201);
2005
- })
2006
- // Delete saved workflows only; built-ins always remain (spec 012).
2007
- .delete('/workflows/:name', async (c) => {
2008
- const result = await deleteSavedWorkflow(c.get('project').root, c.req.param('name'));
2009
- if ('error' in result)
2010
- return c.json({ error: result.error }, result.status);
2011
- return c.json({ ok: true, path: result.path });
2012
- })
2013
- // Import support for the builder (spec 012): parse + validate a pasted
2014
- // workflow YAML (either form) and hand back the normalized definition. The
2015
- // server owns YAML parsing — the GUI stays dependency-free.
2016
- .post('/workflows/parse', jsonZodValidator(parseWorkflowSchema), async (c) => {
2017
- const parsed = { data: c.req.valid('json') };
2018
- let raw;
2019
- try {
2020
- raw = parseYaml(parsed.data.yaml);
2021
- }
2022
- catch (err) {
2023
- const message = err instanceof Error ? err.message : String(err);
2024
- return c.json({ error: `not valid YAML: ${message}` }, 400);
2025
- }
2026
- const doc = workflowFileSchema.safeParse(raw);
2027
- if (!doc.success) {
2028
- return c.json({ error: doc.error.issues.map((i) => i.message).join('; ') }, 400);
2029
- }
2030
- const normalized = normalizeWorkflowDoc(doc.data);
2031
- const issue = stepsIssue(normalized.steps);
2032
- if (issue)
2033
- return c.json({ error: issue }, 400);
2034
- return c.json(normalized);
2035
- });
2036
- // ---- chained family: plan (project-scoped) ----
2037
- const planRoutes = new Hono()
2038
- .post('/plan', jsonZodValidator(planSchema), async (c) => {
2039
- const { root: repoRoot, manager } = c.get('project');
2040
- const parsed = { data: c.req.valid('json') };
2041
- const planner = resolveRunnerId((await loadConfig(repoRoot, deps.home)).defaultRunner);
2042
- const blocked = await providerActionError([planner], { repoRoot, picks: { [planner]: parsed.data.agentProfile } });
2043
- if (blocked)
2044
- return c.json({ error: blocked }, 409);
2045
- const badProfile = await agentProfileRefusal(resolveWorkspaceProfile, planner, parsed.data.agentProfile);
2046
- if (badProfile)
2047
- return c.json({ error: badProfile.error }, badProfile.status);
2048
- return c.json(await planChain(repoRoot, parsed.data.task, skillCatalog, deps.home, manager.createRunner, parsed.data.agentProfile));
2049
- });
2050
- const manualChecks = new Map();
2051
- /**
2052
- * The automations gate (#801): with `CEZ_AUTOMATIONS=0`, every route of the feature
2053
- * answers 409 before touching a store, a lease or GitHub.
2054
- *
2055
- * Written as MIDDLEWARE rather than a line in each handler so the family cannot drift: a route
2056
- * added to either chain below inherits the gate from its path, where a per-handler check is one
2057
- * omission away from an ungated endpoint.
2058
- *
2059
- * Registered against EXPLICIT paths, never `use('*')`. Both chains are mounted with
2060
- * `.route('/', …)` alongside a dozen unrelated sub-apps, and `route()` re-registers a sub-app's
2061
- * middleware under the mount prefix — so a `'*'` here would gate the entire `/api/v1` surface,
2062
- * including `/health`. The two-line pairing (`/automations` and `/automations/*`) is what makes
2063
- * a path match both the collection and everything under it.
2064
- */
2065
- const requireAutomations = async (c, next) => {
2066
- if (!capabilities().automations)
2067
- return c.json({ error: AUTOMATIONS_OFF }, 409);
2068
- await next();
2069
- };
2070
- /** The schedule runner for a route's project: launches into that project's own run manager. */
2071
- const scheduleHandle = (project) => {
2072
- const timeZone = localTimeZone();
2073
- return {
2074
- projectId: project.id,
2075
- store: project.automationStore,
2076
- timeZone,
2077
- launch: (definition, occurrence, receiptId) => launchScheduledRun({
2078
- root: project.root,
2079
- manager: project.manager,
2080
- store: project.store,
2081
- definition,
2082
- occurrence,
2083
- receiptId,
2084
- projectName: basename(project.root),
2085
- timeZone,
2086
- }),
2087
- onChange: (automationId, revision) => emitAutomationChange(project, automationId, revision),
2088
- // A route's write settles a crash-left reservation first, as the timer does (#1465).
2089
- reconcile: async () => { reconcileAutomationReceipts(project.automationStore, project.store); },
2090
- };
2091
- };
2092
- /** The automations family's behavior, shared with the session tools (#1465). */
2093
- const automationService = createAutomationService({ home: deps.home,
2094
- timeZone: localTimeZone,
2095
- discovery: { models: modelCatalog, providers: () => providerStatus() },
2096
- scheduleHandle: (project) => scheduleHandle(project),
2097
- emitChange: (project, automationId, revision, deleted) => emitAutomationChange(project, automationId, revision, deleted),
2098
- changed: automationsChanged,
2099
- // Awaits the driver's settled probe (per-repo cache + in-flight dedupe, 5 s timeout, never
2100
- // throws): a "still being checked" answer would leave the cockpit's GitHub option disabled
2101
- // because it does not refetch when the probe completes. `/health` keeps `detectCached`.
2102
- githubAvailability: async (root) => {
2103
- const forge = resolveProjectForge(await getRepoInfo(root));
2104
- return forge ? forge.detect() : { available: false, reason: 'No GitHub remote is configured' };
2105
- },
2106
- hasGithubRemote: async (root) => Boolean(resolveProjectForge(await getRepoInfo(root))), });
2107
- // #1465: every project's manager gets the schedule tools over this service. A manager reads
2108
- // them at call time, so a session recovered before its project's context finished building
2109
- // reaches them once this runs. The tools themselves are disabled by CEZ_AUTOMATIONS=0.
2110
- const attachAutomationTools = (project) => project.manager.setAutomationTools?.(createAutomationToolService(automationService, project, { timeZone: localTimeZone }));
2111
- attachAutomationTools(bootContext);
2112
- for (const id of contexts.ids()) {
2113
- const ctx = contexts.peek(id);
2114
- if (ctx)
2115
- attachAutomationTools(ctx);
2116
- }
2117
- contexts.onContextBuilt(attachAutomationTools);
2118
- // ---- chained family: GitHub automations (project-scoped) ----
2119
- // Every handler below reads `c.get('project')` — the definitions, their runtime state and the
2120
- // execution log are per-project files — so the family is project-scoped and mounted with the
2121
- // rest of the mirrored table. The one exception is the manual-check read, which touches no
2122
- // project at all; it is its own workspace-level family below.
2123
- const automationsRoutes = new Hono()
2124
- .use('/automations', requireAutomations)
2125
- .use('/automations/*', requireAutomations)
2126
- .use('/automation-log', requireAutomations)
2127
- .use('/automation-log/*', requireAutomations)
2128
- .get('/automations', queryZodValidator(automationListQuerySchema), async (c) => {
2129
- return c.json(await automationService.list(c.get('project'), c.req.valid('query')));
2130
- })
2131
- .post('/automations', jsonZodValidator(() => automationCreateSchema, { runners: { ids: ['task.runner', 'task.steps.*.runner'] } }), async (c) => {
2132
- const result = await automationService.create(c.get('project'), c.req.valid('json'));
2133
- if (!result.ok)
2134
- return c.json({ error: result.error }, result.status);
2135
- const once = onceCreateAnswer(result.automation);
2136
- return c.json({ automation: result.automation, ...(once ? { once } : {}) }, 201);
2137
- })
2138
- .get('/automations/:id', (c) => {
2139
- const result = automationService.get(c.get('project'), c.req.param('id'));
2140
- if (!result.ok)
2141
- return c.json({ error: result.error }, result.status);
2142
- return c.json(result.body);
2143
- })
2144
- .put('/automations/:id', jsonZodValidator(() => automationUpdateSchema, { runners: { ids: ['task.runner', 'task.steps.*.runner'] } }), async (c) => {
2145
- const result = await automationService.update(c.get('project'), c.req.param('id'), c.req.valid('json'));
2146
- if (!result.ok)
2147
- return c.json({ error: result.error }, result.status);
2148
- return c.json({ automation: result.automation });
2149
- })
2150
- .delete('/automations/:id', async (c) => {
2151
- const result = await automationService.remove(c.get('project'), c.req.param('id'));
2152
- if (!result.ok)
2153
- return c.json({ error: result.error }, result.status);
2154
- return c.body(null, 204);
2155
- })
2156
- .post('/automations/:id/enable', async (c) => {
2157
- const result = await automationService.enable(c.get('project'), c.req.param('id'));
2158
- if (!result.ok)
2159
- return c.json({ error: result.error }, result.status);
2160
- return c.json({ automation: result.automation });
2161
- })
2162
- .post('/automations/:id/pause', async (c) => {
2163
- const result = await automationService.pause(c.get('project'), c.req.param('id'));
2164
- if (!result.ok)
2165
- return c.json({ error: result.error }, result.status);
2166
- return c.json({ automation: result.automation });
2167
- })
2168
- // One-time schedules only (#1465): archive without launching. 409 for any other automation.
2169
- .post('/automations/:id/cancel', async (c) => {
2170
- const result = await automationService.cancel(c.get('project'), c.req.param('id'));
2171
- if (!result.ok)
2172
- return c.json({ error: result.error }, result.status);
2173
- return c.json({ automation: result.automation });
2174
- })
2175
- // Run now: a schedule fired once by hand, paused or not, outside the timer and under the same
2176
- // lease. A repeating schedule keeps `nextRunAt` and `enabled`; a one-time schedule is consumed
2177
- // (archived) by it. A GitHub automation's equivalent is `check`.
2178
- .post('/automations/:id/run', async (c) => {
2179
- const result = await automationService.runNow(c.get('project'), c.req.param('id'));
2180
- if (!result.ok)
2181
- return c.json({ error: result.error }, result.status);
2182
- return c.json({ runId: result.runId }, 202);
2183
- })
2184
- // The body is validated as MIDDLEWARE, which is what puts it in the route type — and moves
2185
- // the 400 ahead of this route's 404: `POST /automations/<unknown>/check` with a malformed
2186
- // body now answers 400 rather than 404. Nothing else about either answer changed.
2187
- .post('/automations/:id/check', jsonZodValidator(() => automationCheckRequestSchema), async (c) => {
2188
- const project = c.get('project');
2189
- const store = project.automationStore;
2190
- const automation = store.get(c.req.param('id'));
2191
- if (!automation)
2192
- return c.json({ error: 'not found' }, 404);
2193
- if (!isGithubAutomation(automation))
2194
- return c.json({ error: 'a schedule has nothing to preview; use run' }, 409);
2195
- const parsed = { data: c.req.valid('json') };
2196
- // `string`, not `randomUUID`'s template-literal type: the wire carries an opaque id, and
2197
- // leaking `${string}-${string}-…` into the route type would make the contract describe the
2198
- // generator rather than the answer.
2199
- const id = randomUUID();
2200
- const check = { id, automationId: automation.id, mode: parsed.data.mode, status: 'queued', createdAt: new Date().toISOString() };
2201
- if (manualChecks.size >= 200)
2202
- manualChecks.delete(manualChecks.keys().next().value);
2203
- manualChecks.set(id, check);
2204
- void withProjectAdmission(project.dataDir, async function manualCheck() {
2205
- check.status = 'running';
2206
- try {
2207
- const repository = githubRepository(project.root, (await getRepoInfo(project.root))?.remote);
2208
- if (!repository)
2209
- throw new Error('No GitHub remote is configured');
2210
- const scheduler = new ProjectAutomationScheduler({
2211
- projectId: project.id,
2212
- store,
2213
- timeZone: localTimeZone(),
2214
- github: { ...repository, poller: new GithubPoller() },
2215
- launch: parsed.data.mode === 'execute'
2216
- ? (definition, candidate, receiptId) => launchAutomationRun({ root: project.root, manager: project.manager, store: project.store, definition, candidate, receiptId })
2217
- : undefined,
2218
- onChange: (automationId, revision) => emitAutomationChange(project, automationId, revision),
2219
- });
2220
- const result = await scheduler.check(automation, parsed.data.mode);
2221
- Object.assign(check, { status: 'complete', completedAt: new Date().toISOString(), matches: result.candidates.length, truncated: result.truncated });
2222
- }
2223
- catch (error) {
2224
- Object.assign(check, { status: 'error', completedAt: new Date().toISOString(), error: error instanceof Error ? error.message : String(error) });
2225
- }
2226
- }, (error) => { Object.assign(check, { status: 'error', completedAt: new Date().toISOString(), error: error.message }); });
2227
- return c.json({ checkId: id }, 202);
2228
- })
2229
- .get('/automation-log', queryZodValidator(automationLogQuerySchema), (c) => {
2230
- return c.json({ records: c.get('project').automationStore.logs(c.req.valid('query')) });
2231
- })
2232
- .post('/automation-log/:receiptId/retry', async (c) => {
2233
- const result = await retryAutomationLogReceipt({
2234
- project: c.get('project'),
2235
- receiptId: c.req.param('receiptId'),
2236
- scheduleHandle,
2237
- emitChange: emitAutomationChange,
2238
- });
2239
- if (result.status === 202)
2240
- return c.json(result.body, 202);
2241
- return result.status === 404 ? c.json(result.body, 404) : c.json(result.body, 409);
2242
- });
2243
- // ---- chained family: manual automation checks (workspace-level) ----
2244
- // Workspace-level because the handler reads no project: a check lives in the server-memory map
2245
- // above, keyed by an unguessable id that the project-scoped POST hands back. Mounting it under
2246
- // `/api/v1/p/:projectId` too would be a second spelling of a lookup that consults no project.
2247
- const automationChecksRoutes = new Hono()
2248
- .use('/automation-checks/*', requireAutomations)
2249
- .get('/automation-checks/:checkId', (c) => {
2250
- const check = manualChecks.get(c.req.param('checkId'));
2251
- return check ? c.json(check) : c.json({ error: 'not found' }, 404);
696
+ const fsBrowseRoutes = createFsBrowseRoutes(workspaceBrowseRoot);
697
+ const skillsRoutes = createSkillsRoutes({ home: deps.home, capabilities, skillCatalog, resolveWorkspaceProfile });
698
+ const uiStateRoutes = createUiStateRoutes();
699
+ const workflowsRoutes = createWorkflowsRoutes();
700
+ const planRoutes = createPlanRoutes({ home: deps.home, skillCatalog, providerActionError, resolveWorkspaceProfile });
701
+ const { automationsRoutes, automationChecksRoutes } = createAutomationsRouteBundles({
702
+ home: deps.home,
703
+ capabilities,
704
+ modelCatalog,
705
+ providerStatus,
706
+ bootContext,
707
+ contexts,
708
+ workspaceEvents,
709
+ automationsChanged,
710
+ resolveProjectForge,
2252
711
  });
2253
712
  // ---- runs ----------------------------------------------------------------
2254
713
  // Additive `usage` field (#348): the latest CPU/RSS/proc-count sample of the
@@ -3119,33 +1578,7 @@ export function createApp(deps) {
3119
1578
  release();
3120
1579
  }
3121
1580
  });
3122
- // ---- chained family: open-targets (project-scoped) ----
3123
- const openTargetsRoutes = new Hono()
3124
- .get('/open-targets', (c) => c.json({ targets: capabilities().localHandoff ? detectOpenTargets() : [] }))
3125
- // Open the PROJECT ROOT itself (Settings → "Project folder" → Open with). The run route
3126
- // above opens a task worktree and needs a run to name one; this is the repo the cockpit is
3127
- // scoped to, which the scope middleware has already resolved — so no path is accepted from
3128
- // the client and there is nothing to contain.
3129
- .post('/open-in', jsonZodValidator(openProjectInSchema), async (c) => {
3130
- const { root } = c.get('project');
3131
- if (!capabilities().localHandoff) {
3132
- return c.json({ error: 'local handoff is disabled — this cockpit runs in hosted mode (CEZ_REMOTE)' }, 409);
3133
- }
3134
- const { target } = c.req.valid('json');
3135
- // Refused here rather than left to the menu, on the same principle as the accounts route:
3136
- // a `cli:<runner>` handoff would START AN AGENT in the checkout everything else runs in a
3137
- // worktree to protect. Which app APPLIES is a property of the route, not of one client.
3138
- if (agentCliRunner(target) !== null) {
3139
- return c.json({ error: 'agent CLIs open a task worktree, not the project folder' }, 400);
3140
- }
3141
- if (!detectOpenTargets().some((candidate) => candidate.id === target)) {
3142
- return c.json({ error: `no such app on this machine: ${target}` }, 400);
3143
- }
3144
- const opened = await openApp(target, root);
3145
- if (!opened)
3146
- return c.json({ error: `could not open ${target}`, path: root }, 409);
3147
- return c.json({ opened: true, path: root });
3148
- });
1581
+ const openTargetsRoutes = createOpenTargetsRoutes({ capabilities, openApp });
3149
1582
  // Agent screenshots and user attachments — what the run manager persisted out of tool
3150
1583
  // results and pasted messages (`persistAttachment`). `basename` pins reads inside the
3151
1584
  // run's own dir.
@@ -3168,685 +1601,19 @@ export function createApp(deps) {
3168
1601
  txt: 'text/plain; charset=utf-8',
3169
1602
  md: 'text/plain; charset=utf-8',
3170
1603
  };
3171
- // ---- chained family: worktrees (project-scoped) ----
3172
- const worktreesRoutes = new Hono()
3173
- .get('/worktrees', async (c) => {
3174
- const { root: repoRoot, store } = c.get('project');
3175
- // The keep-limit the panel reports is the one the enforcer will actually
3176
- // apply — inherited from the workspace default when this repo sets none.
3177
- const keep = await resolveWorktreeRetention(repoRoot, deps.home);
3178
- const withWorktree = store.queries.listRunsWithWorktree();
3179
- // Listing is on-disk dirs only; parent liveness for #575 reads the store by id
3180
- // so a live `worktree: false` parent is not treated as gone (#570 honesty).
3181
- const runs = withWorktree.filter((r) => r.worktreePath && existsSync(r.worktreePath));
3182
- // The rows the enforcer would reclaim right now: reclaimable AND past the newest `keep`.
3183
- const getRun = memoizeRead((id) => store.getRun(id));
3184
- const workersOf = memoizeRead((id) => store.queries.listWorkersOf(id));
3185
- const pastKeep = new Set(selectReclaimableWorktrees(withWorktree, keep, getRun, workersOf));
3186
- const worktrees = await Promise.all(runs.map(async (r) => ({
3187
- runId: r.id,
3188
- title: r.title ?? r.id,
3189
- status: r.status,
3190
- branch: r.branch ?? null,
3191
- // POSIX `du` — degrades to null (Windows / du missing / error); never blocks.
3192
- sizeBytes: await cachedWorktreeSizeBytes(r.worktreePath),
3193
- finishedAt: r.finishedAt ?? null,
3194
- reclaimable: isReclaimable(r, getRun, workersOf),
3195
- pastKeep: pastKeep.has(r.id),
3196
- })));
3197
- // Total is null when any size degraded, so the panel never shows a wrong sum.
3198
- const totalBytes = worktrees.some((w) => w.sizeBytes === null)
3199
- ? null
3200
- : worktrees.reduce((sum, w) => sum + (w.sizeBytes ?? 0), 0);
3201
- return c.json({ worktrees, totalBytes, keep });
3202
- })
3203
- .post('/worktrees/reclaim', jsonZodValidator(() => reclaimBodySchema, { absent: ({}), message: 'invalid body' }), async (c) => {
3204
- const { root: repoRoot, store } = c.get('project');
3205
- // The body is validated (an empty or `{}` one is accepted) but carries nothing this
3206
- // handler reads; retention is best-effort, so 200 always.
3207
- const { manager } = c.get('project');
3208
- const reclaimed = await reclaimWorktrees(repoRoot, store, await resolveWorktreeRetention(repoRoot, deps.home), {
3209
- claim: (run) => manager.claimWorktreeReclaim(run.id),
3210
- previewHost: deps.previewHost,
3211
- });
3212
- if (reclaimed.length > 0) {
3213
- forgetRepoBranches(repoRoot);
3214
- forgetRepoRead(repoRoot);
3215
- }
3216
- return c.json({ reclaimed });
3217
- })
3218
- // One row's reclaim (issue 08 §B4): the DIRECTORY only, by retention's own rule and helper —
3219
- // the `cez/<id8>` branch is kept, which is what makes this safe to offer on every finished
3220
- // row. `/runs/:id/remove-worktree` (directory AND branch) stays the task screen's action.
3221
- .post('/worktrees/:runId/reclaim', paramZodValidator(reclaimRunParamsSchema), async (c) => {
3222
- const { root: repoRoot, store } = c.get('project');
3223
- const checkout = runCheckout(c.get('project'), c.req.valid('param').runId, 'remove', {
3224
- claim: 'reclaim', checksActive: false, deletion: 'inline',
3225
- nullClaimError: 'this worktree is in use or already reclaimed — only a finished task\'s worktree can be reclaimed',
3226
- });
3227
- if ('status' in checkout)
3228
- return c.json(checkout.body, checkout.status);
3229
- const { run, release } = checkout;
3230
- const worktreeReclaimedAt = await reclaimWorktree(repoRoot, store, run, { previewHost: deps.previewHost }).finally(release);
3231
- if (!worktreeReclaimedAt) {
3232
- return c.json({ error: await reclaimCheckoutError(run) }, 409);
3233
- }
3234
- forgetRepoBranches(repoRoot);
3235
- forgetRepoRead(repoRoot);
3236
- return c.json({ runId: run.id, worktreeReclaimedAt });
3237
- });
3238
- // ---- chained family: SSE streams (project-scoped) ----
3239
- const sseRoutes = new Hono()
3240
- .get('/runs/:id/events', paramZodValidator(runIdParamSchema), queryZodValidator(runEventsQuerySchema), async (c) => {
3241
- const { store, dataDir } = c.get('project');
3242
- const { id } = c.req.valid('param');
3243
- if (!store.getRun(id))
3244
- return c.json({ error: 'not found' }, 404);
3245
- const query = c.req.valid('query');
3246
- if (query.cursor) {
3247
- try {
3248
- await validateLiveCursor(store.claims.sourceDataDir(id), id, query.cursor);
3249
- }
3250
- catch (error) {
3251
- if (error instanceof HistoryCursorError)
3252
- return c.json({ error: error.message }, error.status);
3253
- throw error;
3254
- }
3255
- }
3256
- const lastEventId = Number.parseInt(c.req.header('Last-Event-ID') ?? '', 10);
3257
- const requestedAfter = Math.max(query.afterSeq ?? 0, Number.isSafeInteger(lastEventId) && lastEventId >= 0 ? lastEventId : 0);
3258
- return streamSSENoBuffer(c, async (stream) => {
3259
- const controller = new AbortController();
3260
- const stop = () => controller.abort();
3261
- const onRun = (write) => {
3262
- if (write.run.id === id)
3263
- void stream.writeSSE({ event: 'run', data: JSON.stringify(currentRecord(store, write)) });
3264
- };
3265
- const unsubscribe = store.lifecycle.subscribe({ 'run.created': onRun, 'run.updated': onRun });
3266
- stream.onAbort(() => { stop(); unsubscribe(); });
3267
- const feed = subscribeRunFeed({ store, dataDir }, {
3268
- projectId: c.get('project').id, runId: id, afterSeq: requestedAfter,
3269
- ...(query.cursor ? { cursor: query.cursor } : {}),
3270
- }, {
3271
- event: async (event) => {
3272
- await stream.writeSSE({ id: String(event.seq), event: isV2WireEventType(event.type) ? 'ui-event' : 'run-event', data: JSON.stringify(event) });
3273
- },
3274
- reset: () => { stop(); void stream.close(); },
3275
- // The legacy full-replay endpoint predates the finite batch limit. Preserve its
3276
- // ability to deliver a large persisted event; new multiplex clients rehydrate it.
3277
- }, controller.signal, Infinity);
3278
- const run = store.getRun(id);
3279
- if (run)
3280
- await stream.writeSSE({ event: 'run', data: JSON.stringify(run) });
3281
- try {
3282
- while (!stream.aborted && !controller.signal.aborted) {
3283
- await stream.writeSSE({ event: 'ping', data: '' });
3284
- await stream.sleep(15_000);
3285
- }
3286
- }
3287
- finally {
3288
- stop();
3289
- unsubscribe();
3290
- await feed;
3291
- }
3292
- });
3293
- })
3294
- // Global SSE: run-summary updates for the list view + inbox changes.
3295
- // Scoped `/p/:projectId/events` carries that project's stream in today's
3296
- // shape; the legacy unprefixed alias stays bound to the boot project ONLY
3297
- // (spec "Legacy aliases" — widening it would be a silent behavioral break;
3298
- // the all-project stream arrives as `/api/workspace/events` in step 2.8).
3299
- .get('/events', (c) => {
3300
- const { store } = c.get('project');
3301
- return streamSSENoBuffer(c, async (stream) => {
3302
- const onRun = (write) => void stream.writeSSE({ event: 'run', data: JSON.stringify(currentRecord(store, write)) });
3303
- const onDeleted = ({ runId: id }) => void stream.writeSSE({
3304
- event: 'run-deleted',
3305
- data: JSON.stringify({ id }),
3306
- });
3307
- // Live resource telemetry (#348): the sampler ticks ~every 2 s only
3308
- // while some run has a registered process; each tick is relayed as one
3309
- // `usage` message (runId → {cpuPct, rssBytes, procCount}). Never
3310
- // persisted — the NDJSON transcripts stay usage-free. The sampler is
3311
- // module-global, so a snapshot carries EVERY project's runs — split it
3312
- // by ownership and relay only this project's rows, never a stamped
3313
- // whole (multi-project spec, step 2.4: filtered, not stamped).
3314
- const offUsage = onUsage((usage) => {
3315
- const owned = {};
3316
- for (const [runId, sample] of Object.entries(usage)) {
3317
- if (store.getRun(runId))
3318
- owned[runId] = sample;
3319
- }
3320
- void stream.writeSSE({ event: 'usage', data: JSON.stringify(owned) });
3321
- });
3322
- const unsubscribe = store.lifecycle.subscribe({ 'run.created': onRun, 'run.updated': onRun, 'run.deleted': onDeleted });
3323
- stream.onAbort(() => {
3324
- unsubscribe();
3325
- offUsage();
3326
- });
3327
- while (!stream.aborted) {
3328
- await stream.writeSSE({ event: 'ping', data: '' });
3329
- await stream.sleep(15_000);
3330
- }
3331
- });
3332
- });
3333
- // ---- chained family: workspace SSE stream (workspace-level) ----
3334
- const workspaceEventsRoutes = new Hono()
3335
- // `?runs=summary` (hearsay-tools/cezarion#2730) carries list rows with a contiguous `seq`
3336
- // instead of full records; without it the stream stays byte-identical for older readers.
3337
- .get('/workspace/events', queryZodValidator(workspaceEventsQuerySchema), (c) => {
3338
- const mode = c.req.valid('query').runs === 'summary' ? 'summary' : 'full';
3339
- return streamSSENoBuffer(c, async (stream) => {
3340
- // The boot context never lives in the lazy map: the feed keeps it under its registry id
3341
- // (`resolveBootProject`, NOT `bootContext.id`, which may be the reserved alias when
3342
- // registration was suppressed).
3343
- const bootProject = await resolveBootProject();
3344
- // Attach, relay and `ready` happen in one synchronous block, so no frame can slip
3345
- // between the feed's `seq` and this connection's `ready`.
3346
- const detach = workspaceRunFeed.connect(bootProject, mode, (event, data) => void stream.writeSSE({ event, data }));
3347
- // Workspace-level events (project-added / project-removed / checkout-progress plus
3348
- // host-wide unstamped provider-status) — relayed verbatim under their own names. The
3349
- // feed detaches a removed project's store itself.
3350
- const offWorkspace = workspaceEvents.on((event, data) => {
3351
- void stream.writeSSE({ event, data: JSON.stringify(data) });
3352
- });
3353
- stream.onAbort(() => {
3354
- detach();
3355
- offWorkspace();
3356
- });
3357
- await stream.writeSSE({
3358
- event: 'ready',
3359
- data: JSON.stringify(mode === 'summary' ? { generation: serverGeneration, seq: workspaceRunFeed.seq() } : { generation: serverGeneration }),
3360
- });
3361
- while (!stream.aborted) {
3362
- await stream.writeSSE({ event: 'ping', data: '' });
3363
- await stream.sleep(15_000);
3364
- }
3365
- });
3366
- });
3367
- /** A ref-status list: `null` means malformed (the caller answers 400), `[]` means "not asked
3368
- * for". Absent and empty are the same request — neither names a number. */
3369
- const parseRefNumbers = (raw) => {
3370
- const parts = (raw ?? '').split(',').map((p) => p.trim()).filter(Boolean);
3371
- if (parts.length > GH_REF_STATUS_MAX)
3372
- return null;
3373
- const numbers = [];
3374
- for (const part of parts) {
3375
- const n = Number(part);
3376
- if (!Number.isInteger(n) || n <= 0 || String(n) !== part)
3377
- return null;
3378
- numbers.push(n);
3379
- }
3380
- return numbers;
3381
- };
3382
- const githubRoutes = new Hono()
3383
- .get('/github',
3384
- // `limit` stays a bare string: the handler's `Number.parseInt`/`Number.isFinite` fallback to
3385
- // 30 already accepts `?limit=banana`, and a numeric schema would 400 it instead. The
3386
- // cursors and done flags page each side on its own (hearsay-tools/cezarion#1183); the
3387
- // schema refuses a done side that also carries its cursor, and both sides done.
3388
- queryZodValidator(githubListQuerySchema), async (c) => {
3389
- const { root: repoRoot } = c.get('project');
3390
- const query = c.req.valid('query');
3391
- const limit = Number.parseInt(query.limit ?? '', 10);
3392
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).list({
3393
- refresh: query.refresh === '1',
3394
- limit: Number.isFinite(limit) ? limit : 30,
3395
- issuesCursor: query.issuesCursor,
3396
- prsCursor: query.prsCursor,
3397
- issuesDone: query.issuesDone === '1',
3398
- prsDone: query.prsDone === '1',
3399
- }));
3400
- })
3401
- .get('/github/projects', queryZodValidator(githubProjectsQuerySchema), async (c) => {
3402
- return c.json(await resolveForgeRoot(c.get('project').root, deps.forgeFactory).projects(c.req.valid('query').generation));
3403
- })
3404
- .get('/github/comments/:kind/:number', queryZodValidator(refreshQuery), async (c) => {
3405
- const { root: repoRoot } = c.get('project');
3406
- const parsed = commentsParams.safeParse({
3407
- kind: c.req.param('kind'),
3408
- number: c.req.param('number'),
3409
- });
3410
- if (!parsed.success)
3411
- return c.json({ error: 'invalid kind or number' }, 400);
3412
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).comments(parsed.data.kind, parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
3413
- })
3414
- // One issue/PR by number, any state (#692) — the task page's item tabs. Same in-payload
3415
- // degrade as the siblings: `item: null` is "no such number", `available: false` is "could not
3416
- // ask"; never a 5xx.
3417
- .get('/github/items/:kind/:number', paramZodValidator(githubItemParamsSchema, { message: 'invalid kind or number' }), queryZodValidator(refreshQuery), async (c) => {
3418
- const { root: repoRoot } = c.get('project');
3419
- const { kind, number } = c.req.valid('param');
3420
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).item(kind, number, { refresh: c.req.valid('query').refresh === '1' }));
3421
- })
3422
- // Lazy checks glyphs for on-screen PR rows (#664). Additive sibling of /api/github — the list
3423
- // call dropped `statusCheckRollup` (the dominant cost), so the glyph is hydrated here per
3424
- // visible row. `prs` is a comma-separated list of positive integers, capped at GH_CHECKS_MAX;
3425
- // anything malformed is a 400. Same in-payload availability degrade as the list (never a 5xx).
3426
- // `prs` is the one genuinely REQUIRED query key on this server, so it is the one validated
3427
- // strictly — `.min(1)` because `?prs=` answered `missing prs query` before it answered
3428
- // `invalid prs query`, and both spellings must keep their own words.
3429
- .get('/github/checks', queryZodValidator(githubChecksQuerySchema, { message: 'missing prs query' }), async (c) => {
3430
- const { root: repoRoot } = c.get('project');
3431
- const raw = c.req.valid('query').prs;
3432
- const parts = raw.split(',').map((p) => p.trim()).filter(Boolean);
3433
- if (parts.length === 0 || parts.length > GH_CHECKS_MAX)
3434
- return c.json({ error: 'invalid prs query' }, 400);
3435
- const numbers = [];
3436
- for (const part of parts) {
3437
- const n = Number(part);
3438
- if (!Number.isInteger(n) || n <= 0 || String(n) !== part)
3439
- return c.json({ error: 'invalid prs query' }, 400);
3440
- numbers.push(n);
3441
- }
3442
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).checks(numbers));
3443
- })
3444
- // Comment counts for loaded list rows (hearsay-tools/cezarion#1183). The list defers them
3445
- // (`commentsDeferred`) because they were ~0.4 s of every page; the cockpit asks here after
3446
- // paint. Same shape and in-payload degrade as /github/checks: at most 100 positive numbers,
3447
- // 400 on anything malformed, never a 5xx.
3448
- .get('/github/comment-counts', queryZodValidator(githubCommentCountsQuerySchema, { message: 'invalid comment-counts query' }), async (c) => {
3449
- const { kind, numbers, refresh } = c.req.valid('query');
3450
- return c.json(await resolveForgeRoot(c.get('project').root, deps.forgeFactory).commentCounts(kind, numbers.split(',').map(Number), { refresh: refresh === '1' }));
3451
- })
3452
- // Search across ALL states (#730). Additive sibling of `/github`, which lists the OPEN set
3453
- // only (`gh issue/pr list` defaults to `--state open`) — so the tab's in-memory filter can
3454
- // never match a closed or merged item, and this is the path it falls back to. Same in-payload
3455
- // availability degrade as the list (never a 5xx); malformed params are a 400. Deliberately
3456
- // uncached: it is typed-into, not polled, and the driver's own cap bounds the work.
3457
- .get('/github/search', queryZodValidator(githubSearchQuerySchema, { message: 'invalid search query' }), async (c) => {
3458
- const { root: repoRoot } = c.get('project');
3459
- const { kind, q, limit } = c.req.valid('query');
3460
- const forge = resolveForgeRoot(repoRoot, deps.forgeFactory);
3461
- if (!forge.searchItems)
3462
- return c.json({ available: false, reason: 'GitHub is unavailable', items: [] });
3463
- return c.json(await forge.searchItems(kind, q, limit === undefined ? {} : { limit }));
3464
- })
3465
- // Batched status for the PR/issue chips a task table paints. Additive sibling of
3466
- // /github/checks and shaped like it: comma-separated positive integers, capped at
3467
- // GH_REF_STATUS_MAX per kind, malformed input is a 400, and an unreachable forge degrades in
3468
- // the payload. Unlike /github/checks BOTH keys are optional — a table may hold only issues —
3469
- // but at least one must name something, or the request asks for nothing.
3470
- .get('/github/ref-status', queryZodValidator(githubRefsQuerySchema), async (c) => {
3471
- const { root: repoRoot } = c.get('project');
3472
- const { prs, issues } = c.req.valid('query');
3473
- const parsedPrs = parseRefNumbers(prs);
3474
- const parsedIssues = parseRefNumbers(issues);
3475
- if (parsedPrs === null || parsedIssues === null)
3476
- return c.json({ error: 'invalid ref-status query' }, 400);
3477
- if (parsedPrs.length === 0 && parsedIssues.length === 0) {
3478
- return c.json({ error: 'missing prs or issues query' }, 400);
3479
- }
3480
- return c.json(await resolveForgeRoot(repoRoot, deps.forgeFactory).refStatus({ prs: parsedPrs, issues: parsedIssues }));
3481
- })
3482
- .get('/github/prs/:number/merge-state', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), queryZodValidator(refreshQuery), async (c) => {
3483
- const { root: repoRoot } = c.get('project');
3484
- const parsed = { data: c.req.valid('param') };
3485
- const forge = resolveProjectForge(await getRepoInfo(repoRoot));
3486
- if (!forge?.prMergeState)
3487
- return c.json({ available: false, reason: 'GitHub merge state is unavailable' });
3488
- return c.json(await forge.prMergeState(parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
3489
- })
3490
- .post('/github/prs/:number/merge', paramZodValidator(mergeNumberParams, { message: 'invalid pull request number' }), jsonZodValidator(() => mergeBodySchema, { message: 'invalid merge request' }), async (c) => {
3491
- const { root: repoRoot } = c.get('project');
3492
- const parsedNumber = { data: c.req.valid('param') };
3493
- const body = { data: c.req.valid('json') };
3494
- const forge = resolveProjectForge(await getRepoInfo(repoRoot));
3495
- if (!forge?.mergePR)
3496
- return c.json({ error: 'GitHub merge is unavailable' }, 409);
3497
- const result = await forge.mergePR(parsedNumber.data.number, body.data);
3498
- if (result.merged) {
3499
- return c.json(result);
3500
- }
3501
- return c.json({
3502
- error: result.error,
3503
- ...(result.code ? { code: result.code } : {}),
3504
- ...(result.current ? { current: result.current } : {}),
3505
- }, result.status);
3506
- })
3507
- .get('/github/prs/:number/changes',
3508
- // Split out of one `safeParse` over both inputs, because a path param and the query string
3509
- // are separate validation targets to Hono and only a split makes each visible to the route
3510
- // type. Both keep the single 400 sentence the combined parse answered. `refresh` stays
3511
- // STRICT here (`?refresh=true` is a 400 today, unlike everywhere else on this server).
3512
- paramZodValidator(prChangesParams, { message: 'invalid pull request number or refresh flag' }), queryZodValidator(prChangesQuery, { message: 'invalid pull request number or refresh flag' }), async (c) => {
3513
- const { root: repoRoot } = c.get('project');
3514
- const parsed = { data: c.req.valid('param') };
3515
- const forge = resolveForgeRoot(repoRoot, deps.forgeFactory);
3516
- if (!forge.prDiff)
3517
- return c.json({ available: false, reason: 'GitHub is unavailable' });
3518
- try {
3519
- return c.json(await forge.prDiff(parsed.data.number, { refresh: c.req.valid('query').refresh === '1' }));
3520
- }
3521
- catch (err) {
3522
- if (err instanceof GithubPrNotFoundError)
3523
- return c.json({ error: err.message }, 404);
3524
- throw err;
3525
- }
3526
- });
3527
- // The full comment thread for one issue/PR (#499). Additive sibling of /api/github — lazy
3528
- // (fetched only while a detail view is open), zod-validated params, 400 on garbage, and the
3529
- // same in-payload availability degrade (gh missing / offline / 404 all render as a hint).
3530
- const commentsParams = z.object({
3531
- kind: z.enum(['issue', 'pr']),
3532
- number: z.coerce.number().int().positive(),
3533
- });
3534
- const branchForge = deps.branchForge ?? createGithubBranchForge({ forgeFactory: deps.forgeFactory });
3535
- const branchClassifyInput = (project) => classifyInputFor({ ...project, home: deps.home }, branchForge);
3536
- // ---- chained family: repo / git (project-scoped) ----
3537
- const repoRoutes = new Hono()
3538
- .get('/repo', async (c) => {
3539
- const { root: repoRoot, store } = c.get('project');
3540
- const info = await getRepoInfo(repoRoot);
3541
- if (!info)
3542
- return c.json({
3543
- info: null,
3544
- status: [],
3545
- log: [],
3546
- branches: [],
3547
- baseBranch: null,
3548
- tracking: null,
3549
- });
3550
- // Status stays fresh for edits made outside Squawk; only ref-derived reads are cached.
3551
- const [status, config] = await Promise.all([
3552
- getStatus(info.root),
3553
- loadConfig(repoRoot, deps.home),
3554
- ]);
3555
- // The helper validates refs and branch-owner evidence before reusing log attribution.
3556
- const refs = await readRepoRefs(info, config.baseBranch, store.queries);
3557
- return c.json({
3558
- info,
3559
- status,
3560
- log: refs.log,
3561
- branches: refs.branches,
3562
- baseBranch: config.baseBranch ?? null,
3563
- tracking: refs.tracking,
3564
- });
3565
- })
3566
- // Every local branch, classified (issue 08 §A/§B2) — cached on the refs state, so the
3567
- // sidebar's counts do not shell out on every render.
3568
- .get('/repo/branches', async (c) => {
3569
- const input = await branchClassifyInput(c.get('project'));
3570
- if (!input)
3571
- return c.json({ base: '', prStateKnown: false, branches: [], counts: { notLanded: 0, cleanup: 0 } });
3572
- return c.json(await readRepoBranches(input));
3573
- })
3574
- // The same classification's counts alone (hearsay-tools/cezarion#2029): the always-mounted Git
3575
- // sidebar reads these, so it never pays for a diff stat per branch.
3576
- .get('/repo/branches/counts', async (c) => {
3577
- const input = await branchClassifyInput(c.get('project'));
3578
- if (!input)
3579
- return c.json({ base: '', prStateKnown: false, counts: { notLanded: 0, cleanup: 0 }, allBranches: 0 });
3580
- return c.json(await readRepoBranchCounts(input));
3581
- })
3582
- // Delete local branches (issue 08 §B3). The server re-classifies and never trusts the
3583
- // client's class: nothing here can delete work that is not on the base without the typed
3584
- // confirmation, and nothing in use can be deleted at all.
3585
- .post('/repo/branches/delete', jsonZodValidator(deleteBranchesInputSchema), async (c) => {
3586
- const input = await branchClassifyInput(c.get('project'));
3587
- if (!input)
3588
- return c.json({ error: 'not a git repository', refused: [] }, 409);
3589
- const body = c.req.valid('json');
3590
- // The cockpit's checkout switch and pull hold this, not the worktree lock: without it a switch
3591
- // could check a candidate out after the delete read the worktree list, and `update-ref` would
3592
- // delete the branch HEAD now names.
3593
- const release = claimRepoGitMutation(input.root);
3594
- if (!release)
3595
- return c.json({ error: 'a branch switch or pull is running — try again when it finishes', refused: [] }, 409);
3596
- const result = await deleteBranches(input, body.names, body.confirm).finally(release);
3597
- forgetRepoRead(input.root);
3598
- if (result.deleted.length === 0) {
3599
- return c.json({ error: result.refused[0]?.reason ?? 'nothing was deleted', refused: result.refused }, 409);
3600
- }
3601
- return c.json(result, 200);
3602
- })
3603
- .get('/repo/diff', async (c) => {
3604
- const { root: repoRoot } = c.get('project');
3605
- const info = await getRepoInfo(repoRoot);
3606
- if (!info)
3607
- return c.text('not a git repository');
3608
- return c.text(await getDiff(info.root));
3609
- })
3610
- // One commit's message + stat + patch — the Repo view expands it inline.
3611
- // `?structured=1` is the ADDITIVE sibling (R5 Step 1.7): the new repo view's commit-diff
3612
- // shape `{sha, subject, author, when, files, stat}` with 409 + reason on failure. The
3613
- // legacy text answer below is what the route returns without the flag, in-band failure
3614
- // sentences included.
3615
- //
3616
- // `Accept: application/json` reaches the same structured answer without the flag, and
3617
- // `Accept: text/plain` asks for the blob; the flag still wins whenever it is present, and a
3618
- // request with no opinion still gets the blob. See `negotiate`.
3619
- .get('/repo/commit/:sha', queryZodValidator(commitQuerySchema), async (c) => {
3620
- const { root: repoRoot } = c.get('project');
3621
- c.header('vary', 'Accept');
3622
- const { structured } = c.req.valid('query');
3623
- const wantsJson = structured !== undefined
3624
- ? structured === '1'
3625
- : negotiate(c.req.header('accept'), COMMIT_FORMATS) === 'application/json';
3626
- const info = await getRepoInfo(repoRoot);
3627
- if (wantsJson) {
3628
- if (!info)
3629
- return c.json({ error: 'not a git repository' }, 409);
3630
- const result = await collectCommitChanges(info.root, c.req.param('sha'));
3631
- if (!result.ok)
3632
- return c.json({ error: result.error }, 409);
3633
- return c.json(result.commit);
3634
- }
3635
- if (!info)
3636
- return c.text('not a git repository');
3637
- try {
3638
- return c.text(await getCommit(info.root, c.req.param('sha')));
3639
- }
3640
- catch (err) {
3641
- return c.text(`(git show failed: ${err instanceof Error ? err.message : String(err)})`);
3642
- }
3643
- })
3644
- // Structured sibling of the text-blob /api/repo/diff above (protected
3645
- // surface, untouched): the same {files, stat} shape the session /changes
3646
- // route serves, here for the MAIN working tree's uncommitted changes vs
3647
- // HEAD (redesign R5 Step 1.3 — §"Git/session API additions").
3648
- .get('/repo/changes', async (c) => {
3649
- const { root: repoRoot } = c.get('project');
3650
- const info = await getRepoInfo(repoRoot);
3651
- if (!info)
3652
- return c.json({ error: 'not a git repository' }, 409);
3653
- // The user's REAL working tree — never stage into their index (a GET must not write).
3654
- const result = await collectChanges(info.root, 'HEAD', {
3655
- intentToAdd: false,
3656
- });
3657
- if (!result.ok)
3658
- return c.json({ error: result.error }, 409);
3659
- return c.json(result.changes);
3660
- })
3661
- .get('/repo/pull', async (c) => {
3662
- const { root } = c.get('project');
3663
- const result = await localPullBranches(root);
3664
- if ('error' in result)
3665
- return c.json(result, 409);
3666
- return c.json(result);
3667
- })
3668
- .post('/repo/pull', jsonZodValidator(repoPullInputSchema), async (c) => {
3669
- const { root, store, manager } = c.get('project');
3670
- const info = await getRepoInfo(root);
3671
- if (!info)
3672
- return c.json({ error: 'not a git repository' }, 409);
3673
- const config = await loadConfig(root, deps.home);
3674
- const result = await pullRepoCheckout(info.root, c.req.valid('json'), config.baseBranch,
3675
- // Every id, not the live set: the manager may still hold a run whose record already
3676
- // settled (a worker's execution winding down). Ids only, nothing decoded.
3677
- () => store.queries.listRunIds().some((id) => manager.isActive(id)));
3678
- forgetRepoRead(info.root);
3679
- if (!result.ok)
3680
- return c.json(result.value, 409);
3681
- return c.json(result.value, 200);
3682
- })
3683
- .post('/repo/branch', jsonZodValidator(() => repoBranchSchema), async (c) => {
3684
- const { root: repoRoot } = c.get('project');
3685
- const info = await getRepoInfo(repoRoot);
3686
- if (!info)
3687
- return c.json({ error: 'not a git repository' }, 409);
3688
- const release = claimRepoGitMutation(info.root);
3689
- if (!release)
3690
- return c.json({ error: 'A Git operation is already in progress for this repository.' }, 409);
3691
- try {
3692
- const input = c.req.valid('json');
3693
- const result = await createOrSwitchBranch(info.root, input.name, input.from);
3694
- forgetRepoBranches(info.root);
3695
- forgetRepoRead(info.root);
3696
- if (!result.ok)
3697
- return c.json({ error: result.error }, 409);
3698
- return c.json({ branch: result.branch, created: result.created });
3699
- }
3700
- finally {
3701
- release();
3702
- }
3703
- });
3704
- /** #917, hearsay-tools/squawk#914: setup and teardown commands run on the host. */
3705
- const WORKTREE_COMMANDS_HOSTED_ERROR = `Worktree setup and teardown commands are read-only on this remote cockpit. To allow remote edits, run \`${productIdentity().command} remote-settings enable\` on the machine running Squawk.`;
3706
- // The Settings → Agent defaults knobs in one read (R6 Step 1.5) — an ADDITIVE
3707
- // sibling of PUT /api/config below; /api/health keeps its protected shape.
3708
- const configAnswer = async (repoRoot, config) => {
3709
- const archive = resolveArchiveOnMerge(config, await loadWorkspaceConfig(deps.home.workspaceConfig));
3710
- const nativeModels = await readAgentModelDefaults(repoRoot);
3711
- const setup = reportWorktreeCommands(config.worktreeSetup);
3712
- const teardown = reportWorktreeCommands(config.worktreeTeardown);
3713
- const modelsLocked = agentModelsLocked(repoRoot, process.env, deps.home);
3714
- return {
3715
- archiveOnMerge: config.archiveOnMerge ?? null,
3716
- effectiveArchiveOnMerge: archive.enabled,
3717
- archiveOnMergeSource: archive.source,
3718
- baseBranch: config.baseBranch ?? null,
3719
- defaultRunner: config.defaultRunner,
3720
- systemPrompt: config.systemPrompt ?? null,
3721
- // Native defaults seed each runner independently. A Squawk preset remains
3722
- // selectable unless the operator opts into the fixed-model policy.
3723
- defaultModels: modelsLocked
3724
- ? nativeModels
3725
- : { ...nativeModels, ...config.defaultModels },
3726
- modelsLocked,
3727
- maxParallel: config.maxParallel,
3728
- memoryLimitMb: config.memoryLimitMb ?? null,
3729
- // Count-based worktree retention (#483): keep the last N finished worktrees
3730
- // on disk. 0 = unlimited. Always materialized (schema default 10).
3731
- worktreeRetention: config.worktreeRetention,
3732
- // Live title updates (task auto-naming spec): tri-state — null means "no
3733
- // config key, the CEZ_TITLE_UPDATES env default (ON) decides".
3734
- liveTitleUpdates: config.liveTitleUpdates ?? null,
3735
- // Optional review gate (#489): tri-state — null means "no config key, the
3736
- // CEZ_REVIEW_GATE env default (OFF) decides".
3737
- reviewGate: config.reviewGate ?? null,
3738
- // Worktree setup (#917) and teardown (hearsay-tools/squawk#914): an invalid value is reported.
3739
- worktreeSetup: setup.value, worktreeSetupIssue: setup.issue,
3740
- worktreeTeardown: teardown.value, worktreeTeardownIssue: teardown.issue,
3741
- };
3742
- };
3743
- // ---- chained family: per-repo config (project-scoped) ----
3744
- const configRoutes = new Hono()
3745
- .get('/config', async (c) => {
3746
- const repoRoot = c.get('project').root;
3747
- return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot, deps.home)));
3748
- })
3749
- .put('/config', jsonZodValidator(() => setConfigSchema, { runners: { ids: ['defaultRunner'], keys: ['defaultModels'] } }), async (c) => {
3750
- const { root: repoRoot, dataDir } = c.get('project');
3751
- const parsed = { data: c.req.valid('json') };
3752
- if (agentModelsLocked(repoRoot, process.env, deps.home) && parsed.data.defaultModels !== undefined) {
3753
- return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
3754
- }
3755
- // Host commands need settings administration (hearsay-tools/cezarion#2428), checked before any write.
3756
- if ([parsed.data.worktreeSetup, parsed.data.worktreeTeardown].some((v) => v !== undefined) && !capabilities().settingsAdmin) {
3757
- return c.json({ error: WORKTREE_COMMANDS_HOSTED_ERROR }, 409);
3758
- }
3759
- const refused = await writeMergedConfig(dataDir, parsed.data).catch((err) => ({ failed: err instanceof Error ? err.message : String(err) }));
3760
- if (typeof refused === 'object')
3761
- return c.json({ error: refused.failed }, 500);
3762
- if (refused !== undefined)
3763
- return c.json({ error: refused }, 409);
3764
- if (parsed.data.archiveOnMerge !== undefined)
3765
- deps.archiveOnMergeChanged?.();
3766
- // Pre-R6 answer shape ({baseBranch, defaultRunner}) + additive R6 fields.
3767
- return c.json(await configAnswer(repoRoot, await loadConfig(repoRoot, deps.home)));
3768
- });
3769
- // ---- chained family: agent-config (project-scoped) -----------------------
3770
- // Agent config is project-scoped (spec #404, adapted to the multi-project
3771
- // route seam from #521): handlers resolve the selected repo through the
3772
- // same ProjectContext as every other mirrored route. Chained (not statements)
3773
- // so `AppType` carries it — see `healthRoutes`.
3774
- const agentConfigRoutes = new Hono()
3775
- .get('/agent-config', async (c) => {
3776
- const editable = capabilities().settingsAdmin;
3777
- return c.json(await listAgentConfig(c.get('project').root, process.env, editable));
3778
- })
3779
- .get('/agent-config/:id', async (c) => {
3780
- const id = c.req.param('id');
3781
- const def = findConfigFile(id);
3782
- if (!def)
3783
- return c.json({ error: 'unknown config file' }, 404);
3784
- if (def.tracked === 'outside-repo' && !capabilities().settingsAdmin) {
3785
- const error = `this file lives in your home directory and is not served on a remote cockpit — run \`${productIdentity().command} remote-settings enable\` on the host to allow it`;
3786
- return c.json({ error }, 409);
3787
- }
3788
- const read = await readConfigFile(id, c.get('project').root);
3789
- if (read === null)
3790
- return c.json({ error: 'unknown config file' }, 404);
3791
- if ('error' in read)
3792
- return c.json({ error: read.error }, 500);
3793
- return c.json(read);
3794
- })
3795
- .put('/agent-config/:id', jsonZodValidator(setAgentConfigSchema), async (c) => {
3796
- // Hooks and MCP commands run on the host: writes need settings administration (ADR 0055),
3797
- // re-gated on every request.
3798
- if (!capabilities().settingsAdmin) {
3799
- return c.json({
3800
- error: `editing agent config is disabled on this remote cockpit — run \`${productIdentity().command} remote-settings enable\` on the host to allow it`,
3801
- }, 409);
3802
- }
3803
- const parsed = { data: c.req.valid('json') };
3804
- const out = await writeConfigFile(c.req.param('id'), parsed.data.content, parsed.data.version, c.get('project').root);
3805
- if (out === null)
3806
- return c.json({ error: 'unknown config file' }, 404);
3807
- if (!out.ok)
3808
- return c.json({ error: out.error }, out.status);
3809
- return c.json(out.read);
3810
- });
3811
- // ---- assemble the chained families --------------------------------------
3812
- // Every chained family is registered ONCE and mounted into the versioned table. There is no
3813
- // second, unversioned spelling: `/api/*` was removed once the whole API was reachable under
3814
- // `/api/v1`. One surface means one thing to keep working, and
3815
- // it is the one the typed client describes.
3816
- //
3817
- // MOUNT ORDER IS REGISTRATION ORDER. Hono matches in the order routes were added, so each
3818
- // family keeps its internal order and the families keep theirs relative to each other.
3819
- //
3820
- // Written as ONE chained expression because that is the only shape Hono can infer route types
3821
- // from — it is what puts these routes in `AppType`, and so in the typed client.
3822
- // ---- chained family: agent webhooks (hearsay-tools/cezarion#1576, project-scoped) ----
3823
- // What `cez webhook` calls from inside a task: list the webhooks the owner exposed to agents in
3824
- // this project, and send one report through one of them. A webhook closed to agents answers
3825
- // the same 404 as an unknown one, so this interface cannot even confirm it exists.
3826
- const agentWebhooksRoutes = new Hono()
3827
- .get('/agent-webhooks', async (c) => {
3828
- const project = c.get('project');
3829
- const body = { webhooks: agentWebhooks(await registryEntry(project.id, project.root, deps.home).catch(() => undefined)) };
3830
- return c.json(body);
3831
- })
3832
- .post('/agent-webhooks/:webhook', paramZodValidator(agentWebhookParamsSchema.pick({ webhook: true })), jsonZodValidator(sendAgentReportInputSchema), async (c) => {
3833
- const project = c.get('project');
3834
- const { webhook: ref } = c.req.valid('param');
3835
- const entry = await registryEntry(project.id, project.root, deps.home).catch(() => undefined);
3836
- const webhook = agentWebhook(entry, ref);
3837
- if (!entry || !webhook)
3838
- return c.json({ error: `no webhook named "${ref}" is open to agents in this project — run \`${productIdentity().command} webhook list\`` }, 404);
3839
- const outcome = await sendAgentReport({
3840
- projectId: entry.id,
3841
- webhook,
3842
- input: c.req.valid('json'),
3843
- store: project.store,
3844
- origin: taskWebhooks.currentOrigin(),
3845
- fetch: deps.taskWebhookFetch,
3846
- });
3847
- const body = { ...outcome, webhook: { id: webhook.id, name: webhook.name } };
3848
- return c.json(body);
1604
+ const worktreesRoutes = createWorktreesRoutes({ home: deps.home, previewHost: deps.previewHost });
1605
+ const sseRoutes = createSseRoutes();
1606
+ const workspaceEventsRoutes = createWorkspaceEventsRoutes({
1607
+ serverGeneration,
1608
+ resolveBootProject,
1609
+ workspaceRunFeed,
1610
+ workspaceEvents,
3849
1611
  });
1612
+ const githubRoutes = createGithubRoutes({ forgeFactory: deps.forgeFactory, resolveProjectForge });
1613
+ const repoRoutes = createRepoRoutes({ home: deps.home, forgeFactory: deps.forgeFactory, branchForge: deps.branchForge });
1614
+ const configRoutes = createConfigRoutes({ home: deps.home, capabilities, archiveOnMergeChanged: deps.archiveOnMergeChanged });
1615
+ const agentConfigRoutes = createAgentConfigRoutes(capabilities);
1616
+ const agentWebhooksRoutes = createAgentWebhooksRoutes({ home: deps.home, taskWebhooks, taskWebhookFetch: deps.taskWebhookFetch });
3850
1617
  const v1 = new Hono()
3851
1618
  .use('*', resolveProjectScope)
3852
1619
  .route('/', skillsRoutes)
@@ -3867,173 +1634,15 @@ export function createApp(deps) {
3867
1634
  .route('/', agentConfigRoutes);
3868
1635
  projectRoutePaths = new Set(v1.routes.filter((route) => route.method !== 'ALL')
3869
1636
  .flatMap((route) => [V1_PREFIX, V1_SCOPED_PREFIX].map((prefix) => `${route.method} ${prefix}${route.path}`)));
3870
- // ---- chained family: the cross-project run index (workspace-level) -------
3871
- /**
3872
- * How many ARCHIVED root runs each project may contribute, newest first (#864). The index is a
3873
- * FINDER, not a listing: every unarchived ROOT run is in it (so a project's pills miss nothing
3874
- * live or unread), and older archived runs are reached through `GET /workspace/runs-search` and
3875
- * the project's own archived pages. Owned workers are never in it: the pills, ⌘K and the global
3876
- * Tasks page list no workers, and a parent's wait label comes from its own delegation. `truncated` names the projects this bit, so a consumer never
3877
- * has to pretend the list is complete.
3878
- */
3879
- const RUNS_INDEX_PER_PROJECT = ARCHIVED_WINDOW;
3880
- /**
3881
- * Every number a run MENTIONS — a superset of what its chip will show.
3882
- *
3883
- * Deliberately not `taskReference()`'s rule: which of a run's references is displayed is the
3884
- * cockpit's decision (#407, #526), and re-deriving it here would be a second rule that drifts
3885
- * from the first. This feeds a CACHE READ, which costs nothing per number, so asking about one
3886
- * the client will not paint is free and asking about one it will is the whole point.
3887
- */
3888
- const mentionedReferenceNumbers = (run) => {
3889
- const numbers = (run.pullRequests ?? []).map(pr => pr.number);
3890
- for (const url of [run.pullRequestUrl, run.referencedPullRequestUrl, run.referencedIssueUrl]) {
3891
- const number = url ? refNumberFromUrl(url) : null;
3892
- if (number !== null)
3893
- numbers.push(number);
3894
- }
3895
- for (const number of [run.prNumber, run.issueNumber, run.markerRefs?.pr, run.markerRefs?.issue]) {
3896
- if (typeof number === 'number' && Number.isInteger(number) && number > 0)
3897
- numbers.push(number);
3898
- }
3899
- return numbers;
3900
- };
3901
- /**
3902
- * `GET /workspace/runs-index` — every registered project's recent tasks in one slim answer, so
3903
- * ⌘K can find a task without knowing which project it lives in.
3904
- *
3905
- * Workspace-level and single-mount for the obvious reason: a project-scoped spelling of "all
3906
- * projects" is a contradiction. The per-project source is chosen the same way the automation
3907
- * coordinator's boot fan-out chooses it (`bootContext` for the boot project, `contexts.peek`
3908
- * for anything this process already owns, disk otherwise) — and never `contexts.context()`,
3909
- * which would build a context, prune worktrees and `recover()` running agents. Typing in a
3910
- * search box must not resume work; see `runs/run-index.ts`.
3911
- */
3912
- const coldRepoHandles = new ColdRepoHandles(deps.forgeFactory);
3913
- /**
3914
- * Every registered project whose runs can be read, and its owned store when this process holds
3915
- * one (`bootContext` for the boot project, `contexts.peek` otherwise) — never a built context.
3916
- * Without a store, the caller reads the project cold from `dataDir` with `handle`. The source
3917
- * rule both workspace run routes share, so the index and the search can never disagree on it.
3918
- */
3919
- const projectRunSources = async () => {
3920
- let projects = [];
3921
- try {
3922
- projects = await workspaceProjects.listProjects();
3923
- }
3924
- catch {
3925
- // unreadable workspace — no rows, never a 500. The palette degrades to the active
3926
- // project's own run list, which it holds either way.
3927
- }
3928
- const bootId = await resolveBootProject(projects);
3929
- coldRepoHandles.retainRoots(new Set(projects
3930
- .filter((project) => project.status !== 'missing' && project.id !== bootId && !contexts.peek(project.id))
3931
- .map((project) => project.root)));
3932
- // An unfinished migration finishes first. No folder or a fence: no runs. `not-git` still has an `.ai/cezar` worth indexing.
3933
- return (await prepareProjects(projects, { ownership: deps.ownership, homes: [deps.home] })).filter((project) => project.status !== 'missing' && !projectAdmissionRefusal(projectPaths(project.root).write)).map((project) => {
3934
- const owned = project.id === bootId ? bootContext : contexts.peek(project.id);
3935
- // A cold project's repository identity only: asking for an owned one starts a discovery
3936
- // nothing reads.
3937
- return { project, store: owned?.store, dataDir: projectPaths(project.root).write, handle: owned ? undefined : coldRepoHandles.get(project.root) };
3938
- });
3939
- };
3940
- /**
3941
- * One project's contribution to a workspace run route. An owned store throws what its database
3942
- * throws (busy, damaged); like a cold project that cannot be read, it then contributes nothing,
3943
- * so one project never fails every project's index or search (#864).
3944
- */
3945
- const readProjectRuns = (projectId, read) => {
3946
- try {
3947
- return read();
3948
- }
3949
- catch (error) {
3950
- console.warn(`[hsq] runs of project ${projectId} could not be read for the workspace run index: ${error instanceof Error ? error.message : String(error)}`);
3951
- return { runs: [], truncated: false };
3952
- }
3953
- };
3954
- const runsIndexRoutes = new Hono()
3955
- .get('/workspace/runs-index', async (c) => {
3956
- const runs = [];
3957
- const truncated = [];
3958
- // Statuses the server already holds, shipped WITH the rows that carry the references. The
3959
- // cockpit would otherwise ask for them a beat after the table paints — one round trip per
3960
- // project, and a visible flash of un-coloured chips before it lands. Cache-only, so this
3961
- // never touches `gh` and never slows the index down; anything cold stays absent and the
3962
- // lazy `/github/ref-status` route fills it in.
3963
- const referenceStatuses = {};
3964
- const sources = await projectRunSources();
3965
- // Read after the last await and before the synchronous reads below: every frame at or below
3966
- // it is in this snapshot, and a frame above it is newer (hearsay-tools/cezarion#2730).
3967
- const eventSeq = workspaceRunFeed.seq();
3968
- for (const { project, store: owned, dataDir, handle } of sources) {
3969
- // Both sources answer the same window, newest first: every unarchived run, plus the
3970
- // newest archived roots (#864). An owned project lays its held records over its rows; a
3971
- // cold one reads its stored summaries, at most one archived root past the window.
3972
- //
3973
- // Archived runs are INCLUDED. The active project's rows reach the palette through
3974
- // `GET /run-summaries`, which carries them too, and excluding them here would mean a task
3975
- // is findable while you stand in its project and vanishes the moment you leave — the
3976
- // exact asymmetry a cross-project finder exists to remove.
3977
- const window = readProjectRuns(project.id, () => owned
3978
- ? owned.queries.listRunSummaries({ archivedWindow: RUNS_INDEX_PER_PROJECT, roots: true })
3979
- : readRunIndexFromDisk(dataDir, { handle, archivedWindow: RUNS_INDEX_PER_PROJECT, roots: true }));
3980
- if (window.truncated)
3981
- truncated.push(project.id);
3982
- const recent = window.runs.map(withLiveUsage);
3983
- const mentioned = [];
3984
- for (const run of recent) {
3985
- runs.push({ projectId: project.id, ...run });
3986
- mentioned.push(...mentionedReferenceNumbers(run));
3987
- }
3988
- if (mentioned.length > 0) {
3989
- const cached = resolveForgeRoot(project.root, deps.forgeFactory).cachedRefStatuses(mentioned);
3990
- // Only when something was actually warm. A project key holding two empty maps is noise
3991
- // that every consumer would have to look past, and it would blur the one rule this
3992
- // payload has: absent means nothing is known.
3993
- if (Object.keys(cached.prs).length > 0 || Object.keys(cached.issues).length > 0) {
3994
- referenceStatuses[project.id] = cached;
3995
- }
3996
- }
3997
- }
3998
- runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
3999
- const body = {
4000
- runs,
4001
- perProjectLimit: RUNS_INDEX_PER_PROJECT,
4002
- truncated,
4003
- referenceStatuses,
4004
- generation: serverGeneration,
4005
- eventSeq,
4006
- };
4007
- return c.json(body);
4008
- })
4009
- /**
4010
- * `GET /workspace/runs-search` (#864) — every registered project's ROOT runs, archived or not,
4011
- * that match `q`, newest first: what lets ⌘K find a run past a project's window. Same source
4012
- * rule and the same side-effect-free contract as the index above.
4013
- */
4014
- .get('/workspace/runs-search', queryZodValidator(runsSearchQuerySchema), async (c) => {
4015
- const { q, limit = RUNS_SEARCH_PER_PROJECT_MAX } = c.req.valid('query');
4016
- const runs = [];
4017
- const truncated = [];
4018
- const tokens = searchTokens(q);
4019
- for (const { project, store: owned, dataDir, handle } of await projectRunSources()) {
4020
- // The palette filters its rows by project name too, so a token naming this project is
4021
- // already satisfied here: `shop database` searches shop for `database` (#864 review). A
4022
- // query that only names the project adds nothing past the index's rows for it.
4023
- const name = project.name.toLowerCase();
4024
- const rest = tokens.filter((token) => !name.includes(token));
4025
- if (rest.length === 0)
4026
- continue;
4027
- const scoped = rest.join(' ');
4028
- const found = readProjectRuns(project.id, () => owned ? owned.queries.searchRunSummaries(scoped, limit) : searchRunIndexFromDisk(dataDir, scoped, { handle, limit }));
4029
- if (found.truncated)
4030
- truncated.push(project.id);
4031
- for (const run of found.runs)
4032
- runs.push({ projectId: project.id, ...withLiveUsage(run) });
4033
- }
4034
- runs.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
4035
- const body = { runs, truncated };
4036
- return c.json(body);
1637
+ const runsIndexRoutes = createRunsIndexRoutes({
1638
+ loadPreparedProjects: (projects) => prepareProjects(projects, { ownership: deps.ownership, homes: [deps.home] }),
1639
+ forgeFactory: deps.forgeFactory,
1640
+ bootContext,
1641
+ contexts,
1642
+ workspaceProjects,
1643
+ workspaceRunFeed,
1644
+ serverGeneration,
1645
+ withLiveUsage,
4037
1646
  });
4038
1647
  // Workspace-level families answer for the whole workspace, so they are single-mount: never a
4039
1648
  // project-scoped spelling, which would be a second surface to protect with no consumer.
@@ -4083,7 +1692,6 @@ export function createApp(deps) {
4083
1692
  /** The host a thread link names (#589): the bound one, or loopback for a wildcard bind. */
4084
1693
  /** The built-in skills a project's manager offers (#774). Test apps inject partial managers. */
4085
1694
  export { cockpitOriginFor } from './server-deps.js';
4086
- const webhookNameTakenError = (name) => `this project already has a webhook named "${name.trim()}" — pick another name`;
4087
1695
  /**
4088
1696
  * Validate topic-bus upgrades before handshake. Local Host must be loopback. Same-authority or
4089
1697
  * native clients are trusted; verified dev proxies are trusted. Metadata-free foreign loopback