@sentry/junior 0.310.0 → 0.312.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 (157) hide show
  1. package/dist/{adapter-context-BhKpjpGD.js → adapter-context-BRjEWRy1.js} +2 -2
  2. package/dist/adapter-iIq7ihf7.js +259 -0
  3. package/dist/{admin-tgZEZAk2.js → admin-DhInw5K9.js} +1 -2
  4. package/dist/{agent-runner-D9cvNlQl.js → agent-runner-C9iDurwX.js} +6507 -7721
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -6
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1625 -535
  9. package/dist/{app-B_7Wn0en.d.ts → app-DRFrC8Mw.d.ts} +14 -10
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +454 -994
  12. package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-DrKi7w3d.js} +10 -85
  13. package/dist/callback-mFlTUWWx.js +75 -0
  14. package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-D7xapBAX.js} +1 -1
  15. package/dist/channel-access-CJGfNTdn.js +221 -0
  16. package/dist/child-message-DcsritGf.js +179 -0
  17. package/dist/cli/chat.js +18 -19
  18. package/dist/cli/check.js +23 -29
  19. package/dist/cli/init.js +1 -7
  20. package/dist/cli/main.js +3 -7
  21. package/dist/cli/plugins.js +8 -7
  22. package/dist/cli/run.d.ts +1 -2
  23. package/dist/cli/run.js +1 -2
  24. package/dist/cli/snapshot-create.js +5 -5
  25. package/dist/cli/upgrade.d.ts +1 -1
  26. package/dist/cli/upgrade.js +3 -3
  27. package/dist/{config-Dkt2Le2b.js → config-kXB2Y5tl.js} +294 -28
  28. package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-O6pV5004.js} +7 -7
  29. package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-uNOv_x68.js} +87 -24
  30. package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-L4ja1_W6.js} +1 -1
  31. package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-CeLbHqdw.js} +56 -49
  32. package/dist/{credential-sync-vGnrB0BY.js → credential-sync-I8VBGk05.js} +16 -16
  33. package/dist/{projection-jZSlEAXG.js → credentialed-Cb6E2phL.js} +16268 -16821
  34. package/dist/{db-B4Hjxr-u.d.ts → db-BbC5stfa.d.ts} +13 -6
  35. package/dist/{db-CFZggNoy.js → db-LAyyX8tk.js} +1698 -1046
  36. package/dist/{executor-BPkZDx5-.js → executor-SCub-fAq.js} +552 -181
  37. package/dist/{html-2r2KmLwi.js → html-BCZ3Xtb_.js} +6 -6
  38. package/dist/{session-stop-BfY4rhJs.js → ingest-BDf3D50j.js} +2134 -2553
  39. package/dist/{install-C-oE6C_u.js → install-DCFJFkC0.js} +2 -2
  40. package/dist/instrumentation.js +4 -4
  41. package/dist/{lineage-CsvrEFQe.js → lineage-B_m-4TJw.js} +2 -2
  42. package/dist/{stop-DYzjRf2U.js → list-CN2QA2R9.js} +1656 -685
  43. package/dist/{logging-D5gkyvnK.js → logging-dQ9ZRGQ8.js} +47 -9
  44. package/dist/media-CYm1QD8T.js +2356 -0
  45. package/dist/{message-DwvJ-I3w.js → message-DSXGj1hM.js} +19 -29
  46. package/dist/{model-input-MAq2881y.js → model-input--TrP9hYV.js} +3 -3
  47. package/dist/nitro.d.ts +1 -1
  48. package/dist/nitro.js +4 -3
  49. package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-DHCZC6B4.js} +2 -2
  50. package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-pPMGnDZt.js} +1 -1
  51. package/dist/{registry-BBkWFCl8.js → registry-CZOzddwu.js} +5 -8
  52. package/dist/{resolve-B38MkHXE.js → resolve-cKOQ14Dh.js} +3 -3
  53. package/dist/{result-BaqSZcJb.js → result-DcvEOe1r.js} +119 -93
  54. package/dist/result-event-type-BdIJuZxg.js +48 -0
  55. package/dist/rule-DAxQY-1h.js +20 -0
  56. package/dist/{runner-11h8PrHh.js → runner-DBfUW44l.js} +14 -16
  57. package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
  58. package/dist/{schema-DriSvB40.d.ts → schema-BEHKxr4I.d.ts} +861 -298
  59. package/dist/{schema-obw5jvR4.js → schema-Bk9Nm2E8.js} +344 -153
  60. package/dist/{service-account-Bx93N1n1.js → service-account-CVYsFjty.js} +3 -3
  61. package/dist/{service-account-Zc5bUcIJ.js → service-account-Ts4ulcrV.js} +68 -68
  62. package/dist/{skills-C8Npu5zO.js → skills-VTnhAJWm.js} +2 -2
  63. package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -11
  64. package/dist/{spawn-CXr58R0x.js → spawn-vxAarlX5.js} +6 -6
  65. package/dist/start-conversation-CEn2KH1A.js +941 -0
  66. package/dist/{state-CGrGVeQC.js → state-C1P3_Ywk.js} +4 -4
  67. package/dist/statuses-_cRJHXK7.js +150 -0
  68. package/dist/store-DFZaN-Ix.js +492 -0
  69. package/dist/task-queue-Cx4Lmjyk.js +90 -0
  70. package/dist/task-runner-CbTwFA6k.js +1432 -0
  71. package/dist/{thread-context-Dyj1KWaY.js → thread-context-BkAZDTX2.js} +13 -11
  72. package/dist/thread-state-DhPndWi1.js +5625 -0
  73. package/dist/{validation-DxVNIxA0.js → validation-nIzMtAVJ.js} +1 -1
  74. package/dist/{task-queue-CaZffYaH.js → vercel-queue-hW90XzbG.js} +93 -172
  75. package/dist/{version-Cr7Z71yG.js → version-Brbtz4Qf.js} +1 -1
  76. package/dist/version.js +1 -1
  77. package/dist/{warmup-C6LOZ2d2.js → warmup-BDA5myRK.js} +5832 -4567
  78. package/dist/web-message-id-C6P83ans.js +10 -0
  79. package/dist/{worker-CUBtu1Li.js → worker-D63RcaVD.js} +20 -8
  80. package/migrations/0126_artifact_drop_public.sql +8 -0
  81. package/migrations/0127_artifact_path.sql +4 -0
  82. package/migrations/0128_artifact_path_index.sql +1 -0
  83. package/migrations/0129_review_item_answered_index.sql +1 -0
  84. package/migrations/0130_review_item_status_index.sql +1 -0
  85. package/migrations/0131_brief_outcome_status.sql +1 -0
  86. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  87. package/migrations/0133_brief_created_at_index.sql +1 -0
  88. package/migrations/0134_slack_person_search_index.sql +1 -0
  89. package/migrations/0135_code_change_size.sql +3 -0
  90. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  91. package/migrations/0137_inbox_snoozes.sql +27 -0
  92. package/migrations/0138_code_change_search_index.sql +2 -0
  93. package/migrations/0139_review_item_owner.sql +22 -0
  94. package/migrations/0140_review_item_owner_index.sql +1 -0
  95. package/migrations/0141_memory_core_adoption.sql +89 -0
  96. package/migrations/0142_memory_core_indexes.sql +17 -0
  97. package/migrations/0143_todos.sql +14 -0
  98. package/migrations/0144_inbox_items.sql +32 -0
  99. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  100. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  101. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  102. package/migrations/0148_authorization_request_index.sql +1 -0
  103. package/migrations/0149_conversation_metadata.sql +10 -0
  104. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  105. package/migrations/0151_conversation_search_index.sql +1 -0
  106. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  107. package/migrations/0153_artifact_expiry.sql +1 -0
  108. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  109. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  110. package/migrations/0156_conversation_kind_lead.sql +6 -0
  111. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  112. package/migrations/meta/0126_snapshot.json +5488 -0
  113. package/migrations/meta/0127_snapshot.json +5519 -0
  114. package/migrations/meta/0128_snapshot.json +5519 -0
  115. package/migrations/meta/0129_snapshot.json +5547 -0
  116. package/migrations/meta/0130_snapshot.json +5563 -0
  117. package/migrations/meta/0131_snapshot.json +5569 -0
  118. package/migrations/meta/0132_snapshot.json +5569 -0
  119. package/migrations/meta/0133_snapshot.json +5590 -0
  120. package/migrations/meta/0134_snapshot.json +5606 -0
  121. package/migrations/meta/0135_snapshot.json +5624 -0
  122. package/migrations/meta/0136_snapshot.json +5624 -0
  123. package/migrations/meta/0137_snapshot.json +5864 -0
  124. package/migrations/meta/0138_snapshot.json +5894 -0
  125. package/migrations/meta/0139_snapshot.json +5898 -0
  126. package/migrations/meta/0140_snapshot.json +5919 -0
  127. package/migrations/meta/0141_snapshot.json +6429 -0
  128. package/migrations/meta/0142_snapshot.json +6457 -0
  129. package/migrations/meta/0143_snapshot.json +6434 -0
  130. package/migrations/meta/0144_snapshot.json +6434 -0
  131. package/migrations/meta/0145_snapshot.json +6440 -0
  132. package/migrations/meta/0146_snapshot.json +6446 -0
  133. package/migrations/meta/0147_snapshot.json +6452 -0
  134. package/migrations/meta/0148_snapshot.json +6474 -0
  135. package/migrations/meta/0149_snapshot.json +6490 -0
  136. package/migrations/meta/0150_snapshot.json +6490 -0
  137. package/migrations/meta/0151_snapshot.json +6505 -0
  138. package/migrations/meta/0152_snapshot.json +6505 -0
  139. package/migrations/meta/0153_snapshot.json +6511 -0
  140. package/migrations/meta/0154_snapshot.json +6533 -0
  141. package/migrations/meta/0155_snapshot.json +6511 -0
  142. package/migrations/meta/0156_snapshot.json +6511 -0
  143. package/migrations/meta/0157_snapshot.json +6527 -0
  144. package/migrations/meta/_journal.json +224 -0
  145. package/package.json +7 -8
  146. package/skills/design-automation-skill/SKILL.md +108 -0
  147. package/dist/briefs-DKxkoruh.js +0 -395
  148. package/dist/conversation-M9KZ5JxF.js +0 -1024
  149. package/dist/prompt-CaMyeCpA.js +0 -910
  150. package/dist/schedule-DWxZ3kja.js +0 -1146
  151. package/dist/store-D4FQ1Nml.js +0 -335
  152. package/dist/task-runner-Dm7BHbGp.js +0 -287
  153. package/dist/turn-session-routing-CD0BRCex.js +0 -263
  154. package/dist/turn-user-message-9IxeEv5v.js +0 -364
  155. package/dist/users-CaUAYMb3.js +0 -181
  156. package/dist/viewer-AHldghAD.js +0 -212
  157. package/dist/web-message-id-BT8Mg8LL.js +0 -418
