@hearsay-tools/squawk 0.18.0-dev.8312 → 0.18.0-dev.8318

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.
@@ -1,7 +1,6 @@
1
1
  import { memoizeRead } from './bounded-read-cache.js';
2
2
  import { cachedWorktreeSizeBytes } from './worktree-size-cache.js';
3
3
  import { readRepoRefs, forgetRepoRead } from './repo-read-cache.js';
4
- import { allocateAgentProfileId } from './agent-profile-id.js';
5
4
  import { runnerSkillsQuerySchema } from '../contract/index.js';
6
5
  import { readRunnerSkills } from './runner-skills.js';
7
6
  import { runCheckout, preparePublishCheckout, reclaimCheckoutError } from './run-checkout.js';
@@ -15,17 +14,15 @@ import { writeMergedConfig } from './config-merge.js';
15
14
  import { applyWorkspaceConfigPatch } from './workspace-config-patch.js';
16
15
  import { retryAutomationLogReceipt } from './automation-log-retry.js';
17
16
  import { automationCreateSchema, automationUpdateSchema, automationCheckRequestSchema, automationLogQuerySchema } from '../contract/index.js';
18
- import { providerConnectSchema, createAgentProfileSchema, updateAgentProfileSchema, selectAgentProfileSchema, providerEnabledSchema, providerRetrySchema, providerRouteParamsSchema, agentProfileRouteParamsSchema } from '../contract/index.js';
19
17
  import { planSchema, parseWorkflowSchema } from '../contract/index.js';
20
18
  import { uiStateBody } from '../contract/index.js';
21
19
  import { queuedMessagePatchSchema, continueSchema, archiveSchema, openInSchema } from '../contract/index.js';
22
- import { refreshQuery, strictRefreshQuerySchema, browseQuerySchema, worktreeFilesQuerySchema } from '../contract/index.js';
20
+ import { refreshQuery, browseQuerySchema, worktreeFilesQuerySchema } from '../contract/index.js';
23
21
  import { mergeNumberParams, prChangesParams, prChangesQuery, mergeBodySchema } from '../contract/index.js';
24
22
  import { gitCommitSchema, reclaimBodySchema, repoBranchSchema } from '../contract/index.js';
25
23
  import { setConfigSchema, setAgentConfigSchema } from '../contract/index.js';
26
24
  import { saveWorkflowInputSchema as saveWorkflowSchema } from '../contract/index.js';
27
25
  import { patchRunInputSchema as patchRunSchema, messageInputSchema as messageSchema } from '../contract/index.js';
28
- import { checkoutProjectInputSchema as checkoutSchema, registerProjectInputSchema as registerProjectSchema } from '../contract/index.js';
29
26
  import { setWorkspaceConfigInputSchema as workspaceConfigUpdateSchema } from '../contract/index.js';
30
27
  import { reclaimRunParamsSchema } from '../contract/index.js';
31
28
  import { githubChecksQuerySchema } from '../contract/index.js';
@@ -34,13 +31,11 @@ import { commitQuerySchema } from '../contract/index.js';
34
31
  import { imageMimeType } from '../contract/index.js';
35
32
  import { providerForActiveRun } from '../contract/index.js';
36
33
  import { removedRunnerMessage } from '../contract/index.js';
37
- import { defined } from '../core/defined.js';
38
34
  import { isAbsoluteHostPath } from '../core/host-path.js';
39
35
  import { resolveArchiveOnMerge, resolveGlobalArchiveOnMerge } from '../archive-on-merge-setting.js';
40
36
  import { permissionDecisionSchema } from '../contract/index.js';
41
37
  import { runIdParamSchema as permissionRunIdParamSchema } from '../contract/index.js';
42
38
  import { CheckoutProgressCache } from './checkout-progress.js';
43
- import { checkoutProgressParamsSchema, createProjectInputSchema } from '../contract/index.js';
44
39
  import { createWorkspaceLiveRoutes } from './workspace-live-routes.js';
45
40
  import { createActivityRoutes } from './activity-routes.js';
46
41
  import { createRunnersRoutes } from './runners-routes.js';
@@ -67,15 +62,14 @@ import { githubRepository } from '../automations/github-repository.js';
67
62
  import { ProjectAutomationScheduler } from '../automations/scheduler.js';
68
63
  import { launchAutomationRun, launchScheduledRun, reconcileAutomationReceipts } from '../automations/task-template.js';
69
64
  import { isGithubAutomation, } from '../automations/types.js';
