@promptbook/cli 0.112.0 → 0.113.0-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +45 -29
  2. package/agents/default/developer.book +2 -1
  3. package/apps/agents-server/next.config.ts +21 -0
  4. package/apps/agents-server/src/app/admin/limits/LimitsClient.tsx +1 -1
  5. package/apps/agents-server/src/app/admin/task-manager/TaskManagerTaskRow.tsx +7 -2
  6. package/apps/agents-server/src/app/admin/update/UpdateClient.tsx +52 -33
  7. package/apps/agents-server/src/app/api/agent-folders/[folderId]/visibility/route.ts +19 -7
  8. package/apps/agents-server/src/app/api/agents/[agentName]/route.ts +8 -18
  9. package/apps/agents-server/src/app/api/internal/agent-runner-limits/route.ts +1 -1
  10. package/apps/agents-server/src/app/api/page-preview/check/route.ts +5 -20
  11. package/apps/agents-server/src/app/api/page-preview/interact/route.ts +179 -0
  12. package/apps/agents-server/src/app/api/page-preview/live/route.ts +67 -0
  13. package/apps/agents-server/src/app/api/page-preview/screenshot/route.ts +13 -21
  14. package/apps/agents-server/src/app/api/v1/agents/[agentId]/route.ts +13 -8
  15. package/apps/agents-server/src/components/AgentProfile/AgentCapabilityChips.tsx +39 -5
  16. package/apps/agents-server/src/components/Homepage/AgentCard.tsx +7 -1
  17. package/apps/agents-server/src/components/Homepage/AgentsList.tsx +3 -0
  18. package/apps/agents-server/src/components/Homepage/AgentsListHeader.tsx +41 -0
  19. package/apps/agents-server/src/components/Homepage/hiddenFolders.ts +104 -0
  20. package/apps/agents-server/src/components/Homepage/useAgentsListQueryState.ts +35 -0
  21. package/apps/agents-server/src/components/Homepage/useAgentsListState.ts +24 -4
  22. package/apps/agents-server/src/constants/chatVisualMode.ts +1 -1
  23. package/apps/agents-server/src/constants/serverLimits.ts +19 -0
  24. package/apps/agents-server/src/constants/themeMode.ts +1 -1
  25. package/apps/agents-server/src/database/migrations/2026-05-2600-default-theme.sql +2 -2
  26. package/apps/agents-server/src/database/seedCoreAgents.ts +0 -2
  27. package/apps/agents-server/src/database/seedDefaultAgents.ts +0 -2
  28. package/apps/agents-server/src/tools/agent_progress.ts +4 -10
  29. package/apps/agents-server/src/utils/agentVisibility.ts +25 -62
  30. package/apps/agents-server/src/utils/chatTasksAdmin.ts +3 -1
  31. package/apps/agents-server/src/utils/createAgentWithDefaultVisibility.ts +3 -1
  32. package/apps/agents-server/src/utils/externalChatRunner/processExternalUserChatJob.ts +9 -17
  33. package/apps/agents-server/src/utils/getAdminChatTasksResponse/mapVpsSelfUpdateJobToAdminChatTask.ts +84 -0
  34. package/apps/agents-server/src/utils/getAdminChatTasksResponse.ts +195 -5
  35. package/apps/agents-server/src/utils/localChatRunner/LocalUserChatJobMetadata.ts +15 -5
  36. package/apps/agents-server/src/utils/localChatRunner/processLocalUserChatJob.ts +17 -26
  37. package/apps/agents-server/src/utils/pagePreview/livePagePreviewSessions.ts +365 -0
  38. package/apps/agents-server/src/utils/pagePreview/resolvePagePreviewRequestUrl.ts +74 -0
  39. package/apps/agents-server/src/utils/serverLimits.ts +2 -0
  40. package/apps/agents-server/src/utils/serverManagement/createManagedServer/seedServerCoreAgents.ts +2 -2
  41. package/apps/agents-server/src/utils/serverManagement/createManagedServer/seedServerDefaultAgents.ts +1 -1
  42. package/apps/agents-server/src/utils/userChat/createUserChatHarnessProgressCard.ts +0 -6
  43. package/apps/agents-server/src/utils/userChat/createUserChatRunnerProgressCard.ts +0 -6
  44. package/apps/agents-server/src/utils/userChat/userChatMessageLifecycle.ts +69 -0
  45. package/apps/agents-server/src/utils/userChat/userChatProgressCard.ts +0 -6
  46. package/apps/agents-server/src/utils/vpsSelfUpdate.ts +150 -24
  47. package/esm/apps/agents-server/src/constants/serverLimits.d.ts +17 -0
  48. package/esm/index.es.js +581 -93
  49. package/esm/index.es.js.map +1 -1
  50. package/esm/scripts/run-agent-messages/main/runMultipleAgentMessages.d.ts +1 -0
  51. package/esm/scripts/run-agent-messages/main/tickAgentMessages.d.ts +1 -0
  52. package/esm/src/_packages/core.index.d.ts +22 -0
  53. package/esm/src/_packages/types.index.d.ts +2 -0
  54. package/esm/src/book-2.0/agent-source/AgentBasicInformation.d.ts +2 -0
  55. package/esm/src/book-2.0/agent-source/agentSourceVisibility.d.ts +97 -0
  56. package/esm/src/book-2.0/agent-source/agentSourceVisibility.test.d.ts +1 -0
  57. package/esm/src/book-components/BookEditor/BookEditorMonacoTokenization.d.ts +1 -0
  58. package/esm/src/book-components/Chat/Chat/CitationIframePreview.d.ts +2 -2
  59. package/esm/src/book-components/Chat/utils/livePagePreviewConstants.d.ts +12 -0
  60. package/esm/src/cli/cli-commands/agents-server/buildAgentsServer.d.ts +6 -0
  61. package/esm/src/collection/agent-collection/CreateAgentInput.d.ts +2 -1
  62. package/esm/src/collection/agent-collection/constructors/agent-collection-in-supabase/prepareAgentSourceForPersistence.d.ts +21 -1
  63. package/esm/src/commitments/META_VISIBILITY/META_VISIBILITY.d.ts +27 -0
  64. package/esm/src/commitments/index.d.ts +2 -1
  65. package/esm/src/version.d.ts +1 -1
  66. package/package.json +1 -1
  67. package/src/_packages/core.index.ts +22 -0
  68. package/src/_packages/types.index.ts +2 -0
  69. package/src/book-2.0/agent-source/AgentBasicInformation.ts +2 -0
  70. package/src/book-2.0/agent-source/agentSourceVisibility.ts +214 -0
  71. package/src/book-2.0/agent-source/parseAgentSource/applyMetaCommitment.ts +17 -0
  72. package/src/book-2.0/book-language-documentation/createStandaloneBookLanguageMarkdown.ts +1 -0
  73. package/src/book-components/BookEditor/BookEditorMonacoTokenization.ts +11 -0
  74. package/src/book-components/BookEditor/useBookEditorMonacoLanguage.ts +7 -3
  75. package/src/book-components/Chat/Chat/Chat.module.css +14 -5
  76. package/src/book-components/Chat/Chat/CitationIframePreview.tsx +197 -22
  77. package/src/book-components/Chat/utils/livePagePreviewConstants.ts +17 -0
  78. package/src/cli/cli-commands/agents-server/buildAgentsServer.ts +144 -16
  79. package/src/cli/cli-commands/agents-server/startAgentsServer.ts +22 -2
  80. package/src/cli/cli-commands/coder/getDefaultCoderPackageJsonScripts.ts +1 -1
  81. package/src/cli/cli-commands/coder/run.ts +30 -0
  82. package/src/collection/agent-collection/CreateAgentInput.ts +10 -5
  83. package/src/collection/agent-collection/constructors/agent-collection-in-supabase/AgentCollectionInSupabase.ts +7 -3
  84. package/src/collection/agent-collection/constructors/agent-collection-in-supabase/createAgentPersistenceRecords.ts +7 -4
  85. package/src/collection/agent-collection/constructors/agent-collection-in-supabase/prepareAgentSourceForPersistence.ts +44 -8
  86. package/src/commitments/META_VISIBILITY/META_VISIBILITY.ts +78 -0
  87. package/src/commitments/index.ts +2 -0
  88. package/src/other/templates/getTemplatesPipelineCollection.ts +826 -650
  89. package/src/version.ts +2 -2
  90. package/src/versions.txt +2 -0
  91. package/umd/apps/agents-server/src/constants/serverLimits.d.ts +17 -0
  92. package/umd/index.umd.js +581 -93
  93. package/umd/index.umd.js.map +1 -1
  94. package/umd/scripts/run-agent-messages/main/runMultipleAgentMessages.d.ts +1 -0
  95. package/umd/scripts/run-agent-messages/main/tickAgentMessages.d.ts +1 -0
  96. package/umd/src/_packages/core.index.d.ts +22 -0
  97. package/umd/src/_packages/types.index.d.ts +2 -0
  98. package/umd/src/book-2.0/agent-source/AgentBasicInformation.d.ts +2 -0
  99. package/umd/src/book-2.0/agent-source/agentSourceVisibility.d.ts +97 -0
  100. package/umd/src/book-2.0/agent-source/agentSourceVisibility.test.d.ts +1 -0
  101. package/umd/src/book-components/BookEditor/BookEditorMonacoTokenization.d.ts +1 -0
  102. package/umd/src/book-components/Chat/Chat/CitationIframePreview.d.ts +2 -2
  103. package/umd/src/book-components/Chat/utils/livePagePreviewConstants.d.ts +12 -0
  104. package/umd/src/cli/cli-commands/agents-server/buildAgentsServer.d.ts +6 -0
  105. package/umd/src/collection/agent-collection/CreateAgentInput.d.ts +2 -1
  106. package/umd/src/collection/agent-collection/constructors/agent-collection-in-supabase/prepareAgentSourceForPersistence.d.ts +21 -1
  107. package/umd/src/commitments/META_VISIBILITY/META_VISIBILITY.d.ts +27 -0
  108. package/umd/src/commitments/index.d.ts +2 -1
  109. package/umd/src/version.d.ts +1 -1
