@hearsay-tools/squawk 0.18.0-dev.8321 → 0.18.0-dev.8324
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/live-routes.d.ts +6 -6
- package/dist/server/runs-routes.d.ts +13039 -0
- package/dist/server/runs-routes.js +834 -0
- package/dist/server/runs-routes.js.map +1 -0
- package/dist/server/server.d.ts +2257 -2257
- package/dist/server/server.js +22 -986
- package/dist/server/server.js.map +1 -1
- package/dist/server/workspace-live-routes.d.ts +6 -6
- package/package.json +4 -4
package/dist/server/server.js
CHANGED
|
@@ -1,85 +1,39 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { adoptFallbackControl, protectFallbackRun, runArtifactDirectory } from './project-run-files.js';
|
|
3
|
-
import { projectPaths, fallbackProjectWriteError } from '../project-paths.js';
|
|
1
|
+
import { projectPaths } from '../project-paths.js';
|
|
4
2
|
import { reportsRoutes } from './reports-api.js';
|
|
5
|
-
import { queuedMessagePatchSchema, continueSchema, archiveSchema, openInSchema } from '../contract/index.js';
|
|
6
|
-
import { worktreeFilesQuerySchema } from '../contract/index.js';
|
|
7
|
-
import { gitCommitSchema } from '../contract/index.js';
|
|
8
|
-
import { patchRunInputSchema as patchRunSchema, messageInputSchema as messageSchema } from '../contract/index.js';
|
|
9
|
-
import { imageMimeType } from '../contract/index.js';
|
|
10
|
-
import { providerForActiveRun } from '../contract/index.js';
|
|
11
|
-
import { removedRunnerMessage } from '../contract/index.js';
|
|
12
|
-
import { permissionDecisionSchema } from '../contract/index.js';
|
|
13
|
-
import { runIdParamSchema as permissionRunIdParamSchema } from '../contract/index.js';
|
|
14
3
|
import { CheckoutProgressCache } from './checkout-progress.js';
|
|
15
4
|
import { createWorkspaceLiveRoutes } from './workspace-live-routes.js';
|
|
16
5
|
import { createActivityRoutes } from './activity-routes.js';
|
|
17
6
|
import { createRunnersRoutes } from './runners-routes.js';
|
|
18
7
|
import { createWorkspaceProjects, createWorkspaceProjectContexts, createTaskWebhooks } from './workspace-projects.js';
|
|
19
|
-
import { latestSession } from '../contract/index.js';
|
|
20
|
-
import { ARCHIVED_RUNS_PAGE_DEFAULT } from '../contract/index.js';
|
|
21
|
-
import { archivedRunsQuerySchema, createRunInputSchema, runSummariesQuerySchema } from '../contract/index.js';
|
|
22
|
-
import { DelegationService } from '../delegation/service.js';
|
|
23
|
-
import { runRelationships } from './run-relationships.js';
|
|
24
|
-
import { delegationFailure } from '../delegation/routes.js';
|
|
25
|
-
import { workerDestroyRequestSchema, workerEmptyRequestSchema, runRelationshipsSchema } from '../contract/index.js';
|
|
26
8
|
import { randomUUID } from 'node:crypto';
|
|
27
|
-
import { readFile } from 'node:fs/promises';
|
|
28
9
|
import { basename, dirname, join } from 'node:path';
|
|
29
10
|
import { fileURLToPath } from 'node:url';
|
|
30
11
|
import { Hono } from 'hono';
|
|
31
12
|
import { bodyLimit } from 'hono/body-limit';
|
|
32
13
|
import { matchedRoutes } from 'hono/route';
|
|
33
|
-
import { jsonZodValidator, paramZodValidator, queryZodValidator } from './validators.js';
|
|
34
|
-
import { pinRunInputSchema, archiveFinishedRequestSchema, markAllReadRequestSchema, notifyRunInputSchema } from '../contract/index.js';
|
|
35
14
|
// A contract VALUE, like `workspaceUiStateSchema` in workspace/migrations.ts — the request
|
|
36
15
|
// schema this route validates with is the same one the client compiles against.
|
|
37
|
-
import {
|
|
38
|
-
import { attachmentFileParamSchema, } from '../contract/index.js';
|
|
39
|
-
import { taskWebhooks as taskWebhookList } from '../workspace/webhooks.js';
|
|
16
|
+
import { registeredRunners } from '../core/runner-registry.js';
|
|
40
17
|
import { environmentStamp } from '../core/backend-detect.js';
|
|
41
|
-
import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
|
|
42
18
|
import { createModelsRoutes } from './models-routes.js';
|
|
43
19
|
import { createProviderSignInRoutes } from './provider-sign-in-routes.js';
|
|
44
|
-
import { allUsage,
|
|
45
|
-
import { readHandoff, renderHandoffRecords } from '../handoff.js';
|
|
46
|
-
import { HistoryCursorError, deriveRunContextEvents, readRunHistoryPage } from '../runs/event-history.js';
|
|
47
|
-
import { ARCHIVED_WINDOW } from '../runs/run-index.js';
|
|
48
|
-
import { ownPullRequestNumbers } from '../runs/pull-requests.js';
|
|
49
|
-
import { runHistoryQuerySchema, runIdParamSchema } from '../contract/index.js';
|
|
50
|
-
import { resolveAttachmentPathAsync } from '../workflows/attachment-path.js';
|
|
51
|
-
import { artifactParamsSchema, fileLinkQuerySchema } from '../contract/index.js';
|
|
52
|
-
import { listArtifacts, readArtifact, readArtifactMetadata } from '../artifacts/store.js';
|
|
53
|
-
import { artifactPreview, loadFileLink, rasterMime } from '../artifacts/resolve.js';
|
|
54
|
-
import { toPastedContent } from '../workflows/pasted-content.js';
|
|
55
|
-
import { isUntouchedCancelledRun } from '../workflows/run/run-guards.js';
|
|
56
|
-
import { worktreeDiff } from '../git-worktree.js';
|
|
57
|
-
import { releaseThenRemoveWorktree } from '../git-worktree-release.js';
|
|
20
|
+
import { allUsage, onUsage } from '../core/process-usage.js';
|
|
58
21
|
import { getRepoInfo } from './git.js';
|
|
59
22
|
import { createHealthCache, HEALTH_TTL_MS } from './health-cache.js';
|
|
60
|
-
import { FILE_FORMATS, negotiate } from './accept-negotiation.js';
|
|
61
23
|
import { authorityOfHost, authorityOfOrigin, hostnameOfHost, hostnameOfOrigin } from './host-authority.js';
|
|
62
24
|
import { pluginHealth, pluginLoadReport } from '../plugin/loader.js';
|
|
63
25
|
import { createBackendChecks } from './backend-checks.js';
|
|
64
|
-
import {
|
|
65
|
-
import { healthConfig, loadConfig } from '../config.js';
|
|
26
|
+
import { healthConfig } from '../config.js';
|
|
66
27
|
import { defaultWorkspaceConfig, loadWorkspaceConfig } from '../workspace/config.js';
|
|
67
28
|
import { DEFAULT_AGENT_ACCOUNT_ID, defaultAgentAccountStore, loadAgentAccounts } from '../workspace/agent-accounts.js';
|
|
68
29
|
import { defaultAgentProfile, listAgentProfiles, resolveStoredProfile } from '../workspace/agent-profiles.js';
|
|
69
|
-
import { profileEnv } from '../core/agent-profiles.js';
|
|
70
|
-
import { shellQuote, withEnvPrefix } from '../core/shell-env.js';
|
|
71
|
-
import { resumeCommand } from '../core/runner-cli.js';
|
|
72
30
|
import { createWorkspaceRunFeed } from './workspace-run-feed.js';
|
|
73
31
|
import { isLoopbackHostHeader, resolveCapabilities } from './capabilities.js';
|
|
74
|
-
import { resolveForge
|
|
32
|
+
import { resolveForge } from './forge/index.js';
|
|
75
33
|
import { withProjectAdmission } from './cockpit-ownership.js';
|
|
76
34
|
import { prepareProjects } from '../project-migration/auto.js';
|
|
77
|
-
import { freshCliHandoff, openRunApp, openRunCli, openRunDefaultApp } from './open-in-targets.js';
|
|
78
|
-
import { agentCliRunner } from './open-in-app.js';
|
|
79
35
|
import { ProviderRuntimeAuthObserver } from './provider-auth-runtime.js';
|
|
80
|
-
import { continueRunProviders } from './provider-action-gate.js';
|
|
81
36
|
import { attachProjectWebhooks, createBootContext, createProviderStatus, resolveServerDeps, watchProviderRuntimeAuth } from './server-deps.js';
|
|
82
|
-
import { NO_WEBHOOK_ERROR, agentProfileRefusal, clientRequestOf, launchRun, modelLockRefusal, notifyRefusal, providerGateRefusal, replayedRun, resolveStartWorkflow, startRunInput, } from './start-run-options.js';
|
|
83
37
|
import { ASSET_CACHE_CONTROL, BUILD_HINT_HTML, assetContentType, isSafeAssetFilename, resolveGetRequest, } from './static-ui.js';
|
|
84
38
|
import { compression, createStaticAssets, isFile } from './static-assets.js';
|
|
85
39
|
import { registerBrandFileRoutes } from './brand-file-routes.js';
|
|
@@ -91,6 +45,7 @@ import { createGithubRoutes } from './github-routes.js';
|
|
|
91
45
|
import { createOpenTargetsRoutes, createRepoRoutes, createWorktreesRoutes } from './repo-routes.js';
|
|
92
46
|
import { createFsBrowseRoutes, createRunsIndexRoutes, createWorkspaceConfigRoutes, createWorkspaceEventsRoutes } from './workspace-routes.js';
|
|
93
47
|
import { createAgentConfigRoutes, createAgentWebhooksRoutes, createConfigRoutes, createPlanRoutes, createSkillsRoutes, createSseRoutes, createUiStateRoutes, createWorkflowsRoutes } from './project-settings-routes.js';
|
|
48
|
+
import { createRunsRoutes, withLiveUsage } from './runs-routes.js';
|
|
94
49
|
// ---- project-scoped routing (multi-project spec, step 2.2) -----------------
|
|
95
50
|
export { WorkspaceEventBus } from './server-types.js';
|
|
96
51
|
/**
|
|
@@ -127,26 +82,7 @@ export function projectRouteManifest(app) {
|
|
|
127
82
|
}
|
|
128
83
|
return manifest;
|
|
129
84
|
}
|
|
130
|
-
/** 409 body for every automations route while GitHub automations are off (#801). */
|
|
131
|
-
/** 404 body for a run whose row is in runs.db but whose record this Squawk cannot decode (#779). */
|
|
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.`;
|
|
133
85
|
// ---- workspace SSE (multi-project spec, step 2.8) --------------------------
|
|
134
|
-
// Queued prompt stack bounds (#472). The per-message bounds mirror `messageSchema`
|
|
135
|
-
// above; the one that actually matters is the FOLDED total, because 20 messages of
|
|
136
|
-
// 100 000 chars each would otherwise compose a ~2 M-character {{task}}.
|
|
137
|
-
const MAX_QUEUED_MESSAGES = 20;
|
|
138
|
-
const MAX_QUEUED_ATTACHMENTS = 8;
|
|
139
|
-
const MAX_FOLDED_TASK_CHARS = 200_000;
|
|
140
|
-
/** Length of the prompt a run would execute with — `task` plus its whole stack,
|
|
141
|
-
* composed exactly as `hydrateQueuedInput` composes it. Checked against the
|
|
142
|
-
* PROSPECTIVE state so the user is stopped at the write, not at dequeue where
|
|
143
|
-
* there would be no one left to tell. */
|
|
144
|
-
function foldedLength(task, stack) {
|
|
145
|
-
return [task, ...stack.map((m) => m.text)]
|
|
146
|
-
.map((part) => part.trim())
|
|
147
|
-
.filter((part) => part.length > 0)
|
|
148
|
-
.join('\n\n').length;
|
|
149
|
-
}
|
|
150
86
|
// Request-body size guards (#429). A generous global cap keeps a single
|
|
151
87
|
// localhost request from being unbounded (the largest legit body is 4 pasted
|
|
152
88
|
// images at ~7 MB base64 each); the ui-state PUT gets a much tighter cap since
|
|
@@ -593,38 +529,6 @@ export function createApp(deps) {
|
|
|
593
529
|
return { error: `unknown ${provider} account: ${profileId}` };
|
|
594
530
|
return { profile: resolveStoredProfile(stored) };
|
|
595
531
|
};
|
|
596
|
-
const openHandoffCheckout = (c, suffix = '') => {
|
|
597
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'open');
|
|
598
|
-
if ('status' in checkout)
|
|
599
|
-
return checkout;
|
|
600
|
-
// Hosted mode: there is no "my machine" to open a terminal on. The UI
|
|
601
|
-
// hides the button when localHandoff is false — this is defense in depth.
|
|
602
|
-
return !capabilities().localHandoff
|
|
603
|
-
? { status: 409, body: { error: `local handoff is disabled — this cockpit runs in hosted mode (CEZ_REMOTE)${suffix}` } }
|
|
604
|
-
: checkout;
|
|
605
|
-
};
|
|
606
|
-
/**
|
|
607
|
-
* The environment a terminal handoff must carry so the CLI lands on the right account.
|
|
608
|
-
*
|
|
609
|
-
* `profileId` is the one RECORDED on the step that owns the session, never the project's
|
|
610
|
-
* current selection: `claude --resume <id>` reads `<configDir>/sessions`, so a handoff for a
|
|
611
|
-
* run started on the work account and resumed after the project was switched back would find
|
|
612
|
-
* nothing and silently open a fresh conversation.
|
|
613
|
-
*/
|
|
614
|
-
const handoffEnv = async (provider, profileId) => {
|
|
615
|
-
const resolved = await resolveWorkspaceProfile(provider, profileId);
|
|
616
|
-
if ('error' in resolved) {
|
|
617
|
-
return { error: `this session belongs to an account that no longer exists (${profileId})` };
|
|
618
|
-
}
|
|
619
|
-
const { profile } = resolved;
|
|
620
|
-
return { env: profile.isDefault ? {} : profileEnv(provider, profile.path) };
|
|
621
|
-
};
|
|
622
|
-
/** The copy-paste fallback shown when no terminal could be opened — same account, spelled for
|
|
623
|
-
* this platform's shell. `null` when the account environment cannot be embedded safely. */
|
|
624
|
-
const handoffFallbackCommand = (cwd, command, env) => {
|
|
625
|
-
const prefixed = withEnvPrefix(command, env, process.platform);
|
|
626
|
-
return prefixed === null ? null : `cd ${shellQuote(cwd)} && ${prefixed}`;
|
|
627
|
-
};
|
|
628
532
|
/** A registered project's realpath'd root, or null when the id is unknown. */
|
|
629
533
|
const projectRootFor = async (projectId) => {
|
|
630
534
|
try {
|
|
@@ -709,898 +613,30 @@ export function createApp(deps) {
|
|
|
709
613
|
automationsChanged,
|
|
710
614
|
resolveProjectForge,
|
|
711
615
|
});
|
|
712
|
-
// ---- runs ----------------------------------------------------------------
|
|
713
|
-
// Additive `usage` field (#348): the latest CPU/RSS/proc-count sample of the
|
|
714
|
-
// run's live process tree — absent for finished runs and when `ps` yields
|
|
715
|
-
// nothing. The stored record itself is never touched.
|
|
716
|
-
const withUsage = (run, finishBlocked) => {
|
|
717
|
-
const usage = currentUsage(run.id);
|
|
718
|
-
const { sessionId, backend } = latestSession(run);
|
|
719
|
-
const command = sessionId ? resumeCommand(resolveRunnerId(backend), sessionId) : null;
|
|
720
|
-
return { ...run, ...(usage ? { usage } : {}), ...(command ? { cliResumeCommand: command } : {}),
|
|
721
|
-
...(runnerDefinition(resolveRunnerId(backend)).cli.interactive === false ? { cliHandoff: false } : {}),
|
|
722
|
-
...(finishBlocked !== undefined ? { finishBlocked } : {}) };
|
|
723
|
-
};
|
|
724
|
-
// A list row (#817) with the same live `usage` sample `withUsage` attaches. The sampler is
|
|
725
|
-
// process-wide, so a workspace-level answer can carry it for every project's runs at once — a
|
|
726
|
-
// cold project's stored summaries included. Appended last, exactly where `toRunSummary` puts it.
|
|
727
|
-
const withLiveUsage = (summary) => {
|
|
728
|
-
const usage = currentUsage(summary.id);
|
|
729
|
-
return usage ? { ...summary, usage } : summary;
|
|
730
|
-
};
|
|
731
616
|
// One run feed for every workspace stream connection (hearsay-tools/cezarion#2730): one store
|
|
732
617
|
// subscription per project, one process-wide `seq`, each frame built once per mode.
|
|
733
618
|
const workspaceRunFeed = createWorkspaceRunFeed({
|
|
734
619
|
bootStore: bootContext.store, contexts, onWorkspaceEvent: (listener) => workspaceEvents.on(listener),
|
|
735
620
|
onUsage, allUsage, withLiveUsage,
|
|
736
621
|
});
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
if (!refusal)
|
|
754
|
-
return next();
|
|
755
|
-
// The delegation route in this family answers in the delegation error shape it always uses.
|
|
756
|
-
return c.req.path.endsWith('/worker-destroy')
|
|
757
|
-
? c.json({ code: 'incompatible_state', error: refusal }, 409)
|
|
758
|
-
: c.json({ error: refusal }, 409);
|
|
759
|
-
};
|
|
760
|
-
// ---- chained family: runs lifecycle + artifacts (project-scoped) ----
|
|
761
|
-
const delegationService = deps.delegation?.service ?? new DelegationService(deps.workerCleanup);
|
|
762
|
-
delegationService.setDiscovery({ models: modelCatalog, providers: providerStatus });
|
|
763
|
-
const runsRoutes = new Hono()
|
|
764
|
-
.use('/runs/:id', adoptFallbackControl, requireRunControl)
|
|
765
|
-
.use('/runs/:id/*', adoptFallbackControl, requireRunControl)
|
|
766
|
-
// Legacy (older clients): every full record. The cockpit and `cez task` read `/run-summaries`.
|
|
767
|
-
.get('/runs', (c) => c.json(c.get('project').store.queries.listAllRunsForLegacyRoute().map(run => withUsage(run))))
|
|
768
|
-
// The slim list (#817): the same runs in the same order as `GET /runs`, from the stored
|
|
769
|
-
// `toRunSummary` column with memory laid over it (#779), so the list decodes no record.
|
|
770
|
-
// `?archived=recent` (#864) is the window the cockpit reads: every unarchived run plus the newest
|
|
771
|
-
// `ARCHIVED_WINDOW` archived roots. The default stays every run, for clients that list them all.
|
|
772
|
-
.get('/run-summaries', queryZodValidator(runSummariesQuerySchema), (c) => {
|
|
773
|
-
const archivedWindow = c.req.valid('query').archived === 'recent' ? ARCHIVED_WINDOW : undefined;
|
|
774
|
-
return c.json(c.get('project').store.queries.listRunSummaries({ archivedWindow }).runs.map(withLiveUsage));
|
|
775
|
-
})
|
|
776
|
-
// The archived roots past that window, a page at a time, newest first (#864).
|
|
777
|
-
.get('/run-summaries/archived', queryZodValidator(archivedRunsQuerySchema), (c) => {
|
|
778
|
-
const { before, limit, q } = c.req.valid('query');
|
|
779
|
-
const project = c.get('project');
|
|
780
|
-
// The page shows each task's origin line, so `q` matches what it names: the automation's
|
|
781
|
-
// name, or its recorded id while automations are off, as the cockpit's filter does (#1616).
|
|
782
|
-
const automationNames = new Map(capabilities().automations
|
|
783
|
-
? project.automationStore.list().map((automation) => [automation.id, automation.name]) : []);
|
|
784
|
-
const page = project.store.queries.listArchivedRuns({
|
|
785
|
-
limit: limit ?? ARCHIVED_RUNS_PAGE_DEFAULT,
|
|
786
|
-
automationNames,
|
|
787
|
-
...(before !== undefined ? { before } : {}),
|
|
788
|
-
...(q !== undefined ? { q } : {}),
|
|
789
|
-
});
|
|
790
|
-
if ('error' in page)
|
|
791
|
-
return c.json({ error: page.error }, 400);
|
|
792
|
-
const body = { ...page, runs: page.runs.map(withLiveUsage) };
|
|
793
|
-
return c.json(body);
|
|
794
|
-
})
|
|
795
|
-
.get('/runs/:id/relationships', paramZodValidator(runIdParamSchema), queryZodValidator(workerEmptyRequestSchema), (c) => {
|
|
796
|
-
const { store } = c.get('project');
|
|
797
|
-
const run = store.getRun(c.req.valid('param').id);
|
|
798
|
-
if (!run)
|
|
799
|
-
return c.json({ error: 'not found' }, 404);
|
|
800
|
-
return c.json(runRelationshipsSchema.parse(runRelationships(store, run)));
|
|
801
|
-
})
|
|
802
|
-
.post('/runs/:id/worker-destroy', queryZodValidator(workerEmptyRequestSchema, { code: 'invalid_input', message: 'Invalid cleanup query' }), paramZodValidator(runIdParamSchema, { code: 'invalid_input', message: 'Invalid worker ID' }), jsonZodValidator(workerDestroyRequestSchema, { absent: {}, malformed: null, code: 'invalid_input', message: 'Invalid cleanup input' }), async (c) => {
|
|
803
|
-
const project = c.get('project');
|
|
804
|
-
delegationService.registerProject(project);
|
|
805
|
-
try {
|
|
806
|
-
const result = await delegationService.destroyForHuman(project.id, c.req.valid('param').id, c.req.valid('json'));
|
|
807
|
-
return result.state === 'incomplete' ? c.json(result, 409) : c.json(result, 200);
|
|
808
|
-
}
|
|
809
|
-
catch (error) {
|
|
810
|
-
const failure = delegationFailure(error);
|
|
811
|
-
return c.json(failure.body, failure.status);
|
|
812
|
-
}
|
|
813
|
-
})
|
|
814
|
-
// Registered before the `/:id/...` routes so "archive-finished" and "read-all"
|
|
815
|
-
// never match as a run id.
|
|
816
|
-
.post('/runs/archive-finished', jsonZodValidator(archiveFinishedRequestSchema, { absent: {}, malformed: null }), (c) => c.json(c.get('project').store.archive.archiveFinished(c.req.valid('json').scope, c.req.valid('json').automation)))
|
|
817
|
-
// The read-receipt sweep (#unread-done-items) — the mark-read twin of the archive
|
|
818
|
-
// sweep above, and under the same registration-order guard.
|
|
819
|
-
.post('/runs/read-all', jsonZodValidator(markAllReadRequestSchema, { absent: {}, malformed: null }), (c) => c.json({ read: c.get('project').store.readFlags.markAllRead(c.req.valid('json').automation) }))
|
|
820
|
-
.post('/runs/:id/archive', jsonZodValidator(archiveSchema, { absent: ({}) }), async (c) => {
|
|
821
|
-
const { store } = c.get('project');
|
|
822
|
-
const id = c.req.param('id');
|
|
823
|
-
// An empty/absent body archives (the common case); a malformed body degrades
|
|
824
|
-
// to `{}` just as before, but a wrong-typed `archived` is now a 400 (#429).
|
|
825
|
-
// Archiving also retires any pending usage-limit resume, but that rule belongs to
|
|
826
|
-
// `setArchived` itself — the bulk sweep must obey it too (spec
|
|
827
|
-
// 2026-08-03-auto-resume-after-usage-limit).
|
|
828
|
-
const parsed = { data: c.req.valid('json') };
|
|
829
|
-
const run = store.archive.setArchived(id, parsed.data.archived !== false);
|
|
830
|
-
return run ? c.json(run) : c.json({ error: 'not found' }, 404);
|
|
831
|
-
})
|
|
832
|
-
// Pin one task to the top of this project's list, or unpin it (#935). The archive route's
|
|
833
|
-
// twin in every respect: an absent body pins (the common case), the answer is the updated
|
|
834
|
-
// record, and the change rides the existing `run` SSE because `setPinned` touches. No new
|
|
835
|
-
// event and no new response shape.
|
|
836
|
-
.post('/runs/:id/pin', paramZodValidator(runIdParamSchema), jsonZodValidator(pinRunInputSchema, { absent: {}, malformed: null }), (c) => {
|
|
837
|
-
const { store } = c.get('project');
|
|
838
|
-
const run = store.readFlags.setPinned(c.req.valid('param').id, c.req.valid('json').pinned !== false);
|
|
839
|
-
return run ? c.json(run) : c.json({ error: 'not found' }, 404);
|
|
840
|
-
})
|
|
841
|
-
// Task webhook opt-in for one run (#589), valid in every state — handing a finished task to a
|
|
842
|
-
// bot for follow-up is a real case. Turning it on sends one `task.subscribed` delivery with
|
|
843
|
-
// the note; the note never reaches the agent session. Either direction leaves a durable
|
|
844
|
-
// `handoff` event so the thread shows when and why. Idempotent: repeating `true` with a
|
|
845
|
-
// new note is how "Send a note…" works.
|
|
846
|
-
.post('/runs/:id/notify', paramZodValidator(runIdParamSchema), jsonZodValidator(notifyRunInputSchema), async (c) => {
|
|
847
|
-
const project = c.get('project');
|
|
848
|
-
const { id } = c.req.valid('param');
|
|
849
|
-
const { notify, message } = c.req.valid('json');
|
|
850
|
-
if (!project.store.getRun(id))
|
|
851
|
-
return c.json({ error: 'not found' }, 404);
|
|
852
|
-
if (notify) {
|
|
853
|
-
const entry = await projectRegistryEntry(project.id).catch(() => undefined);
|
|
854
|
-
if (taskWebhookList(entry).length === 0)
|
|
855
|
-
return c.json({ error: NO_WEBHOOK_ERROR }, 400);
|
|
856
|
-
}
|
|
857
|
-
const run = project.store.updateRun(id, { notify: notify ? true : undefined });
|
|
858
|
-
if (!run)
|
|
859
|
-
return c.json({ error: 'not found' }, 404);
|
|
860
|
-
project.store.eventLog.appendEvent(id, {
|
|
861
|
-
type: 'handoff',
|
|
862
|
-
notify,
|
|
863
|
-
...(message === undefined ? {} : { message }),
|
|
864
|
-
});
|
|
865
|
-
if (notify)
|
|
866
|
-
taskWebhooks.attach(project).subscribed(id, message);
|
|
867
|
-
return c.json(run);
|
|
868
|
-
})
|
|
869
|
-
// The per-task off switch for that resume (the workspace setting is Settings → Resources).
|
|
870
|
-
// Idempotent: a run with nothing pending answers 200 too, because "this task will not
|
|
871
|
-
// resume itself" is equally true either way.
|
|
872
|
-
.delete('/runs/:id/auto-resume', (c) => {
|
|
873
|
-
const { store, manager } = c.get('project');
|
|
874
|
-
const id = c.req.param('id');
|
|
875
|
-
if (!store.getRun(id))
|
|
876
|
-
return c.json({ error: 'not found' }, 404);
|
|
877
|
-
manager.cancelAutoResume(id);
|
|
878
|
-
return c.json({ cancelled: true });
|
|
879
|
-
})
|
|
880
|
-
.post('/runs/:id/read', (c) => {
|
|
881
|
-
// No body: opening a thread marks it read, full stop. Stamps `seenAt = now` and
|
|
882
|
-
// returns the updated record (which also rides the `run` SSE via `touch`).
|
|
883
|
-
const run = c.get('project').store.readFlags.setRead(c.req.param('id'));
|
|
884
|
-
return run ? c.json(run) : c.json({ error: 'not found' }, 404);
|
|
885
|
-
})
|
|
886
|
-
.post('/runs/:id/unread', (c) => {
|
|
887
|
-
// The mark-unread twin (#775) — bodyless like its read counterpart: clearing the
|
|
888
|
-
// receipt is the whole action, so there is nothing to say about it. Sits under
|
|
889
|
-
// `/runs/:id/`, so the `read-all` registration-order caveat above does not apply.
|
|
890
|
-
const run = c.get('project').store.readFlags.setUnread(c.req.param('id'));
|
|
891
|
-
return run ? c.json(run) : c.json({ error: 'not found' }, 404);
|
|
892
|
-
})
|
|
893
|
-
.post('/runs', jsonZodValidator(createRunInputSchema, { runners: { ids: ['runner', 'steps.*.runner'] } }), async (c) => {
|
|
894
|
-
const { id: projectId, root: repoRoot, manager, store } = c.get('project');
|
|
895
|
-
const body = c.req.valid('json');
|
|
896
|
-
const clientRequest = clientRequestOf(body);
|
|
897
|
-
if (clientRequest) {
|
|
898
|
-
const replay = replayedRun(store.queries, clientRequest);
|
|
899
|
-
if (replay && 'error' in replay)
|
|
900
|
-
return c.json({ error: replay.error }, replay.status);
|
|
901
|
-
if (replay)
|
|
902
|
-
return c.json(replay.run, 200);
|
|
903
|
-
}
|
|
904
|
-
const locked = modelLockRefusal(repoRoot, body, deps.home);
|
|
905
|
-
if (locked)
|
|
906
|
-
return c.json({ error: locked.error }, locked.status);
|
|
907
|
-
const resolved = await resolveStartWorkflow(repoRoot, body);
|
|
908
|
-
if ('error' in resolved)
|
|
909
|
-
return c.json({ error: resolved.error }, resolved.status);
|
|
910
|
-
const { workflow } = resolved;
|
|
911
|
-
const runner = body.runner === undefined ? (await loadConfig(repoRoot, deps.home)).defaultRunner : registeredRunnerId(body.runner);
|
|
912
|
-
const blocked = await providerGateRefusal(providerActionError, workflow, runner, { repoRoot, picks: { [runner]: body.agentProfile } });
|
|
913
|
-
if (blocked)
|
|
914
|
-
return c.json({ error: blocked.error }, blocked.status);
|
|
915
|
-
const badProfile = await agentProfileRefusal(resolveWorkspaceProfile, runner, body.agentProfile);
|
|
916
|
-
if (badProfile)
|
|
917
|
-
return c.json({ error: badProfile.error }, badProfile.status);
|
|
918
|
-
const noWebhook = await notifyRefusal(body.notify, projectId, projectRegistryEntry);
|
|
919
|
-
if (noWebhook)
|
|
920
|
-
return c.json({ error: noWebhook.error }, noWebhook.status);
|
|
921
|
-
const started = launchRun(manager, workflow, startRunInput(body), clientRequest);
|
|
922
|
-
if ('error' in started)
|
|
923
|
-
return c.json({ error: started.error }, started.status);
|
|
924
|
-
return c.json(started.run, started.status);
|
|
925
|
-
})
|
|
926
|
-
.get('/runs/:id', (c) => {
|
|
927
|
-
const { store, manager } = c.get('project');
|
|
928
|
-
const id = c.req.param('id');
|
|
929
|
-
const run = store.getRun(id);
|
|
930
|
-
if (run)
|
|
931
|
-
return c.json(withUsage(run, manager.finishBlockedReason(run.id) ?? null));
|
|
932
|
-
// A row in runs.db this version cannot decode (#779): listed until read, so say why it will not open.
|
|
933
|
-
return c.json({ error: store.isUnreadable(id) ? UNREADABLE_RUN_ERROR : 'not found' }, 404);
|
|
934
|
-
})
|
|
935
|
-
.get('/runs/:id/history', paramZodValidator(runIdParamSchema), queryZodValidator(runHistoryQuerySchema), async (c) => {
|
|
936
|
-
const { store } = c.get('project');
|
|
937
|
-
const { id } = c.req.valid('param');
|
|
938
|
-
if (!store.getRun(id))
|
|
939
|
-
return c.json({ error: 'not found' }, 404);
|
|
940
|
-
try {
|
|
941
|
-
return c.json(await readRunHistoryPage(store.claims.sourceDataDir(id), id, c.req.valid('query').cursor));
|
|
942
|
-
}
|
|
943
|
-
catch (error) {
|
|
944
|
-
if (error instanceof HistoryCursorError)
|
|
945
|
-
return c.json({ error: error.message }, error.status);
|
|
946
|
-
throw error;
|
|
947
|
-
}
|
|
948
|
-
})
|
|
949
|
-
.get('/runs/:id/history-context', paramZodValidator(runIdParamSchema), async (c) => {
|
|
950
|
-
const { store } = c.get('project');
|
|
951
|
-
const { id } = c.req.valid('param');
|
|
952
|
-
if (!store.getRun(id))
|
|
953
|
-
return c.json({ error: 'not found' }, 404);
|
|
954
|
-
return c.json(await deriveRunContextEvents(store.claims.sourceDataDir(id), id));
|
|
955
|
-
})
|
|
956
|
-
// Editable titles (#389). The UI displays `titleSummary ?? title`, so a
|
|
957
|
-
// user edit sets BOTH: `title` (the record's own name — the raw task stops
|
|
958
|
-
// being it the moment the user renames the run) and `titleSummary` (what
|
|
959
|
-
// actually displays). The auto-summarizer only ever fills an *unset*
|
|
960
|
-
// titleSummary (TurnBookkeeper.recordTurnEnd), so an edit wins over any past or
|
|
961
|
-
// future auto-summary. Answers the updated record.
|
|
962
|
-
.patch('/runs/:id', jsonZodValidator(patchRunSchema), async (c) => {
|
|
963
|
-
const { store, manager } = c.get('project');
|
|
964
|
-
const id = c.req.param('id');
|
|
965
|
-
if (!store.getRun(id))
|
|
966
|
-
return c.json({ error: 'not found' }, 404);
|
|
967
|
-
const parsed = { data: c.req.valid('json') };
|
|
968
|
-
// The prompt is editable only while the run is still queued (#472). Checked
|
|
969
|
-
// BEFORE the title write so a rejected PATCH is a no-op rather than a partial
|
|
970
|
-
// one. `title` itself keeps working on any status — no regression to #389.
|
|
971
|
-
if (parsed.data.task !== undefined) {
|
|
972
|
-
const foldedChars = foldedLength(parsed.data.task, store.getRun(id)?.queuedMessages ?? []);
|
|
973
|
-
if (foldedChars > MAX_FOLDED_TASK_CHARS) {
|
|
974
|
-
return c.json({
|
|
975
|
-
error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${foldedChars})`,
|
|
976
|
-
}, 400);
|
|
977
|
-
}
|
|
978
|
-
if (!manager.editTask(id, parsed.data.task)) {
|
|
979
|
-
return c.json({ error: 'run already started' }, 409);
|
|
980
|
-
}
|
|
981
|
-
}
|
|
982
|
-
if (parsed.data.title !== undefined) {
|
|
983
|
-
// titleOrigin 'user' permanently stops the namer's live updates for this run
|
|
984
|
-
// (spec 2026-07-17-task-auto-naming).
|
|
985
|
-
store.updateRun(id, {
|
|
986
|
-
title: parsed.data.title,
|
|
987
|
-
titleSummary: parsed.data.title,
|
|
988
|
-
titleOrigin: 'user',
|
|
989
|
-
});
|
|
990
|
-
}
|
|
991
|
-
// Completion controls and task access (hearsay-tools/cezarion#2784) change at any status.
|
|
992
|
-
const { title: _title, task: _task, ...options } = parsed.data;
|
|
993
|
-
if (Object.values(options).some(value => value !== undefined))
|
|
994
|
-
store.updateRun(id, options);
|
|
995
|
-
return c.json(store.getRun(id));
|
|
996
|
-
})
|
|
997
|
-
.post('/runs/:id/cancel', (c) => {
|
|
998
|
-
const { store, manager } = c.get('project');
|
|
999
|
-
const id = c.req.param('id');
|
|
1000
|
-
if (!store.getRun(id))
|
|
1001
|
-
return c.json({ error: 'not found' }, 404);
|
|
1002
|
-
// Still asked of the manager after an adoption stopped the run: a worker's stop bookkeeping is its.
|
|
1003
|
-
const cancelled = manager.cancel(id) || c.get('stoppedOnAdoption') === true;
|
|
1004
|
-
return c.json({ cancelled });
|
|
1005
|
-
})
|
|
1006
|
-
// Live-session participation (spec 002): deliver a user message (text +
|
|
1007
|
-
// pasted screenshots) into the run's open claude session.
|
|
1008
|
-
.post('/runs/:id/permissions', paramZodValidator(permissionRunIdParamSchema), jsonZodValidator(permissionDecisionSchema), (c) => {
|
|
1009
|
-
const { store, manager } = c.get('project');
|
|
1010
|
-
const { id } = c.req.valid('param');
|
|
1011
|
-
if (!store.getRun(id))
|
|
1012
|
-
return c.json({ error: 'not found' }, 404);
|
|
1013
|
-
const { requestId, optionId } = c.req.valid('json');
|
|
1014
|
-
if (!manager.respondPermission(id, requestId, optionId)) {
|
|
1015
|
-
return c.json({ error: 'permission request is no longer available or option is invalid' }, 409);
|
|
1016
|
-
}
|
|
1017
|
-
return c.json({ delivered: true });
|
|
1018
|
-
})
|
|
1019
|
-
.post('/runs/:id/messages', jsonZodValidator(messageSchema), async (c) => {
|
|
1020
|
-
const { store, manager } = c.get('project');
|
|
1021
|
-
const id = c.req.param('id');
|
|
1022
|
-
const run = store.getRun(id);
|
|
1023
|
-
if (!run)
|
|
1024
|
-
return c.json({ error: 'not found' }, 404);
|
|
1025
|
-
const parsed = { data: c.req.valid('json') };
|
|
1026
|
-
// Stacking onto a queued prompt mutates an existing task and invokes no provider.
|
|
1027
|
-
// Provider availability still gates live delivery after the record leaves `queued`, but
|
|
1028
|
-
// must not strand prompt authoring just because an unrelated fallback provider is
|
|
1029
|
-
// disconnected (provider-auth spec: disabling never blocks existing-task mutations).
|
|
1030
|
-
// In the dequeue race, the ladder below safely turns this into a starting-state buffer.
|
|
1031
|
-
if (run.status !== 'queued') {
|
|
1032
|
-
const blocked = await providerActionError([resolveRunnerId(providerForActiveRun(run))], { repoRoot: c.get('project').root, run, live: true });
|
|
1033
|
-
if (blocked)
|
|
1034
|
-
return c.json({ error: blocked }, 409);
|
|
1035
|
-
}
|
|
1036
|
-
const content = [
|
|
1037
|
-
...parsed.data.images.map(toPastedContent),
|
|
1038
|
-
...(parsed.data.text.trim() ? [{ type: 'text', text: parsed.data.text }] : []),
|
|
1039
|
-
];
|
|
1040
|
-
// Three-rung delivery ladder (#472). Branch on the ENGINE's answer rather
|
|
1041
|
-
// than a status read here: the handler cannot observe the dequeue safely
|
|
1042
|
-
// (the record is written a tick later), the engine can.
|
|
1043
|
-
// live session → delivered · still queued → folded into the prompt
|
|
1044
|
-
// starting up → buffered · anything else → 409, exactly as before
|
|
1045
|
-
if (manager.sendMessage(id, content))
|
|
1046
|
-
return c.json({ delivered: true });
|
|
1047
|
-
const currentRun = store.getRun(id);
|
|
1048
|
-
const stack = currentRun?.queuedMessages ?? [];
|
|
1049
|
-
// Bounds apply only to a message that is actually about to be stacked. Without this
|
|
1050
|
-
// gate an over-long message posted to a *finished* run would answer `400 prompt too
|
|
1051
|
-
// long` when the truthful answer is `409 session closed`. The status read is safe
|
|
1052
|
-
// here because it only decides whether to reject EARLY — `enqueueMessage` still
|
|
1053
|
-
// re-checks against the engine's own queue before writing anything.
|
|
1054
|
-
if (currentRun?.status === 'queued') {
|
|
1055
|
-
if (stack.length >= MAX_QUEUED_MESSAGES) {
|
|
1056
|
-
return c.json({ error: `too many queued messages — ${MAX_QUEUED_MESSAGES} message limit` }, 400);
|
|
1057
|
-
}
|
|
1058
|
-
const stackedImages = stack.reduce((n, m) => n + (m.images?.length ?? 0), 0);
|
|
1059
|
-
if (stackedImages + parsed.data.images.length > MAX_QUEUED_ATTACHMENTS) {
|
|
1060
|
-
return c.json({ error: `too many queued attachments — ${MAX_QUEUED_ATTACHMENTS} attachment limit across the stack` }, 400);
|
|
1061
|
-
}
|
|
1062
|
-
const prospective = foldedLength(currentRun.task, [...stack, { text: parsed.data.text }]);
|
|
1063
|
-
if (prospective > MAX_FOLDED_TASK_CHARS) {
|
|
1064
|
-
return c.json({
|
|
1065
|
-
error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
|
|
1066
|
-
}, 400);
|
|
1067
|
-
}
|
|
1068
|
-
}
|
|
1069
|
-
const queued = manager.enqueueMessage(id, content);
|
|
1070
|
-
if (queued)
|
|
1071
|
-
return c.json({ queued: true, message: queued });
|
|
1072
|
-
if (manager.deferMessage(id, content))
|
|
1073
|
-
return c.json({ deferred: true });
|
|
1074
|
-
return c.json({ error: 'session closed' }, 409);
|
|
1075
|
-
})
|
|
1076
|
-
// Edit / remove a stacked message (#472). Registered before any conflicting
|
|
1077
|
-
// `/:id` route so `queued-messages` never matches as a run id.
|
|
1078
|
-
.patch('/runs/:id/queued-messages/:msgId', jsonZodValidator(queuedMessagePatchSchema), async (c) => {
|
|
1079
|
-
const { store, manager } = c.get('project');
|
|
1080
|
-
const id = c.req.param('id');
|
|
1081
|
-
const run = store.getRun(id);
|
|
1082
|
-
if (!run)
|
|
1083
|
-
return c.json({ error: 'not found' }, 404);
|
|
1084
|
-
const parsed = { data: c.req.valid('json') };
|
|
1085
|
-
const msgId = c.req.param('msgId');
|
|
1086
|
-
const stack = run.queuedMessages ?? [];
|
|
1087
|
-
const existing = stack.find((m) => m.id === msgId);
|
|
1088
|
-
if (!existing)
|
|
1089
|
-
return c.json({ error: 'not found' }, 404);
|
|
1090
|
-
const effectiveText = parsed.data.text ?? existing.text;
|
|
1091
|
-
const effectiveImageCount = parsed.data.images?.length ?? existing.images?.length ?? 0;
|
|
1092
|
-
if (!effectiveText.trim() && effectiveImageCount === 0) {
|
|
1093
|
-
return c.json({ error: 'message needs text or at least one attachment' }, 400);
|
|
1094
|
-
}
|
|
1095
|
-
const others = stack.filter((m) => m.id !== msgId);
|
|
1096
|
-
const stackedImages = others.reduce((n, m) => n + (m.images?.length ?? 0), 0);
|
|
1097
|
-
if (stackedImages + effectiveImageCount > MAX_QUEUED_ATTACHMENTS) {
|
|
1098
|
-
return c.json({ error: `too many queued attachments — ${MAX_QUEUED_ATTACHMENTS} attachment limit across the stack` }, 400);
|
|
1099
|
-
}
|
|
1100
|
-
const prospective = foldedLength(run.task, [...others, { text: effectiveText }]);
|
|
1101
|
-
if (prospective > MAX_FOLDED_TASK_CHARS) {
|
|
1102
|
-
return c.json({
|
|
1103
|
-
error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
|
|
1104
|
-
}, 400);
|
|
1105
|
-
}
|
|
1106
|
-
const images = parsed.data.images?.map(toPastedContent);
|
|
1107
|
-
const message = manager.editQueuedMessage(id, msgId, {
|
|
1108
|
-
...(parsed.data.text !== undefined ? { text: parsed.data.text } : {}),
|
|
1109
|
-
...(images !== undefined ? { images } : {}),
|
|
1110
|
-
});
|
|
1111
|
-
if (!message)
|
|
1112
|
-
return c.json({ error: 'run already started' }, 409);
|
|
1113
|
-
return c.json({ message });
|
|
1114
|
-
})
|
|
1115
|
-
.delete('/runs/:id/queued-messages/:msgId', (c) => {
|
|
1116
|
-
const { store, manager } = c.get('project');
|
|
1117
|
-
const id = c.req.param('id');
|
|
1118
|
-
const run = store.getRun(id);
|
|
1119
|
-
if (!run)
|
|
1120
|
-
return c.json({ error: 'not found' }, 404);
|
|
1121
|
-
const msgId = c.req.param('msgId');
|
|
1122
|
-
if (!(run.queuedMessages ?? []).some((m) => m.id === msgId)) {
|
|
1123
|
-
return c.json({ error: 'not found' }, 404);
|
|
1124
|
-
}
|
|
1125
|
-
if (!manager.removeQueuedMessage(id, msgId))
|
|
1126
|
-
return c.json({ error: 'run already started' }, 409);
|
|
1127
|
-
return c.json({ removed: true });
|
|
1128
|
-
})
|
|
1129
|
-
// "Finish": gracefully close a waiting session — the run completes as done.
|
|
1130
|
-
.post('/runs/:id/finish', (c) => {
|
|
1131
|
-
const { store, manager } = c.get('project');
|
|
1132
|
-
const id = c.req.param('id');
|
|
1133
|
-
if (!store.getRun(id))
|
|
1134
|
-
return c.json({ error: 'not found' }, 404);
|
|
1135
|
-
const finished = manager.finish(id);
|
|
1136
|
-
if (!finished)
|
|
1137
|
-
return c.json({ error: manager.finishBlockedReason(id) ?? 'no open session' }, 409);
|
|
1138
|
-
return c.json({ finished: true });
|
|
1139
|
-
})
|
|
1140
|
-
// "Continue" (spec 003): reopen a finished run's session in-process.
|
|
1141
|
-
.post('/runs/:id/continue', jsonZodValidator(continueSchema, { absent: ({}), runners: { ids: ['runner'] } }), async (c) => {
|
|
1142
|
-
const { root: repoRoot, store, manager } = c.get('project');
|
|
1143
|
-
const id = c.req.param('id');
|
|
1144
|
-
const run = store.getRun(id);
|
|
1145
|
-
if (!run)
|
|
1146
|
-
return c.json({ error: 'not found' }, 404);
|
|
1147
|
-
// Bounded resume text (#429); an empty/absent body still just re-runs on the
|
|
1148
|
-
// run's current backend, and a runner/model override reopens on that engine (#401).
|
|
1149
|
-
const parsed = { data: c.req.valid('json') };
|
|
1150
|
-
if (agentModelsLocked(repoRoot, process.env, deps.home) &&
|
|
1151
|
-
(parsed.data.model?.trim() || parsed.data.effort?.trim())) {
|
|
1152
|
-
return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
|
|
1153
|
-
}
|
|
1154
|
-
// Untouched tasks execute their original workflow, including step-level runners.
|
|
1155
|
-
// Resolve the same fallback as POST /runs, and pass it through so validation
|
|
1156
|
-
// and execution use the same provider even when the record inherited config.
|
|
1157
|
-
// Before the provider check: a run saved on a removed runner has no provider of its own.
|
|
1158
|
-
if (run.removedRunner !== undefined && parsed.data.runner === undefined) {
|
|
1159
|
-
return c.json({ error: removedRunnerMessage(run.removedRunner) }, 409);
|
|
1160
|
-
}
|
|
1161
|
-
const untouched = isUntouchedCancelledRun(run);
|
|
1162
|
-
const { original: originalProvider, target: provider, required } = await continueRunProviders(run, parsed.data.runner, untouched, async () => (await loadConfig(repoRoot, deps.home)).defaultRunner);
|
|
1163
|
-
const blocked = await providerActionError(required, { repoRoot, run, untouched, runners: { original: originalProvider, target: provider } });
|
|
1164
|
-
if (blocked)
|
|
1165
|
-
return c.json({ error: blocked }, 409);
|
|
1166
|
-
const result = manager.continueRun(id, {
|
|
1167
|
-
text: parsed.data.text,
|
|
1168
|
-
images: parsed.data.images?.map(toPastedContent),
|
|
1169
|
-
runner: untouched || parsed.data.runner !== undefined ? provider : undefined,
|
|
1170
|
-
...(untouched ? { originalRunner: originalProvider } : {}),
|
|
1171
|
-
model: parsed.data.model,
|
|
1172
|
-
effort: parsed.data.effort,
|
|
1173
|
-
});
|
|
1174
|
-
if (!result.ok)
|
|
1175
|
-
return c.json({ error: result.error }, 409);
|
|
1176
|
-
return c.json({ continued: true });
|
|
1177
|
-
})
|
|
1178
|
-
// "Open in terminal" (spec 003): hand the session off to a real terminal —
|
|
1179
|
-
// in the task's worktree when it still exists (spec 006).
|
|
1180
|
-
.post('/runs/:id/open-in-cli', async (c) => {
|
|
1181
|
-
const project = c.get('project');
|
|
1182
|
-
const checkout = openHandoffCheckout(c, '; resume the session from a machine that has the checkout');
|
|
1183
|
-
if ('status' in checkout)
|
|
1184
|
-
return c.json(checkout.body, checkout.status);
|
|
1185
|
-
if (checkout.run.removedRunner !== undefined)
|
|
1186
|
-
return c.json({ error: removedRunnerMessage(checkout.run.removedRunner) }, 409);
|
|
1187
|
-
const { sessionId, backend: savedBackend, profileId } = latestSession(checkout.run), backend = resolveRunnerId(savedBackend);
|
|
1188
|
-
if (!sessionId)
|
|
1189
|
-
return c.json({ error: 'no agent session to resume' }, 409);
|
|
1190
|
-
if (runnerDefinition(backend).cli.interactive === false)
|
|
1191
|
-
return c.json({ error: 'this runner has no interactive CLI' }, 409);
|
|
1192
|
-
const resume = checkout.resumeAllowed ? resumeCommand(backend, sessionId) : undefined;
|
|
1193
|
-
// Fails closed on an id we do not recognise — see resumeCommand (open-mercato/cezar#431).
|
|
1194
|
-
if (resume === null)
|
|
1195
|
-
return c.json({ error: 'the recorded session id has an unexpected shape' }, 409);
|
|
1196
|
-
const blocked = await providerActionError([backend], { repoRoot: project.root, picks: { [backend]: resume ? profileId ?? DEFAULT_AGENT_ACCOUNT_ID : undefined } });
|
|
1197
|
-
if (blocked)
|
|
1198
|
-
return c.json({ error: blocked }, 409);
|
|
1199
|
-
const cwd = checkout.directory();
|
|
1200
|
-
const refusal = fallbackProjectWriteError(cwd);
|
|
1201
|
-
if (refusal)
|
|
1202
|
-
return c.json({ error: refusal }, 409);
|
|
1203
|
-
const account = resume
|
|
1204
|
-
? { command: resume, ...await handoffEnv(backend, profileId) }
|
|
1205
|
-
: await freshCliHandoff(backend, project.root, deps.home);
|
|
1206
|
-
if ('error' in account)
|
|
1207
|
-
return c.json({ error: account.error }, 409);
|
|
1208
|
-
const { command } = account;
|
|
1209
|
-
const fallback = handoffFallbackCommand(cwd, command, account.env);
|
|
1210
|
-
// Fail closed for the same reason as the session id: a terminal opened without the
|
|
1211
|
-
// account's config dir resumes nothing and says nothing about why.
|
|
1212
|
-
if (fallback === null) {
|
|
1213
|
-
return c.json({ error: 'this account\'s folder cannot be used in a terminal command' }, 409);
|
|
1214
|
-
}
|
|
1215
|
-
const opened = await openTerminal(cwd, command, account.env);
|
|
1216
|
-
if (!opened) {
|
|
1217
|
-
return c.json({ error: 'no terminal emulator found', command: fallback }, 409);
|
|
1218
|
-
}
|
|
1219
|
-
return c.json({ opened: true, command });
|
|
1220
|
-
})
|
|
1221
|
-
// Open a run's worktree (or the repo root) in the chosen local app.
|
|
1222
|
-
.post('/runs/:id/open-in', jsonZodValidator(openInSchema), async (c) => {
|
|
1223
|
-
const project = c.get('project');
|
|
1224
|
-
const checkout = openHandoffCheckout(c);
|
|
1225
|
-
if ('status' in checkout)
|
|
1226
|
-
return c.json(checkout.body, checkout.status);
|
|
1227
|
-
// Follows the safeParse convention (#429); the downstream allowlist match is the real
|
|
1228
|
-
// injection guard, this just validates the shape.
|
|
1229
|
-
const { target, path: relPath } = c.req.valid('json');
|
|
1230
|
-
const dir = checkout.directory();
|
|
1231
|
-
if (target === 'default') {
|
|
1232
|
-
const worktree = checkout.defaultWorktree();
|
|
1233
|
-
if (typeof worktree !== 'string')
|
|
1234
|
-
return c.json(worktree.body, worktree.status);
|
|
1235
|
-
return openRunDefaultApp(c, worktree, relPath, openFile);
|
|
1236
|
-
}
|
|
1237
|
-
const cliRunner = agentCliRunner(target);
|
|
1238
|
-
if (cliRunner) {
|
|
1239
|
-
return openRunCli(c, checkout.run, cliRunner, dir, project.root, { home: deps.home,
|
|
1240
|
-
providerActionError, resumeCommand, handoffEnv, handoffFallbackCommand, openTerminal,
|
|
1241
|
-
}, checkout);
|
|
1242
|
-
}
|
|
1243
|
-
return openRunApp(c, target, dir, openApp);
|
|
1244
|
-
})
|
|
1245
|
-
// Handoff journal plus stored records (hearsay-tools/cezarion#1809): unknown task is 404; no file is ''.
|
|
1246
|
-
.get('/runs/:id/handoff', (c) => {
|
|
1247
|
-
const { store } = c.get('project');
|
|
1248
|
-
const run = store.getRun(c.req.param('id'));
|
|
1249
|
-
if (!run)
|
|
1250
|
-
return c.json({ error: 'not found' }, 404);
|
|
1251
|
-
return c.text(renderHandoffRecords(readHandoff(store.claims.sourceDataDir(run.id), run.id), run.handoffRecords), 200, {
|
|
1252
|
-
'content-type': 'text/markdown; charset=utf-8',
|
|
1253
|
-
});
|
|
1254
|
-
})
|
|
1255
|
-
.get('/runs/:id/images/:file', paramZodValidator(attachmentFileParamSchema), async (c) => {
|
|
1256
|
-
const { store } = c.get('project');
|
|
1257
|
-
const run = store.getRun(c.req.param('id'));
|
|
1258
|
-
if (!run)
|
|
1259
|
-
return c.json({ error: 'not found' }, 404);
|
|
1260
|
-
const file = c.req.valid('param').file;
|
|
1261
|
-
const path = await resolveAttachmentPathAsync(store.claims.sourceDataDir(run.id), run.id, file);
|
|
1262
|
-
if (!path)
|
|
1263
|
-
return c.json({ error: 'not found' }, 404);
|
|
1264
|
-
const ext = file.split('.').pop() ?? '';
|
|
1265
|
-
const image = IMAGE_TYPES[ext];
|
|
1266
|
-
// An image answers exactly as it always has — the cockpit renders it in an `<img>`.
|
|
1267
|
-
// Everything else is a user-supplied file (#950) and leaves under the download headers.
|
|
1268
|
-
const type = image ?? FILE_TYPES[ext] ?? 'application/octet-stream';
|
|
1269
|
-
return new Response(await readFile(path), {
|
|
1270
|
-
headers: {
|
|
1271
|
-
'content-type': type,
|
|
1272
|
-
'cache-control': 'private, max-age=31536000, immutable',
|
|
1273
|
-
...(image
|
|
1274
|
-
? {}
|
|
1275
|
-
: {
|
|
1276
|
-
'x-content-type-options': 'nosniff',
|
|
1277
|
-
// Engine-generated names are `pasted-3.pdf`-shaped, but a header value is not the
|
|
1278
|
-
// place to find out otherwise: anything exotic degrades to an underscore rather
|
|
1279
|
-
// than to a quote that could split the header.
|
|
1280
|
-
'content-disposition': `attachment; filename="${file.replace(/[^A-Za-z0-9._-]/g, '_')}"`,
|
|
1281
|
-
}),
|
|
1282
|
-
},
|
|
1283
|
-
});
|
|
1284
|
-
})
|
|
1285
|
-
// Task diff (spec 006): what this run changed — its worktree vs its base.
|
|
1286
|
-
.get('/runs/:id/diff', async (c) => {
|
|
1287
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'existing-worktree' });
|
|
1288
|
-
if ('body' in checkout)
|
|
1289
|
-
return c.json(checkout.body, checkout.status);
|
|
1290
|
-
if (!checkout.directory)
|
|
1291
|
-
return c.text('(no worktree — this task ran directly in the repo working tree)');
|
|
1292
|
-
const result = await worktreeDiff(checkout.directory, checkout.run.baseBranch ?? 'HEAD', undefined, checkout.beforeLiveIndex);
|
|
1293
|
-
if (typeof result !== 'string')
|
|
1294
|
-
return c.json({ error: result.error }, 409);
|
|
1295
|
-
return c.text(result);
|
|
1296
|
-
})
|
|
1297
|
-
.get('/runs/:id/changes', async (c) => {
|
|
1298
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
|
|
1299
|
-
if ('body' in checkout)
|
|
1300
|
-
return c.json(checkout.body, checkout.status);
|
|
1301
|
-
const { run, directory: workingDirectory } = checkout;
|
|
1302
|
-
const result = await collectChanges(workingDirectory, run.baseBranch ?? 'HEAD', {
|
|
1303
|
-
beforeLiveIndex: checkout.beforeLiveIndex,
|
|
1304
|
-
taskBranch: run.branch,
|
|
1305
|
-
// Anchors a repointed worktree at the branch as this run found it (#751).
|
|
1306
|
-
runStartedAt: run.startedAt,
|
|
1307
|
-
// A read-only GET against the user's real checkout must never modify its index.
|
|
1308
|
-
intentToAdd: run.worktreePath ? undefined : false,
|
|
1309
|
-
});
|
|
1310
|
-
if (!result.ok)
|
|
1311
|
-
return c.json({ error: result.error }, 409);
|
|
1312
|
-
return c.json(result.changes);
|
|
1313
|
-
})
|
|
1314
|
-
// The run's own commits (<base>..HEAD on the worktree branch) — the Commits tab.
|
|
1315
|
-
.get('/runs/:id/commits', async (c) => {
|
|
1316
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
|
|
1317
|
-
if ('body' in checkout)
|
|
1318
|
-
return c.json(checkout.body, checkout.status);
|
|
1319
|
-
const { run, directory: workingDirectory } = checkout;
|
|
1320
|
-
const result = await collectRunCommits(workingDirectory, run.baseBranch ?? 'HEAD');
|
|
1321
|
-
if (!result.ok)
|
|
1322
|
-
return c.json({ error: result.error }, 409);
|
|
1323
|
-
return c.json({ commits: result.commits });
|
|
1324
|
-
})
|
|
1325
|
-
// One of the run's commits, structured like the Changes tab (reuses collectCommitChanges).
|
|
1326
|
-
.get('/runs/:id/commit/:sha', async (c) => {
|
|
1327
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
|
|
1328
|
-
if ('body' in checkout)
|
|
1329
|
-
return c.json(checkout.body, checkout.status);
|
|
1330
|
-
const { directory: workingDirectory } = checkout;
|
|
1331
|
-
const result = await collectCommitChanges(workingDirectory, c.req.param('sha'));
|
|
1332
|
-
if (!result.ok)
|
|
1333
|
-
return c.json({ error: result.error }, 409);
|
|
1334
|
-
return c.json(result.commit);
|
|
1335
|
-
})
|
|
1336
|
-
.get('/runs/:id/file-link', paramZodValidator(artifactParamsSchema.omit({ artifactId: true })), queryZodValidator(fileLinkQuerySchema), async (c) => {
|
|
1337
|
-
const { root, store } = c.get('project');
|
|
1338
|
-
const checkout = runCheckout(c.get('project'), c.req.valid('param').id, 'read', { directory: 'recorded-path-or-root' });
|
|
1339
|
-
if ('body' in checkout)
|
|
1340
|
-
return c.json(checkout.body, checkout.status);
|
|
1341
|
-
const { run, directory: workingDirectory } = checkout;
|
|
1342
|
-
const query = c.req.valid('query');
|
|
1343
|
-
const loaded = await loadFileLink({ dataDir: store.claims.sourceDataDir(run.id), runId: run.id, projectRoot: root, workingDirectory, path: query.path });
|
|
1344
|
-
if (query.raw === '1') {
|
|
1345
|
-
if (!loaded.imageBytes || loaded.preview.type !== 'file')
|
|
1346
|
-
return c.json({ error: 'Only bounded raster images can be served inline.' }, 409);
|
|
1347
|
-
return c.body(new Uint8Array(loaded.imageBytes).buffer, 200, {
|
|
1348
|
-
'content-type': rasterMime(loaded.preview.path), 'x-content-type-options': 'nosniff',
|
|
1349
|
-
'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
|
|
1350
|
-
});
|
|
1351
|
-
}
|
|
1352
|
-
return c.json(loaded.preview);
|
|
1353
|
-
})
|
|
1354
|
-
.get('/runs/:id/artifacts', paramZodValidator(artifactParamsSchema.omit({ artifactId: true })), async (c) => {
|
|
1355
|
-
const { store } = c.get('project');
|
|
1356
|
-
const id = c.req.valid('param').id;
|
|
1357
|
-
if (!store.getRun(id))
|
|
1358
|
-
return c.json({ error: 'not found' }, 404);
|
|
1359
|
-
return c.json({ artifacts: await listArtifacts(runArtifactDirectory(store, id), id) });
|
|
1360
|
-
})
|
|
1361
|
-
.get('/runs/:id/artifacts/:artifactId', paramZodValidator(artifactParamsSchema), async (c) => {
|
|
1362
|
-
const { store } = c.get('project');
|
|
1363
|
-
const { id, artifactId } = c.req.valid('param');
|
|
1364
|
-
if (!store.getRun(id))
|
|
1365
|
-
return c.json({ error: 'not found' }, 404);
|
|
1366
|
-
const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
|
|
1367
|
-
if (!entry)
|
|
1368
|
-
return c.json({ error: 'Published file is missing or unavailable.' }, 404);
|
|
1369
|
-
return c.json(artifactPreview(entry.metadata, entry.bytes));
|
|
1370
|
-
})
|
|
1371
|
-
.get('/runs/:id/artifacts/:artifactId/metadata', paramZodValidator(artifactParamsSchema), async (c) => {
|
|
1372
|
-
const { store } = c.get('project');
|
|
1373
|
-
const { id, artifactId } = c.req.valid('param');
|
|
1374
|
-
if (!store.getRun(id))
|
|
1375
|
-
return c.json({ error: 'not found' }, 404);
|
|
1376
|
-
const artifact = await readArtifactMetadata(runArtifactDirectory(store, id), id, artifactId);
|
|
1377
|
-
if (!artifact)
|
|
1378
|
-
return c.json({ error: 'Published file is missing or unavailable.' }, 404);
|
|
1379
|
-
return c.json({ artifact });
|
|
1380
|
-
})
|
|
1381
|
-
.get('/runs/:id/artifacts/:artifactId/download', paramZodValidator(artifactParamsSchema), async (c) => {
|
|
1382
|
-
const { store } = c.get('project');
|
|
1383
|
-
const { id, artifactId } = c.req.valid('param');
|
|
1384
|
-
if (!store.getRun(id))
|
|
1385
|
-
return c.json({ error: 'not found' }, 404);
|
|
1386
|
-
const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
|
|
1387
|
-
if (!entry)
|
|
1388
|
-
return c.json({ error: 'Published file is missing or unavailable.' }, 404);
|
|
1389
|
-
return c.body(new Uint8Array(entry.bytes).buffer, 200, {
|
|
1390
|
-
'content-type': 'application/octet-stream', 'x-content-type-options': 'nosniff',
|
|
1391
|
-
'content-disposition': `attachment; filename="${entry.metadata.name.replace(/[^A-Za-z0-9._-]/g, '_')}"`,
|
|
1392
|
-
'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
|
|
1393
|
-
});
|
|
1394
|
-
})
|
|
1395
|
-
.get('/runs/:id/artifacts/:artifactId/image', paramZodValidator(artifactParamsSchema), async (c) => {
|
|
1396
|
-
const { store } = c.get('project');
|
|
1397
|
-
const { id, artifactId } = c.req.valid('param');
|
|
1398
|
-
if (!store.getRun(id))
|
|
1399
|
-
return c.json({ error: 'not found' }, 404);
|
|
1400
|
-
const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
|
|
1401
|
-
if (!entry)
|
|
1402
|
-
return c.json({ error: 'Published file is missing or unavailable.' }, 404);
|
|
1403
|
-
const mime = rasterMime(entry.metadata.name);
|
|
1404
|
-
if (!mime)
|
|
1405
|
-
return c.json({ error: 'Only raster images can be served inline.' }, 409);
|
|
1406
|
-
return c.body(new Uint8Array(entry.bytes).buffer, 200, {
|
|
1407
|
-
'content-type': mime, 'x-content-type-options': 'nosniff',
|
|
1408
|
-
'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
|
|
1409
|
-
});
|
|
1410
|
-
})
|
|
1411
|
-
// Files tab: directory listing (path omitted or a dir) or file content
|
|
1412
|
-
// (size-capped, binary flagged). Traversal-safe — readWorktreePath rejects
|
|
1413
|
-
// anything escaping the worktree. `raw=1` (R5 Step 1.6) serves the BYTES of
|
|
1414
|
-
// image files only, for the preview's inline <img> — never HTML/JS/etc., so
|
|
1415
|
-
// no worktree file can become a same-origin document, and never past the
|
|
1416
|
-
// size cap. The no-script CSP neutralizes SVG opened as a top-level URL.
|
|
1417
|
-
//
|
|
1418
|
-
// An `Accept` that asks for images reaches the same raw branch without the flag — which is
|
|
1419
|
-
// what an `<img>` sends — while the flag still wins whenever it is present and `*<slash>*`
|
|
1420
|
-
// (every `fetch`) still gets the JSON listing. See `negotiate`.
|
|
1421
|
-
.get('/runs/:id/files', queryZodValidator(worktreeFilesQuerySchema), async (c) => {
|
|
1422
|
-
const query = c.req.valid('query');
|
|
1423
|
-
c.header('vary', 'Accept');
|
|
1424
|
-
const wantsRaw = query.raw !== undefined
|
|
1425
|
-
? query.raw === '1'
|
|
1426
|
-
: negotiate(c.req.header('accept'), FILE_FORMATS) === 'image/*';
|
|
1427
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
|
|
1428
|
-
if ('body' in checkout)
|
|
1429
|
-
return c.json(checkout.body, checkout.status);
|
|
1430
|
-
const { directory: workingDirectory } = checkout;
|
|
1431
|
-
const result = await readWorktreePath(workingDirectory, query.path ?? '');
|
|
1432
|
-
if (result.kind === 'invalid' || result.kind === 'missing') {
|
|
1433
|
-
return c.json({ error: result.error }, 409);
|
|
1434
|
-
}
|
|
1435
|
-
if (result.kind === 'dir') {
|
|
1436
|
-
return c.json({
|
|
1437
|
-
// `as const` or the literal widens to `string` during Hono's route-type inference,
|
|
1438
|
-
// which erases the discriminant a consumer narrows on — `entry.type === 'dir'` then
|
|
1439
|
-
// leaves `never` and every field access on it fails. The wire was always 'dir'.
|
|
1440
|
-
type: 'dir',
|
|
1441
|
-
path: result.path,
|
|
1442
|
-
entries: result.entries,
|
|
1443
|
-
});
|
|
1444
|
-
}
|
|
1445
|
-
if (wantsRaw) {
|
|
1446
|
-
const mime = imageMimeType(result.path);
|
|
1447
|
-
if (mime === null || result.tooLarge) {
|
|
1448
|
-
// `?raw=1` ASKED for bytes, so it hears why it cannot have them (a 409 with the
|
|
1449
|
-
// reason). An `Accept` is only a preference, so a
|
|
1450
|
-
// resource with no image representation falls THROUGH to the JSON answer below rather
|
|
1451
|
-
// than turning a browser's navigation to a text file into an error.
|
|
1452
|
-
if (query.raw !== undefined) {
|
|
1453
|
-
const error = mime === null
|
|
1454
|
-
? `raw serving is limited to images: ${result.path}`
|
|
1455
|
-
: `file too large to serve raw (${result.size} bytes): ${result.path}`;
|
|
1456
|
-
return c.json({ error }, 409);
|
|
1457
|
-
}
|
|
1458
|
-
}
|
|
1459
|
-
else {
|
|
1460
|
-
const bytes = await readFile(join(workingDirectory, result.path));
|
|
1461
|
-
return c.body(new Uint8Array(bytes).buffer, 200, {
|
|
1462
|
-
'content-type': mime,
|
|
1463
|
-
'x-content-type-options': 'nosniff',
|
|
1464
|
-
'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
|
|
1465
|
-
});
|
|
1466
|
-
}
|
|
1467
|
-
}
|
|
1468
|
-
return c.json({
|
|
1469
|
-
type: 'file',
|
|
1470
|
-
path: result.path,
|
|
1471
|
-
size: result.size,
|
|
1472
|
-
binary: result.binary,
|
|
1473
|
-
tooLarge: result.tooLarge,
|
|
1474
|
-
...(result.content !== undefined ? { content: result.content } : {}),
|
|
1475
|
-
});
|
|
1476
|
-
})
|
|
1477
|
-
.post('/runs/:id/git/commit', jsonZodValidator(gitCommitSchema), async (c) => {
|
|
1478
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'mutate');
|
|
1479
|
-
if ('status' in checkout)
|
|
1480
|
-
return c.json(checkout.body, checkout.status);
|
|
1481
|
-
const parsed = { data: c.req.valid('json') };
|
|
1482
|
-
const result = await commitAll(checkout.directory, parsed.data.message);
|
|
1483
|
-
if (!result.ok)
|
|
1484
|
-
return c.json({ error: result.error }, 409);
|
|
1485
|
-
return c.json({ committed: true, sha: result.sha });
|
|
1486
|
-
})
|
|
1487
|
-
.post('/runs/:id/git/push', async (c) => {
|
|
1488
|
-
const { root: repoRoot } = c.get('project');
|
|
1489
|
-
const checkout = runCheckout(c.get('project'), c.req.param('id'), 'mutate');
|
|
1490
|
-
if ('status' in checkout)
|
|
1491
|
-
return c.json(checkout.body, checkout.status);
|
|
1492
|
-
const { run } = checkout;
|
|
1493
|
-
const result = await pushCurrentBranch(checkout.directory);
|
|
1494
|
-
if (!result.ok)
|
|
1495
|
-
return c.json({ error: result.error }, 409);
|
|
1496
|
-
const repoBase = forgeWebRoot((await getRepoInfo(repoRoot))?.remote) ?? undefined;
|
|
1497
|
-
resolveForgeRoot(repoRoot, deps.forgeFactory).branchPushed(ownPullRequestNumbers(run, repoBase));
|
|
1498
|
-
return c.json({
|
|
1499
|
-
pushed: true,
|
|
1500
|
-
branch: result.branch,
|
|
1501
|
-
remote: result.remote,
|
|
1502
|
-
upstreamSet: result.upstreamSet,
|
|
1503
|
-
});
|
|
1504
|
-
})
|
|
1505
|
-
// Draft PR from the review gate (spec 009): final autosave → push →
|
|
1506
|
-
// `gh pr create --draft`; on success the run completes as done with the PR
|
|
1507
|
-
// badge. Failures come back as 409 with a `manual` merge command the GUI
|
|
1508
|
-
// shows next to the toast. CEZ_DRY_RUN=1 fakes the URL (no push, no gh).
|
|
1509
|
-
.post('/runs/:id/pr', async (c) => {
|
|
1510
|
-
const { root: repoRoot, store } = c.get('project');
|
|
1511
|
-
const id = c.req.param('id');
|
|
1512
|
-
const checkout = runCheckout(c.get('project'), id, 'publish');
|
|
1513
|
-
if ('status' in checkout)
|
|
1514
|
-
return c.json(checkout.body, checkout.status);
|
|
1515
|
-
const { release } = checkout;
|
|
1516
|
-
try {
|
|
1517
|
-
const prepared = await preparePublishCheckout(c.get('project'), id);
|
|
1518
|
-
if ('status' in prepared)
|
|
1519
|
-
return c.json(prepared.body, prepared.status);
|
|
1520
|
-
const { run } = prepared;
|
|
1521
|
-
const outcome = await resolveForgeRoot(repoRoot, deps.forgeFactory).createPR({
|
|
1522
|
-
repoRoot,
|
|
1523
|
-
run,
|
|
1524
|
-
handoffText: readHandoff(store.claims.sourceDataDir(id), id),
|
|
1525
|
-
});
|
|
1526
|
-
if (!outcome.ok) {
|
|
1527
|
-
return c.json({ error: outcome.error, manual: `git merge ${run.branch}` }, 409);
|
|
1528
|
-
}
|
|
1529
|
-
store.move(id, 'draft-pr', { pullRequestUrl: outcome.url });
|
|
1530
|
-
store.eventLog.appendEvent(id, {
|
|
1531
|
-
type: 'note',
|
|
1532
|
-
message: `draft PR created: ${outcome.url}${outcome.dryRun ? ' (dry run — no real PR)' : ''}`,
|
|
1533
|
-
});
|
|
1534
|
-
return c.json({ url: outcome.url, dryRun: outcome.dryRun }, 201);
|
|
1535
|
-
}
|
|
1536
|
-
finally {
|
|
1537
|
-
release();
|
|
1538
|
-
}
|
|
1539
|
-
})
|
|
1540
|
-
// Archived tasks keep their worktree for inspection; this is the explicit
|
|
1541
|
-
// "🧹 Remove worktree" cleanup (spec 006).
|
|
1542
|
-
.post('/runs/:id/remove-worktree', protectFallbackRun('worktree'), async (c) => {
|
|
1543
|
-
const { root: repoRoot, store } = c.get('project');
|
|
1544
|
-
const id = c.req.param('id');
|
|
1545
|
-
const checkout = runCheckout(c.get('project'), id, 'remove', {
|
|
1546
|
-
claim: 'publish', checksActive: true, deletion: 'worktree',
|
|
1547
|
-
nullClaimError: 'worktree cleanup pending — retry after cleanup is confirmed',
|
|
1548
|
-
});
|
|
1549
|
-
if ('status' in checkout)
|
|
1550
|
-
return c.json(checkout.body, checkout.status);
|
|
1551
|
-
const { run, release } = checkout;
|
|
1552
|
-
try {
|
|
1553
|
-
if (run.worktreePath)
|
|
1554
|
-
await releaseThenRemoveWorktree({ previewHost: deps.previewHost }, id, repoRoot, run.worktreePath, run.branch);
|
|
1555
|
-
store.updateRun(id, { worktreePath: undefined, branch: undefined });
|
|
1556
|
-
return c.json({ removed: true });
|
|
1557
|
-
}
|
|
1558
|
-
finally {
|
|
1559
|
-
release();
|
|
1560
|
-
}
|
|
1561
|
-
})
|
|
1562
|
-
.delete('/runs/:id', protectFallbackRun('record'), async (c) => {
|
|
1563
|
-
const { root: repoRoot, store } = c.get('project');
|
|
1564
|
-
const id = c.req.param('id');
|
|
1565
|
-
const checkout = runCheckout(c.get('project'), id, 'remove', {
|
|
1566
|
-
claim: 'publish', checksActive: true, deletion: 'record',
|
|
1567
|
-
nullClaimError: 'worktree cleanup pending — retry after cleanup is confirmed',
|
|
1568
|
-
});
|
|
1569
|
-
if ('status' in checkout)
|
|
1570
|
-
return c.json(checkout.body, checkout.status);
|
|
1571
|
-
const { run, release } = checkout;
|
|
1572
|
-
try {
|
|
1573
|
-
if (run.delegation?.role !== 'worker' && run.worktreePath)
|
|
1574
|
-
await releaseThenRemoveWorktree({ previewHost: deps.previewHost }, id, repoRoot, run.worktreePath, run.branch);
|
|
1575
|
-
return store.retention.deleteRun(id) ? c.json({ deleted: true }) : c.json({ error: 'history cleanup incomplete — retry deletion' }, 409);
|
|
1576
|
-
}
|
|
1577
|
-
finally {
|
|
1578
|
-
release();
|
|
1579
|
-
}
|
|
622
|
+
const runsRoutes = createRunsRoutes({
|
|
623
|
+
home: deps.home,
|
|
624
|
+
forgeFactory: deps.forgeFactory,
|
|
625
|
+
delegation: deps.delegation,
|
|
626
|
+
workerCleanup: deps.workerCleanup,
|
|
627
|
+
previewHost: deps.previewHost,
|
|
628
|
+
capabilities,
|
|
629
|
+
modelCatalog,
|
|
630
|
+
providerStatus,
|
|
631
|
+
providerActionError,
|
|
632
|
+
resolveWorkspaceProfile,
|
|
633
|
+
projectRegistryEntry,
|
|
634
|
+
taskWebhooks,
|
|
635
|
+
openTerminal,
|
|
636
|
+
openFile,
|
|
637
|
+
openApp,
|
|
1580
638
|
});
|
|
1581
639
|
const openTargetsRoutes = createOpenTargetsRoutes({ capabilities, openApp });
|
|
1582
|
-
// Agent screenshots and user attachments — what the run manager persisted out of tool
|
|
1583
|
-
// results and pasted messages (`persistAttachment`). `basename` pins reads inside the
|
|
1584
|
-
// run's own dir.
|
|
1585
|
-
const IMAGE_TYPES = {
|
|
1586
|
-
img: 'application/octet-stream', // Legacy catch-all image uploads retain inline headers.
|
|
1587
|
-
png: 'image/png',
|
|
1588
|
-
jpg: 'image/jpeg',
|
|
1589
|
-
webp: 'image/webp',
|
|
1590
|
-
gif: 'image/gif',
|
|
1591
|
-
};
|
|
1592
|
-
/**
|
|
1593
|
-
* What a NON-image attachment is served as (#950). These are user-supplied bytes coming back
|
|
1594
|
-
* from the cockpit's own origin, so the content type is the narrowest true one and it never
|
|
1595
|
-
* travels alone: `nosniff` stops a browser from upgrading it to something executable, and an
|
|
1596
|
-
* attachment disposition stops it from being rendered as a document in the cockpit's origin at
|
|
1597
|
-
* all. Anything not named here keeps the pre-existing `application/octet-stream` default.
|
|
1598
|
-
*/
|
|
1599
|
-
const FILE_TYPES = {
|
|
1600
|
-
pdf: 'application/pdf',
|
|
1601
|
-
txt: 'text/plain; charset=utf-8',
|
|
1602
|
-
md: 'text/plain; charset=utf-8',
|
|
1603
|
-
};
|
|
1604
640
|
const worktreesRoutes = createWorktreesRoutes({ home: deps.home, previewHost: deps.previewHost });
|
|
1605
641
|
const sseRoutes = createSseRoutes();
|
|
1606
642
|
const workspaceEventsRoutes = createWorkspaceEventsRoutes({
|