70
- import { mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';
65
+ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
71
66
  import { basename, dirname, join } from 'node:path';
72
67
  import { fileURLToPath } from 'node:url';
73
68
  import { Hono } from 'hono';
74
69
  import { bodyLimit } from 'hono/body-limit';
75
- import { streamSSE } from 'hono/streaming';
76
70
  import { matchedRoutes } from 'hono/route';
77
71
  import { jsonZodValidator, paramZodValidator, queryZodValidator } from './validators.js';
78
- import { deliverOnce, registryEntry, sendAgentReport } from '../runs/webhook.js';
72
+ import { registryEntry, sendAgentReport } from '../runs/webhook.js';
79
73
  import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
80
74
  import { z } from 'zod';
81
75
  import { repoPullInputSchema, deleteBranchesInputSchema } from '../contract/index.js';
@@ -85,15 +79,13 @@ import { setWorkspaceUiStateInputSchema } from '../contract/index.js';
85
79
  // A contract VALUE, like `workspaceUiStateSchema` in workspace/migrations.ts — the request
86
80
  // schema this route validates with is the same one the client compiles against.
87
81
  import { openProjectInSchema } from '../contract/index.js';
88
- import { isRegisteredRunner, knownRunnerIds, registeredRunnerId, registeredRunners, resolveRunnerId, runnerDefinition } from '../core/runner-registry.js';
82
+ import { registeredRunnerId, registeredRunners, resolveRunnerId, runnerDefinition } from '../core/runner-registry.js';
89
83
  import { REMOVED_RUNNER_IDS } from '../runs/legacy-run-rows.js';
90
84
  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';
85
+ import { agentWebhookParamsSchema, sendAgentReportInputSchema } from '../contract/index.js';
86
+ import { agentWebhook, agentWebhooks, taskWebhooks as taskWebhookList } from '../workspace/webhooks.js';
94
87
  import { environmentStamp } from '../core/backend-detect.js';
95
88
  import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
96
- import { applyProviderEnablement } from '../core/provider-availability.js';
97
89
  import { createModelsRoutes } from './models-routes.js';
98
90
  import { createProviderSignInRoutes } from './provider-sign-in-routes.js';
99
91
  import { allUsage, currentUsage, onUsage } from '../core/process-usage.js';
@@ -133,21 +125,18 @@ import { readConfigFile, writeConfigFile } from '../agent-config/files.js';
133
125
  import { readAgentModelDefaults } from '../agent-config/models.js';
134
126
  import { listAgentConfig } from '../agent-config/service.js';
135
127
  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';
128
+ import { defaultWorkspaceConfig, loadWorkspaceConfig, mergeWriteWorkspaceConfig, effectiveComposerDefault } from '../workspace/config.js';
129
+ import { DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, loadAgentAccounts } from '../workspace/agent-accounts.js';
130
+ import { defaultAgentProfile, listAgentProfiles, resolveStoredProfile } from '../workspace/agent-profiles.js';
131
+ import { profileEnv } from '../core/agent-profiles.js';
140
132
  import { shellQuote, withEnvPrefix } from '../core/shell-env.js';
141
133
  import { resumeCommand } from '../core/runner-cli.js';
142
- import { normalizeProjectTags, probeProjectStatus, toProjectListEntry, registerProject, removeProject, shouldRegisterProject, } from '../workspace/projects.js';
143
134
  import { mergeWriteWorkspaceUiState, readWorkspaceUiState } from '../workspace/ui-state.js';
144
- import { checkoutRepo } from './checkout.js';
145
- import { createProject, listGithubOwners } from './create-project.js';
146
135
  import { createWorkspaceRunFeed, currentRecord } from './workspace-run-feed.js';
147
136
  import { mergeWriteProjectUiState, readUiState } from '../ui-state.js';
148
137
  import { expandTilde } from '../paths.js';
149
138
  import { isLoopbackHostHeader, resolveCapabilities } from './capabilities.js';
150
- import { browseDirectory, isInsideBrowseRoot, isLexicallyInsideBrowseRoot, resolveBrowseRoot } from './fs-browse.js';
139
+ import { browseDirectory, resolveBrowseRoot } from './fs-browse.js';
151
140
  import { resolveForge, forgeWebRoot, resolveForgeRoot, GithubPrNotFoundError, GH_CHECKS_MAX, GH_REF_STATUS_MAX } from './forge/index.js';
152
141
  import { refNumberFromUrl } from '../contract/index.js';
153
142
  import { projectAdmissionRefusal, withProjectAdmission } from './cockpit-ownership.js';
@@ -156,17 +145,16 @@ import { freshCliHandoff, openRunApp, openRunCli, openRunDefaultApp } from './op
156
145
  import { agentCliRunner, detectOpenTargets } from './open-in-app.js';
157
146
  import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
158
147
  import { continueRunProviders } from './provider-action-gate.js';
159
- import { attachProjectWebhooks, createBootContext, createProviderStatus, emitProviderRow, resolveServerDeps, watchProviderRuntimeAuth, } from './server-deps.js';
148
+ import { attachProjectWebhooks, createBootContext, createProviderStatus, resolveServerDeps, watchProviderRuntimeAuth } from './server-deps.js';
160
149
  import { NO_WEBHOOK_ERROR, agentProfileRefusal, clientRequestOf, launchRun, modelLockRefusal, notifyRefusal, providerGateRefusal, replayedRun, resolveStartWorkflow, startRunInput, } from './start-run-options.js';
161
150
  import { ASSET_CACHE_CONTROL, BUILD_HINT_HTML, assetContentType, isSafeAssetFilename, resolveGetRequest, } from './static-ui.js';
162
151
  import { compression, createStaticAssets, isFile } from './static-assets.js';
163
152
  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
- };
153
+ import { createProjectsRoutes } from './projects-routes.js';
154
+ import { createAgentProfilesRoutes, createProvidersRoutes } from './providers-routes.js';
155
+ import { hostedProfileRefusal, streamSSENoBuffer, UI_STATE_BODY_LIMIT, WorkspaceEventBus } from './server-types.js';
156
+ // ---- project-scoped routing (multi-project spec, step 2.2) -----------------
157
+ export { WorkspaceEventBus } from './server-types.js';
170
158
  /**
171
159
  * The public API surface (spec 2026-07-23-independent-server-web-packages).
172
160
  *
@@ -205,40 +193,7 @@ export function projectRouteManifest(app) {
205
193
  const AUTOMATIONS_OFF = 'Automations are disabled — unset CEZ_AUTOMATIONS or set it to 1 and restart to enable them';
206
194
  /** 404 body for a run whose row is in runs.db but whose record this Squawk cannot decode (#779). */