@@ -0,0 +1,365 @@
1
+ import type { Page } from 'playwright';
2
+ import { spaceTrim } from 'spacetrim';
3
+ import {
4
+ LIVE_PAGE_PREVIEW_VIEWPORT_HEIGHT,
5
+ LIVE_PAGE_PREVIEW_VIEWPORT_WIDTH,
6
+ } from '../../../../../src/book-components/Chat/utils/livePagePreviewConstants';
7
+ import { KnowledgeScrapeError } from '../../../../../src/errors/KnowledgeScrapeError';
8
+ import { $provideBrowserForServer } from '../../tools/$provideBrowserForServer';
9
+
10
+ /**
11
+ * Pattern for live-preview session identifiers created by the browser client.
12
+ */
13
+ const LIVE_PAGE_PREVIEW_SESSION_ID_PATTERN = /^[a-zA-Z0-9_-]{1,128}$/;
14
+
15
+ /**
16
+ * Navigation timeout for opening a live knowledge preview page.
17
+ */
18
+ const LIVE_PAGE_PREVIEW_NAVIGATION_TIMEOUT_MS = 30_000;
19
+
20
+ /**
21
+ * Playwright action timeout for live-preview interactions.
22
+ */
23
+ const LIVE_PAGE_PREVIEW_ACTION_TIMEOUT_MS = 5_000;
24
+
25
+ /**
26
+ * Idle session lifetime before a stale live-preview page is closed.
27
+ */
28
+ const LIVE_PAGE_PREVIEW_SESSION_IDLE_TIMEOUT_MS = 60_000;
29
+
30
+ /**
31
+ * Multipart response boundary used by the live-preview image stream.
32
+ */
33
+ const LIVE_PAGE_PREVIEW_STREAM_BOUNDARY = 'page-preview-frame';
34
+
35
+ /**
36
+ * Delay between live-preview browser frames.
37
+ */
38
+ const LIVE_PAGE_PREVIEW_FRAME_INTERVAL_MS = 500;
39
+
40
+ /**
41
+ * JPEG quality for live-preview browser frames.
42
+ */
43
+ const LIVE_PAGE_PREVIEW_JPEG_QUALITY = 65;
44
+
45
+ /**
46
+ * Browser page stored for a live knowledge preview session.
47
+ */
48
+ type LivePagePreviewSession = {
49
+ readonly page: Page;
50
+ readonly url: string;
51
+ lastAccessedAt: number;
52
+ };
53
+
54
+ /**
55
+ * Pointer interaction sent from the live preview image to the browser page.
56
+ */
57
+ type LivePagePreviewClickInteraction = {
58
+ readonly type: 'click';
59
+ readonly x: number;
60
+ readonly y: number;
61
+ };
62
+
63
+ /**
64
+ * Wheel interaction sent from the live preview image to the browser page.
65
+ */
66
+ type LivePagePreviewWheelInteraction = {
67
+ readonly type: 'wheel';
68
+ readonly deltaX: number;
69
+ readonly deltaY: number;
70
+ };
71
+
72
+ /**
73
+ * Keyboard interaction sent from the live preview image to the browser page.
74
+ */
75
+ type LivePagePreviewKeyDownInteraction = {
76
+ readonly type: 'keyDown';
77
+ readonly key: string;
78
+ };
79
+
80
+ /**
81
+ * Supported interaction payload for a live knowledge preview session.
82
+ */
83
+ export type LivePagePreviewInteraction =
84
+ | LivePagePreviewClickInteraction
85
+ | LivePagePreviewWheelInteraction
86
+ | LivePagePreviewKeyDownInteraction;
87
+
88
+ /**
89
+ * Active browser pages for live knowledge previews.
90
+ */
91
+ const LIVE_PAGE_PREVIEW_SESSIONS = new Map<string, LivePagePreviewSession>();
92
+
93
+ /**
94
+ * Content type for the live-preview multipart image stream.
95
+ */
96
+ export const LIVE_PAGE_PREVIEW_STREAM_CONTENT_TYPE = `multipart/x-mixed-replace; boundary=${LIVE_PAGE_PREVIEW_STREAM_BOUNDARY}`;
97
+
98
+ /**
99
+ * Checks whether a live-preview session identifier is safe to use as a map key.
100
+ *
101
+ * @param sessionId - Candidate session identifier.
102
+ * @returns True when the value is a valid live-preview session id.
103
+ */
104
+ export function isLivePagePreviewSessionId(sessionId: string): boolean {
105
+ return LIVE_PAGE_PREVIEW_SESSION_ID_PATTERN.test(sessionId);
106
+ }
107
+
108
+ /**
109
+ * Opens or reuses the browser page for one live knowledge preview.
110
+ *
111
+ * @param options - Session, target URL, and request cancellation signal.
112
+ * @returns Playwright page backing the live preview.
113
+ */
114
+ export async function getOrCreateLivePagePreviewSession(options: {
115
+ readonly sessionId: string;
116
+ readonly url: string;
117
+ readonly signal: AbortSignal;
118
+ }): Promise<Page> {
119
+ pruneExpiredLivePagePreviewSessions();
120
+
121
+ const existingSession = LIVE_PAGE_PREVIEW_SESSIONS.get(options.sessionId);
122
+ if (existingSession && existingSession.url === options.url && !existingSession.page.isClosed()) {
123
+ existingSession.lastAccessedAt = Date.now();
124
+ return existingSession.page;
125
+ }
126
+
127
+ if (existingSession) {
128
+ await closeLivePagePreviewSession(options.sessionId);
129
+ }
130
+
131
+ const browserContext = await $provideBrowserForServer({
132
+ signal: options.signal,
133
+ sessionId: options.sessionId,
134
+ });
135
+ const page = await browserContext.newPage();
136
+
137
+ try {
138
+ page.setDefaultNavigationTimeout(LIVE_PAGE_PREVIEW_NAVIGATION_TIMEOUT_MS);
139
+ page.setDefaultTimeout(LIVE_PAGE_PREVIEW_ACTION_TIMEOUT_MS);
140
+ await page.setViewportSize({
141
+ width: LIVE_PAGE_PREVIEW_VIEWPORT_WIDTH,
142
+ height: LIVE_PAGE_PREVIEW_VIEWPORT_HEIGHT,
143
+ });
144
+ await page.goto(options.url, {
145
+ waitUntil: 'domcontentloaded',
146
+ timeout: LIVE_PAGE_PREVIEW_NAVIGATION_TIMEOUT_MS,
147
+ });
148
+ } catch {
149
+ await closeLivePagePreviewPage(page);
150
+ throw new KnowledgeScrapeError(
151
+ spaceTrim(`
152
+ Failed to open live knowledge preview for \`${options.url}\`.
153
+
154
+ The browser session could not navigate to the requested source.
155
+ `),
156
+ );
157
+ }
158
+
159
+ LIVE_PAGE_PREVIEW_SESSIONS.set(options.sessionId, {
160
+ page,
161
+ url: options.url,
162
+ lastAccessedAt: Date.now(),
163
+ });
164
+
165
+ return page;
166
+ }
167
+
168
+ /**
169
+ * Closes one live knowledge preview session if it exists.
170
+ *
171
+ * @param sessionId - Live-preview session identifier.
172
+ */
173
+ export async function closeLivePagePreviewSession(sessionId: string): Promise<void> {
174
+ const existingSession = LIVE_PAGE_PREVIEW_SESSIONS.get(sessionId);
175
+ if (!existingSession) {
176
+ return;
177
+ }
178
+
179
+ LIVE_PAGE_PREVIEW_SESSIONS.delete(sessionId);
180
+ await closeLivePagePreviewPage(existingSession.page);
181
+ }
182
+
183
+ /**
184
+ * Creates an MJPEG stream from an active live-preview browser page.
185
+ *
186
+ * @param options - Session identifier, browser page, and request cancellation signal.
187
+ * @returns Readable stream that emits JPEG browser frames until the client disconnects.
188
+ */
189
+ export function createLivePagePreviewStream(options: {
190
+ readonly sessionId: string;
191
+ readonly page: Page;
192
+ readonly signal: AbortSignal;
193
+ }): ReadableStream<Uint8Array> {
194
+ const encoder = new TextEncoder();
195
+ let isStreamClosed = false;
196
+ let isSessionClosed = false;
197
+
198
+ const closeSessionOnce = async (): Promise<void> => {
199
+ if (isSessionClosed) {
200
+ return;
201
+ }
202
+
203
+ isSessionClosed = true;
204
+ await closeLivePagePreviewSession(options.sessionId);
205
+ };
206
+
207
+ return new ReadableStream<Uint8Array>({
208
+ async start(controller) {
209
+ const handleAbort = (): void => {
210
+ isStreamClosed = true;
211
+ void closeSessionOnce();
212
+ };
213
+
214
+ options.signal.addEventListener('abort', handleAbort, { once: true });
215
+
216
+ try {
217
+ while (!isStreamClosed && !options.signal.aborted && !options.page.isClosed()) {
218
+ const buffer = await options.page.screenshot({
219
+ type: 'jpeg',
220
+ quality: LIVE_PAGE_PREVIEW_JPEG_QUALITY,
221
+ });
222
+
223
+ if (isStreamClosed || options.signal.aborted || options.page.isClosed()) {
224
+ break;
225
+ }
226
+
227
+ const header = [
228
+ '',
229
+ `--${LIVE_PAGE_PREVIEW_STREAM_BOUNDARY}`,
230
+ 'Content-Type: image/jpeg',
231
+ `Content-Length: ${buffer.length}`,
232
+ '',
233
+ '',
234
+ ].join('\r\n');
235
+
236
+ controller.enqueue(encoder.encode(header));
237
+ controller.enqueue(buffer);
238
+
239
+ await waitForLivePagePreviewFrame(options.signal);
240
+ }
241
+ } catch (error) {
242
+ if (!isStreamClosed && !options.signal.aborted) {
243
+ console.error('Error streaming live page preview:', error);
244
+ }
245
+ } finally {
246
+ isStreamClosed = true;
247
+ options.signal.removeEventListener('abort', handleAbort);
248
+ await closeSessionOnce();
249
+
250
+ try {
251
+ controller.close();
252
+ } catch {
253
+ // The client can disconnect before the server closes the stream.
254
+ }
255
+ }
256
+ },
257
+ async cancel() {
258
+ isStreamClosed = true;
259
+ await closeSessionOnce();
260
+ },
261
+ });
262
+ }
263
+
264
+ /**
265
+ * Applies one browser interaction to an active live preview session.
266
+ *
267
+ * @param options - Session identifier and normalized interaction.
268
+ * @returns True when the interaction was applied to an active session.
269
+ */
270
+ export async function applyLivePagePreviewInteraction(options: {
271
+ readonly sessionId: string;
272
+ readonly interaction: LivePagePreviewInteraction;
273
+ }): Promise<boolean> {
274
+ const session = LIVE_PAGE_PREVIEW_SESSIONS.get(options.sessionId);
275
+ if (!session || session.page.isClosed()) {
276
+ LIVE_PAGE_PREVIEW_SESSIONS.delete(options.sessionId);
277
+ return false;
278
+ }
279
+
280
+ session.lastAccessedAt = Date.now();
281
+
282
+ switch (options.interaction.type) {
283
+ case 'click':
284
+ await session.page.mouse.click(
285
+ clampLivePagePreviewCoordinate(options.interaction.x, LIVE_PAGE_PREVIEW_VIEWPORT_WIDTH),
286
+ clampLivePagePreviewCoordinate(options.interaction.y, LIVE_PAGE_PREVIEW_VIEWPORT_HEIGHT),
287
+ );
288
+ return true;
289
+
290
+ case 'wheel':
291
+ await session.page.mouse.wheel(options.interaction.deltaX, options.interaction.deltaY);
292
+ return true;
293
+
294
+ case 'keyDown':
295
+ await session.page.keyboard.press(options.interaction.key);
296
+ return true;
297
+ }
298
+ }
299
+
300
+ /**
301
+ * Removes stale live-preview sessions left behind by disconnected clients.
302
+ */
303
+ function pruneExpiredLivePagePreviewSessions(): void {
304
+ const now = Date.now();
305
+ for (const [sessionId, session] of LIVE_PAGE_PREVIEW_SESSIONS) {
306
+ const isExpired = now - session.lastAccessedAt > LIVE_PAGE_PREVIEW_SESSION_IDLE_TIMEOUT_MS;
307
+ if (isExpired || session.page.isClosed()) {
308
+ LIVE_PAGE_PREVIEW_SESSIONS.delete(sessionId);
309
+ void closeLivePagePreviewPage(session.page);
310
+ }
311
+ }
312
+ }
313
+
314
+ /**
315
+ * Waits between streamed browser frames, resolving early when the request is aborted.
316
+ *
317
+ * @param signal - Request cancellation signal.
318
+ */
319
+ async function waitForLivePagePreviewFrame(signal: AbortSignal): Promise<void> {
320
+ if (signal.aborted) {
321
+ return;
322
+ }
323
+
324
+ await new Promise<void>((resolve) => {
325
+ const timeout = setTimeout(() => {
326
+ signal.removeEventListener('abort', handleAbort);
327
+ resolve();
328
+ }, LIVE_PAGE_PREVIEW_FRAME_INTERVAL_MS);
329
+
330
+ function handleAbort(): void {
331
+ clearTimeout(timeout);
332
+ resolve();
333
+ }
334
+
335
+ signal.addEventListener('abort', handleAbort, { once: true });
336
+ });
337
+ }
338
+
339
+ /**
340
+ * Closes a Playwright page while ignoring cleanup errors.
341
+ *
342
+ * @param page - Browser page to close.
343
+ */
344
+ async function closeLivePagePreviewPage(page: Page): Promise<void> {
345
+ if (page.isClosed()) {
346
+ return;
347
+ }
348
+
349
+ await page.close().catch(() => undefined);
350
+ }
351
+
352
+ /**
353
+ * Clamps a pointer coordinate to the configured live-preview viewport.
354
+ *
355
+ * @param value - Raw coordinate from the web UI.
356
+ * @param maximum - Maximum coordinate value for one axis.
357
+ * @returns Coordinate safe to pass into Playwright.
358
+ */
359
+ function clampLivePagePreviewCoordinate(value: number, maximum: number): number {
360
+ if (!Number.isFinite(value)) {
361
+ return 0;
362
+ }
363
+
364
+ return Math.min(Math.max(value, 0), maximum);
365
+ }
@@ -0,0 +1,74 @@
1
+ import type { NextRequest } from 'next/server';
2
+ import { NextResponse } from 'next/server';
3
+ import { assertsError } from '../../../../../src/errors/assertsError';
4
+ import { assertSafeUrl } from '../assertSafeUrl';
5
+ import { getCurrentUser } from '../getCurrentUser';
6
+
7
+ /**
8
+ * Query parameter used by page-preview API endpoints.
9
+ */
10
+ const PAGE_PREVIEW_URL_QUERY_PARAMETER = 'url';
11
+
12
+ /**
13
+ * Successful page-preview request URL resolution.
14
+ */
15
+ type PagePreviewRequestUrlSuccess = {
16
+ readonly url: string;
17
+ readonly errorResponse: null;
18
+ };
19
+
20
+ /**
21
+ * Failed page-preview request URL resolution.
22
+ */
23
+ type PagePreviewRequestUrlFailure = {
24
+ readonly url: null;
25
+ readonly errorResponse: NextResponse;
26
+ };
27
+
28
+ /**
29
+ * Result of authenticating and validating a page-preview request URL.
30
+ */
31
+ export type PagePreviewRequestUrlResolution = PagePreviewRequestUrlSuccess | PagePreviewRequestUrlFailure;
32
+
33
+ /**
34
+ * Authenticates a page-preview request and validates its target URL against SSRF-sensitive destinations.
35
+ *
36
+ * @param request - Incoming Next.js request.
37
+ * @returns Valid target URL or a ready-made error response.
38
+ */
39
+ export async function resolvePagePreviewRequestUrl(request: NextRequest): Promise<PagePreviewRequestUrlResolution> {
40
+ const currentUser = await getCurrentUser();
41
+ if (!currentUser) {
42
+ return {
43
+ url: null,
44
+ errorResponse: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
45
+ };
46
+ }
47
+
48
+ const url = request.nextUrl.searchParams.get(PAGE_PREVIEW_URL_QUERY_PARAMETER);
49
+
50
+ if (!url) {
51
+ return {
52
+ url: null,
53
+ errorResponse: NextResponse.json(
54
+ { error: `Missing required query parameter: ${PAGE_PREVIEW_URL_QUERY_PARAMETER}` },
55
+ { status: 400 },
56
+ ),
57
+ };
58
+ }
59
+
60
+ try {
61
+ assertSafeUrl(url);
62
+ } catch (error) {
63
+ assertsError(error);
64
+ return {
65
+ url: null,
66
+ errorResponse: NextResponse.json({ error: error.message }, { status: 400 }),
67
+ };
68
+ }
69
+
70
+ return {
71
+ url,
72
+ errorResponse: null,
73
+ };
74
+ }
@@ -46,6 +46,7 @@ export type SpawnAgentLimits = {
46
46
  */
47
47
  export type LocalAgentRunnerLimits = {
48
48
  readonly maxFailedAttempts: number;
49
+ readonly maxParallelMessages: number;
49
50
  };
50
51
 
51
52
  /**
@@ -270,6 +271,7 @@ export async function getLocalAgentRunnerLimits(): Promise<LocalAgentRunnerLimit
270
271
  const limits = await getServerLimits();
271
272
  return {
272
273
  maxFailedAttempts: limits[SERVER_LIMIT_KEYS.LOCAL_AGENT_RUNNER_MAX_FAILED_ATTEMPTS],
274
+ maxParallelMessages: limits[SERVER_LIMIT_KEYS.LOCAL_AGENT_RUNNER_MAX_PARALLEL_MESSAGES],
273
275
  };
274
276
  }
275
277
 
@@ -35,7 +35,7 @@ export async function seedServerCoreAgents(
35
35
  const createdAt = new Date().toISOString();
36
36
  const { agentInsertRecord, agentHistoryInsertRecord } = createAgentPersistenceRecords(
37
37
  coreAgentBook,
38
- { folderId: coreFolderId, sortOrder: index, visibility: DEFAULT_AGENT_VISIBILITY },
38
+ { folderId: coreFolderId, sortOrder: index },
39
39
  createdAt,
40
40
  );
41
41
 
@@ -158,5 +158,5 @@ async function insertCoreFolder(
158
158
  }),
159
159
  );
160
160
 
161
- return insertResult.rows[0].id;
161
+ return insertResult.rows[0]!.id;
162
162
  }
@@ -29,7 +29,7 @@ export async function seedServerDefaultAgents(
29
29
  const createdAt = new Date().toISOString();
30
30
  const { agentInsertRecord, agentHistoryInsertRecord } = createAgentPersistenceRecords(
31
31
  defaultAgentBook,
32
- { sortOrder: index, visibility: DEFAULT_AGENT_VISIBILITY },
32
+ { sortOrder: index },
33
33
  createdAt,
34
34
  );
35
35
 
@@ -4,11 +4,6 @@ import { TOOL_TITLES } from '../../../../../src/book-components/Chat/utils/getTo
4
4
  import { isVisibleChatToolCall } from '../../../../../src/book-components/Chat/utils/isVisibleChatToolCall';
5
5
  import { resolveToolCallState } from '../../../../../src/book-components/Chat/utils/resolveToolCallState';
6
6
 
7
- /**
8
- * Default title used while a running chat job reports harness action progress.
9
- */
10
- const USER_CHAT_HARNESS_PROGRESS_TITLE = 'Working on your request';
11
-
12
7
  /**
13
8
  * Creates a user-facing progress card from the latest visible harness/tool action.
14
9
  *
@@ -24,7 +19,6 @@ export function createUserChatHarnessProgressCard(
24
19
  }
25
20
 
26
21
  return {
27
- title: USER_CHAT_HARNESS_PROGRESS_TITLE,
28
22
  now: createHarnessProgressNowText(latestVisibleToolCall),
29
23
  items: [],
30
24
  updatedAt: new Date().toISOString() as NonNullable<ChatMessage['progressCard']>['updatedAt'],
@@ -11,11 +11,6 @@ export type UserChatRunnerKind = 'local' | 'external';
11
11
  */
12
12
  export type UserChatRunnerProgressPhase = 'queued_for_runner';
13
13
 
14
- /**
15
- * Default title used while an out-of-process runner is working on a chat answer.
16
- */
17
- const USER_CHAT_RUNNER_PROGRESS_TITLE = 'Working on your request';
18
-
19
14
  /**
20
15
  * User-facing labels for durable chat runners.
21
16
  */
@@ -35,7 +30,6 @@ export function createUserChatRunnerProgressCard(options: {
35
30
  readonly phase: UserChatRunnerProgressPhase;
36
31
  }): NonNullable<ChatMessage['progressCard']> {
37
32
  return {
38
- title: USER_CHAT_RUNNER_PROGRESS_TITLE,
39
33
  now: createUserChatRunnerProgressNowText(options),
40
34
  items: [],
41
35
  updatedAt: new Date().toISOString() as NonNullable<ChatMessage['progressCard']>['updatedAt'],
@@ -4,6 +4,13 @@ import type { ChatMessage } from '../../../../../src/_packages/types.index';
4
4
  */
5
5
  export type UserChatMessageLifecycleState = NonNullable<ChatMessage['lifecycleState']>;
6
6
 
7
+ /**
8
+ * Message shape written into local/external chat-runner `.book` files.
9
+ */
10
+ export type UserChatRunnerThreadMessage = Pick<ChatMessage, 'content'> & {
11
+ sender: 'USER' | 'AGENT';
12
+ };
13
+
7
14
  /**
8
15
  * Creates one persisted user-authored message for a durable chat turn.
9
16
  */
@@ -89,6 +96,36 @@ export function resolvePromptThreadBeforeUserMessage(
89
96
  return messages.slice(0, userMessageIndex);
90
97
  }
91
98
 
99
+ /**
100
+ * Creates the complete chat thread mirrored to a runner before it writes the next answer.
101
+ */
102
+ export function createUserChatRunnerThreadMessages(options: {
103
+ messages: ReadonlyArray<ChatMessage>;
104
+ userMessageId: string;
105
+ resolveInitialAgentMessage: () => string | null | undefined;
106
+ }): Array<UserChatRunnerThreadMessage> {
107
+ const userMessage = options.messages.find((message) => message.id === options.userMessageId);
108
+ if (!userMessage) {
109
+ return [];
110
+ }
111
+
112
+ const previousThreadMessages = resolvePromptThreadBeforeUserMessage(options.messages, options.userMessageId);
113
+
114
+ return [
115
+ ...createInitialUserChatRunnerThreadMessages({
116
+ isFirstUserTurn: previousThreadMessages.length === 0,
117
+ resolveInitialAgentMessage: options.resolveInitialAgentMessage,
118
+ }),
119
+ ...previousThreadMessages,
120
+ userMessage,
121
+ ]
122
+ .filter(isUserChatRunnerThreadMessage)
123
+ .map((message) => ({
124
+ sender: message.sender,
125
+ content: message.content,
126
+ }));
127
+ }
128
+
92
129
  /**
93
130
  * Maps durable job status values to message lifecycle labels rendered by the UI.
94
131
  */
@@ -107,3 +144,35 @@ export function resolveMessageLifecycleStateFromJobStatus(status: string): UserC
107
144
  return 'completed';
108
145
  }
109
146
  }
147
+
148
+ /**
149
+ * Recreates the synthetic first agent message that the UI shows for empty durable chats.
150
+ */
151
+ function createInitialUserChatRunnerThreadMessages(options: {
152
+ isFirstUserTurn: boolean;
153
+ resolveInitialAgentMessage: () => string | null | undefined;
154
+ }): Array<UserChatRunnerThreadMessage> {
155
+ if (!options.isFirstUserTurn) {
156
+ return [];
157
+ }
158
+
159
+ const initialAgentMessage = options.resolveInitialAgentMessage();
160
+ if (!initialAgentMessage || initialAgentMessage.trim().length === 0) {
161
+ return [];
162
+ }
163
+
164
+ return [
165
+ {
166
+ sender: 'AGENT',
167
+ content: initialAgentMessage,
168
+ },
169
+ ];
170
+ }
171
+
172
+ /**
173
+ * Returns true when one persisted message should be visible to out-of-process runners.
174
+ */
175
+ function isUserChatRunnerThreadMessage(message: ChatMessage): message is ChatMessage & UserChatRunnerThreadMessage {
176
+ const isRunnerSender = message.sender === 'USER' || message.sender === 'AGENT';
177
+ return message.isComplete !== false && isRunnerSender;
178
+ }
@@ -75,11 +75,6 @@ export type UserChatProgressContext = {
75
75
  readonly isAgentKitCached?: boolean;
76
76
  };
77
77
 
78
- /**
79
- * Default title used by durable chat progress cards.
80
- */
81
- const USER_CHAT_PROGRESS_TITLE = 'Working on your request';
82
-
83
78
  /**
84
79
  * Ordered progress item identifiers shared across all durable chat phases.
85
80
  */
@@ -165,7 +160,6 @@ export function createUserChatProgressCard(
165
160
  const { now, next } = composeUserChatProgressPhaseText(phase, context);
166
161
 
167
162
  return {
168
- title: USER_CHAT_PROGRESS_TITLE,
169
163
  now,
170
164
  next,
171
165
  items: USER_CHAT_PROGRESS_ITEMS.map((item) => ({