@sentry/junior 0.311.0 → 0.313.0

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 (120) hide show
  1. package/dist/{adapter-B1wujchl.js → adapter-CYAvJzZS.js} +1 -1
  2. package/dist/{adapter-context-G2M0y6rP.js → adapter-context-CVsHoVSf.js} +2 -2
  3. package/dist/{admin-DCiBhUT1.js → admin-Cyhb4TwZ.js} +1 -1
  4. package/dist/{agent-runner-BVHPUIc8.js → agent-runner-B5y9MsT-.js} +3487 -3493
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.d.ts +2 -2
  8. package/dist/api.js +294 -311
  9. package/dist/{app-Cw5Vy6H6.d.ts → app-DA8-hCMj.d.ts} +2 -9
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +336 -604
  12. package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-iZXadLV3.js} +60 -85
  13. package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-kkE3hvCX.js} +1 -1
  14. package/dist/channel-access-mt7K6dPh.js +221 -0
  15. package/dist/cli/chat.js +18 -19
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +0 -1
  18. package/dist/cli/main.js +3 -7
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/run.d.ts +1 -2
  21. package/dist/cli/run.js +1 -2
  22. package/dist/cli/snapshot-create.js +5 -5
  23. package/dist/cli/upgrade.d.ts +1 -1
  24. package/dist/cli/upgrade.js +3 -3
  25. package/dist/{config-BrXDQefC.js → config-CWbwKj0j.js} +59 -27
  26. package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-CxyFzdlF.js} +7 -8
  27. package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-BEXLD3Me.js} +86 -21
  28. package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-BrMiDN61.js} +1 -1
  29. package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-B35eu0uz.js} +78 -56
  30. package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-DWTOEQrm.js} +15 -15
  31. package/dist/{projection-Cns7XwWa.js → credentialed-Dyv8b-lu.js} +16306 -20732
  32. package/dist/{db-7ETESH44.d.ts → db-DYGcXYl3.d.ts} +11 -6
  33. package/dist/{db-DTxzH7u5.js → db-PwSRzWWn.js} +181 -100
  34. package/dist/{executor-DqTiYj9S.js → executor-CgWyWfYz.js} +117 -99
  35. package/dist/{html-B9Sl4Axb.js → html-DidUcRhI.js} +6 -6
  36. package/dist/ingest-B0AggUEC.js +7931 -0
  37. package/dist/{install-Sg4ePfLl.js → install-2urLLXNt.js} +2 -2
  38. package/dist/instrumentation.js +3 -3
  39. package/dist/{lineage-BHAMpNKr.js → lineage-BXplQAVH.js} +2 -2
  40. package/dist/{stop-CYsfc0Ed.js → list-DyIyReSV.js} +709 -475
  41. package/dist/{logging-FjclQsXu.js → logging-DNt-qOIO.js} +1 -1
  42. package/dist/{schedule-BLJ476XQ.js → media-B0pZJ0bG.js} +1058 -11
  43. package/dist/{message-CJ7_RL50.js → message-Z5YKC-Af.js} +35 -28
  44. package/dist/{model-input-CMLh4Cwq.js → model-input-BhPJYdSV.js} +3 -3
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +4 -3
  47. package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-ByvDdcdY.js} +2 -2
  48. package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-D-kK0yoN.js} +1 -1
  49. package/dist/{registry-BPwuOP2O.js → registry-POH4bZC4.js} +1 -1
  50. package/dist/reporting-window-C4dbzDiR.js +124 -0
  51. package/dist/request-deadline-BUiRYQYj.js +24 -0
  52. package/dist/{resolve-BK29bBry.js → resolve-CWtBNSKP.js} +3 -3
  53. package/dist/{runner-BcAE-cJm.js → runner-CsZ_VRxp.js} +14 -16
  54. package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
  55. package/dist/{schema-DYcJeV7d.d.ts → schema-DBf18QPS.d.ts} +2773 -3630
  56. package/dist/{schema-BLgSZXcL.js → schema-DojR2uCL.js} +106 -121
  57. package/dist/{service-account-iJoCtkHR.js → service-account-CDYb9hfX.js} +3 -3
  58. package/dist/{service-account-gN0zqf0S.js → service-account-o15pZWcJ.js} +5 -5
  59. package/dist/{skills-BoZ80epJ.js → skills-B0jP4whm.js} +2 -2
  60. package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-D26t9kBC.js} +9 -9
  61. package/dist/{spawn-Dk92r7mX.js → spawn-BjljgExZ.js} +14 -32
  62. package/dist/start-conversation-DbVujrwO.js +755 -0
  63. package/dist/{state-DH3Cmgp3.js → state-BTawTCme.js} +4 -4
  64. package/dist/statuses-BKwqCPhj.js +69 -0
  65. package/dist/store-CjXrp-Up.js +492 -0
  66. package/dist/task-queue-Cwlatjz3.js +90 -0
  67. package/dist/task-runner--Ke8KSMf.js +1432 -0
  68. package/dist/{thread-context-BW2BsQbH.js → thread-context-B8exINEe.js} +6 -7
  69. package/dist/turn-membership-DTR3SaKD.js +5859 -0
  70. package/dist/{validation-DrJd0nnq.js → validation-Ce0qbMlT.js} +1 -1
  71. package/dist/{task-queue-C_zldF5J.js → vercel-queue-q4z8w5QO.js} +93 -172
  72. package/dist/{version-CNKZ8owc.js → version-DFh4n9nr.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{warmup-BWdHew2H.js → warmup-D5hzqTcp.js} +4853 -13605
  75. package/dist/web-message-id-C6P83ans.js +10 -0
  76. package/dist/{worker-t9qpu_Zx.js → worker-CDg9Lbpg.js} +20 -7
  77. package/migrations/0143_todos.sql +14 -0
  78. package/migrations/0144_inbox_items.sql +32 -0
  79. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  80. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  81. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  82. package/migrations/0148_authorization_request_index.sql +1 -0
  83. package/migrations/0149_conversation_metadata.sql +10 -0
  84. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  85. package/migrations/0151_conversation_search_index.sql +1 -0
  86. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  87. package/migrations/0153_artifact_expiry.sql +1 -0
  88. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  89. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  90. package/migrations/0156_conversation_kind_lead.sql +6 -0
  91. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  92. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  93. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  94. package/migrations/meta/0143_snapshot.json +6434 -0
  95. package/migrations/meta/0144_snapshot.json +6434 -0
  96. package/migrations/meta/0145_snapshot.json +6440 -0
  97. package/migrations/meta/0146_snapshot.json +6446 -0
  98. package/migrations/meta/0147_snapshot.json +6452 -0
  99. package/migrations/meta/0148_snapshot.json +6474 -0
  100. package/migrations/meta/0149_snapshot.json +6490 -0
  101. package/migrations/meta/0150_snapshot.json +6490 -0
  102. package/migrations/meta/0151_snapshot.json +6505 -0
  103. package/migrations/meta/0152_snapshot.json +6505 -0
  104. package/migrations/meta/0153_snapshot.json +6511 -0
  105. package/migrations/meta/0154_snapshot.json +6533 -0
  106. package/migrations/meta/0155_snapshot.json +6511 -0
  107. package/migrations/meta/0156_snapshot.json +6511 -0
  108. package/migrations/meta/0157_snapshot.json +6527 -0
  109. package/migrations/meta/0158_snapshot.json +6515 -0
  110. package/migrations/meta/0159_snapshot.json +6515 -0
  111. package/migrations/meta/_journal.json +120 -1
  112. package/package.json +6 -6
  113. package/skills/design-automation-skill/SKILL.md +108 -0
  114. package/dist/briefs-BDjnug6Y.js +0 -395
  115. package/dist/conversation-ca__NDQW.js +0 -1063
  116. package/dist/prompt-CDqcsDYC.js +0 -910
  117. package/dist/store-DmmMIrQi.js +0 -335
  118. package/dist/task-runner-C7oCJQIx.js +0 -294
  119. package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
  120. package/dist/web-message-id-Ch5dPq-a.js +0 -306
@@ -1,261 +0,0 @@
1
- import { Co as getDispatchRecord, S as persistConversationMessages, _l as JUNIOR_THREAD_STATE_TTL_MS, bo as getDispatchConversationId, xl as createDurableLocationConfigurationService } from "./projection-Cns7XwWa.js";
2
- import { Y as toOptionalString } from "./logging-FjclQsXu.js";
3
- import { o as getDb } from "./db-DTxzH7u5.js";
4
- import { i as getStateAdapter } from "./adapter-B1wujchl.js";
5
- import * as z from "zod";
6
- // src/chat/state/conversation.ts
7
- function defaultConversationState() {
8
- return {
9
- schemaVersion: 1,
10
- messages: [],
11
- processing: {},
12
- vision: { byFileId: {} }
13
- };
14
- }
15
- const nonEmptyString = z.string().refine((value) => value.trim().length > 0);
16
- const optionalString = nonEmptyString.optional().catch(void 0);
17
- const optionalNumber = z.number().optional().catch(void 0);
18
- const pendingAuthCommonFields = {
19
- provider: nonEmptyString,
20
- actorId: nonEmptyString,
21
- sessionId: nonEmptyString,
22
- linkSentAtMs: z.number(),
23
- scope: optionalString
24
- };
25
- const pendingAuthSchema = z.discriminatedUnion("kind", [z.object({
26
- ...pendingAuthCommonFields,
27
- kind: z.literal("mcp"),
28
- authSessionId: nonEmptyString
29
- }), z.object({
30
- ...pendingAuthCommonFields,
31
- kind: z.literal("plugin")
32
- })]);
33
- const visionSummarySchema = z.object({
34
- summary: nonEmptyString,
35
- analyzedAtMs: z.number().refine((value) => value !== 0)
36
- });
37
- const storedThreadStateSchema = z.object({ conversation: z.object({
38
- processing: z.object({
39
- activeTurnId: optionalString,
40
- lastCompletedAtMs: optionalNumber,
41
- pendingAuth: pendingAuthSchema.optional().catch(void 0)
42
- }).catch({}),
43
- vision: z.object({
44
- backfillCompletedAtMs: optionalNumber,
45
- byFileId: z.record(z.string(), z.unknown()).catch({})
46
- }).catch({ byFileId: {} })
47
- }).catch({
48
- processing: {},
49
- vision: { byFileId: {} }
50
- }) });
51
- /** Safely coerce an unknown persisted value into a ThreadConversationState. */
52
- function coerceThreadConversationState(value) {
53
- const parsed = storedThreadStateSchema.safeParse(value);
54
- if (!parsed.success) return defaultConversationState();
55
- const { processing, vision } = parsed.data.conversation;
56
- const byFileId = {};
57
- for (const [fileId, entry] of Object.entries(vision.byFileId)) {
58
- if (fileId.trim().length === 0) continue;
59
- const summary = visionSummarySchema.safeParse(entry);
60
- if (!summary.success) continue;
61
- byFileId[fileId] = summary.data;
62
- }
63
- return {
64
- schemaVersion: 1,
65
- messages: [],
66
- processing,
67
- vision: {
68
- backfillCompletedAtMs: vision.backfillCompletedAtMs,
69
- byFileId
70
- }
71
- };
72
- }
73
- /**
74
- * Wrap active conversation control into the thread scratch envelope.
75
- *
76
- * Visible history lives in SQL. Image summaries use a separate disposable
77
- * cache, so thread scratch does not retain them.
78
- */
79
- function buildConversationStatePatch(conversation) {
80
- return { conversation: {
81
- schemaVersion: 1,
82
- processing: { ...conversation.processing }
83
- } };
84
- }
85
- // src/chat/runtime/thread-state.ts
86
- function threadStateKey(threadId) {
87
- return `thread-state:${threadId}`;
88
- }
89
- function channelStateKey(channelId) {
90
- return `channel-state:${channelId}`;
91
- }
92
- function buildThreadStatePayload(patch) {
93
- const payload = {};
94
- if (patch.conversation) Object.assign(payload, buildConversationStatePatch(patch.conversation));
95
- if (patch.sandboxRef !== void 0) {
96
- payload["app_sandbox_id"] = patch.sandboxRef?.id ?? "";
97
- payload["app_sandbox_dependency_profile_hash"] = patch.sandboxRef?.profileHash ?? "";
98
- payload["app_sandbox_workspace_id"] = patch.sandboxRef?.workspaceId ?? "";
99
- }
100
- return payload;
101
- }
102
- /**
103
- * Merge a payload into thread scratch with Junior's TTL.
104
- *
105
- * Chat SDK state writes hardcode a 30-day TTL. This boundary owns Junior's
106
- * shorter retention policy for the same scratch keys.
107
- */
108
- async function mergePersistedState(key, payload) {
109
- if (Object.keys(payload).length === 0) return;
110
- const stateAdapter = getStateAdapter();
111
- await stateAdapter.connect();
112
- const existing = await stateAdapter.get(key) ?? {};
113
- await stateAdapter.set(key, {
114
- ...existing,
115
- ...payload
116
- }, JUNIOR_THREAD_STATE_TTL_MS);
117
- }
118
- /** Extract persisted sandbox metadata from thread state payload. */
119
- function getPersistedSandboxState(state) {
120
- const id = toOptionalString(state["app_sandbox_id"]);
121
- if (!id) return;
122
- const profileHash = toOptionalString(state["app_sandbox_dependency_profile_hash"]);
123
- const workspaceId = toOptionalString(state["app_sandbox_workspace_id"]);
124
- return {
125
- id,
126
- ...profileHash ? { profileHash } : void 0,
127
- ...workspaceId ? { workspaceId } : void 0
128
- };
129
- }
130
- /** Persist only the Redis-backed runtime scratch in a thread-state patch. */
131
- async function persistThreadRuntimeState(conversationId, patch) {
132
- await mergePersistedState(threadStateKey(conversationId), buildThreadStatePayload(patch));
133
- }
134
- /** Load the persisted state payload for a thread without requiring a Chat singleton. */
135
- async function getPersistedThreadState(threadId) {
136
- const stateAdapter = getStateAdapter();
137
- await stateAdapter.connect();
138
- return await stateAdapter.get(threadStateKey(threadId)) ?? {};
139
- }
140
- /** Persist a thread-state patch by thread id without constructing a Chat thread. */
141
- async function persistThreadStateById(threadId, patch) {
142
- if (patch.conversation) await persistConversationMessages({
143
- conversation: patch.conversation,
144
- conversationId: threadId
145
- });
146
- await mergePersistedState(threadStateKey(threadId), buildThreadStatePayload(patch));
147
- }
148
- /** Load legacy Redis-backed channel state during the SQL cutover. */
149
- async function getLegacyChannelState(channelId) {
150
- const stateAdapter = getStateAdapter();
151
- await stateAdapter.connect();
152
- return await stateAdapter.get(channelStateKey(channelId)) ?? {};
153
- }
154
- /**
155
- * Resolve durable location configuration.
156
- *
157
- * Slack still reads the old channel-id Redis bag once during cutover.
158
- */
159
- function getLocationConfigurationService(destination) {
160
- if (destination.platform !== "slack") throw new Error("Location configuration requires a Slack Location");
161
- return createDurableLocationConfigurationService({
162
- destination,
163
- db: getDb(),
164
- loadLegacy: async () => await getLegacyChannelState(destination.channelId)
165
- });
166
- }
167
- // src/chat/services/turn-session-routing.ts
168
- async function loadConversationChain(conversationId, conversationStore) {
169
- const chain = [];
170
- const seen = /* @__PURE__ */ new Set();
171
- let cursor = conversationId;
172
- while (cursor && !seen.has(cursor)) {
173
- seen.add(cursor);
174
- const conversation = await conversationStore.get({ conversationId: cursor });
175
- if (!conversation) break;
176
- chain.push(conversation);
177
- cursor = conversation.parentConversationId;
178
- }
179
- return chain;
180
- }
181
- /**
182
- * Normalize a stored Slack session source against the conversation destination.
183
- *
184
- * Does not create channel or thread values from the conversation id.
185
- */
186
- function slackSourceForDestination(args) {
187
- if (args.source?.kind !== "slack" || args.source.channelId !== args.destination.channelId) return;
188
- const threadTs = args.source.threadTs?.trim();
189
- return {
190
- kind: "slack",
191
- visibility: args.source.visibility ?? "public",
192
- teamId: args.source.teamId?.trim() || args.destination.teamId,
193
- channelId: args.source.channelId,
194
- ...threadTs ? { threadTs } : void 0
195
- };
196
- }
197
- /**
198
- * Resolve the Conversation Location, Destination, and session Source.
199
- *
200
- * Reads parent Conversations when this Conversation has no Destination.
201
- */
202
- async function resolveConversationRouting(args) {
203
- const conversationStore = args.conversationStore ?? (await import("./db-DTxzH7u5.js").then((n) => n.n)).getConversationStore();
204
- const chain = await loadConversationChain(args.conversationId, conversationStore);
205
- let destination;
206
- let source;
207
- let location;
208
- for (const conversation of chain) {
209
- destination ??= conversation.destination;
210
- source ??= conversation.sessionSource;
211
- location ??= conversation.location;
212
- if (destination && source) break;
213
- }
214
- if (!destination) return;
215
- if (destination.platform === "slack") {
216
- const slackSource = slackSourceForDestination({
217
- destination,
218
- source
219
- });
220
- return {
221
- destination,
222
- ...location ? { location } : void 0,
223
- ...slackSource ? { source: slackSource } : void 0
224
- };
225
- }
226
- return {
227
- destination,
228
- ...location ? { location } : void 0,
229
- ...source ? { source } : void 0
230
- };
231
- }
232
- /** Require the Conversation Destination and Source from SQL. */
233
- async function resolveTurnSessionRouting(args) {
234
- const routing = await resolveConversationRouting(args);
235
- if (!routing?.destination || !routing.source) throw new Error(`Conversation ${args.conversationId} is missing durable routing metadata`);
236
- return {
237
- destination: routing.destination,
238
- ...routing.location ? { location: routing.location } : void 0,
239
- source: routing.source
240
- };
241
- }
242
- /**
243
- * Require the Destination and Source to resume a Turn.
244
- *
245
- * A dispatch Conversation stores the dispatch Source, which has no session
246
- * Source. Its dispatch record owns the Destination and Source.
247
- */
248
- async function resolveTurnResumeRouting(args) {
249
- if (!args.dispatchId) return await resolveTurnSessionRouting(args);
250
- const dispatch = await getDispatchRecord(args.dispatchId);
251
- if (!dispatch) throw new Error(`Dispatch record is missing for ${args.dispatchId}`);
252
- const dispatchConversationId = getDispatchConversationId(dispatch);
253
- if (dispatchConversationId !== args.conversationId) throw new Error(`Dispatch ${dispatch.id} belongs to ${dispatchConversationId}, not ${args.conversationId}`);
254
- const location = (await resolveConversationRouting(args))?.location;
255
- return {
256
- destination: dispatch.destination,
257
- ...location ? { location } : void 0,
258
- source: dispatch.source
259
- };
260
- }
261
- export { getPersistedThreadState as a, coerceThreadConversationState as c, getPersistedSandboxState as i, resolveTurnResumeRouting as n, persistThreadRuntimeState as o, getLocationConfigurationService as r, persistThreadStateById as s, resolveConversationRouting as t };
@@ -1,306 +0,0 @@
1
- import * as z from "zod";
2
- // src/api/reporting-window.ts
3
- /** Shared UTC day/hour/six-hour windows for dashboard activity series. */
4
- const HOUR_MS = 36e5;
5
- const SIX_HOUR_MS = 6 * HOUR_MS;
6
- const DAY_MS = 24 * HOUR_MS;
7
- /** Start of the UTC calendar day containing `valueMs`. */
8
- function startOfUtcDay(valueMs) {
9
- const date = new Date(valueMs);
10
- date.setUTCHours(0, 0, 0, 0);
11
- return date;
12
- }
13
- /** Start of the UTC hour containing `valueMs`. */
14
- function startOfUtcHour(valueMs) {
15
- const date = new Date(valueMs);
16
- date.setUTCMinutes(0, 0, 0);
17
- return date;
18
- }
19
- /** Start of the UTC 6-hour bucket containing `valueMs` (00/06/12/18). */
20
- function startOfUtcSixHour(valueMs) {
21
- const date = startOfUtcHour(valueMs);
22
- date.setUTCHours(Math.floor(date.getUTCHours() / 6) * 6, 0, 0, 0);
23
- return date;
24
- }
25
- /** UTC day key `YYYY-MM-DD`. */
26
- function utcDayKey(value) {
27
- return (typeof value === "number" ? new Date(value) : value).toISOString().slice(0, 10);
28
- }
29
- /** UTC hour key `YYYY-MM-DDTHH`. */
30
- function utcHourKey(value) {
31
- return (typeof value === "number" ? new Date(value) : value).toISOString().slice(0, 13);
32
- }
33
- /** UTC 6-hour bucket key `YYYY-MM-DDTHH` at 00/06/12/18. */
34
- function utcSixHourKey(value) {
35
- return utcHourKey(startOfUtcSixHour(typeof value === "number" ? value : value.getTime()));
36
- }
37
- /** Inclusive trailing UTC day window ending on today's UTC day. */
38
- function trailingUtcDayWindow(nowMs, dayCount) {
39
- const end = startOfUtcDay(nowMs);
40
- const start = new Date(end);
41
- start.setUTCDate(start.getUTCDate() - (dayCount - 1));
42
- return {
43
- end,
44
- start
45
- };
46
- }
47
- /** Inclusive trailing UTC hour window ending on the current UTC hour. */
48
- function trailingUtcHourWindow(nowMs, hourCount = 24) {
49
- const end = startOfUtcHour(nowMs);
50
- return {
51
- end,
52
- start: /* @__PURE__ */ new Date(end.getTime() - (hourCount - 1) * HOUR_MS)
53
- };
54
- }
55
- /** Inclusive trailing UTC 6-hour window ending on the current 6h bucket. */
56
- function trailingUtcSixHourWindow(nowMs, bucketCount = 28) {
57
- const end = startOfUtcSixHour(nowMs);
58
- return {
59
- end,
60
- start: /* @__PURE__ */ new Date(end.getTime() - (bucketCount - 1) * SIX_HOUR_MS)
61
- };
62
- }
63
- /** Fill a fixed UTC day window from a sparse map. */
64
- function fillUtcDays(args) {
65
- const { end, start } = trailingUtcDayWindow(args.nowMs, args.count);
66
- const items = [];
67
- for (const cursor = new Date(start); cursor.getTime() <= end.getTime(); cursor.setUTCDate(cursor.getUTCDate() + 1)) {
68
- const date = utcDayKey(cursor);
69
- items.push(args.rows.get(date) ?? args.empty(date));
70
- }
71
- return items;
72
- }
73
- /** Fill a fixed UTC hour window from a sparse map. */
74
- function fillUtcHours(args) {
75
- const hourCount = args.count ?? 24;
76
- const { end, start } = trailingUtcHourWindow(args.nowMs, hourCount);
77
- const items = [];
78
- for (const cursor = new Date(start); cursor.getTime() <= end.getTime(); cursor.setTime(cursor.getTime() + HOUR_MS)) {
79
- const date = utcHourKey(cursor);
80
- items.push(args.rows.get(date) ?? args.empty(date));
81
- }
82
- return items;
83
- }
84
- /** Fill a fixed UTC 6-hour window from a map of known rows. */
85
- function fillUtcSixHours(args) {
86
- const bucketCount = args.count ?? 28;
87
- const { end, start } = trailingUtcSixHourWindow(args.nowMs, bucketCount);
88
- const items = [];
89
- for (const cursor = new Date(start); cursor.getTime() <= end.getTime(); cursor.setTime(cursor.getTime() + SIX_HOUR_MS)) {
90
- const date = utcSixHourKey(cursor);
91
- items.push(args.rows.get(date) ?? args.empty(date));
92
- }
93
- return items;
94
- }
95
- /**
96
- * Sum hour rows into trailing 6-hour buckets.
97
- * Adds number fields. Keeps other fields from the first row in the bucket.
98
- * Sets `date` to the 6-hour bucket key.
99
- */
100
- function sumUtcHoursIntoSixHours(args) {
101
- const bucketCount = args.count ?? 28;
102
- const bySix = /* @__PURE__ */ new Map();
103
- for (const hour of args.hours) {
104
- const key = utcSixHourKey(Date.parse(`${hour.date}:00:00.000Z`));
105
- const next = {
106
- ...bySix.get(key) ?? args.empty(key),
107
- date: key
108
- };
109
- for (const [field, value] of Object.entries(hour)) {
110
- if (field === "date") continue;
111
- if (typeof value === "number") {
112
- const prior = next[field];
113
- next[field] = (typeof prior === "number" ? prior : 0) + value;
114
- }
115
- }
116
- bySix.set(key, next);
117
- }
118
- return fillUtcSixHours({
119
- count: bucketCount,
120
- empty: args.empty,
121
- nowMs: args.nowMs,
122
- rows: bySix
123
- });
124
- }
125
- // src/api/schema/common.ts
126
- /** Stable error body returned by Junior-owned REST endpoints. */
127
- const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
128
- /**
129
- * Carries a content token in both directions. A custom header, not `ETag` /
130
- * `If-None-Match`: the Vercel CDN removes `If-None-Match` before it calls the
131
- * function, with every `Cache-Control` value, and no setting stops this. The
132
- * CDN then answers a match with a 304 only after the function built the full
133
- * response, so the read is not saved and the 304 does not show in app
134
- * telemetry. A probe deployment confirmed this for `private, no-cache`,
135
- * `no-cache`, `private, no-store`, `private, max-age=0, must-revalidate`, and
136
- * no header. See
137
- * https://vercel.com/docs/manage-cdn-usage#optimizing-fast-origin-transfer.
138
- * A read that sends the token of the copy it holds gets an empty 304 while
139
- * the content is unchanged.
140
- */
141
- const CONTENT_VERSION_HEADER = "x-junior-content-version";
142
- // src/chat/plan/types.ts
143
- /** Statuses of a Plan item. `done` and `cancelled` close it. */
144
- const PLAN_ITEM_STATUSES = [
145
- "pending",
146
- "in_progress",
147
- "blocked",
148
- "done",
149
- "cancelled"
150
- ];
151
- /** Whether an item with this status is still work to do. */
152
- function isOpenPlanItemStatus(status) {
153
- return status !== "done" && status !== "cancelled";
154
- }
155
- /** Model-facing tool that changes the plan. */
156
- const UPDATE_PLAN_TOOL_NAME = "updatePlan";
157
- /** Assignee text for the plan's own agent, in tool results and blocks. */
158
- const SELF_PLAN_ASSIGNEE = "self";
159
- // src/api/schema/user-customization.ts
160
- /** Longest customization text one user can save. */
161
- const USER_CUSTOMIZATION_MAX_CHARS = 1e3;
162
- /** Saved customization text. An empty string means none. */
163
- const userCustomizationTextSchema = z.string().trim().max(USER_CUSTOMIZATION_MAX_CHARS);
164
- /** Request and response body for the viewer's customization. */
165
- const userCustomizationSchema = z.object({ customization: userCustomizationTextSchema }).strict();
166
- // src/chat/attachments/media.ts
167
- const INPUT_IMAGE_TYPES = [
168
- "image/png",
169
- "image/jpeg",
170
- "image/gif",
171
- "image/webp"
172
- ];
173
- /** Video types that browsers play in a `<video>` element. */
174
- const INLINE_VIDEO_TYPES = ["video/mp4", "video/webm"];
175
- /** Leading bytes of each accepted image type. `null` matches any byte. */
176
- const IMAGE_SIGNATURES = [
177
- {
178
- mediaType: "image/png",
179
- bytes: [
180
- 137,
181
- 80,
182
- 78,
183
- 71,
184
- 13,
185
- 10,
186
- 26,
187
- 10
188
- ]
189
- },
190
- {
191
- mediaType: "image/jpeg",
192
- bytes: [
193
- 255,
194
- 216,
195
- 255
196
- ]
197
- },
198
- {
199
- mediaType: "image/gif",
200
- bytes: [
201
- 71,
202
- 73,
203
- 70,
204
- 56,
205
- 55,
206
- 97
207
- ]
208
- },
209
- {
210
- mediaType: "image/gif",
211
- bytes: [
212
- 71,
213
- 73,
214
- 70,
215
- 56,
216
- 57,
217
- 97
218
- ]
219
- },
220
- {
221
- mediaType: "image/webp",
222
- bytes: [
223
- 82,
224
- 73,
225
- 70,
226
- 70,
227
- null,
228
- null,
229
- null,
230
- null,
231
- 87,
232
- 69,
233
- 66,
234
- 80
235
- ]
236
- }
237
- ];
238
- /**
239
- * Detect an accepted image type from file bytes. Use this instead of a file
240
- * name or declared content type, which can be wrong.
241
- */
242
- function detectImageMediaType(data) {
243
- return IMAGE_SIGNATURES.find(({ bytes }) => data.length >= bytes.length && bytes.every((byte, index) => byte === null || data[index] === byte))?.mediaType;
244
- }
245
- /** Report whether a media type is a raster image accepted by vision models. */
246
- function isVisionImageMediaType(mediaType) {
247
- const normalized = mediaType.split(";", 1)[0]?.trim().toLowerCase();
248
- return normalized ? INPUT_IMAGE_TYPES.some((type) => type === normalized) : false;
249
- }
250
- // src/chat/agent-invocations/result-event-type.ts
251
- /** Event namespace of the messages between a parent and its child agents. */
252
- const AGENT_INVOCATION_EVENT_NAMESPACE = "junior";
253
- const AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
254
- /** Build the Event type of the parent message for one agent invocation result. */
255
- function agentInvocationResultEventType(status) {
256
- return `${AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX}${status}`;
257
- }
258
- /** True when an Event type names an agent invocation result. */
259
- function isAgentInvocationResultEventType(eventType) {
260
- return eventType.startsWith(AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX);
261
- }
262
- /** Event type of the `reply` that ends a child agent's Turn. */
263
- const AGENT_REPLY_EVENT_TYPE = "agent.reply";
264
- /** Event type of a message that a child agent sends to its parent. */
265
- const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
266
- /**
267
- * Event type of a parent agent task or message to a child that no agent
268
- * invocation names.
269
- */
270
- const AGENT_PARENT_MESSAGE_EVENT_TYPE = "agent.parent_message";
271
- // src/chat/agent-invocations/statuses.ts
272
- const AGENT_INVOCATION_STATUSES = [
273
- "pending",
274
- "running",
275
- "paused",
276
- "blocked",
277
- "completed",
278
- "failed",
279
- "stopped"
280
- ];
281
- const AGENT_INVOCATION_MAILBOX_STATUSES = ["pending", "appended"];
282
- /**
283
- * Parent mailbox append state. Only terminal invocations have a value.
284
- * `replaced` means the child still had open work, so a later agent invocation
285
- * on the same child sends the result instead. `skipped` means a stop ended
286
- * the work, so the result is never used. `steered` means the agent invocation
287
- * that was running read the input as a steering message, so its result covers
288
- * this one.
289
- */
290
- const AGENT_INVOCATION_PARENT_MAILBOX_STATUSES = [
291
- "pending",
292
- "appended",
293
- "replaced",
294
- "skipped",
295
- "steered"
296
- ];
297
- // src/chat/conversations/web-message-id.ts
298
- /**
299
- * Build the retry-stable Message id shared by web ingress and browser sends.
300
- * Keep the existing hash and prefix so retries still address stored Messages.
301
- */
302
- async function webMessageId(args) {
303
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${args.conversationId}\u0000${args.idempotencyKey}`));
304
- return `api-msg:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 24)}`;
305
- }
306
- export { sumUtcHoursIntoSixHours as A, apiErrorSchema as C, fillUtcHours as D, fillUtcDays as E, trailingUtcHourWindow as M, trailingUtcSixHourWindow as N, fillUtcSixHours as O, utcHourKey as P, CONTENT_VERSION_HEADER as S, HOUR_MS as T, userCustomizationTextSchema as _, AGENT_INVOCATION_EVENT_NAMESPACE as a, UPDATE_PLAN_TOOL_NAME as b, AGENT_REPLY_EVENT_TYPE as c, INLINE_VIDEO_TYPES as d, INPUT_IMAGE_TYPES as f, userCustomizationSchema as g, USER_CUSTOMIZATION_MAX_CHARS as h, AGENT_INVOCATION_STATUSES as i, trailingUtcDayWindow as j, startOfUtcHour as k, agentInvocationResultEventType as l, isVisionImageMediaType as m, AGENT_INVOCATION_MAILBOX_STATUSES as n, AGENT_MESSAGE_EVENT_TYPE as o, detectImageMediaType as p, AGENT_INVOCATION_PARENT_MAILBOX_STATUSES as r, AGENT_PARENT_MESSAGE_EVENT_TYPE as s, webMessageId as t, isAgentInvocationResultEventType as u, PLAN_ITEM_STATUSES as v, DAY_MS as w, isOpenPlanItemStatus as x, SELF_PLAN_ASSIGNEE as y };