207
195
  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
- };
196
+ // ---- workspace SSE (multi-project spec, step 2.8) --------------------------
242
197
  // Queued prompt stack bounds (#472). The per-message bounds mirror `messageSchema`
243
198
  // above; the one that actually matters is the FOLDED total, because 20 messages of
244
199
  // 100 000 chars each would otherwise compose a ~2 M-character {{task}}.
@@ -260,8 +215,6 @@ function foldedLength(task, stack) {
260
215
  // images at ~7 MB base64 each); the ui-state PUT gets a much tighter cap since
261
216
  // it only ever carries small GUI prefs.
262
217
  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
218
  // The return type is INFERRED on purpose: it is the chained app type built at the bottom of
266
219
  // this function, and `AppType` (src/server/app-type.ts) is `ReturnType<typeof createApp>`.
267
220
  // Annotating it `Hono` here would erase every route from the type and leave the typed client
@@ -354,65 +307,6 @@ export function createApp(deps) {
354
307
  contexts.onContextBuilt((ctx) => workspaceEvents.emit('project-ready', { project: ctx.id }));
355
308
  const projectRegistryEntry = workspaceProjects.registryEntry;
356
309
  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
310
  const app = new Hono();
417
311
  app.use('*', compression);
418
312
  // One cache per app: immutable bundle bytes and their negotiated encodings share a cap.
@@ -809,475 +703,28 @@ export function createApp(deps) {
809
703
  return null;
810
704
  }
811
705
  };
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 });
706
+ const providersRoutes = createProvidersRoutes({
707
+ bootRoot,
708
+ capabilities,
709
+ modelCatalog,
710
+ providerAuth,
711
+ providerStatus,
712
+ invalidateHostModels,
713
+ workspaceConfig,
714
+ workspaceEvents,
715
+ openTerminal,
716
+ resolveWorkspaceProfile,
926
717
  });
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
- })(),
718
+ const agentProfilesRoutes = createAgentProfilesRoutes({
719
+ home: deps.home,
720
+ capabilities,
721
+ providerAuth,
722
+ providerStatus,
723
+ invalidateHostModels,
724
+ workspaceProjects,
725
+ resolveWorkspaceProfile,
726
+ projectRootFor,
964
727
  });
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
728
  const workspaceBrowseRoot = async () => {
1282
729
  try {
1283
730
  return (await loadWorkspaceConfig(deps.home.workspaceConfig)).browseRoot;
@@ -1286,510 +733,19 @@ export function createApp(deps) {
1286
733
  return defaultWorkspaceConfig().browseRoot;
1287
734
  }
1288
735
  };
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);
736
+ const projectsRoutes = createProjectsRoutes({
737
+ home: deps.home,
738
+ capabilities,
739
+ contexts,
740
+ workspaceProjects,
741
+ workspaceEvents,
742
+ checkoutProgress,
743
+ semaphore: deps.semaphore,
744
+ taskWebhookFetch: deps.taskWebhookFetch,
745
+ cloneRunner: deps.cloneRunner,
746
+ projectCommandRunner: deps.projectCommandRunner,
747
+ workspaceBrowseRoot,
1634
748
  });
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
749
  // ---- GUI clone (multi-project spec, step 4.3) ----------------------------
1794
750
  // "Add project → Clone from GitHub": clone into the checkout root, then
1795
751
  // register the result through `registerFolder` above (same guards, same
@@ -4083,7 +3039,6 @@ export function createApp(deps) {
4083
3039
  /** The host a thread link names (#589): the bound one, or loopback for a wildcard bind. */
4084
3040
  /** The built-in skills a project's manager offers (#774). Test apps inject partial managers. */
4085
3041
  export { cockpitOriginFor } from './server-deps.js';
4086
- const webhookNameTakenError = (name) => `this project already has a webhook named "${name.trim()}" — pick another name`;
4087
3042
  /**
4088
3043
  * Validate topic-bus upgrades before handshake. Local Host must be loopback. Same-authority or
4089
3044
  * native clients are trusted; verified dev proxies are trusted. Metadata-free foreign loopback