@promptbook/cli 0.113.0-0 → 0.113.0-2

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 (35) hide show
  1. package/README.md +1 -17
  2. package/agents/default/developer.book +3 -0
  3. package/apps/agents-server/src/app/admin/task-manager/TaskManagerClient.tsx +3 -3
  4. package/apps/agents-server/src/app/admin/task-manager/TaskManagerTaskRow.tsx +11 -2
  5. package/apps/agents-server/src/app/admin/task-manager/TaskManagerTasksCard.tsx +5 -5
  6. package/apps/agents-server/src/app/api/page-preview/input/route.ts +161 -0
  7. package/apps/agents-server/src/app/api/page-preview/stream/route.ts +81 -0
  8. package/apps/agents-server/src/components/Header/HeaderHomepageLink.tsx +1 -1
  9. package/apps/agents-server/src/constants/chatVisualMode.ts +1 -1
  10. package/apps/agents-server/src/constants/themeMode.ts +1 -1
  11. package/apps/agents-server/src/database/migrations/2026-05-2600-default-theme.sql +2 -2
  12. package/apps/agents-server/src/utils/chatTasksAdmin.ts +4 -1
  13. package/apps/agents-server/src/utils/createPagePreviewBrowserStream.ts +179 -0
  14. package/apps/agents-server/src/utils/getAdminChatTasksResponse/mapVpsSelfUpdateJobToAdminChatTask.ts +84 -0
  15. package/apps/agents-server/src/utils/getAdminChatTasksResponse.ts +221 -5
  16. package/apps/agents-server/src/utils/pagePreviewBrowserSessions.ts +234 -0
  17. package/apps/agents-server/src/utils/vpsSelfUpdate.ts +12 -0
  18. package/esm/index.es.js +26 -5
  19. package/esm/index.es.js.map +1 -1
  20. package/esm/src/book-components/Chat/Chat/CitationIframePreview.d.ts +2 -2
  21. package/esm/src/book-components/Chat/Chat/CitationIframePreview.test.d.ts +2 -0
  22. package/esm/src/version.d.ts +1 -1
  23. package/package.json +1 -1
  24. package/src/book-components/Chat/Chat/Chat.module.css +37 -0
  25. package/src/book-components/Chat/Chat/CitationIframePreview.tsx +138 -11
  26. package/src/book-components/Chat/Chat/createProgressCardChecklistMarkdown.ts +1 -8
  27. package/src/cli/promptbookCli.ts +28 -3
  28. package/src/other/templates/getTemplatesPipelineCollection.ts +750 -812
  29. package/src/version.ts +2 -2
  30. package/src/versions.txt +2 -0
  31. package/umd/index.umd.js +26 -5
  32. package/umd/index.umd.js.map +1 -1
  33. package/umd/src/book-components/Chat/Chat/CitationIframePreview.d.ts +2 -2
  34. package/umd/src/book-components/Chat/Chat/CitationIframePreview.test.d.ts +2 -0
  35. package/umd/src/version.d.ts +1 -1
