@hearsay-tools/squawk 0.18.0-dev.8318 → 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.
@@ -0,0 +1,834 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { Hono } from 'hono';
4
+ import { providerForActiveRun } from '../contract/index.js';
5
+ import { artifactParamsSchema, fileLinkQuerySchema } from '../contract/index.js';
6
+ import { runRelationshipsSchema, workerDestroyRequestSchema, workerEmptyRequestSchema } from '../contract/index.js';
7
+ import { runHistoryQuerySchema, runIdParamSchema } from '../contract/index.js';
8
+ import { imageMimeType } from '../contract/index.js';
9
+ import { permissionDecisionSchema } from '../contract/index.js';
10
+ import { worktreeFilesQuerySchema } from '../contract/index.js';
11
+ import { gitCommitSchema } from '../contract/index.js';
12
+ import { ARCHIVED_RUNS_PAGE_DEFAULT } from '../contract/index.js';
13
+ import { latestSession } from '../contract/index.js';
14
+ import { archiveSchema, continueSchema, openInSchema, queuedMessagePatchSchema } from '../contract/index.js';
15
+ import { removedRunnerMessage } from '../contract/index.js';
16
+ import { archiveFinishedRequestSchema, archivedRunsQuerySchema, attachmentFileParamSchema, createRunInputSchema, markAllReadRequestSchema, messageInputSchema as messageSchema, notifyRunInputSchema, patchRunInputSchema as patchRunSchema, pinRunInputSchema, runSummariesQuerySchema, } from '../contract/index.js';
17
+ import { artifactPreview, loadFileLink, rasterMime } from '../artifacts/resolve.js';
18
+ import { listArtifacts, readArtifact, readArtifactMetadata } from '../artifacts/store.js';
19
+ import { loadConfig } from '../config.js';
20
+ import { AGENT_MODELS_LOCKED_ERROR, agentModelsLocked } from '../core/agent-model-policy.js';
21
+ import { profileEnv } from '../core/agent-profiles.js';
22
+ import { currentUsage } from '../core/process-usage.js';
23
+ import { resumeCommand } from '../core/runner-cli.js';
24
+ import { registeredRunnerId, resolveRunnerId, runnerDefinition } from '../core/runner-registry.js';
25
+ import { shellQuote, withEnvPrefix } from '../core/shell-env.js';
26
+ import { delegationFailure } from '../delegation/routes.js';
27
+ import { DelegationService } from '../delegation/service.js';
28
+ import { worktreeDiff } from '../git-worktree.js';
29
+ import { releaseThenRemoveWorktree } from '../git-worktree-release.js';
30
+ import { readHandoff, renderHandoffRecords } from '../handoff.js';
31
+ import { fallbackProjectWriteError } from '../project-paths.js';
32
+ import { deriveRunContextEvents, HistoryCursorError, readRunHistoryPage } from '../runs/event-history.js';
33
+ import { ownPullRequestNumbers } from '../runs/pull-requests.js';
34
+ import { ARCHIVED_WINDOW } from '../runs/run-index.js';
35
+ import { resolveAttachmentPathAsync } from '../workflows/attachment-path.js';
36
+ import { toPastedContent } from '../workflows/pasted-content.js';
37
+ import { isUntouchedCancelledRun } from '../workflows/run/run-guards.js';
38
+ import { DEFAULT_AGENT_ACCOUNT_ID } from '../workspace/agent-accounts.js';
39
+ import { taskWebhooks as taskWebhookList } from '../workspace/webhooks.js';
40
+ import { FILE_FORMATS, negotiate } from './accept-negotiation.js';
41
+ import { forgeWebRoot, resolveForgeRoot } from './forge/index.js';
42
+ import { getRepoInfo } from './git.js';
43
+ import { collectChanges, collectCommitChanges, collectRunCommits, commitAll, pushCurrentBranch, readWorktreePath } from './git-changes.js';
44
+ import { agentCliRunner } from './open-in-app.js';
45
+ import { freshCliHandoff, openRunApp, openRunCli, openRunDefaultApp } from './open-in-targets.js';
46
+ import { adoptFallbackControl, protectFallbackRun, runArtifactDirectory } from './project-run-files.js';
47
+ import { continueRunProviders } from './provider-action-gate.js';
48
+ import { preparePublishCheckout, runCheckout } from './run-checkout.js';
49
+ import { runRelationships } from './run-relationships.js';
50
+ import { agentProfileRefusal, clientRequestOf, launchRun, modelLockRefusal, NO_WEBHOOK_ERROR, notifyRefusal, providerGateRefusal, replayedRun, resolveStartWorkflow, startRunInput, } from './start-run-options.js';
51
+ import { jsonZodValidator, paramZodValidator, queryZodValidator } from './validators.js';
52
+ 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.`;
53
+ const MAX_QUEUED_MESSAGES = 20;
54
+ const MAX_QUEUED_ATTACHMENTS = 8;
55
+ const MAX_FOLDED_TASK_CHARS = 200_000;
56
+ const IMAGE_TYPES = {
57
+ img: 'application/octet-stream',
58
+ png: 'image/png',
59
+ jpg: 'image/jpeg',
60
+ webp: 'image/webp',
61
+ gif: 'image/gif',
62
+ };
63
+ const FILE_TYPES = {
64
+ pdf: 'application/pdf',
65
+ txt: 'text/plain; charset=utf-8',
66
+ md: 'text/plain; charset=utf-8',
67
+ };
68
+ function foldedLength(task, stack) {
69
+ return [task, ...stack.map((m) => m.text)]
70
+ .map((part) => part.trim())
71
+ .filter((part) => part.length > 0)
72
+ .join('\n\n').length;
73
+ }
74
+ export function withLiveUsage(summary) {
75
+ const usage = currentUsage(summary.id);
76
+ return usage ? { ...summary, usage } : summary;
77
+ }
78
+ function withUsage(run, finishBlocked) {
79
+ const usage = currentUsage(run.id);
80
+ const { sessionId, backend } = latestSession(run);
81
+ const command = sessionId ? resumeCommand(resolveRunnerId(backend), sessionId) : null;
82
+ return {
83
+ ...run,
84
+ ...(usage ? { usage } : {}),
85
+ ...(command ? { cliResumeCommand: command } : {}),
86
+ ...(runnerDefinition(resolveRunnerId(backend)).cli.interactive === false ? { cliHandoff: false } : {}),
87
+ ...(finishBlocked !== undefined ? { finishBlocked } : {}),
88
+ };
89
+ }
90
+ export function createRunsRoutes(deps) {
91
+ const { home, forgeFactory, previewHost, capabilities, modelCatalog, providerStatus, providerActionError, resolveWorkspaceProfile, projectRegistryEntry, taskWebhooks, openTerminal, openFile, openApp, } = deps;
92
+ const openHandoffCheckout = (c, suffix = '') => {
93
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'open');
94
+ if ('status' in checkout)
95
+ return checkout;
96
+ return !capabilities().localHandoff
97
+ ? { status: 409, body: { error: `local handoff is disabled — this cockpit runs in hosted mode (CEZ_REMOTE)${suffix}` } }
98
+ : checkout;
99
+ };
100
+ const handoffEnv = async (provider, profileId) => {
101
+ const resolved = await resolveWorkspaceProfile(provider, profileId);
102
+ if ('error' in resolved) {
103
+ return { error: `this session belongs to an account that no longer exists (${profileId})` };
104
+ }
105
+ const { profile } = resolved;
106
+ return { env: profile.isDefault ? {} : profileEnv(provider, profile.path) };
107
+ };
108
+ const handoffFallbackCommand = (cwd, command, env) => {
109
+ const prefixed = withEnvPrefix(command, env, process.platform);
110
+ return prefixed === null ? null : `cd ${shellQuote(cwd)} && ${prefixed}`;
111
+ };
112
+ const requireRunControl = async (c, next) => {
113
+ const id = c.req.param('id');
114
+ if (c.req.method === 'GET' || c.req.method === 'HEAD' || id === undefined)
115
+ return next();
116
+ const { store, manager } = c.get('project');
117
+ if (store.claims.runOwnership(id) === 'orphaned') {
118
+ const stop = c.req.method === 'POST' && c.req.path.endsWith('/cancel');
119
+ if (await manager.adoptOrphanedRun(id, { stop }) && stop && store.getRun(id)?.status === 'cancelled')
120
+ c.set('stoppedOnAdoption', true);
121
+ }
122
+ const refusal = store.claims.writeRefusal(id);
123
+ if (!refusal)
124
+ return next();
125
+ return c.req.path.endsWith('/worker-destroy')
126
+ ? c.json({ code: 'incompatible_state', error: refusal }, 409)
127
+ : c.json({ error: refusal }, 409);
128
+ };
129
+ const delegationService = deps.delegation?.service ?? new DelegationService(deps.workerCleanup);
130
+ delegationService.setDiscovery({ models: modelCatalog, providers: providerStatus });
131
+ return new Hono()
132
+ .use('/runs/:id', adoptFallbackControl, requireRunControl)
133
+ .use('/runs/:id/*', adoptFallbackControl, requireRunControl)
134
+ .get('/runs', (c) => c.json(c.get('project').store.queries.listAllRunsForLegacyRoute().map(run => withUsage(run))))
135
+ .get('/run-summaries', queryZodValidator(runSummariesQuerySchema), (c) => {
136
+ const archivedWindow = c.req.valid('query').archived === 'recent' ? ARCHIVED_WINDOW : undefined;
137
+ return c.json(c.get('project').store.queries.listRunSummaries({ archivedWindow }).runs.map(withLiveUsage));
138
+ })
139
+ .get('/run-summaries/archived', queryZodValidator(archivedRunsQuerySchema), (c) => {
140
+ const { before, limit, q } = c.req.valid('query');
141
+ const project = c.get('project');
142
+ const automationNames = new Map(capabilities().automations
143
+ ? project.automationStore.list().map((automation) => [automation.id, automation.name]) : []);
144
+ const page = project.store.queries.listArchivedRuns({
145
+ limit: limit ?? ARCHIVED_RUNS_PAGE_DEFAULT,
146
+ automationNames,
147
+ ...(before !== undefined ? { before } : {}),
148
+ ...(q !== undefined ? { q } : {}),
149
+ });
150
+ if ('error' in page)
151
+ return c.json({ error: page.error }, 400);
152
+ const body = { ...page, runs: page.runs.map(withLiveUsage) };
153
+ return c.json(body);
154
+ })
155
+ .get('/runs/:id/relationships', paramZodValidator(runIdParamSchema), queryZodValidator(workerEmptyRequestSchema), (c) => {
156
+ const { store } = c.get('project');
157
+ const run = store.getRun(c.req.valid('param').id);
158
+ if (!run)
159
+ return c.json({ error: 'not found' }, 404);
160
+ return c.json(runRelationshipsSchema.parse(runRelationships(store, run)));
161
+ })
162
+ .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) => {
163
+ const project = c.get('project');
164
+ delegationService.registerProject(project);
165
+ try {
166
+ const result = await delegationService.destroyForHuman(project.id, c.req.valid('param').id, c.req.valid('json'));
167
+ return result.state === 'incomplete' ? c.json(result, 409) : c.json(result, 200);
168
+ }
169
+ catch (error) {
170
+ const failure = delegationFailure(error);
171
+ return c.json(failure.body, failure.status);
172
+ }
173
+ })
174
+ .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)))
175
+ .post('/runs/read-all', jsonZodValidator(markAllReadRequestSchema, { absent: {}, malformed: null }), (c) => c.json({ read: c.get('project').store.readFlags.markAllRead(c.req.valid('json').automation) }))
176
+ .post('/runs/:id/archive', jsonZodValidator(archiveSchema, { absent: ({}) }), async (c) => {
177
+ const { store } = c.get('project');
178
+ const id = c.req.param('id');
179
+ const parsed = { data: c.req.valid('json') };
180
+ const run = store.archive.setArchived(id, parsed.data.archived !== false);
181
+ return run ? c.json(run) : c.json({ error: 'not found' }, 404);
182
+ })
183
+ .post('/runs/:id/pin', paramZodValidator(runIdParamSchema), jsonZodValidator(pinRunInputSchema, { absent: {}, malformed: null }), (c) => {
184
+ const { store } = c.get('project');
185
+ const run = store.readFlags.setPinned(c.req.valid('param').id, c.req.valid('json').pinned !== false);
186
+ return run ? c.json(run) : c.json({ error: 'not found' }, 404);
187
+ })
188
+ .post('/runs/:id/notify', paramZodValidator(runIdParamSchema), jsonZodValidator(notifyRunInputSchema), async (c) => {
189
+ const project = c.get('project');
190
+ const { id } = c.req.valid('param');
191
+ const { notify, message } = c.req.valid('json');
192
+ if (!project.store.getRun(id))
193
+ return c.json({ error: 'not found' }, 404);
194
+ if (notify) {
195
+ const entry = await projectRegistryEntry(project.id).catch(() => undefined);
196
+ if (taskWebhookList(entry).length === 0)
197
+ return c.json({ error: NO_WEBHOOK_ERROR }, 400);
198
+ }
199
+ const run = project.store.updateRun(id, { notify: notify ? true : undefined });
200
+ if (!run)
201
+ return c.json({ error: 'not found' }, 404);
202
+ project.store.eventLog.appendEvent(id, {
203
+ type: 'handoff',
204
+ notify,
205
+ ...(message === undefined ? {} : { message }),
206
+ });
207
+ if (notify)
208
+ taskWebhooks.attach(project).subscribed(id, message);
209
+ return c.json(run);
210
+ })
211
+ .delete('/runs/:id/auto-resume', (c) => {
212
+ const { store, manager } = c.get('project');
213
+ const id = c.req.param('id');
214
+ if (!store.getRun(id))
215
+ return c.json({ error: 'not found' }, 404);
216
+ manager.cancelAutoResume(id);
217
+ return c.json({ cancelled: true });
218
+ })
219
+ .post('/runs/:id/read', (c) => {
220
+ const run = c.get('project').store.readFlags.setRead(c.req.param('id'));
221
+ return run ? c.json(run) : c.json({ error: 'not found' }, 404);
222
+ })
223
+ .post('/runs/:id/unread', (c) => {
224
+ const run = c.get('project').store.readFlags.setUnread(c.req.param('id'));
225
+ return run ? c.json(run) : c.json({ error: 'not found' }, 404);
226
+ })
227
+ .post('/runs', jsonZodValidator(createRunInputSchema, { runners: { ids: ['runner', 'steps.*.runner'] } }), async (c) => {
228
+ const { id: projectId, root: repoRoot, manager, store } = c.get('project');
229
+ const body = c.req.valid('json');
230
+ const clientRequest = clientRequestOf(body);
231
+ if (clientRequest) {
232
+ const replay = replayedRun(store.queries, clientRequest);
233
+ if (replay && 'error' in replay)
234
+ return c.json({ error: replay.error }, replay.status);
235
+ if (replay)
236
+ return c.json(replay.run, 200);
237
+ }
238
+ const locked = modelLockRefusal(repoRoot, body, home);
239
+ if (locked)
240
+ return c.json({ error: locked.error }, locked.status);
241
+ const resolved = await resolveStartWorkflow(repoRoot, body);
242
+ if ('error' in resolved)
243
+ return c.json({ error: resolved.error }, resolved.status);
244
+ const { workflow } = resolved;
245
+ const runner = body.runner === undefined ? (await loadConfig(repoRoot, home)).defaultRunner : registeredRunnerId(body.runner);
246
+ const blocked = await providerGateRefusal(providerActionError, workflow, runner, { repoRoot, picks: { [runner]: body.agentProfile } });
247
+ if (blocked)
248
+ return c.json({ error: blocked.error }, blocked.status);
249
+ const badProfile = await agentProfileRefusal(resolveWorkspaceProfile, runner, body.agentProfile);
250
+ if (badProfile)
251
+ return c.json({ error: badProfile.error }, badProfile.status);
252
+ const noWebhook = await notifyRefusal(body.notify, projectId, projectRegistryEntry);
253
+ if (noWebhook)
254
+ return c.json({ error: noWebhook.error }, noWebhook.status);
255
+ const started = launchRun(manager, workflow, startRunInput(body), clientRequest);
256
+ if ('error' in started)
257
+ return c.json({ error: started.error }, started.status);
258
+ return c.json(started.run, started.status);
259
+ })
260
+ .get('/runs/:id', (c) => {
261
+ const { store, manager } = c.get('project');
262
+ const id = c.req.param('id');
263
+ const run = store.getRun(id);
264
+ if (run)
265
+ return c.json(withUsage(run, manager.finishBlockedReason(run.id) ?? null));
266
+ return c.json({ error: store.isUnreadable(id) ? UNREADABLE_RUN_ERROR : 'not found' }, 404);
267
+ })
268
+ .get('/runs/:id/history', paramZodValidator(runIdParamSchema), queryZodValidator(runHistoryQuerySchema), async (c) => {
269
+ const { store } = c.get('project');
270
+ const { id } = c.req.valid('param');
271
+ if (!store.getRun(id))
272
+ return c.json({ error: 'not found' }, 404);
273
+ try {
274
+ return c.json(await readRunHistoryPage(store.claims.sourceDataDir(id), id, c.req.valid('query').cursor));
275
+ }
276
+ catch (error) {
277
+ if (error instanceof HistoryCursorError)
278
+ return c.json({ error: error.message }, error.status);
279
+ throw error;
280
+ }
281
+ })
282
+ .get('/runs/:id/history-context', paramZodValidator(runIdParamSchema), async (c) => {
283
+ const { store } = c.get('project');
284
+ const { id } = c.req.valid('param');
285
+ if (!store.getRun(id))
286
+ return c.json({ error: 'not found' }, 404);
287
+ return c.json(await deriveRunContextEvents(store.claims.sourceDataDir(id), id));
288
+ })
289
+ .patch('/runs/:id', jsonZodValidator(patchRunSchema), async (c) => {
290
+ const { store, manager } = c.get('project');
291
+ const id = c.req.param('id');
292
+ if (!store.getRun(id))
293
+ return c.json({ error: 'not found' }, 404);
294
+ const parsed = { data: c.req.valid('json') };
295
+ if (parsed.data.task !== undefined) {
296
+ const foldedChars = foldedLength(parsed.data.task, store.getRun(id)?.queuedMessages ?? []);
297
+ if (foldedChars > MAX_FOLDED_TASK_CHARS) {
298
+ return c.json({
299
+ error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${foldedChars})`,
300
+ }, 400);
301
+ }
302
+ if (!manager.editTask(id, parsed.data.task)) {
303
+ return c.json({ error: 'run already started' }, 409);
304
+ }
305
+ }
306
+ if (parsed.data.title !== undefined) {
307
+ store.updateRun(id, {
308
+ title: parsed.data.title,
309
+ titleSummary: parsed.data.title,
310
+ titleOrigin: 'user',
311
+ });
312
+ }
313
+ const { title: _title, task: _task, ...options } = parsed.data;
314
+ if (Object.values(options).some(value => value !== undefined))
315
+ store.updateRun(id, options);
316
+ return c.json(store.getRun(id));
317
+ })
318
+ .post('/runs/:id/cancel', (c) => {
319
+ const { store, manager } = c.get('project');
320
+ const id = c.req.param('id');
321
+ if (!store.getRun(id))
322
+ return c.json({ error: 'not found' }, 404);
323
+ const cancelled = manager.cancel(id) || c.get('stoppedOnAdoption') === true;
324
+ return c.json({ cancelled });
325
+ })
326
+ .post('/runs/:id/permissions', paramZodValidator(runIdParamSchema), jsonZodValidator(permissionDecisionSchema), (c) => {
327
+ const { store, manager } = c.get('project');
328
+ const { id } = c.req.valid('param');
329
+ if (!store.getRun(id))
330
+ return c.json({ error: 'not found' }, 404);
331
+ const { requestId, optionId } = c.req.valid('json');
332
+ if (!manager.respondPermission(id, requestId, optionId)) {
333
+ return c.json({ error: 'permission request is no longer available or option is invalid' }, 409);
334
+ }
335
+ return c.json({ delivered: true });
336
+ })
337
+ .post('/runs/:id/messages', jsonZodValidator(messageSchema), async (c) => {
338
+ const { store, manager } = c.get('project');
339
+ const id = c.req.param('id');
340
+ const run = store.getRun(id);
341
+ if (!run)
342
+ return c.json({ error: 'not found' }, 404);
343
+ const parsed = { data: c.req.valid('json') };
344
+ if (run.status !== 'queued') {
345
+ const blocked = await providerActionError([resolveRunnerId(providerForActiveRun(run))], { repoRoot: c.get('project').root, run, live: true });
346
+ if (blocked)
347
+ return c.json({ error: blocked }, 409);
348
+ }
349
+ const content = [
350
+ ...parsed.data.images.map(toPastedContent),
351
+ ...(parsed.data.text.trim() ? [{ type: 'text', text: parsed.data.text }] : []),
352
+ ];
353
+ if (manager.sendMessage(id, content))
354
+ return c.json({ delivered: true });
355
+ const currentRun = store.getRun(id);
356
+ const stack = currentRun?.queuedMessages ?? [];
357
+ if (currentRun?.status === 'queued') {
358
+ if (stack.length >= MAX_QUEUED_MESSAGES) {
359
+ return c.json({ error: `too many queued messages — ${MAX_QUEUED_MESSAGES} message limit` }, 400);
360
+ }
361
+ const stackedImages = stack.reduce((n, m) => n + (m.images?.length ?? 0), 0);
362
+ if (stackedImages + parsed.data.images.length > MAX_QUEUED_ATTACHMENTS) {
363
+ return c.json({ error: `too many queued attachments — ${MAX_QUEUED_ATTACHMENTS} attachment limit across the stack` }, 400);
364
+ }
365
+ const prospective = foldedLength(currentRun.task, [...stack, { text: parsed.data.text }]);
366
+ if (prospective > MAX_FOLDED_TASK_CHARS) {
367
+ return c.json({
368
+ error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
369
+ }, 400);
370
+ }
371
+ }
372
+ const queued = manager.enqueueMessage(id, content);
373
+ if (queued)
374
+ return c.json({ queued: true, message: queued });
375
+ if (manager.deferMessage(id, content))
376
+ return c.json({ deferred: true });
377
+ return c.json({ error: 'session closed' }, 409);
378
+ })
379
+ .patch('/runs/:id/queued-messages/:msgId', jsonZodValidator(queuedMessagePatchSchema), async (c) => {
380
+ const { store, manager } = c.get('project');
381
+ const id = c.req.param('id');
382
+ const run = store.getRun(id);
383
+ if (!run)
384
+ return c.json({ error: 'not found' }, 404);
385
+ const parsed = { data: c.req.valid('json') };
386
+ const msgId = c.req.param('msgId');
387
+ const stack = run.queuedMessages ?? [];
388
+ const existing = stack.find((m) => m.id === msgId);
389
+ if (!existing)
390
+ return c.json({ error: 'not found' }, 404);
391
+ const effectiveText = parsed.data.text ?? existing.text;
392
+ const effectiveImageCount = parsed.data.images?.length ?? existing.images?.length ?? 0;
393
+ if (!effectiveText.trim() && effectiveImageCount === 0) {
394
+ return c.json({ error: 'message needs text or at least one attachment' }, 400);
395
+ }
396
+ const others = stack.filter((m) => m.id !== msgId);
397
+ const stackedImages = others.reduce((n, m) => n + (m.images?.length ?? 0), 0);
398
+ if (stackedImages + effectiveImageCount > MAX_QUEUED_ATTACHMENTS) {
399
+ return c.json({ error: `too many queued attachments — ${MAX_QUEUED_ATTACHMENTS} attachment limit across the stack` }, 400);
400
+ }
401
+ const prospective = foldedLength(run.task, [...others, { text: effectiveText }]);
402
+ if (prospective > MAX_FOLDED_TASK_CHARS) {
403
+ return c.json({
404
+ error: `prompt too long — ${MAX_FOLDED_TASK_CHARS} character limit across the task and its queued messages (would be ${prospective})`,
405
+ }, 400);
406
+ }
407
+ const images = parsed.data.images?.map(toPastedContent);
408
+ const message = manager.editQueuedMessage(id, msgId, {
409
+ ...(parsed.data.text !== undefined ? { text: parsed.data.text } : {}),
410
+ ...(images !== undefined ? { images } : {}),
411
+ });
412
+ if (!message)
413
+ return c.json({ error: 'run already started' }, 409);
414
+ return c.json({ message });
415
+ })
416
+ .delete('/runs/:id/queued-messages/:msgId', (c) => {
417
+ const { store, manager } = c.get('project');
418
+ const id = c.req.param('id');
419
+ const run = store.getRun(id);
420
+ if (!run)
421
+ return c.json({ error: 'not found' }, 404);
422
+ const msgId = c.req.param('msgId');
423
+ if (!(run.queuedMessages ?? []).some((m) => m.id === msgId)) {
424
+ return c.json({ error: 'not found' }, 404);
425
+ }
426
+ if (!manager.removeQueuedMessage(id, msgId))
427
+ return c.json({ error: 'run already started' }, 409);
428
+ return c.json({ removed: true });
429
+ })
430
+ .post('/runs/:id/finish', (c) => {
431
+ const { store, manager } = c.get('project');
432
+ const id = c.req.param('id');
433
+ if (!store.getRun(id))
434
+ return c.json({ error: 'not found' }, 404);
435
+ const finished = manager.finish(id);
436
+ if (!finished)
437
+ return c.json({ error: manager.finishBlockedReason(id) ?? 'no open session' }, 409);
438
+ return c.json({ finished: true });
439
+ })
440
+ .post('/runs/:id/continue', jsonZodValidator(continueSchema, { absent: ({}), runners: { ids: ['runner'] } }), async (c) => {
441
+ const { root: repoRoot, store, manager } = c.get('project');
442
+ const id = c.req.param('id');
443
+ const run = store.getRun(id);
444
+ if (!run)
445
+ return c.json({ error: 'not found' }, 404);
446
+ const body = c.req.valid('json');
447
+ if (agentModelsLocked(repoRoot, process.env, home) &&
448
+ (body.model?.trim() || body.effort?.trim())) {
449
+ return c.json({ error: AGENT_MODELS_LOCKED_ERROR }, 409);
450
+ }
451
+ if (run.removedRunner !== undefined && body.runner === undefined) {
452
+ return c.json({ error: removedRunnerMessage(run.removedRunner) }, 409);
453
+ }
454
+ const untouched = isUntouchedCancelledRun(run);
455
+ const { original: originalProvider, target: provider, required } = await continueRunProviders(run, body.runner, untouched, async () => (await loadConfig(repoRoot, home)).defaultRunner);
456
+ const blocked = await providerActionError(required, { repoRoot, run, untouched, runners: { original: originalProvider, target: provider } });
457
+ if (blocked)
458
+ return c.json({ error: blocked }, 409);
459
+ const result = manager.continueRun(id, {
460
+ text: body.text,
461
+ images: body.images?.map(toPastedContent),
462
+ runner: untouched || body.runner !== undefined ? provider : undefined,
463
+ ...(untouched ? { originalRunner: originalProvider } : {}),
464
+ model: body.model,
465
+ effort: body.effort,
466
+ });
467
+ if (!result.ok)
468
+ return c.json({ error: result.error }, 409);
469
+ return c.json({ continued: true });
470
+ })
471
+ .post('/runs/:id/open-in-cli', async (c) => {
472
+ const project = c.get('project');
473
+ const checkout = openHandoffCheckout(c, '; resume the session from a machine that has the checkout');
474
+ if ('status' in checkout)
475
+ return c.json(checkout.body, checkout.status);
476
+ if (checkout.run.removedRunner !== undefined)
477
+ return c.json({ error: removedRunnerMessage(checkout.run.removedRunner) }, 409);
478
+ const { sessionId, backend: savedBackend, profileId } = latestSession(checkout.run), backend = resolveRunnerId(savedBackend);
479
+ if (!sessionId)
480
+ return c.json({ error: 'no agent session to resume' }, 409);
481
+ if (runnerDefinition(backend).cli.interactive === false)
482
+ return c.json({ error: 'this runner has no interactive CLI' }, 409);
483
+ const resume = checkout.resumeAllowed ? resumeCommand(backend, sessionId) : undefined;
484
+ if (resume === null)
485
+ return c.json({ error: 'the recorded session id has an unexpected shape' }, 409);
486
+ const blocked = await providerActionError([backend], { repoRoot: project.root, picks: { [backend]: resume ? profileId ?? DEFAULT_AGENT_ACCOUNT_ID : undefined } });
487
+ if (blocked)
488
+ return c.json({ error: blocked }, 409);
489
+ const cwd = checkout.directory();
490
+ const refusal = fallbackProjectWriteError(cwd);
491
+ if (refusal)
492
+ return c.json({ error: refusal }, 409);
493
+ const account = resume
494
+ ? { command: resume, ...await handoffEnv(backend, profileId) }
495
+ : await freshCliHandoff(backend, project.root, home);
496
+ if ('error' in account)
497
+ return c.json({ error: account.error }, 409);
498
+ const { command } = account;
499
+ const fallback = handoffFallbackCommand(cwd, command, account.env);
500
+ if (fallback === null) {
501
+ return c.json({ error: 'this account\'s folder cannot be used in a terminal command' }, 409);
502
+ }
503
+ const opened = await openTerminal(cwd, command, account.env);
504
+ if (!opened) {
505
+ return c.json({ error: 'no terminal emulator found', command: fallback }, 409);
506
+ }
507
+ return c.json({ opened: true, command });
508
+ })
509
+ .post('/runs/:id/open-in', jsonZodValidator(openInSchema), async (c) => {
510
+ const project = c.get('project');
511
+ const checkout = openHandoffCheckout(c);
512
+ if ('status' in checkout)
513
+ return c.json(checkout.body, checkout.status);
514
+ const { target, path: relPath } = c.req.valid('json');
515
+ const dir = checkout.directory();
516
+ if (target === 'default') {
517
+ const worktree = checkout.defaultWorktree();
518
+ if (typeof worktree !== 'string')
519
+ return c.json(worktree.body, worktree.status);
520
+ return openRunDefaultApp(c, worktree, relPath, openFile);
521
+ }
522
+ const cliRunner = agentCliRunner(target);
523
+ if (cliRunner) {
524
+ return openRunCli(c, checkout.run, cliRunner, dir, project.root, {
525
+ home,
526
+ providerActionError, resumeCommand, handoffEnv, handoffFallbackCommand, openTerminal,
527
+ }, checkout);
528
+ }
529
+ return openRunApp(c, target, dir, openApp);
530
+ })
531
+ .get('/runs/:id/handoff', (c) => {
532
+ const { store } = c.get('project');
533
+ const run = store.getRun(c.req.param('id'));
534
+ if (!run)
535
+ return c.json({ error: 'not found' }, 404);
536
+ return c.text(renderHandoffRecords(readHandoff(store.claims.sourceDataDir(run.id), run.id), run.handoffRecords), 200, {
537
+ 'content-type': 'text/markdown; charset=utf-8',
538
+ });
539
+ })
540
+ .get('/runs/:id/images/:file', paramZodValidator(attachmentFileParamSchema), async (c) => {
541
+ const { store } = c.get('project');
542
+ const run = store.getRun(c.req.param('id'));
543
+ if (!run)
544
+ return c.json({ error: 'not found' }, 404);
545
+ const file = c.req.valid('param').file;
546
+ const path = await resolveAttachmentPathAsync(store.claims.sourceDataDir(run.id), run.id, file);
547
+ if (!path)
548
+ return c.json({ error: 'not found' }, 404);
549
+ const ext = file.split('.').pop() ?? '';
550
+ const image = IMAGE_TYPES[ext];
551
+ const type = image ?? FILE_TYPES[ext] ?? 'application/octet-stream';
552
+ return new Response(await readFile(path), {
553
+ headers: {
554
+ 'content-type': type,
555
+ 'cache-control': 'private, max-age=31536000, immutable',
556
+ ...(image
557
+ ? {}
558
+ : {
559
+ 'x-content-type-options': 'nosniff',
560
+ 'content-disposition': `attachment; filename="${file.replace(/[^A-Za-z0-9._-]/g, '_')}"`,
561
+ }),
562
+ },
563
+ });
564
+ })
565
+ .get('/runs/:id/diff', async (c) => {
566
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'existing-worktree' });
567
+ if ('body' in checkout)
568
+ return c.json(checkout.body, checkout.status);
569
+ if (!checkout.directory)
570
+ return c.text('(no worktree — this task ran directly in the repo working tree)');
571
+ const result = await worktreeDiff(checkout.directory, checkout.run.baseBranch ?? 'HEAD', undefined, checkout.beforeLiveIndex);
572
+ if (typeof result !== 'string')
573
+ return c.json({ error: result.error }, 409);
574
+ return c.text(result);
575
+ })
576
+ .get('/runs/:id/changes', async (c) => {
577
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
578
+ if ('body' in checkout)
579
+ return c.json(checkout.body, checkout.status);
580
+ const { run, directory: workingDirectory } = checkout;
581
+ const result = await collectChanges(workingDirectory, run.baseBranch ?? 'HEAD', {
582
+ beforeLiveIndex: checkout.beforeLiveIndex,
583
+ taskBranch: run.branch,
584
+ runStartedAt: run.startedAt,
585
+ intentToAdd: run.worktreePath ? undefined : false,
586
+ });
587
+ if (!result.ok)
588
+ return c.json({ error: result.error }, 409);
589
+ return c.json(result.changes);
590
+ })
591
+ .get('/runs/:id/commits', async (c) => {
592
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
593
+ if ('body' in checkout)
594
+ return c.json(checkout.body, checkout.status);
595
+ const { run, directory: workingDirectory } = checkout;
596
+ const result = await collectRunCommits(workingDirectory, run.baseBranch ?? 'HEAD');
597
+ if (!result.ok)
598
+ return c.json({ error: result.error }, 409);
599
+ return c.json({ commits: result.commits });
600
+ })
601
+ .get('/runs/:id/commit/:sha', async (c) => {
602
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
603
+ if ('body' in checkout)
604
+ return c.json(checkout.body, checkout.status);
605
+ const { directory: workingDirectory } = checkout;
606
+ const result = await collectCommitChanges(workingDirectory, c.req.param('sha'));
607
+ if (!result.ok)
608
+ return c.json({ error: result.error }, 409);
609
+ return c.json(result.commit);
610
+ })
611
+ .get('/runs/:id/file-link', paramZodValidator(artifactParamsSchema.omit({ artifactId: true })), queryZodValidator(fileLinkQuerySchema), async (c) => {
612
+ const { root, store } = c.get('project');
613
+ const checkout = runCheckout(c.get('project'), c.req.valid('param').id, 'read', { directory: 'recorded-path-or-root' });
614
+ if ('body' in checkout)
615
+ return c.json(checkout.body, checkout.status);
616
+ const { run, directory: workingDirectory } = checkout;
617
+ const query = c.req.valid('query');
618
+ const loaded = await loadFileLink({ dataDir: store.claims.sourceDataDir(run.id), runId: run.id, projectRoot: root, workingDirectory, path: query.path });
619
+ if (query.raw === '1') {
620
+ if (!loaded.imageBytes || loaded.preview.type !== 'file')
621
+ return c.json({ error: 'Only bounded raster images can be served inline.' }, 409);
622
+ return c.body(new Uint8Array(loaded.imageBytes).buffer, 200, {
623
+ 'content-type': rasterMime(loaded.preview.path), 'x-content-type-options': 'nosniff',
624
+ 'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
625
+ });
626
+ }
627
+ return c.json(loaded.preview);
628
+ })
629
+ .get('/runs/:id/artifacts', paramZodValidator(artifactParamsSchema.omit({ artifactId: true })), async (c) => {
630
+ const { store } = c.get('project');
631
+ const id = c.req.valid('param').id;
632
+ if (!store.getRun(id))
633
+ return c.json({ error: 'not found' }, 404);
634
+ return c.json({ artifacts: await listArtifacts(runArtifactDirectory(store, id), id) });
635
+ })
636
+ .get('/runs/:id/artifacts/:artifactId', paramZodValidator(artifactParamsSchema), async (c) => {
637
+ const { store } = c.get('project');
638
+ const { id, artifactId } = c.req.valid('param');
639
+ if (!store.getRun(id))
640
+ return c.json({ error: 'not found' }, 404);
641
+ const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
642
+ if (!entry)
643
+ return c.json({ error: 'Published file is missing or unavailable.' }, 404);
644
+ return c.json(artifactPreview(entry.metadata, entry.bytes));
645
+ })
646
+ .get('/runs/:id/artifacts/:artifactId/metadata', paramZodValidator(artifactParamsSchema), async (c) => {
647
+ const { store } = c.get('project');
648
+ const { id, artifactId } = c.req.valid('param');
649
+ if (!store.getRun(id))
650
+ return c.json({ error: 'not found' }, 404);
651
+ const artifact = await readArtifactMetadata(runArtifactDirectory(store, id), id, artifactId);
652
+ if (!artifact)
653
+ return c.json({ error: 'Published file is missing or unavailable.' }, 404);
654
+ return c.json({ artifact });
655
+ })
656
+ .get('/runs/:id/artifacts/:artifactId/download', paramZodValidator(artifactParamsSchema), async (c) => {
657
+ const { store } = c.get('project');
658
+ const { id, artifactId } = c.req.valid('param');
659
+ if (!store.getRun(id))
660
+ return c.json({ error: 'not found' }, 404);
661
+ const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
662
+ if (!entry)
663
+ return c.json({ error: 'Published file is missing or unavailable.' }, 404);
664
+ return c.body(new Uint8Array(entry.bytes).buffer, 200, {
665
+ 'content-type': 'application/octet-stream', 'x-content-type-options': 'nosniff',
666
+ 'content-disposition': `attachment; filename="${entry.metadata.name.replace(/[^A-Za-z0-9._-]/g, '_')}"`,
667
+ 'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
668
+ });
669
+ })
670
+ .get('/runs/:id/artifacts/:artifactId/image', paramZodValidator(artifactParamsSchema), async (c) => {
671
+ const { store } = c.get('project');
672
+ const { id, artifactId } = c.req.valid('param');
673
+ if (!store.getRun(id))
674
+ return c.json({ error: 'not found' }, 404);
675
+ const entry = await readArtifact(runArtifactDirectory(store, id), id, artifactId);
676
+ if (!entry)
677
+ return c.json({ error: 'Published file is missing or unavailable.' }, 404);
678
+ const mime = rasterMime(entry.metadata.name);
679
+ if (!mime)
680
+ return c.json({ error: 'Only raster images can be served inline.' }, 409);
681
+ return c.body(new Uint8Array(entry.bytes).buffer, 200, {
682
+ 'content-type': mime, 'x-content-type-options': 'nosniff',
683
+ 'content-security-policy': "default-src 'none'; sandbox", 'cache-control': 'private, no-store',
684
+ });
685
+ })
686
+ .get('/runs/:id/files', queryZodValidator(worktreeFilesQuerySchema), async (c) => {
687
+ const query = c.req.valid('query');
688
+ c.header('vary', 'Accept');
689
+ const wantsRaw = query.raw !== undefined
690
+ ? query.raw === '1'
691
+ : negotiate(c.req.header('accept'), FILE_FORMATS) === 'image/*';
692
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'read', { directory: 'working-directory' });
693
+ if ('body' in checkout)
694
+ return c.json(checkout.body, checkout.status);
695
+ const { directory: workingDirectory } = checkout;
696
+ const result = await readWorktreePath(workingDirectory, query.path ?? '');
697
+ if (result.kind === 'invalid' || result.kind === 'missing') {
698
+ return c.json({ error: result.error }, 409);
699
+ }
700
+ if (result.kind === 'dir') {
701
+ return c.json({
702
+ type: 'dir',
703
+ path: result.path,
704
+ entries: result.entries,
705
+ });
706
+ }
707
+ if (wantsRaw) {
708
+ const mime = imageMimeType(result.path);
709
+ if (mime === null || result.tooLarge) {
710
+ if (query.raw !== undefined) {
711
+ const error = mime === null
712
+ ? `raw serving is limited to images: ${result.path}`
713
+ : `file too large to serve raw (${result.size} bytes): ${result.path}`;
714
+ return c.json({ error }, 409);
715
+ }
716
+ }
717
+ else {
718
+ const bytes = await readFile(join(workingDirectory, result.path));
719
+ return c.body(new Uint8Array(bytes).buffer, 200, {
720
+ 'content-type': mime,
721
+ 'x-content-type-options': 'nosniff',
722
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; sandbox",
723
+ });
724
+ }
725
+ }
726
+ return c.json({
727
+ type: 'file',
728
+ path: result.path,
729
+ size: result.size,
730
+ binary: result.binary,
731
+ tooLarge: result.tooLarge,
732
+ ...(result.content !== undefined ? { content: result.content } : {}),
733
+ });
734
+ })
735
+ .post('/runs/:id/git/commit', jsonZodValidator(gitCommitSchema), async (c) => {
736
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'mutate');
737
+ if ('status' in checkout)
738
+ return c.json(checkout.body, checkout.status);
739
+ const parsed = { data: c.req.valid('json') };
740
+ const result = await commitAll(checkout.directory, parsed.data.message);
741
+ if (!result.ok)
742
+ return c.json({ error: result.error }, 409);
743
+ return c.json({ committed: true, sha: result.sha });
744
+ })
745
+ .post('/runs/:id/git/push', async (c) => {
746
+ const { root: repoRoot } = c.get('project');
747
+ const checkout = runCheckout(c.get('project'), c.req.param('id'), 'mutate');
748
+ if ('status' in checkout)
749
+ return c.json(checkout.body, checkout.status);
750
+ const { run } = checkout;
751
+ const result = await pushCurrentBranch(checkout.directory);
752
+ if (!result.ok)
753
+ return c.json({ error: result.error }, 409);
754
+ const repoBase = forgeWebRoot((await getRepoInfo(repoRoot))?.remote) ?? undefined;
755
+ resolveForgeRoot(repoRoot, forgeFactory).branchPushed(ownPullRequestNumbers(run, repoBase));
756
+ return c.json({
757
+ pushed: true,
758
+ branch: result.branch,
759
+ remote: result.remote,
760
+ upstreamSet: result.upstreamSet,
761
+ });
762
+ })
763
+ .post('/runs/:id/pr', async (c) => {
764
+ const { root: repoRoot, store } = c.get('project');
765
+ const id = c.req.param('id');
766
+ const checkout = runCheckout(c.get('project'), id, 'publish');
767
+ if ('status' in checkout)
768
+ return c.json(checkout.body, checkout.status);
769
+ const { release } = checkout;
770
+ try {
771
+ const prepared = await preparePublishCheckout(c.get('project'), id);
772
+ if ('status' in prepared)
773
+ return c.json(prepared.body, prepared.status);
774
+ const { run } = prepared;
775
+ const outcome = await resolveForgeRoot(repoRoot, forgeFactory).createPR({
776
+ repoRoot,
777
+ run,
778
+ handoffText: readHandoff(store.claims.sourceDataDir(id), id),
779
+ });
780
+ if (!outcome.ok) {
781
+ return c.json({ error: outcome.error, manual: `git merge ${run.branch}` }, 409);
782
+ }
783
+ store.move(id, 'draft-pr', { pullRequestUrl: outcome.url });
784
+ store.eventLog.appendEvent(id, {
785
+ type: 'note',
786
+ message: `draft PR created: ${outcome.url}${outcome.dryRun ? ' (dry run — no real PR)' : ''}`,
787
+ });
788
+ return c.json({ url: outcome.url, dryRun: outcome.dryRun }, 201);
789
+ }
790
+ finally {
791
+ release();
792
+ }
793
+ })
794
+ .post('/runs/:id/remove-worktree', protectFallbackRun('worktree'), async (c) => {
795
+ const { root: repoRoot, store } = c.get('project');
796
+ const id = c.req.param('id');
797
+ const checkout = runCheckout(c.get('project'), id, 'remove', {
798
+ claim: 'publish', checksActive: true, deletion: 'worktree',
799
+ nullClaimError: 'worktree cleanup pending — retry after cleanup is confirmed',
800
+ });
801
+ if ('status' in checkout)
802
+ return c.json(checkout.body, checkout.status);
803
+ const { run, release } = checkout;
804
+ try {
805
+ if (run.worktreePath)
806
+ await releaseThenRemoveWorktree({ previewHost }, id, repoRoot, run.worktreePath, run.branch);
807
+ store.updateRun(id, { worktreePath: undefined, branch: undefined });
808
+ return c.json({ removed: true });
809
+ }
810
+ finally {
811
+ release();
812
+ }
813
+ })
814
+ .delete('/runs/:id', protectFallbackRun('record'), async (c) => {
815
+ const { root: repoRoot, store } = c.get('project');
816
+ const id = c.req.param('id');
817
+ const checkout = runCheckout(c.get('project'), id, 'remove', {
818
+ claim: 'publish', checksActive: true, deletion: 'record',
819
+ nullClaimError: 'worktree cleanup pending — retry after cleanup is confirmed',
820
+ });
821
+ if ('status' in checkout)
822
+ return c.json(checkout.body, checkout.status);
823
+ const { run, release } = checkout;
824
+ try {
825
+ if (run.delegation?.role !== 'worker' && run.worktreePath)
826
+ await releaseThenRemoveWorktree({ previewHost }, id, repoRoot, run.worktreePath, run.branch);
827
+ return store.retention.deleteRun(id) ? c.json({ deleted: true }) : c.json({ error: 'history cleanup incomplete — retry deletion' }, 409);
828
+ }
829
+ finally {
830
+ release();
831
+ }
832
+ });
833
+ }
834
+ //# sourceMappingURL=runs-routes.js.map