@@ -1,395 +0,0 @@
1
- import { F as briefResourceLabel, L as parseBriefInput, M as briefCodeChangeSchema, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-M9KZ5JxF.js";
2
- import { c as generateBrief, n as briefEntriesFromReportEvents, t as BRIEF_PROMPT, u as completeObject } from "./prompt-CaMyeCpA.js";
3
- import { CLI_USAGE } from "./cli/run.js";
4
- import * as z from "zod";
5
- import path from "node:path";
6
- import { mkdir, readFile, writeFile } from "node:fs/promises";
7
- // src/chat/briefs/render.ts
8
- function list(items, empty) {
9
- return items.length > 0 ? items.map((item) => `- ${item}`).join("\n") : empty;
10
- }
11
- function escapeLabel(label) {
12
- return label.replaceAll("[", "\\[").replaceAll("]", "\\]");
13
- }
14
- function formatCost(costUsd) {
15
- return costUsd === void 0 ? "not reported" : `$${costUsd.toFixed(6)}`;
16
- }
17
- function formatCount(count, noun) {
18
- return `${count} ${noun}${count === 1 ? "" : "s"}`;
19
- }
20
- function formatRecordCodeChange(change) {
21
- const dates = [
22
- change.openedAt ? `opened ${change.openedAt}` : void 0,
23
- change.mergedAt ? `merged ${change.mergedAt}` : void 0,
24
- change.closedAt ? `closed ${change.closedAt}` : void 0
25
- ].filter((value) => Boolean(value));
26
- return `[${escapeLabel(`${change.repository}#${change.number}${change.title ? ` · ${change.title}` : ""}`)}](${change.url}) · ${change.state}${dates.length ? ` · ${dates.join(" · ")}` : ""}`;
27
- }
28
- /** Render the final Brief and its local evidence check as readable Markdown. */
29
- function renderBriefMarkdown(args) {
30
- const { brief, evidence } = args.generation;
31
- const links = brief.links.map((link) => `[${escapeLabel(link.label)}](${link.url}) · ${link.kind}${link.status ? ` · ${link.status}` : ""}`);
32
- const dropped = evidence.droppedUrls.length ? evidence.droppedUrls.map((url) => `raw \`${url.raw}\` · normalized \`${url.normalized}\``) : ["None"];
33
- const record = brief.record;
34
- const location = record.location ? `${record.location.provider}${record.location.channelName ? ` · ${record.location.channelName}` : ""}` : "None";
35
- return [
36
- `# ${args.input.title ?? `Brief ${args.input.conversationId}`}`,
37
- "",
38
- "## Record",
39
- "",
40
- `- Started: ${record.startedAt}`,
41
- `- Last activity: ${record.lastActivityAt}`,
42
- `- Duration: ${record.durationMs} ms`,
43
- `- Location: ${location}`,
44
- `- Messages: ${formatCount(record.userMessages, "user message")} · ${formatCount(record.assistantMessages, "assistant message")} · ${formatCount(record.toolResults, "tool result")}`,
45
- `- Events: ${record.events}`,
46
- `- Turns: ${record.turns ?? "not reported"}`,
47
- "- Participants:",
48
- ...list(record.participants.map((participant) => `${participant.name} · ${participant.messages} message${participant.messages === 1 ? "" : "s"}`), "None.").split("\n").map((line) => ` ${line}`),
49
- "- Code changes:",
50
- ...list(record.codeChanges.map(formatRecordCodeChange), "None.").split("\n").map((line) => ` ${line}`),
51
- "",
52
- "## Summary",
53
- "",
54
- brief.summary,
55
- "",
56
- "## Intent",
57
- "",
58
- brief.intent,
59
- "",
60
- `## Outcome · ${brief.outcome.status}`,
61
- "",
62
- brief.outcome.text,
63
- "",
64
- "## Decisions",
65
- "",
66
- "### Stated",
67
- "",
68
- list(brief.decisions.filter((decision) => decision.kind === "stated").map((decision) => `${decision.text}${decision.by ? ` — ${decision.by}` : ""}`), "None."),
69
- "",
70
- "### Confirmed",
71
- "",
72
- list(brief.decisions.filter((decision) => decision.kind === "confirmed").map((decision) => `${decision.text}${decision.by ? ` — ${decision.by}` : ""}`), "None."),
73
- "",
74
- "### Assumed (not confirmed)",
75
- "",
76
- list(brief.decisions.filter((decision) => decision.kind === "assumed").map((decision) => `${decision.text}${decision.by ? ` — ${decision.by}` : ""}`), "None."),
77
- "",
78
- "## Facts",
79
- "",
80
- list(brief.facts, "None."),
81
- "",
82
- "## Links",
83
- "",
84
- list(links, "None."),
85
- "",
86
- "## Keywords",
87
- "",
88
- brief.keywords.join(", ") || "None.",
89
- "",
90
- "---",
91
- "",
92
- "### Evidence check",
93
- "",
94
- `- Conversation: \`${args.input.conversationId}\``,
95
- `- Through index: ${args.generation.throughIndex}`,
96
- `- Versions generated: ${args.versionCount}`,
97
- `- Model: \`${args.model}\``,
98
- `- Code changes: ${evidence.codeChangeCount}`,
99
- `- Resources: ${evidence.resourceCount}`,
100
- `- Model URLs: ${evidence.keptUrlCount} kept of ${evidence.citedUrlCount}`,
101
- `- Coerced decision kinds: ${evidence.coercedDecisionKinds}`,
102
- `- Dropped attributions: ${evidence.droppedAttributionCount}`,
103
- `- Dropped runtime-marker items: ${evidence.droppedRuntimeMarkerCount}`,
104
- `- Merged claim without evidence: ${evidence.mergedClaimWithoutEvidence ? "yes" : "no"}`,
105
- `- Cost: ${formatCost(args.totalCostUsd)}`,
106
- "- Dropped URLs:",
107
- ...dropped.map((url) => ` - ${url}`),
108
- ""
109
- ].join("\n");
110
- }
111
- // src/chat/briefs/snapshot.ts
112
- const conversationSnapshotSchema = z.object({
113
- schemaVersion: z.literal(1),
114
- pulledAt: z.string().datetime(),
115
- detail: conversationDetailReportSchema,
116
- eventPages: z.array(conversationEventPageSchema),
117
- codeChanges: z.array(briefCodeChangeSchema)
118
- }).strict();
119
- /** Create the self-contained wire snapshot used for local Brief replay. */
120
- function createConversationSnapshot(args) {
121
- return conversationSnapshotSchema.parse({
122
- schemaVersion: 1,
123
- pulledAt: args.pulledAt ?? (/* @__PURE__ */ new Date()).toISOString(),
124
- detail: args.detail,
125
- eventPages: args.eventPages,
126
- codeChanges: args.codeChanges ?? []
127
- });
128
- }
129
- function allEvents(snapshot) {
130
- const bySequence = /* @__PURE__ */ new Map();
131
- for (const event of [...snapshot.eventPages.flatMap((page) => page.events), ...snapshot.detail.events]) bySequence.set(event.seq, event);
132
- return [...bySequence.values()].sort((left, right) => left.seq - right.seq);
133
- }
134
- function assertAvailableHistory(snapshot) {
135
- if ([snapshot.detail.eventHistory, ...snapshot.eventPages.map((page) => page.eventHistory)].some((history) => history.status !== "available")) throw new Error("A Brief snapshot requires available event history");
136
- }
137
- function codeChangeAt(change, boundaryMs) {
138
- if (change.openedAt && Date.parse(change.openedAt) > boundaryMs) return;
139
- const mergedAt = change.mergedAt && Date.parse(change.mergedAt) <= boundaryMs ? change.mergedAt : void 0;
140
- const closedAt = change.closedAt && Date.parse(change.closedAt) <= boundaryMs ? change.closedAt : void 0;
141
- const { mergedAt: _mergedAt, closedAt: _closedAt, ...rest } = change;
142
- return {
143
- ...rest,
144
- state: mergedAt ? "merged" : closedAt ? "closed" : "open",
145
- ...mergedAt ? { mergedAt } : void 0,
146
- ...closedAt ? { closedAt } : void 0
147
- };
148
- }
149
- /**
150
- * Project a downloaded conversation snapshot into generator input. Evidence
151
- * is limited to what existed at the `throughIndex` event, so a replayed
152
- * earlier version cannot cite a later pull request or resource.
153
- */
154
- function briefInputFromSnapshot(snapshot, throughIndex) {
155
- assertAvailableHistory(snapshot);
156
- const detail = snapshot.detail;
157
- const boundary = allEvents(snapshot).filter((event) => event.seq <= throughIndex).at(-1);
158
- if (!boundary) throw new Error(`Snapshot has no event at or before index ${throughIndex}`);
159
- const boundaryMs = Date.parse(boundary.createdAt);
160
- const channelName = detail.channelName?.trim() || detail.channel?.trim();
161
- const hasLocation = Boolean(channelName || detail.locationId);
162
- return parseBriefInput({
163
- conversationId: detail.conversationId,
164
- ...detail.displayTitle.trim() ? { title: detail.displayTitle.trim() } : void 0,
165
- visibility: detail.visibility ?? "public",
166
- ...hasLocation ? { location: {
167
- provider: "slack",
168
- ...channelName ? { channelName } : void 0
169
- } } : void 0,
170
- entries: briefEntriesFromReportEvents(allEvents(snapshot)),
171
- codeChanges: snapshot.codeChanges.flatMap((change) => {
172
- const bounded = codeChangeAt(change, boundaryMs);
173
- return bounded ? [bounded] : [];
174
- }),
175
- resources: (detail.annotations ?? []).flatMap((annotation) => annotation.url !== null && Date.parse(annotation.createdAt) <= boundaryMs ? [{
176
- label: briefResourceLabel(annotation),
177
- url: annotation.url,
178
- ...annotation.status ? { status: annotation.status } : void 0
179
- }] : [])
180
- });
181
- }
182
- /** Return the last event index included in a conversation snapshot. */
183
- function throughIndexFromSnapshot(snapshot) {
184
- return allEvents(snapshot).at(-1)?.seq;
185
- }
186
- /** Return event indexes for turns that reached a successful terminal state. */
187
- function completedTurnIndexesFromSnapshot(snapshot) {
188
- return allEvents(snapshot).filter((event) => event.data.type === "turn_lifecycle" && (event.data.state === "succeeded" || event.data.state === "no_reply" || event.data.state === "blocked")).map((event) => event.seq);
189
- }
190
- // src/cli/briefs.ts
191
- /**
192
- * Local Brief snapshot and replay CLI.
193
- *
194
- * This module owns dashboard download pagination and local files. The Brief
195
- * module owns projection, generation, evidence checks, and rendering.
196
- */
197
- function optionValue(argv, index, option) {
198
- const value = argv[index + 1];
199
- if (!value || value.startsWith("--")) throw new Error(`${option} requires a value`);
200
- return value;
201
- }
202
- function parsePullOptions(argv) {
203
- const conversationIds = [];
204
- let baseUrl;
205
- let token = process.env["JUNIOR_API_TOKEN"]?.trim();
206
- let out;
207
- for (let index = 0; index < argv.length; index += 1) {
208
- const argument = argv[index];
209
- if (argument === "--base-url") {
210
- baseUrl = optionValue(argv, index, argument);
211
- index += 1;
212
- } else if (argument === "--token") {
213
- token = optionValue(argv, index, argument);
214
- index += 1;
215
- } else if (argument === "--out") {
216
- out = optionValue(argv, index, argument);
217
- index += 1;
218
- } else if (argument.startsWith("-")) throw new Error(`Unknown option: ${argument}`);
219
- else conversationIds.push(argument);
220
- }
221
- if (!baseUrl || !token || !out || conversationIds.length === 0) throw new Error(CLI_USAGE);
222
- return {
223
- baseUrl,
224
- conversationIds,
225
- out,
226
- token
227
- };
228
- }
229
- async function parseRunOptions(argv) {
230
- const snapshots = [];
231
- let model;
232
- let promptFile;
233
- let out = process.cwd();
234
- let turnByTurn = false;
235
- for (let index = 0; index < argv.length; index += 1) {
236
- const argument = argv[index];
237
- if (argument === "--model") {
238
- model = optionValue(argv, index, argument);
239
- index += 1;
240
- } else if (argument === "--prompt") {
241
- promptFile = optionValue(argv, index, argument);
242
- index += 1;
243
- } else if (argument === "--out") {
244
- out = optionValue(argv, index, argument);
245
- index += 1;
246
- } else if (argument === "--turn-by-turn") turnByTurn = true;
247
- else if (argument.startsWith("-")) throw new Error(`Unknown option: ${argument}`);
248
- else snapshots.push(argument);
249
- }
250
- if (snapshots.length === 0) throw new Error(CLI_USAGE);
251
- const bot = await configuredBot();
252
- return {
253
- assistantName: bot.userName,
254
- model: model ?? bot.fastModelId,
255
- out,
256
- promptFile,
257
- snapshots,
258
- turnByTurn
259
- };
260
- }
261
- /**
262
- * Read the production bot config only when a run needs it. `chat/config`
263
- * reads `DATABASE_URL` at import, and `briefs pull` must work with only a
264
- * token.
265
- */
266
- async function configuredBot() {
267
- const { botConfig } = await import("./config-Dkt2Le2b.js").then((n) => n.r);
268
- return botConfig;
269
- }
270
- function apiUrl(baseUrl, pathname) {
271
- const base = new URL(baseUrl);
272
- base.pathname = `${base.pathname.replace(/\/*$/, "")}/`;
273
- base.search = "";
274
- base.hash = "";
275
- return new URL(pathname.replace(/^\//, ""), base);
276
- }
277
- async function fetchJson(url, token) {
278
- const response = await fetch(url, { headers: {
279
- accept: "application/json",
280
- authorization: `Bearer ${token}`
281
- } });
282
- if (!response.ok) {
283
- const body = (await response.text()).trim().slice(0, 500);
284
- throw new Error(`Dashboard request failed (${response.status} ${response.statusText})${body ? `: ${body}` : ""}`);
285
- }
286
- return await response.json();
287
- }
288
- async function pullSnapshot(options, conversationId) {
289
- const detailUrl = apiUrl(options.baseUrl, `api/conversations/${encodeURIComponent(conversationId)}`);
290
- detailUrl.searchParams.set("limit", "1000");
291
- const detail = conversationDetailReportSchema.parse(await fetchJson(detailUrl, options.token));
292
- const eventPages = [];
293
- const seenCursors = /* @__PURE__ */ new Set();
294
- let cursor = detail.previousCursor;
295
- while (cursor) {
296
- if (seenCursors.has(cursor)) throw new Error(`Conversation ${conversationId} repeated an event cursor`);
297
- seenCursors.add(cursor);
298
- const eventsUrl = apiUrl(options.baseUrl, `api/conversations/${encodeURIComponent(conversationId)}/events`);
299
- eventsUrl.searchParams.set("before", cursor);
300
- eventsUrl.searchParams.set("limit", "1000");
301
- const page = conversationEventPageSchema.parse(await fetchJson(eventsUrl, options.token));
302
- eventPages.push(page);
303
- cursor = page.previousCursor;
304
- }
305
- return createConversationSnapshot({
306
- detail,
307
- eventPages
308
- });
309
- }
310
- function fileStem(conversationId) {
311
- const stem = conversationId.replaceAll(/[\\/\0]/g, "_");
312
- if (!stem || stem === "." || stem === "..") throw new Error("Conversation id cannot be used as a file name");
313
- return stem;
314
- }
315
- async function pullAll(options) {
316
- await mkdir(options.out, { recursive: true });
317
- for (const conversationId of options.conversationIds) {
318
- const snapshot = await pullSnapshot(options, conversationId);
319
- const output = path.join(options.out, `${fileStem(snapshot.detail.conversationId)}.snapshot.json`);
320
- await writeFile(output, `${JSON.stringify(snapshot, void 0, 2)}\n`);
321
- console.log(output);
322
- }
323
- }
324
- function generationIndexes(snapshot, turnByTurn, throughIndex) {
325
- if (!turnByTurn) return [throughIndex];
326
- const indexes = completedTurnIndexesFromSnapshot(snapshot);
327
- if (indexes.length === 0) throw new Error("Snapshot has no completed turns");
328
- return indexes;
329
- }
330
- async function runSnapshot(snapshotPath, options, prompt) {
331
- const snapshot = conversationSnapshotSchema.parse(JSON.parse(await readFile(snapshotPath, "utf8")));
332
- const finalThroughIndex = throughIndexFromSnapshot(snapshot);
333
- if (finalThroughIndex === void 0) throw new Error(`Snapshot ${snapshotPath} has no Conversation events`);
334
- const input = briefInputFromSnapshot(snapshot, finalThroughIndex);
335
- const versions = [];
336
- for (const throughIndex of generationIndexes(snapshot, options.turnByTurn, finalThroughIndex)) versions.push(await generateBrief({
337
- assistantName: options.assistantName,
338
- completeObject: (request) => completeObject({
339
- ...request,
340
- modelId: options.model,
341
- operation: "brief_update",
342
- cost: { owner: "caller" }
343
- }),
344
- input: briefInputFromSnapshot(snapshot, throughIndex),
345
- previous: versions.at(-1)?.brief,
346
- prompt,
347
- throughIndex
348
- }));
349
- const costs = versions.flatMap((version) => version.costUsd === void 0 ? [] : [version.costUsd]);
350
- const totalCostUsd = costs.length > 0 ? costs.reduce((sum, cost) => sum + cost, 0) : void 0;
351
- const stem = fileStem(input.conversationId);
352
- const jsonPath = path.join(options.out, `${stem}.brief.json`);
353
- const markdownPath = path.join(options.out, `${stem}.brief.md`);
354
- const report = {
355
- schemaVersion: 1,
356
- conversationId: input.conversationId,
357
- model: options.model,
358
- versions,
359
- ...totalCostUsd !== void 0 ? { totalCostUsd } : void 0
360
- };
361
- await Promise.all([writeFile(jsonPath, `${JSON.stringify(report, void 0, 2)}\n`), writeFile(markdownPath, renderBriefMarkdown({
362
- generation: versions.at(-1),
363
- input,
364
- model: options.model,
365
- totalCostUsd,
366
- versionCount: versions.length
367
- }))]);
368
- console.log(jsonPath);
369
- console.log(markdownPath);
370
- }
371
- async function runAll(options) {
372
- const prompt = options.promptFile ? await readFile(options.promptFile, "utf8") : BRIEF_PROMPT;
373
- if (!prompt.trim()) throw new Error("Brief prompt must not be empty");
374
- await mkdir(options.out, { recursive: true });
375
- for (const snapshot of options.snapshots) await runSnapshot(snapshot, options, prompt);
376
- }
377
- /** Run `junior briefs pull` or `junior briefs run`. */
378
- async function runBriefs(argv) {
379
- try {
380
- const [subcommand, ...rest] = argv;
381
- if (subcommand === "pull") {
382
- await pullAll(parsePullOptions(rest));
383
- return 0;
384
- }
385
- if (subcommand === "run") {
386
- await runAll(await parseRunOptions(rest));
387
- return 0;
388
- }
389
- throw new Error(CLI_USAGE);
390
- } catch (error) {
391
- console.error(error instanceof Error ? error.message : String(error));
392
- return 1;
393
- }
394
- }
395
- export { runBriefs };