@@ -0,0 +1,84 @@
1
+ import type { AdminChatTaskRecord } from '../chatTasksAdmin';
2
+ import type { UserChatJobStatus } from '../userChat/UserChatJobRecord';
3
+ import type { VpsSelfUpdateJobSnapshot } from '../vpsSelfUpdate';
4
+
5
+ /**
6
+ * Stable synthetic task id used for the singleton standalone VPS self-update task row.
7
+ *
8
+ * @private internal admin utility of Agents Server
9
+ */
10
+ export const VPS_SELF_UPDATE_ADMIN_CHAT_TASK_ID = 'vps-self-update';
11
+
12
+ /**
13
+ * Synthetic queue name used for the standalone VPS self-update task row.
14
+ *
15
+ * @private internal admin utility of Agents Server
16
+ */
17
+ export const VPS_SELF_UPDATE_ADMIN_CHAT_TASK_QUEUE_NAME = 'vps-self-update';
18
+
19
+ /**
20
+ * Maps a persisted VPS self-update job snapshot to the admin task manager row shape.
21
+ *
22
+ * @param job - Latest persisted self-update job snapshot.
23
+ * @returns Task manager row or `null` when no self-update has ever been triggered on this server.
24
+ */
25
+ export function mapVpsSelfUpdateJobToAdminChatTask(job: VpsSelfUpdateJobSnapshot): AdminChatTaskRecord | null {
26
+ const status = toAdminChatTaskStatus(job);
27
+ if (!status) {
28
+ return null;
29
+ }
30
+
31
+ const isTerminalStatus = status === 'COMPLETED' || status === 'FAILED';
32
+ const startedAt = job.startedAt;
33
+ const finishedAt = isTerminalStatus ? job.finishedAt || startedAt : null;
34
+ const updatedAt = finishedAt || startedAt || new Date().toISOString();
35
+ const errorSummary = job.errorMessage || null;
36
+ const currentStepDetails = job.currentStep || null;
37
+
38
+ return {
39
+ id: VPS_SELF_UPDATE_ADMIN_CHAT_TASK_ID,
40
+ kind: 'VPS_SELF_UPDATE',
41
+ status,
42
+ createdAt: startedAt || updatedAt,
43
+ queuedAt: startedAt || updatedAt,
44
+ startedAt,
45
+ updatedAt,
46
+ finishedAt,
47
+ cancelRequestedAt: null,
48
+ pausedAt: null,
49
+ lastHeartbeatAt: null,
50
+ leaseExpiresAt: null,
51
+ recurrenceIntervalMs: null,
52
+ priority: null,
53
+ attemptCount: 1,
54
+ retryCount: 0,
55
+ lastErrorSummary: errorSummary,
56
+ lastErrorDetails: currentStepDetails,
57
+ userId: 0,
58
+ username: null,
59
+ agentPermanentId: VPS_SELF_UPDATE_ADMIN_CHAT_TASK_ID,
60
+ agentName: job.targetEnvironment.label,
61
+ chatId: job.targetBranch || job.targetEnvironment.branch || VPS_SELF_UPDATE_ADMIN_CHAT_TASK_ID,
62
+ workerId: job.pid !== null ? String(job.pid) : null,
63
+ queueName: VPS_SELF_UPDATE_ADMIN_CHAT_TASK_QUEUE_NAME,
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Maps the shell-owned self-update status to the durable chat-task status enum used by the admin task manager.
69
+ *
70
+ * @param job - Persisted self-update job snapshot.
71
+ * @returns Equivalent durable chat-job status, or `null` when the job is idle (no run has been triggered yet).
72
+ */
73
+ function toAdminChatTaskStatus(job: VpsSelfUpdateJobSnapshot): UserChatJobStatus | null {
74
+ switch (job.status) {
75
+ case 'running':
76
+ return 'RUNNING';
77
+ case 'succeeded':
78
+ return 'COMPLETED';
79
+ case 'failed':
80
+ return 'FAILED';
81
+ case 'idle':
82
+ return null;
83
+ }
84
+ }
@@ -1,8 +1,18 @@
1
1
  import { ensureUserChatTimeoutWorkerBootstrapped } from '@/src/utils/userChatTimeout/ensureUserChatTimeoutWorkerBootstrapped';
2
- import type { AdminChatTaskListResponse } from './chatTasksAdmin';
2
+ import type { AdminChatTaskCounters, AdminChatTaskListResponse, AdminChatTaskRecord } from './chatTasksAdmin';
3
3
  import { getAdminChatTasks } from './getAdminChatTasksResponse/getAdminChatTasks';
4
- import { parseAdminChatTaskQuery } from './getAdminChatTasksResponse/parseAdminChatTaskQuery';
4
+ import { mapVpsSelfUpdateJobToAdminChatTask } from './getAdminChatTasksResponse/mapVpsSelfUpdateJobToAdminChatTask';
5
+ import { parseAdminChatTaskQuery, type ParsedAdminChatTaskQuery } from './getAdminChatTasksResponse/parseAdminChatTaskQuery';
5
6
  import { throttledAdminRecovery } from './getAdminChatTasksResponse/throttledAdminRecovery';
7
+ import { listPagePreviewBrowserAdminTasks } from './pagePreviewBrowserSessions';
8
+ import { readVpsSelfUpdateJobSnapshot } from './vpsSelfUpdate';
9
+
10
+ /**
11
+ * Milliseconds in one hour.
12
+ *
13
+ * @private internal constant of `getAdminChatTasksResponse`
14
+ */
15
+ const HOUR_IN_MILLISECONDS = 60 * 60 * 1000;
6
16
 
7
17
  /**
8
18
  * Successful task-manager response envelope.
@@ -53,13 +63,27 @@ export async function getAdminChatTasksResponse(
53
63
  await throttledAdminRecovery();
54
64
 
55
65
  const adminChatTasks = await getAdminChatTasks(parsedQuery);
66
+ const vpsSelfUpdateTask = await loadVpsSelfUpdateAdminChatTask();
67
+ const pagePreviewBrowserTasks = listPagePreviewBrowserAdminTasks();
68
+ const injectableTasks = [vpsSelfUpdateTask, ...pagePreviewBrowserTasks].filter(
69
+ (task): task is AdminChatTaskRecord => task !== null,
70
+ );
71
+ const injectedTasks = collectAdminChatTasksToInject(injectableTasks, parsedQuery);
72
+ const { items, total } = mergeInjectedAdminChatTasks({
73
+ databaseItems: adminChatTasks.items,
74
+ databaseTotal: adminChatTasks.total,
75
+ injectedTasks,
76
+ page: parsedQuery.page,
77
+ pageSize: parsedQuery.pageSize,
78
+ });
79
+ const counters = mergeInjectedAdminChatTaskCounters(adminChatTasks.counters, injectableTasks);
56
80
 
57
81
  return {
58
82
  status: 200,
59
83
  response: {
60
- items: adminChatTasks.items,
61
- counters: adminChatTasks.counters,
62
- total: adminChatTasks.total,
84
+ items,
85
+ counters,
86
+ total,
63
87
  page: parsedQuery.page,
64
88
  pageSize: parsedQuery.pageSize,
65
89
  view: parsedQuery.view,
@@ -69,3 +93,195 @@ export async function getAdminChatTasksResponse(
69
93
  },
70
94
  };
71
95
  }
96
+
97
+ /**
98
+ * Loads the currently persisted standalone VPS self-update task, if any.
99
+ *
100
+ * The read is defensive so a corrupt status file cannot block the admin task manager from rendering.
101
+ *
102
+ * @returns Injectable task record or `null` when no self-update has ever been triggered on this server.
103
+ */
104
+ async function loadVpsSelfUpdateAdminChatTask(): Promise<AdminChatTaskRecord | null> {
105
+ try {
106
+ const jobSnapshot = await readVpsSelfUpdateJobSnapshot();
107
+ return mapVpsSelfUpdateJobToAdminChatTask(jobSnapshot);
108
+ } catch (error) {
109
+ console.error('[admin-chat-task] failed to load VPS self-update task snapshot', error);
110
+ return null;
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Filters out injected tasks that do not belong to the requested admin task-manager view or search.
116
+ *
117
+ * @param injectableTasks - Synthetic task rows collected from process-local state.
118
+ * @param query - Parsed admin task-manager query.
119
+ * @returns Tasks to inject on top of the database-backed items.
120
+ */
121
+ function collectAdminChatTasksToInject(
122
+ injectableTasks: ReadonlyArray<AdminChatTaskRecord>,
123
+ query: ParsedAdminChatTaskQuery,
124
+ ): ReadonlyArray<AdminChatTaskRecord> {
125
+ const nowTimestamp = Date.now();
126
+ return injectableTasks.filter(
127
+ (task) => matchesAdminChatTaskView(task, query, nowTimestamp) && matchesAdminChatTaskSearch(task, query.search),
128
+ );
129
+ }
130
+
131
+ /**
132
+ * Prepends the injected task rows to the paginated database items so the self-update stays visible on page 1.
133
+ *
134
+ * @param options - Merge inputs.
135
+ * @returns Merged items for the current page and the updated total row count.
136
+ */
137
+ function mergeInjectedAdminChatTasks(options: {
138
+ readonly databaseItems: ReadonlyArray<AdminChatTaskRecord>;
139
+ readonly databaseTotal: number;
140
+ readonly injectedTasks: ReadonlyArray<AdminChatTaskRecord>;
141
+ readonly page: number;
142
+ readonly pageSize: number;
143
+ }): { items: Array<AdminChatTaskRecord>; total: number } {
144
+ const total = options.databaseTotal + options.injectedTasks.length;
145
+
146
+ if (options.injectedTasks.length === 0) {
147
+ return { items: [...options.databaseItems], total };
148
+ }
149
+
150
+ if (options.page !== 1) {
151
+ return { items: [...options.databaseItems], total };
152
+ }
153
+
154
+ const items = [...options.injectedTasks, ...options.databaseItems].slice(0, options.pageSize);
155
+ return { items, total };
156
+ }
157
+
158
+ /**
159
+ * Adds injected tasks to the summary counters so the header metrics stay accurate.
160
+ *
161
+ * @param databaseCounters - Counters computed from durable database rows.
162
+ * @param injectedTasks - Synthetic task rows collected from process-local state.
163
+ * @returns Merged counters including the injected tasks.
164
+ */
165
+ function mergeInjectedAdminChatTaskCounters(
166
+ databaseCounters: AdminChatTaskCounters,
167
+ injectedTasks: ReadonlyArray<AdminChatTaskRecord>,
168
+ ): AdminChatTaskCounters {
169
+ if (injectedTasks.length === 0) {
170
+ return databaseCounters;
171
+ }
172
+
173
+ const nowTimestamp = Date.now();
174
+ const injectedQueuedTimestamps = injectedTasks
175
+ .filter((task) => task.status === 'QUEUED')
176
+ .map((task) => Date.parse(task.queuedAt))
177
+ .filter((timestamp) => Number.isFinite(timestamp));
178
+ const oldestInjectedQueuedAgeMs =
179
+ injectedQueuedTimestamps.length === 0 ? null : nowTimestamp - Math.min(...injectedQueuedTimestamps);
180
+
181
+ return {
182
+ runningCount: databaseCounters.runningCount + injectedTasks.filter((task) => task.status === 'RUNNING').length,
183
+ queuedCount: databaseCounters.queuedCount + injectedTasks.filter((task) => task.status === 'QUEUED').length,
184
+ failedLast24hCount:
185
+ databaseCounters.failedLast24hCount +
186
+ injectedTasks.filter(
187
+ (task) =>
188
+ task.status === 'FAILED' &&
189
+ isIsoTimestampAtOrAfter(task.finishedAt, nowTimestamp - 24 * HOUR_IN_MILLISECONDS),
190
+ ).length,
191
+ oldestQueuedAgeMs: mergeOldestQueuedAge(databaseCounters.oldestQueuedAgeMs, oldestInjectedQueuedAgeMs),
192
+ };
193
+ }
194
+
195
+ /**
196
+ * Merges durable and injected queued-task ages.
197
+ *
198
+ * @param databaseOldestQueuedAgeMs - Oldest durable queued-task age.
199
+ * @param injectedOldestQueuedAgeMs - Oldest injected queued-task age.
200
+ * @returns Oldest queued age across both sources.
201
+ */
202
+ function mergeOldestQueuedAge(
203
+ databaseOldestQueuedAgeMs: number | null,
204
+ injectedOldestQueuedAgeMs: number | null,
205
+ ): number | null {
206
+ if (databaseOldestQueuedAgeMs === null) {
207
+ return injectedOldestQueuedAgeMs;
208
+ }
209
+
210
+ if (injectedOldestQueuedAgeMs === null) {
211
+ return databaseOldestQueuedAgeMs;
212
+ }
213
+
214
+ return Math.max(databaseOldestQueuedAgeMs, injectedOldestQueuedAgeMs);
215
+ }
216
+
217
+ /**
218
+ * Returns whether the injected task belongs in the requested admin task-manager view.
219
+ *
220
+ * @param task - Injected task.
221
+ * @param query - Parsed admin task-manager query.
222
+ * @param nowTimestamp - Current epoch used for time-window filtering.
223
+ * @returns `true` when the task should be included.
224
+ */
225
+ function matchesAdminChatTaskView(
226
+ task: AdminChatTaskRecord,
227
+ query: ParsedAdminChatTaskQuery,
228
+ nowTimestamp: number,
229
+ ): boolean {
230
+ switch (query.view) {
231
+ case 'running':
232
+ return task.status === 'RUNNING';
233
+ case 'queued':
234
+ return task.status === 'QUEUED';
235
+ case 'failed':
236
+ return (
237
+ task.status === 'FAILED' &&
238
+ isIsoTimestampAtOrAfter(task.finishedAt, nowTimestamp - 24 * HOUR_IN_MILLISECONDS)
239
+ );
240
+ case 'all':
241
+ return isIsoTimestampAtOrAfter(task.updatedAt, nowTimestamp - query.timeWindowHours * HOUR_IN_MILLISECONDS);
242
+ case 'active':
243
+ default:
244
+ return task.status === 'QUEUED' || task.status === 'RUNNING';
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Returns whether the injected task matches the free-text admin search input.
250
+ *
251
+ * @param task - Injected task.
252
+ * @param search - Trimmed search text from the parsed query.
253
+ * @returns `true` when the task should be included.
254
+ */
255
+ function matchesAdminChatTaskSearch(task: AdminChatTaskRecord, search: string): boolean {
256
+ if (!search) {
257
+ return true;
258
+ }
259
+
260
+ const normalizedSearch = search.toLowerCase();
261
+ if (task.id.toLowerCase().includes(normalizedSearch)) {
262
+ return true;
263
+ }
264
+ if (task.agentPermanentId.toLowerCase().includes(normalizedSearch)) {
265
+ return true;
266
+ }
267
+ if ((task.agentName || '').toLowerCase().includes(normalizedSearch)) {
268
+ return true;
269
+ }
270
+ return task.chatId.toLowerCase().includes(normalizedSearch);
271
+ }
272
+
273
+ /**
274
+ * Returns whether one ISO timestamp is at or after the given cutoff.
275
+ *
276
+ * @param timestampIso - Optional ISO timestamp.
277
+ * @param cutoffTimestamp - Epoch cutoff in milliseconds.
278
+ * @returns `true` when the timestamp is at or after the cutoff.
279
+ */
280
+ function isIsoTimestampAtOrAfter(timestampIso: string | null, cutoffTimestamp: number): boolean {
281
+ if (!timestampIso) {
282
+ return false;
283
+ }
284
+
285
+ const timestamp = Date.parse(timestampIso);
286
+ return Number.isFinite(timestamp) && timestamp >= cutoffTimestamp;
287
+ }
@@ -0,0 +1,234 @@
1
+ import type { Page } from 'playwright';
2
+ import type { AdminChatTaskRecord } from './chatTasksAdmin';
3
+ import type { UserInfo } from './getCurrentUser';
4
+
5
+ /**
6
+ * Prefix for browser-preview session identifiers created by the citation preview UI.
7
+ *
8
+ * @private internal constant of Agents Server page-preview streaming
9
+ */
10
+ const PAGE_PREVIEW_BROWSER_SESSION_ID_PREFIX = 'page-preview-';
11
+
12
+ /**
13
+ * Pattern accepted for client-created page-preview session identifiers.
14
+ *
15
+ * @private internal constant of Agents Server page-preview streaming
16
+ */
17
+ const PAGE_PREVIEW_BROWSER_SESSION_ID_PATTERN = /^page-preview-[a-z0-9-]{16,80}$/;
18
+
19
+ /**
20
+ * Queue name used when active browser previews are surfaced in the admin task manager.
21
+ *
22
+ * @private internal constant of Agents Server page-preview streaming
23
+ */
24
+ const PAGE_PREVIEW_BROWSER_TASK_QUEUE_NAME = 'page-preview-browser';
25
+
26
+ /**
27
+ * Agent label used by the task manager for browser-preview rows.
28
+ *
29
+ * @private internal constant of Agents Server page-preview streaming
30
+ */
31
+ const PAGE_PREVIEW_BROWSER_TASK_AGENT_NAME = 'Browser preview';
32
+
33
+ /**
34
+ * In-memory record for one live browser preview stream.
35
+ *
36
+ * @private internal type of Agents Server page-preview streaming
37
+ */
38
+ export type PagePreviewBrowserSession = {
39
+ readonly id: string;
40
+ readonly url: string;
41
+ readonly userId: number;
42
+ readonly username: string | null;
43
+ readonly createdAt: string;
44
+ readonly startedAt: string;
45
+ readonly processId: number | null;
46
+ page: Page | null;
47
+ viewport: PagePreviewBrowserViewport | null;
48
+ updatedAt: string;
49
+ lastFrameAt: string | null;
50
+ };
51
+
52
+ /**
53
+ * Browser viewport used to convert pointer ratios into Playwright coordinates.
54
+ *
55
+ * @private internal type of Agents Server page-preview streaming
56
+ */
57
+ export type PagePreviewBrowserViewport = {
58
+ readonly width: number;
59
+ readonly height: number;
60
+ };
61
+
62
+ /**
63
+ * Options used when registering one browser preview stream.
64
+ *
65
+ * @private internal type of Agents Server page-preview streaming
66
+ */
67
+ export type RegisterPagePreviewBrowserSessionOptions = {
68
+ readonly sessionId: string;
69
+ readonly url: string;
70
+ readonly user: UserInfo;
71
+ };
72
+
73
+ /**
74
+ * Shared in-memory browser-preview registry.
75
+ *
76
+ * The route streams are short-lived and tied to the current Node process, so a
77
+ * durable database row would create stale task-manager entries after restarts.
78
+ *
79
+ * @private internal constant of Agents Server page-preview streaming
80
+ */
81
+ const pagePreviewBrowserSessions = new Map<string, PagePreviewBrowserSession>();
82
+
83
+ /**
84
+ * Creates a normalized page-preview browser session id.
85
+ *
86
+ * @param requestedSessionId - Optional client-created session id.
87
+ * @returns Valid session id or `null` when the supplied value is invalid.
88
+ */
89
+ export function normalizePagePreviewBrowserSessionId(requestedSessionId: string | null): string | null {
90
+ if (!requestedSessionId) {
91
+ return null;
92
+ }
93
+
94
+ const normalizedSessionId = requestedSessionId.trim().toLowerCase();
95
+ return PAGE_PREVIEW_BROWSER_SESSION_ID_PATTERN.test(normalizedSessionId) ? normalizedSessionId : null;
96
+ }
97
+
98
+ /**
99
+ * Registers or replaces one active browser preview session.
100
+ *
101
+ * @param options - Session metadata.
102
+ * @returns Registered session snapshot.
103
+ */
104
+ export function registerPagePreviewBrowserSession(
105
+ options: RegisterPagePreviewBrowserSessionOptions,
106
+ ): PagePreviewBrowserSession {
107
+ const now = new Date().toISOString();
108
+ const previousSession = pagePreviewBrowserSessions.get(options.sessionId);
109
+ if (previousSession?.page) {
110
+ void previousSession.page.close().catch(() => undefined);
111
+ }
112
+
113
+ const session: PagePreviewBrowserSession = {
114
+ id: options.sessionId,
115
+ url: options.url,
116
+ userId: options.user.id ?? 0,
117
+ username: options.user.username,
118
+ createdAt: now,
119
+ startedAt: now,
120
+ updatedAt: now,
121
+ lastFrameAt: null,
122
+ processId: typeof process.pid === 'number' ? process.pid : null,
123
+ page: null,
124
+ viewport: null,
125
+ };
126
+
127
+ pagePreviewBrowserSessions.set(options.sessionId, session);
128
+ return session;
129
+ }
130
+
131
+ /**
132
+ * Attaches the Playwright page used by one live browser preview.
133
+ *
134
+ * @param sessionId - Active session id.
135
+ * @param page - Playwright page bound to the stream.
136
+ * @param viewport - Viewport used by the stream.
137
+ */
138
+ export function attachPagePreviewBrowserSessionPage(
139
+ sessionId: string,
140
+ page: Page,
141
+ viewport: PagePreviewBrowserViewport,
142
+ ): void {
143
+ const session = pagePreviewBrowserSessions.get(sessionId);
144
+ if (!session) {
145
+ return;
146
+ }
147
+
148
+ session.page = page;
149
+ session.viewport = viewport;
150
+ session.updatedAt = new Date().toISOString();
151
+ }
152
+
153
+ /**
154
+ * Marks that one stream frame has been delivered.
155
+ *
156
+ * @param sessionId - Active session id.
157
+ */
158
+ export function markPagePreviewBrowserSessionFrame(sessionId: string): void {
159
+ const session = pagePreviewBrowserSessions.get(sessionId);
160
+ if (!session) {
161
+ return;
162
+ }
163
+
164
+ const now = new Date().toISOString();
165
+ session.lastFrameAt = now;
166
+ session.updatedAt = now;
167
+ }
168
+
169
+ /**
170
+ * Removes one browser preview session from the active registry.
171
+ *
172
+ * @param sessionId - Active session id.
173
+ */
174
+ export function finishPagePreviewBrowserSession(sessionId: string): void {
175
+ pagePreviewBrowserSessions.delete(sessionId);
176
+ }
177
+
178
+ /**
179
+ * Returns the active browser preview session when owned by the current user.
180
+ *
181
+ * @param sessionId - Browser preview session id.
182
+ * @param user - Current authenticated user.
183
+ * @returns Session or `null` when missing or owned by a different user.
184
+ */
185
+ export function findUserPagePreviewBrowserSession(
186
+ sessionId: string,
187
+ user: UserInfo,
188
+ ): PagePreviewBrowserSession | null {
189
+ const session = pagePreviewBrowserSessions.get(sessionId);
190
+ if (!session) {
191
+ return null;
192
+ }
193
+
194
+ if ((user.id ?? 0) !== session.userId || user.username !== session.username) {
195
+ return null;
196
+ }
197
+
198
+ return session;
199
+ }
200
+
201
+ /**
202
+ * Lists active browser preview sessions as admin task-manager rows.
203
+ *
204
+ * @returns Task-manager rows for streams currently attached to this process.
205
+ */
206
+ export function listPagePreviewBrowserAdminTasks(): Array<AdminChatTaskRecord> {
207
+ return Array.from(pagePreviewBrowserSessions.values()).map((session) => ({
208
+ id: session.id,
209
+ kind: 'BROWSER_PREVIEW',
210
+ status: 'RUNNING',
211
+ createdAt: session.createdAt,
212
+ queuedAt: session.createdAt,
213
+ startedAt: session.startedAt,
214
+ updatedAt: session.updatedAt,
215
+ finishedAt: null,
216
+ cancelRequestedAt: null,
217
+ pausedAt: null,
218
+ lastHeartbeatAt: session.lastFrameAt,
219
+ leaseExpiresAt: null,
220
+ recurrenceIntervalMs: null,
221
+ priority: null,
222
+ attemptCount: 1,
223
+ retryCount: 0,
224
+ lastErrorSummary: null,
225
+ lastErrorDetails: session.url,
226
+ userId: session.userId,
227
+ username: session.username,
228
+ agentPermanentId: PAGE_PREVIEW_BROWSER_SESSION_ID_PREFIX,
229
+ agentName: PAGE_PREVIEW_BROWSER_TASK_AGENT_NAME,
230
+ chatId: session.url,
231
+ workerId: session.processId === null ? null : String(session.processId),
232
+ queueName: PAGE_PREVIEW_BROWSER_TASK_QUEUE_NAME,
233
+ }));
234
+ }
@@ -1042,6 +1042,18 @@ function resolveVpsSelfUpdateStateDirectory(): string {
1042
1042
  return resolve(dirname(resolveVpsEnvironmentFilePath()), '.promptbook', 'self-update');
1043
1043
  }
1044
1044
 
1045
+ /**
1046
+ * Reads a lightweight snapshot of the currently persisted standalone VPS self-update job.
1047
+ *
1048
+ * Reads only the persisted status file and its log tail — no git access, no remote fetching —
1049
+ * so it is safe to call from frequent polling loops such as the admin task manager.
1050
+ *
1051
+ * @returns Parsed job snapshot (status `idle` when no job has ever been persisted).
1052
+ */
1053
+ export async function readVpsSelfUpdateJobSnapshot(): Promise<VpsSelfUpdateJobSnapshot> {
1054
+ return readPersistedVpsSelfUpdateJob();
1055
+ }
1056
+
1045
1057
  /**
1046
1058
  * Reads one persisted update-job snapshot from disk.
1047
1059
  *
package/esm/index.es.js CHANGED
@@ -59,7 +59,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
59
59
  * @generated
60
60
  * @see https://github.com/webgptorg/promptbook
61
61
  */
62
- const PROMPTBOOK_ENGINE_VERSION = '0.113.0-0';
62
+ const PROMPTBOOK_ENGINE_VERSION = '0.113.0-2';
63
63
  /**
64
64
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
65
65
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -30182,9 +30182,10 @@ function buildAgentMessagePrompt(messageRelativePath, agentSystemMessage) {
30182
30182
 
30183
30183
  [Up to 50,000 CZK](?message=We are posting an order up to 50,000 CZK)
30184
30184
  [Up to 100,000 CZK](?message=We are posting an order up to 100,000 CZK)
30185
- [Over 100,000 CZK](?message=We are posting an order over 100,000 CZK)
30185
+ [Over 100,000 CZK](?messageDraft=We are posting an order over 100,000 CZK)
30186
30186
  \`\`\`
30187
30187
 
30188
+ - You can use \`message\` for message that will be sent immediately after clicking the button, or \`messageDraft\` for message that will be prefilled in the input field for editing before sending.
30188
30189
 
30189
30190
  ## This is how you should behave
30190
30191
 
@@ -54635,6 +54636,12 @@ const DEPRECATED_TOP_LEVEL_COMMAND_MESSAGES = {
54635
54636
  'start-agents-server': 'Use `ptbk agents-server start` instead.',
54636
54637
  'start-pipelines-server': OLD_PIPELINE_SYSTEM_DEPRECATION_MESSAGE,
54637
54638
  };
54639
+ /**
54640
+ * Raw top-level CLI arguments that print the Promptbook version.
54641
+ *
54642
+ * @private internal constant of `promptbookCli`
54643
+ */
54644
+ const VERSION_OPTION_ARGUMENTS = new Set(['-v', '--version']);
54638
54645
  /**
54639
54646
  * Runs CLI utilities of Promptbook package
54640
54647
  *
@@ -54649,8 +54656,13 @@ async function promptbookCli() {
54649
54656
 
54650
54657
  `));
54651
54658
  }
54652
- const cliArguments = process.argv.slice(2);
54653
- const isVerbose = cliArguments.some((arg) => arg === '--verbose' || arg === '-v');
54659
+ const commandLineArguments = process.argv.slice(2);
54660
+ const isVersionRequested = isTopLevelVersionRequested(commandLineArguments);
54661
+ if (isVersionRequested) {
54662
+ console.info(PROMPTBOOK_ENGINE_VERSION);
54663
+ return process.exit(0);
54664
+ }
54665
+ const isVerbose = commandLineArguments.some((argument) => argument === '--verbose' || argument === '-v');
54654
54666
  // <- TODO: Can be this be done with commander before the commander commands are initialized?
54655
54667
  if (isVerbose) {
54656
54668
  console.info(colors.gray(`Promptbook CLI version ${PROMPTBOOK_ENGINE_VERSION} in ${__filename.split('\\').join('/')}`));
@@ -54679,12 +54691,21 @@ async function promptbookCli() {
54679
54691
  $deprecateTopLevelCommands(program);
54680
54692
  // TODO: [🧠] Should it be here or not> $addGlobalOptionsToCommand(program);
54681
54693
  program.commands.forEach($addGlobalOptionsToCommand);
54682
- if (cliArguments.length === 0) {
54694
+ if (commandLineArguments.length === 0) {
54683
54695
  program.outputHelp();
54684
54696
  return process.exit(0);
54685
54697
  }
54686
54698
  program.parse(process.argv);
54687
54699
  }
54700
+ /**
54701
+ * Checks whether the invocation asks for the root Promptbook CLI version.
54702
+ *
54703
+ * @private internal utility of `promptbookCli`
54704
+ */
54705
+ function isTopLevelVersionRequested(commandLineArguments) {
54706
+ const firstCommandLineArgument = commandLineArguments[0];
54707
+ return firstCommandLineArgument !== undefined && VERSION_OPTION_ARGUMENTS.has(firstCommandLineArgument);
54708
+ }
54688
54709
  /**
54689
54710
  * Adds one deprecation notice to each configured top-level legacy command.
54690
54711
  */