@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.
- package/dist/{adapter-B1wujchl.js → adapter-CYAvJzZS.js} +1 -1
- package/dist/{adapter-context-G2M0y6rP.js → adapter-context-CVsHoVSf.js} +2 -2
- package/dist/{admin-DCiBhUT1.js → admin-Cyhb4TwZ.js} +1 -1
- package/dist/{agent-runner-BVHPUIc8.js → agent-runner-B5y9MsT-.js} +3487 -3493
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -6
- package/dist/api.d.ts +2 -2
- package/dist/api.js +294 -311
- package/dist/{app-Cw5Vy6H6.d.ts → app-DA8-hCMj.d.ts} +2 -9
- package/dist/app.d.ts +1 -1
- package/dist/app.js +336 -604
- package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-iZXadLV3.js} +60 -85
- package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-kkE3hvCX.js} +1 -1
- package/dist/channel-access-mt7K6dPh.js +221 -0
- package/dist/cli/chat.js +18 -19
- package/dist/cli/check.js +3 -3
- package/dist/cli/init.js +0 -1
- package/dist/cli/main.js +3 -7
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/run.d.ts +1 -2
- package/dist/cli/run.js +1 -2
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-BrXDQefC.js → config-CWbwKj0j.js} +59 -27
- package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-CxyFzdlF.js} +7 -8
- package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-BEXLD3Me.js} +86 -21
- package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-BrMiDN61.js} +1 -1
- package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-B35eu0uz.js} +78 -56
- package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-DWTOEQrm.js} +15 -15
- package/dist/{projection-Cns7XwWa.js → credentialed-Dyv8b-lu.js} +16306 -20732
- package/dist/{db-7ETESH44.d.ts → db-DYGcXYl3.d.ts} +11 -6
- package/dist/{db-DTxzH7u5.js → db-PwSRzWWn.js} +181 -100
- package/dist/{executor-DqTiYj9S.js → executor-CgWyWfYz.js} +117 -99
- package/dist/{html-B9Sl4Axb.js → html-DidUcRhI.js} +6 -6
- package/dist/ingest-B0AggUEC.js +7931 -0
- package/dist/{install-Sg4ePfLl.js → install-2urLLXNt.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-BHAMpNKr.js → lineage-BXplQAVH.js} +2 -2
- package/dist/{stop-CYsfc0Ed.js → list-DyIyReSV.js} +709 -475
- package/dist/{logging-FjclQsXu.js → logging-DNt-qOIO.js} +1 -1
- package/dist/{schedule-BLJ476XQ.js → media-B0pZJ0bG.js} +1058 -11
- package/dist/{message-CJ7_RL50.js → message-Z5YKC-Af.js} +35 -28
- package/dist/{model-input-CMLh4Cwq.js → model-input-BhPJYdSV.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +4 -3
- package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-ByvDdcdY.js} +2 -2
- package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-D-kK0yoN.js} +1 -1
- package/dist/{registry-BPwuOP2O.js → registry-POH4bZC4.js} +1 -1
- package/dist/reporting-window-C4dbzDiR.js +124 -0
- package/dist/request-deadline-BUiRYQYj.js +24 -0
- package/dist/{resolve-BK29bBry.js → resolve-CWtBNSKP.js} +3 -3
- package/dist/{runner-BcAE-cJm.js → runner-CsZ_VRxp.js} +14 -16
- package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
- package/dist/{schema-DYcJeV7d.d.ts → schema-DBf18QPS.d.ts} +2773 -3630
- package/dist/{schema-BLgSZXcL.js → schema-DojR2uCL.js} +106 -121
- package/dist/{service-account-iJoCtkHR.js → service-account-CDYb9hfX.js} +3 -3
- package/dist/{service-account-gN0zqf0S.js → service-account-o15pZWcJ.js} +5 -5
- package/dist/{skills-BoZ80epJ.js → skills-B0jP4whm.js} +2 -2
- package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-D26t9kBC.js} +9 -9
- package/dist/{spawn-Dk92r7mX.js → spawn-BjljgExZ.js} +14 -32
- package/dist/start-conversation-DbVujrwO.js +755 -0
- package/dist/{state-DH3Cmgp3.js → state-BTawTCme.js} +4 -4
- package/dist/statuses-BKwqCPhj.js +69 -0
- package/dist/store-CjXrp-Up.js +492 -0
- package/dist/task-queue-Cwlatjz3.js +90 -0
- package/dist/task-runner--Ke8KSMf.js +1432 -0
- package/dist/{thread-context-BW2BsQbH.js → thread-context-B8exINEe.js} +6 -7
- package/dist/turn-membership-DTR3SaKD.js +5859 -0
- package/dist/{validation-DrJd0nnq.js → validation-Ce0qbMlT.js} +1 -1
- package/dist/{task-queue-C_zldF5J.js → vercel-queue-q4z8w5QO.js} +93 -172
- package/dist/{version-CNKZ8owc.js → version-DFh4n9nr.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-BWdHew2H.js → warmup-D5hzqTcp.js} +4853 -13605
- package/dist/web-message-id-C6P83ans.js +10 -0
- package/dist/{worker-t9qpu_Zx.js → worker-CDg9Lbpg.js} +20 -7
- package/migrations/0143_todos.sql +14 -0
- package/migrations/0144_inbox_items.sql +32 -0
- package/migrations/0145_todo_changed_by_agent.sql +1 -0
- package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
- package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
- package/migrations/0148_authorization_request_index.sql +1 -0
- package/migrations/0149_conversation_metadata.sql +10 -0
- package/migrations/0150_conversation_metadata_fill.sql +39 -0
- package/migrations/0151_conversation_search_index.sql +1 -0
- package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
- package/migrations/0153_artifact_expiry.sql +1 -0
- package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
- package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
- package/migrations/0156_conversation_kind_lead.sql +6 -0
- package/migrations/0157_conversation_lead_actor_index.sql +1 -0
- package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
- package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
- package/migrations/meta/0143_snapshot.json +6434 -0
- package/migrations/meta/0144_snapshot.json +6434 -0
- package/migrations/meta/0145_snapshot.json +6440 -0
- package/migrations/meta/0146_snapshot.json +6446 -0
- package/migrations/meta/0147_snapshot.json +6452 -0
- package/migrations/meta/0148_snapshot.json +6474 -0
- package/migrations/meta/0149_snapshot.json +6490 -0
- package/migrations/meta/0150_snapshot.json +6490 -0
- package/migrations/meta/0151_snapshot.json +6505 -0
- package/migrations/meta/0152_snapshot.json +6505 -0
- package/migrations/meta/0153_snapshot.json +6511 -0
- package/migrations/meta/0154_snapshot.json +6533 -0
- package/migrations/meta/0155_snapshot.json +6511 -0
- package/migrations/meta/0156_snapshot.json +6511 -0
- package/migrations/meta/0157_snapshot.json +6527 -0
- package/migrations/meta/0158_snapshot.json +6515 -0
- package/migrations/meta/0159_snapshot.json +6515 -0
- package/migrations/meta/_journal.json +120 -1
- package/package.json +6 -6
- package/skills/design-automation-skill/SKILL.md +108 -0
- package/dist/briefs-BDjnug6Y.js +0 -395
- package/dist/conversation-ca__NDQW.js +0 -1063
- package/dist/prompt-CDqcsDYC.js +0 -910
- package/dist/store-DmmMIrQi.js +0 -335
- package/dist/task-runner-C7oCJQIx.js +0 -294
- package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
- package/dist/web-message-id-Ch5dPq-a.js +0 -306
package/dist/prompt-CDqcsDYC.js
DELETED
|
@@ -1,910 +0,0 @@
|
|
|
1
|
-
import { A as searchWeb$1, C as completeObject$1, D as generateImages$1, E as gatewayCostUsd, S as completeDecision$1, T as embedTexts$1, b as GEN_AI_PROVIDER_NAME, ct as createProviderError, ht as resolveGatewayCredential, ot as ProviderError, pt as isProviderRetryError, w as completeText$1, x as GEN_AI_SERVER_ADDRESS } from "./config-BrXDQefC.js";
|
|
2
|
-
import { E as withSpan, _ as runBestEffort, a as extractGenAiUsageSummary, i as extractGenAiUsageAttributes, p as logException } from "./logging-FjclQsXu.js";
|
|
3
|
-
import { Tn as agentTurnCostUsd, r as getConversationEventStore } from "./db-DTxzH7u5.js";
|
|
4
|
-
import { F as briefOutcomeStatusSchema, L as conversationBriefSchema, R as parseBriefInput } from "./conversation-ca__NDQW.js";
|
|
5
|
-
import * as z from "zod";
|
|
6
|
-
import { createGatewayProvider } from "@ai-sdk/gateway";
|
|
7
|
-
import { transcribe } from "ai";
|
|
8
|
-
import { conversationEventPresentationSchema, defineConversationEvent, mentionsTag, renderTag } from "@sentry/junior-plugin-api";
|
|
9
|
-
// src/chat/conversations/structured-events.ts
|
|
10
|
-
/** Reserved namespace for Junior-owned conversation metadata events. */
|
|
11
|
-
const JUNIOR_NATIVE_EVENT_NAMESPACE = "junior";
|
|
12
|
-
const authenticationEventContentSchema = z.object({
|
|
13
|
-
accountLabel: z.string().trim().min(1).max(120).optional(),
|
|
14
|
-
actorId: z.string().min(1),
|
|
15
|
-
authorizationId: z.string().min(1).optional(),
|
|
16
|
-
provider: z.string().regex(/^[a-z][a-z0-9-]*$/),
|
|
17
|
-
providerLabel: z.string().trim().min(1).max(80).optional()
|
|
18
|
-
}).strict();
|
|
19
|
-
const agentsInstructionsUpdatedContentSchema = z.object({
|
|
20
|
-
action: z.enum([
|
|
21
|
-
"loaded",
|
|
22
|
-
"replaced",
|
|
23
|
-
"cleared"
|
|
24
|
-
]),
|
|
25
|
-
directory: z.string().trim().min(1).max(500).optional(),
|
|
26
|
-
fingerprint: z.string().trim().min(1).max(128),
|
|
27
|
-
sources: z.array(z.object({
|
|
28
|
-
content: z.string().min(1).max(32768),
|
|
29
|
-
path: z.string().trim().min(1).max(500)
|
|
30
|
-
}).strict()).max(32),
|
|
31
|
-
textBytes: z.number().int().nonnegative().optional()
|
|
32
|
-
}).strict();
|
|
33
|
-
function providerTitle(content) {
|
|
34
|
-
return content.providerLabel?.trim() || content.provider;
|
|
35
|
-
}
|
|
36
|
-
function agentsInstructionsTitle(action) {
|
|
37
|
-
if (action === "loaded") return "Loaded AGENTS.md";
|
|
38
|
-
if (action === "replaced") return "Updated AGENTS.md";
|
|
39
|
-
return "Cleared AGENTS.md";
|
|
40
|
-
}
|
|
41
|
-
function sourceFilename(sourcePath) {
|
|
42
|
-
return sourcePath.split("/").at(-1) || sourcePath;
|
|
43
|
-
}
|
|
44
|
-
function formatBytes(bytes) {
|
|
45
|
-
if (bytes < 1024) return `${bytes} bytes`;
|
|
46
|
-
const kilobytes = bytes / 1024;
|
|
47
|
-
return `${Number.isInteger(kilobytes) ? kilobytes : kilobytes.toFixed(1)} KB`;
|
|
48
|
-
}
|
|
49
|
-
function agentsInstructionsPreview(content) {
|
|
50
|
-
const source = content.sources[0];
|
|
51
|
-
if (!source) return void 0;
|
|
52
|
-
const filename = sourceFilename(source.path);
|
|
53
|
-
const label = content.sources.length === 1 ? filename : `${content.sources.length} AGENTS.md files`;
|
|
54
|
-
return typeof content.textBytes === "number" ? `${label} · ${formatBytes(content.textBytes)}` : label;
|
|
55
|
-
}
|
|
56
|
-
/** Junior-owned account-link transcript event. */
|
|
57
|
-
const authenticationLinkedEvent = defineConversationEvent({
|
|
58
|
-
name: "authentication_linked",
|
|
59
|
-
version: 1,
|
|
60
|
-
schema: authenticationEventContentSchema,
|
|
61
|
-
renderEvent(event) {
|
|
62
|
-
const provider = providerTitle(event);
|
|
63
|
-
return {
|
|
64
|
-
icon: "link",
|
|
65
|
-
title: `${provider} connected`,
|
|
66
|
-
...event.accountLabel ? { preview: `Connected as \`${event.accountLabel}\`` } : void 0,
|
|
67
|
-
details: [{
|
|
68
|
-
title: `${provider} connected`,
|
|
69
|
-
...event.accountLabel ? { description: `Connected as \`${event.accountLabel}\`` } : void 0,
|
|
70
|
-
metadata: [event.provider]
|
|
71
|
-
}]
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
});
|
|
75
|
-
/** Junior-owned account-unlink transcript event. */
|
|
76
|
-
const authenticationUnlinkedEvent = defineConversationEvent({
|
|
77
|
-
name: "authentication_unlinked",
|
|
78
|
-
version: 1,
|
|
79
|
-
schema: authenticationEventContentSchema,
|
|
80
|
-
renderEvent(event) {
|
|
81
|
-
const provider = providerTitle(event);
|
|
82
|
-
return {
|
|
83
|
-
icon: "key",
|
|
84
|
-
title: `${provider} disconnected`,
|
|
85
|
-
details: [{
|
|
86
|
-
title: `${provider} disconnected`,
|
|
87
|
-
metadata: [event.provider]
|
|
88
|
-
}]
|
|
89
|
-
};
|
|
90
|
-
}
|
|
91
|
-
});
|
|
92
|
-
/** Junior-owned AGENTS.md bootstrap transition for the dashboard timeline. */
|
|
93
|
-
const agentsInstructionsUpdatedEvent = defineConversationEvent({
|
|
94
|
-
name: "agents_instructions_updated",
|
|
95
|
-
version: 1,
|
|
96
|
-
schema: agentsInstructionsUpdatedContentSchema,
|
|
97
|
-
renderEvent(event) {
|
|
98
|
-
const title = agentsInstructionsTitle(event.action);
|
|
99
|
-
const preview = agentsInstructionsPreview(event);
|
|
100
|
-
return {
|
|
101
|
-
icon: "brain",
|
|
102
|
-
title,
|
|
103
|
-
...preview ? { preview } : void 0,
|
|
104
|
-
...event.sources.length > 0 ? { details: event.sources.map((source) => ({
|
|
105
|
-
title: sourceFilename(source.path),
|
|
106
|
-
content: source.content
|
|
107
|
-
})) } : void 0
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
});
|
|
111
|
-
/** Core-written Conversation note. `notes.ts` owns when the model sees it. */
|
|
112
|
-
const conversationNoteEvent = defineConversationEvent({
|
|
113
|
-
name: "conversation_note",
|
|
114
|
-
version: 1,
|
|
115
|
-
schema: z.object({ text: z.string().trim().min(1).max(500) }).strict(),
|
|
116
|
-
renderEvent(event) {
|
|
117
|
-
return {
|
|
118
|
-
icon: "info",
|
|
119
|
-
title: "Note for the next Turn",
|
|
120
|
-
preview: event.text
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
});
|
|
124
|
-
const NATIVE_EVENT_DEFINITIONS = [
|
|
125
|
-
authenticationLinkedEvent,
|
|
126
|
-
authenticationUnlinkedEvent,
|
|
127
|
-
agentsInstructionsUpdatedEvent,
|
|
128
|
-
conversationNoteEvent
|
|
129
|
-
];
|
|
130
|
-
/** Resolve a registered Junior-native conversation event definition. */
|
|
131
|
-
function getJuniorNativeEventDefinition(args) {
|
|
132
|
-
return NATIVE_EVENT_DEFINITIONS.find((definition) => definition.eventName === args.name && definition.version === args.version);
|
|
133
|
-
}
|
|
134
|
-
/** Render one Junior-native event through its active definition. */
|
|
135
|
-
function renderJuniorNativeConversationEvent(args) {
|
|
136
|
-
if (args.namespace !== "junior") return void 0;
|
|
137
|
-
const definition = getJuniorNativeEventDefinition(args);
|
|
138
|
-
if (!definition) return void 0;
|
|
139
|
-
const presentation = definition.renderEvent(definition.parse(args.content));
|
|
140
|
-
return presentation === void 0 ? void 0 : conversationEventPresentationSchema.parse(presentation);
|
|
141
|
-
}
|
|
142
|
-
// src/chat/pi/transcription.ts
|
|
143
|
-
const GEN_AI_OPERATION_TRANSCRIPTION = "transcription";
|
|
144
|
-
const NO_AUDIO_PATTERN = /\(invalid_audio\)\s*$/;
|
|
145
|
-
const SENTENCE_END_PATTERN = /[.?!]["')\]]*$/;
|
|
146
|
-
/** The file has no audio that the model can transcribe. */
|
|
147
|
-
var NoAudioError = class extends Error {
|
|
148
|
-
name = "NoAudioError";
|
|
149
|
-
};
|
|
150
|
-
const diarizedWordsSchema = z.object({ elevenlabs: z.object({ words: z.array(z.object({
|
|
151
|
-
speaker_id: z.string().nullish(),
|
|
152
|
-
start: z.number(),
|
|
153
|
-
text: z.string(),
|
|
154
|
-
type: z.string()
|
|
155
|
-
})) }) });
|
|
156
|
-
/**
|
|
157
|
-
* Group diarized words into entries. A speech entry ends when the speaker
|
|
158
|
-
* changes or a sentence ends. Each audio event is its own sound entry.
|
|
159
|
-
* Spaces join words and never start an entry.
|
|
160
|
-
*/
|
|
161
|
-
function transcriptEntries(words) {
|
|
162
|
-
const entries = [];
|
|
163
|
-
let current;
|
|
164
|
-
for (const word of words) {
|
|
165
|
-
if (word.type === "spacing") {
|
|
166
|
-
if (current) current.text += word.text;
|
|
167
|
-
continue;
|
|
168
|
-
}
|
|
169
|
-
if (word.type === "audio_event") {
|
|
170
|
-
entries.push({
|
|
171
|
-
kind: "sound",
|
|
172
|
-
startSeconds: word.start,
|
|
173
|
-
text: word.text.replace(/^[[(]+|[\])]+$/g, "")
|
|
174
|
-
});
|
|
175
|
-
current = void 0;
|
|
176
|
-
continue;
|
|
177
|
-
}
|
|
178
|
-
const speaker = word.speaker_id ?? void 0;
|
|
179
|
-
if (!current || current.speaker !== speaker) {
|
|
180
|
-
current = {
|
|
181
|
-
kind: "speech",
|
|
182
|
-
startSeconds: word.start,
|
|
183
|
-
text: "",
|
|
184
|
-
...speaker ? { speaker } : void 0
|
|
185
|
-
};
|
|
186
|
-
entries.push(current);
|
|
187
|
-
}
|
|
188
|
-
current.text += word.text;
|
|
189
|
-
if (SENTENCE_END_PATTERN.test(word.text)) current = void 0;
|
|
190
|
-
}
|
|
191
|
-
return entries.map((entry) => ({
|
|
192
|
-
...entry,
|
|
193
|
-
text: entry.text.trim()
|
|
194
|
-
})).filter((entry) => entry.text.length > 0);
|
|
195
|
-
}
|
|
196
|
-
/**
|
|
197
|
-
* Keep the classification of a failed call, but not the SDK error. That
|
|
198
|
-
* error keeps the request body, and the body holds the signed URL.
|
|
199
|
-
*/
|
|
200
|
-
function withoutSourceUrl(error, sourceUrl, modelId) {
|
|
201
|
-
const failure = error instanceof Error ? error : void 0;
|
|
202
|
-
const message = (failure?.message ?? String(error)).replaceAll(sourceUrl, "<signed URL>");
|
|
203
|
-
const classified = createProviderError(Object.assign(new Error(message, { cause: failure?.cause }), {
|
|
204
|
-
code: failure && "code" in failure ? failure.code : void 0,
|
|
205
|
-
statusCode: failure && "statusCode" in failure ? failure.statusCode : void 0
|
|
206
|
-
}), { modelId });
|
|
207
|
-
return new ProviderError({
|
|
208
|
-
cause: new Error(message),
|
|
209
|
-
kind: classified.kind,
|
|
210
|
-
modelId,
|
|
211
|
-
retryable: classified.retryable,
|
|
212
|
-
retryAfterMs: classified.retryAfterMs,
|
|
213
|
-
status: classified.status
|
|
214
|
-
});
|
|
215
|
-
}
|
|
216
|
-
/**
|
|
217
|
-
* Transcribe speech in a file that the provider downloads from `sourceUrl`.
|
|
218
|
-
*
|
|
219
|
-
* The URL goes to the provider as `sourceUrl` with empty audio, so the file
|
|
220
|
-
* never passes through this process. The URL is a bearer credential: it is
|
|
221
|
-
* not put on spans, logs, or errors.
|
|
222
|
-
*/
|
|
223
|
-
async function transcribeFromUrl$1(params) {
|
|
224
|
-
const credential = await resolveGatewayCredential();
|
|
225
|
-
const provider = createGatewayProvider({ apiKey: credential.token });
|
|
226
|
-
try {
|
|
227
|
-
return await withSpan(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", {
|
|
228
|
-
modelId: params.modelId,
|
|
229
|
-
...params.conversationId ? { conversationId: params.conversationId } : void 0
|
|
230
|
-
}, async (setSpanAttributes) => {
|
|
231
|
-
const result = await transcribe({
|
|
232
|
-
model: provider.transcriptionModel(params.modelId),
|
|
233
|
-
audio: /* @__PURE__ */ new Uint8Array(),
|
|
234
|
-
providerOptions: { elevenlabs: {
|
|
235
|
-
diarize: true,
|
|
236
|
-
sourceUrl: params.sourceUrl,
|
|
237
|
-
tagAudioEvents: true
|
|
238
|
-
} },
|
|
239
|
-
...params.signal ? { abortSignal: params.signal } : void 0
|
|
240
|
-
}).catch((error) => {
|
|
241
|
-
if (error instanceof Error && NO_AUDIO_PATTERN.test(error.message)) {
|
|
242
|
-
setSpanAttributes({ "error.type": "invalid_audio" });
|
|
243
|
-
throw new NoAudioError("The file has no audio to transcribe.");
|
|
244
|
-
}
|
|
245
|
-
throw error;
|
|
246
|
-
});
|
|
247
|
-
const costUsd = gatewayCostUsd(result.providerMetadata);
|
|
248
|
-
const generationId = result.providerMetadata["gateway"]?.["generationId"];
|
|
249
|
-
const words = diarizedWordsSchema.safeParse(result.providerMetadata);
|
|
250
|
-
const entries = words.success ? transcriptEntries(words.data.elevenlabs.words) : result.segments.map((segment) => ({
|
|
251
|
-
kind: "speech",
|
|
252
|
-
startSeconds: segment.startSecond,
|
|
253
|
-
text: segment.text
|
|
254
|
-
}));
|
|
255
|
-
setSpanAttributes({
|
|
256
|
-
...typeof generationId === "string" ? { "gen_ai.response.id": generationId } : void 0,
|
|
257
|
-
...result.durationInSeconds !== void 0 ? { "app.transcription.audio_seconds": result.durationInSeconds } : void 0,
|
|
258
|
-
"app.transcription.entry_count": entries.length,
|
|
259
|
-
...extractGenAiUsageAttributes(costUsd !== void 0 ? { cost: { total: costUsd } } : void 0)
|
|
260
|
-
});
|
|
261
|
-
return {
|
|
262
|
-
...costUsd !== void 0 ? { costUsd } : void 0,
|
|
263
|
-
...result.durationInSeconds !== void 0 ? { durationSeconds: result.durationInSeconds } : void 0,
|
|
264
|
-
entries,
|
|
265
|
-
...result.language ? { language: result.language } : void 0
|
|
266
|
-
};
|
|
267
|
-
}, {
|
|
268
|
-
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
269
|
-
"gen_ai.operation.name": GEN_AI_OPERATION_TRANSCRIPTION,
|
|
270
|
-
"gen_ai.request.model": params.modelId,
|
|
271
|
-
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
272
|
-
"server.port": 443,
|
|
273
|
-
"gen_ai.provider.auth_mode": credential.mode
|
|
274
|
-
});
|
|
275
|
-
} catch (error) {
|
|
276
|
-
if (error instanceof NoAudioError) throw error;
|
|
277
|
-
const providerError = withoutSourceUrl(error, params.sourceUrl, params.modelId);
|
|
278
|
-
if (isProviderRetryError(providerError)) throw providerError;
|
|
279
|
-
logException(providerError, "ai.transcription.failed", {
|
|
280
|
-
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
281
|
-
"gen_ai.operation.name": GEN_AI_OPERATION_TRANSCRIPTION,
|
|
282
|
-
"gen_ai.request.model": params.modelId
|
|
283
|
-
});
|
|
284
|
-
throw providerError;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
// src/chat/core-model.ts
|
|
288
|
-
function gatewayParams(params) {
|
|
289
|
-
const { cost: _cost, operation, ...rest } = params;
|
|
290
|
-
return {
|
|
291
|
-
...rest,
|
|
292
|
-
promptName: `junior.${operation}`
|
|
293
|
-
};
|
|
294
|
-
}
|
|
295
|
-
async function recordCost(attribution, costUsd) {
|
|
296
|
-
const { cost, operation } = attribution;
|
|
297
|
-
if (costUsd === void 0 || !("conversationId" in cost)) return;
|
|
298
|
-
await runBestEffort(async () => {
|
|
299
|
-
await getConversationEventStore().append(cost.conversationId, [{
|
|
300
|
-
createdAtMs: Date.now(),
|
|
301
|
-
data: {
|
|
302
|
-
type: "structured_event",
|
|
303
|
-
namespace: JUNIOR_NATIVE_EVENT_NAMESPACE,
|
|
304
|
-
name: operation,
|
|
305
|
-
version: 1,
|
|
306
|
-
...cost.turnId ? { turnId: cost.turnId } : void 0,
|
|
307
|
-
content: { costUsd }
|
|
308
|
-
}
|
|
309
|
-
}], { activity: "preserve" });
|
|
310
|
-
}, "model_cost.record.failed", { "gen_ai.prompt.name": `junior.${operation}` });
|
|
311
|
-
}
|
|
312
|
-
/** Run a text completion and attribute its cost. */
|
|
313
|
-
async function completeText(params) {
|
|
314
|
-
const result = await completeText$1(gatewayParams(params));
|
|
315
|
-
await recordCost(params, agentTurnCostUsd(extractGenAiUsageSummary(result.message)));
|
|
316
|
-
return result;
|
|
317
|
-
}
|
|
318
|
-
/** Run a schema-constrained completion and attribute its cost. */
|
|
319
|
-
async function completeObject(params) {
|
|
320
|
-
const result = await completeObject$1(gatewayParams(params));
|
|
321
|
-
await recordCost(params, result.costUsd);
|
|
322
|
-
return result;
|
|
323
|
-
}
|
|
324
|
-
/** Answer decision questions and attribute the cost. */
|
|
325
|
-
async function completeDecision(params) {
|
|
326
|
-
const result = await completeDecision$1(gatewayParams(params));
|
|
327
|
-
await recordCost(params, result.costUsd);
|
|
328
|
-
return result;
|
|
329
|
-
}
|
|
330
|
-
/** Embed texts with the configured embedding model and attribute the cost. */
|
|
331
|
-
async function embedTexts(params) {
|
|
332
|
-
const { cost, operation: _operation, ...rest } = params;
|
|
333
|
-
const result = await embedTexts$1({
|
|
334
|
-
...rest,
|
|
335
|
-
..."conversationId" in cost ? { metadata: { conversationId: cost.conversationId } } : void 0
|
|
336
|
-
});
|
|
337
|
-
await recordCost(params, result.costUsd);
|
|
338
|
-
return result;
|
|
339
|
-
}
|
|
340
|
-
/** Run one web search and attribute its cost. */
|
|
341
|
-
async function searchWeb(params) {
|
|
342
|
-
const result = await searchWeb$1(gatewayParams(params));
|
|
343
|
-
await recordCost(params, result.costUsd);
|
|
344
|
-
return result;
|
|
345
|
-
}
|
|
346
|
-
/** Generate or edit images and attribute the cost. */
|
|
347
|
-
async function generateImages(params) {
|
|
348
|
-
const { cost: _cost, operation: _operation, ...rest } = params;
|
|
349
|
-
const result = await generateImages$1(rest);
|
|
350
|
-
await recordCost(params, result.costUsd);
|
|
351
|
-
return result;
|
|
352
|
-
}
|
|
353
|
-
/** Transcribe speech in a file at a signed URL and attribute the cost. */
|
|
354
|
-
async function transcribeFromUrl(params) {
|
|
355
|
-
const { cost, operation: _operation, ...rest } = params;
|
|
356
|
-
const result = await transcribeFromUrl$1({
|
|
357
|
-
...rest,
|
|
358
|
-
..."conversationId" in cost ? { conversationId: cost.conversationId } : void 0
|
|
359
|
-
});
|
|
360
|
-
await recordCost(params, result.costUsd);
|
|
361
|
-
return result;
|
|
362
|
-
}
|
|
363
|
-
// src/chat/briefs/generate.ts
|
|
364
|
-
const MAX_INPUT_CHARS = 6e4;
|
|
365
|
-
const MAX_MESSAGE_TEXT_CHARS = 4e3;
|
|
366
|
-
const MAX_TOOL_TEXT_CHARS = 1500;
|
|
367
|
-
const MAX_LINKS = 40;
|
|
368
|
-
const SIZE_CAPS = {
|
|
369
|
-
small: {
|
|
370
|
-
decisions: 3,
|
|
371
|
-
facts: 5,
|
|
372
|
-
keywords: 5
|
|
373
|
-
},
|
|
374
|
-
medium: {
|
|
375
|
-
decisions: 8,
|
|
376
|
-
facts: 10,
|
|
377
|
-
keywords: 8
|
|
378
|
-
},
|
|
379
|
-
large: {
|
|
380
|
-
decisions: 20,
|
|
381
|
-
facts: 15,
|
|
382
|
-
keywords: 12
|
|
383
|
-
}
|
|
384
|
-
};
|
|
385
|
-
const modelBriefSchema = z.object({
|
|
386
|
-
summary: z.string().trim().min(1),
|
|
387
|
-
intent: z.string().trim().min(1),
|
|
388
|
-
outcome: z.object({
|
|
389
|
-
status: briefOutcomeStatusSchema,
|
|
390
|
-
text: z.string().trim().min(1)
|
|
391
|
-
}).strict(),
|
|
392
|
-
decisions: z.array(z.object({
|
|
393
|
-
text: z.string().trim().min(1),
|
|
394
|
-
by: z.string().trim().min(1).nullable(),
|
|
395
|
-
kind: z.enum([
|
|
396
|
-
"stated",
|
|
397
|
-
"confirmed",
|
|
398
|
-
"assumed"
|
|
399
|
-
])
|
|
400
|
-
}).strict()),
|
|
401
|
-
facts: z.array(z.string().trim().min(1)),
|
|
402
|
-
keywords: z.array(z.string().trim().min(1)),
|
|
403
|
-
urls: z.array(z.object({
|
|
404
|
-
label: z.string().trim().min(1),
|
|
405
|
-
url: z.string().trim().min(1).max(2048)
|
|
406
|
-
}).strict())
|
|
407
|
-
}).strict();
|
|
408
|
-
function truncate(value, limit) {
|
|
409
|
-
const trimmed = value.trim();
|
|
410
|
-
return trimmed.length <= limit ? trimmed : trimmed.slice(0, limit);
|
|
411
|
-
}
|
|
412
|
-
function truncateSentence(value, limit) {
|
|
413
|
-
const trimmed = value.trim();
|
|
414
|
-
if (trimmed.length <= limit) return trimmed;
|
|
415
|
-
const bounded = trimmed.slice(0, limit);
|
|
416
|
-
const boundary = Math.max(bounded.lastIndexOf("."), bounded.lastIndexOf("!"), bounded.lastIndexOf("?"));
|
|
417
|
-
if (boundary + 1 >= limit * .6) return bounded.slice(0, boundary + 1).trim();
|
|
418
|
-
return `${trimmed.slice(0, limit - 1).trimEnd()}…`;
|
|
419
|
-
}
|
|
420
|
-
function uniqueStrings(values, limit) {
|
|
421
|
-
const unique = /* @__PURE__ */ new Set();
|
|
422
|
-
for (const value of values) {
|
|
423
|
-
const normalized = truncate(value, 400);
|
|
424
|
-
if (normalized) unique.add(normalized);
|
|
425
|
-
if (unique.size === limit) break;
|
|
426
|
-
}
|
|
427
|
-
return [...unique];
|
|
428
|
-
}
|
|
429
|
-
const RUNTIME_MARKER_TAGS = [
|
|
430
|
-
"active-asks",
|
|
431
|
-
"analysis-error",
|
|
432
|
-
"available-skills",
|
|
433
|
-
"brief-input",
|
|
434
|
-
"compaction",
|
|
435
|
-
"current-instruction",
|
|
436
|
-
"image-attachment",
|
|
437
|
-
"omitted-image-attachments",
|
|
438
|
-
"pi-history",
|
|
439
|
-
"plugin-contribution",
|
|
440
|
-
"resolved-or-replaced-asks",
|
|
441
|
-
"runtime-turn-context",
|
|
442
|
-
"thread-compactions",
|
|
443
|
-
"thread-context",
|
|
444
|
-
"turn-context"
|
|
445
|
-
];
|
|
446
|
-
function hasRuntimeMarker(value) {
|
|
447
|
-
return value.includes("[[NO_REPLY]]") || mentionsTag(value, RUNTIME_MARKER_TAGS);
|
|
448
|
-
}
|
|
449
|
-
const ASSISTANT_ATTRIBUTION = "assistant";
|
|
450
|
-
function normalizeModelBrief(args) {
|
|
451
|
-
let coercedDecisionKinds = 0;
|
|
452
|
-
let droppedAttributionCount = 0;
|
|
453
|
-
let droppedRuntimeMarkerCount = 0;
|
|
454
|
-
const participantNames = new Map(args.record.participants.map((participant) => [participant.name.toLowerCase(), participant.name]));
|
|
455
|
-
participantNames.set(args.assistantName.toLowerCase(), args.assistantName);
|
|
456
|
-
participantNames.set(ASSISTANT_ATTRIBUTION, args.assistantName);
|
|
457
|
-
const attribution = (value) => {
|
|
458
|
-
if (!value?.trim()) return void 0;
|
|
459
|
-
const matched = participantNames.get(value.trim().toLowerCase());
|
|
460
|
-
if (!matched) droppedAttributionCount += 1;
|
|
461
|
-
return matched;
|
|
462
|
-
};
|
|
463
|
-
const decisions = args.model.decisions.flatMap((decision) => {
|
|
464
|
-
if (hasRuntimeMarker(decision.text)) {
|
|
465
|
-
droppedRuntimeMarkerCount += 1;
|
|
466
|
-
return [];
|
|
467
|
-
}
|
|
468
|
-
let by = attribution(decision.by);
|
|
469
|
-
let kind = decision.kind;
|
|
470
|
-
if (by === args.assistantName && kind !== "assumed") {
|
|
471
|
-
kind = "assumed";
|
|
472
|
-
coercedDecisionKinds += 1;
|
|
473
|
-
} else if (by && by !== args.assistantName && kind === "assumed") {
|
|
474
|
-
by = void 0;
|
|
475
|
-
coercedDecisionKinds += 1;
|
|
476
|
-
}
|
|
477
|
-
return [{
|
|
478
|
-
text: truncate(decision.text, 400),
|
|
479
|
-
...by ? { by } : void 0,
|
|
480
|
-
kind
|
|
481
|
-
}];
|
|
482
|
-
});
|
|
483
|
-
const facts = args.model.facts.filter((fact) => {
|
|
484
|
-
const keep = !hasRuntimeMarker(fact);
|
|
485
|
-
if (!keep) droppedRuntimeMarkerCount += 1;
|
|
486
|
-
return keep;
|
|
487
|
-
});
|
|
488
|
-
return {
|
|
489
|
-
brief: conversationBriefSchema.parse({
|
|
490
|
-
schemaVersion: 1,
|
|
491
|
-
record: args.record,
|
|
492
|
-
summary: truncateSentence(args.model.summary, 600),
|
|
493
|
-
intent: truncateSentence(args.model.intent, 400),
|
|
494
|
-
outcome: {
|
|
495
|
-
status: args.model.outcome.status,
|
|
496
|
-
text: truncateSentence(args.model.outcome.text, 600)
|
|
497
|
-
},
|
|
498
|
-
decisions: decisions.slice(0, args.caps.decisions),
|
|
499
|
-
facts: uniqueStrings(facts, args.caps.facts),
|
|
500
|
-
links: args.links,
|
|
501
|
-
keywords: uniqueStrings(args.model.keywords.map((keyword) => keyword.toLowerCase()), args.caps.keywords)
|
|
502
|
-
}),
|
|
503
|
-
coercedDecisionKinds,
|
|
504
|
-
droppedAttributionCount,
|
|
505
|
-
droppedRuntimeMarkerCount
|
|
506
|
-
};
|
|
507
|
-
}
|
|
508
|
-
function inputEntries(input, throughIndex) {
|
|
509
|
-
return input.entries.filter((entry) => entry.index <= throughIndex).map((entry) => {
|
|
510
|
-
const limit = entry.role === "tool" ? MAX_TOOL_TEXT_CHARS : MAX_MESSAGE_TEXT_CHARS;
|
|
511
|
-
return {
|
|
512
|
-
...entry,
|
|
513
|
-
text: entry.text.length > limit ? `${entry.text.slice(0, limit - 1)}…` : entry.text
|
|
514
|
-
};
|
|
515
|
-
});
|
|
516
|
-
}
|
|
517
|
-
function buildBriefRecord(input, entries) {
|
|
518
|
-
if (entries.length === 0) throw new Error("A Brief requires at least one entry through its index");
|
|
519
|
-
const participantByName = /* @__PURE__ */ new Map();
|
|
520
|
-
for (const entry of entries) {
|
|
521
|
-
if (entry.role !== "user" || !entry.author?.trim()) continue;
|
|
522
|
-
const key = entry.author.trim().toLowerCase();
|
|
523
|
-
const participant = participantByName.get(key);
|
|
524
|
-
if (participant) participant.messages += 1;
|
|
525
|
-
else participantByName.set(key, {
|
|
526
|
-
name: entry.author.trim(),
|
|
527
|
-
messages: 1
|
|
528
|
-
});
|
|
529
|
-
}
|
|
530
|
-
const activityTimes = entries.map((entry) => entry.createdAtMs);
|
|
531
|
-
const startedAtMs = Math.min(...activityTimes);
|
|
532
|
-
const lastActivityAtMs = Math.max(...activityTimes);
|
|
533
|
-
const turns = new Set(entries.flatMap((entry) => entry.turnId ? [entry.turnId] : [])).size;
|
|
534
|
-
return {
|
|
535
|
-
startedAt: new Date(startedAtMs).toISOString(),
|
|
536
|
-
lastActivityAt: new Date(lastActivityAtMs).toISOString(),
|
|
537
|
-
durationMs: lastActivityAtMs - startedAtMs,
|
|
538
|
-
participants: [...participantByName.values()],
|
|
539
|
-
userMessages: entries.filter((entry) => entry.role === "user").length,
|
|
540
|
-
assistantMessages: entries.filter((entry) => entry.role === "assistant").length,
|
|
541
|
-
toolResults: entries.filter((entry) => entry.role === "tool").length,
|
|
542
|
-
events: entries.filter((entry) => entry.role === "event").length,
|
|
543
|
-
...turns > 0 ? { turns } : void 0,
|
|
544
|
-
...input.location ? { location: input.location } : void 0,
|
|
545
|
-
codeChanges: input.codeChanges
|
|
546
|
-
};
|
|
547
|
-
}
|
|
548
|
-
function briefSizeClass(record) {
|
|
549
|
-
if (record.userMessages <= 3) return "small";
|
|
550
|
-
if (record.userMessages <= 12) return "medium";
|
|
551
|
-
return "large";
|
|
552
|
-
}
|
|
553
|
-
function promptInput(args) {
|
|
554
|
-
const messages = args.entries.filter((entry) => entry.role !== "tool");
|
|
555
|
-
const tools = args.entries.filter((entry) => entry.role === "tool");
|
|
556
|
-
const keptMessages = [...messages];
|
|
557
|
-
const keptTools = [];
|
|
558
|
-
const base = {
|
|
559
|
-
conversation: {
|
|
560
|
-
id: args.input.conversationId,
|
|
561
|
-
title: args.input.title,
|
|
562
|
-
visibility: args.input.visibility,
|
|
563
|
-
location: args.input.location
|
|
564
|
-
},
|
|
565
|
-
record: args.record,
|
|
566
|
-
sizeClass: args.sizeClass,
|
|
567
|
-
caps: args.caps,
|
|
568
|
-
previousBrief: args.previous,
|
|
569
|
-
resources: args.input.resources
|
|
570
|
-
};
|
|
571
|
-
const serialize = () => {
|
|
572
|
-
const kept = /* @__PURE__ */ new Set([...keptMessages, ...keptTools]);
|
|
573
|
-
return JSON.stringify({
|
|
574
|
-
...base,
|
|
575
|
-
omitted: {
|
|
576
|
-
messages: messages.length - keptMessages.length,
|
|
577
|
-
toolResults: tools.length - keptTools.length
|
|
578
|
-
},
|
|
579
|
-
entries: args.entries.filter((entry) => kept.has(entry))
|
|
580
|
-
});
|
|
581
|
-
};
|
|
582
|
-
let text = serialize();
|
|
583
|
-
while (text.length > MAX_INPUT_CHARS && keptMessages.length > 0) {
|
|
584
|
-
keptMessages.shift();
|
|
585
|
-
text = serialize();
|
|
586
|
-
}
|
|
587
|
-
if (text.length > MAX_INPUT_CHARS) throw new Error("Brief metadata exceeds the 60,000 character input limit");
|
|
588
|
-
for (let index = tools.length - 1; index >= 0; index -= 1) {
|
|
589
|
-
keptTools.push(tools[index]);
|
|
590
|
-
const candidate = serialize();
|
|
591
|
-
if (candidate.length <= MAX_INPUT_CHARS) text = candidate;
|
|
592
|
-
else keptTools.pop();
|
|
593
|
-
}
|
|
594
|
-
return [renderTag("brief-input", {}, [text]), "Return the next Brief as structured data."].join("\n");
|
|
595
|
-
}
|
|
596
|
-
function deterministicLinks(input) {
|
|
597
|
-
return [...input.codeChanges.map((change) => ({
|
|
598
|
-
kind: "code_change",
|
|
599
|
-
label: truncate(`${change.repository}#${change.number}${change.title ? ` · ${change.title}` : ""}`, 400),
|
|
600
|
-
url: change.url,
|
|
601
|
-
status: change.state
|
|
602
|
-
})), ...input.resources.map((resource) => ({
|
|
603
|
-
kind: "resource",
|
|
604
|
-
label: truncate(resource.label, 400),
|
|
605
|
-
url: resource.url,
|
|
606
|
-
...resource.status ? { status: resource.status } : void 0
|
|
607
|
-
}))];
|
|
608
|
-
}
|
|
609
|
-
function decodeHtmlEntities(value) {
|
|
610
|
-
const entities = {
|
|
611
|
-
"'": "'",
|
|
612
|
-
"&": "&",
|
|
613
|
-
">": ">",
|
|
614
|
-
"<": "<",
|
|
615
|
-
""": "\""
|
|
616
|
-
};
|
|
617
|
-
return value.replace(/&(?:amp|lt|gt|quot|#39);/g, (entity) => entities[entity]);
|
|
618
|
-
}
|
|
619
|
-
function endsWithUnopenedBracket(url, open, close) {
|
|
620
|
-
return url.endsWith(close) && url.split(open).length < url.split(close).length;
|
|
621
|
-
}
|
|
622
|
-
/**
|
|
623
|
-
* Strip punctuation that prose attaches to a URL. A closing bracket stays when
|
|
624
|
-
* the URL opened it, so `wiki/Foo_(bar)` survives and `(see https://x/y)` does not.
|
|
625
|
-
*/
|
|
626
|
-
function normalizeCitationUrl(raw) {
|
|
627
|
-
let url = decodeHtmlEntities(raw).trim();
|
|
628
|
-
for (;;) {
|
|
629
|
-
let next = url.replace(/[;,.]+$/, "").replace(/\/+$/, "");
|
|
630
|
-
if (endsWithUnopenedBracket(next, "(", ")") || endsWithUnopenedBracket(next, "[", "]")) next = next.slice(0, -1);
|
|
631
|
-
if (next === url) return url;
|
|
632
|
-
url = next;
|
|
633
|
-
}
|
|
634
|
-
}
|
|
635
|
-
/** Models sometimes append a stray `/https` to a cited URL; try without it. */
|
|
636
|
-
function citationCandidates(raw) {
|
|
637
|
-
const normalized = normalizeCitationUrl(raw);
|
|
638
|
-
const stripped = normalizeCitationUrl(normalized.replace(/\/https?$/i, ""));
|
|
639
|
-
return stripped === normalized ? [normalized] : [normalized, stripped];
|
|
640
|
-
}
|
|
641
|
-
/** URL tokens in prose or Slack `<url|label>` links, normalized for matching. */
|
|
642
|
-
function normalizedUrlTokens(value) {
|
|
643
|
-
const tokens = decodeHtmlEntities(value).match(/https?:\/\/[^\s<>"'|]+/gi);
|
|
644
|
-
return new Set((tokens ?? []).map(normalizeCitationUrl).filter((url) => url.length > 0));
|
|
645
|
-
}
|
|
646
|
-
function buildEvidenceLinks(args) {
|
|
647
|
-
const deterministic = deterministicLinks(args.input);
|
|
648
|
-
const transcriptUrls = normalizedUrlTokens(args.entries.map((entry) => entry.text).join("\n"));
|
|
649
|
-
const priorUrls = new Set((args.previous?.links ?? []).map((link) => normalizeCitationUrl(link.url)));
|
|
650
|
-
const linkedUrls = new Set(deterministic.map((link) => normalizeCitationUrl(link.url)));
|
|
651
|
-
const supportedUrls = /* @__PURE__ */ new Set();
|
|
652
|
-
const droppedUrls = /* @__PURE__ */ new Map();
|
|
653
|
-
const cited = [];
|
|
654
|
-
for (const citation of args.model.urls) {
|
|
655
|
-
const candidates = citationCandidates(citation.url);
|
|
656
|
-
const normalized = candidates.find((candidate) => linkedUrls.has(candidate) || transcriptUrls.has(candidate) || priorUrls.has(candidate));
|
|
657
|
-
if (normalized === void 0) {
|
|
658
|
-
droppedUrls.set(`${citation.url}\0${candidates[0]}`, {
|
|
659
|
-
normalized: candidates[0],
|
|
660
|
-
raw: citation.url
|
|
661
|
-
});
|
|
662
|
-
continue;
|
|
663
|
-
}
|
|
664
|
-
supportedUrls.add(normalized);
|
|
665
|
-
if (linkedUrls.has(normalized)) continue;
|
|
666
|
-
linkedUrls.add(normalized);
|
|
667
|
-
cited.push({
|
|
668
|
-
raw: citation.url,
|
|
669
|
-
link: {
|
|
670
|
-
kind: "url",
|
|
671
|
-
label: truncate(citation.label, 400),
|
|
672
|
-
url: normalized
|
|
673
|
-
}
|
|
674
|
-
});
|
|
675
|
-
}
|
|
676
|
-
const citedLimit = Math.max(0, MAX_LINKS - deterministic.length);
|
|
677
|
-
for (const citation of cited.slice(citedLimit)) droppedUrls.set(`${citation.raw}\0${citation.link.url}`, {
|
|
678
|
-
normalized: citation.link.url,
|
|
679
|
-
raw: citation.raw
|
|
680
|
-
});
|
|
681
|
-
const links = [...deterministic, ...cited.slice(0, citedLimit).map((citation) => citation.link)].slice(0, MAX_LINKS);
|
|
682
|
-
const keptUrls = new Set(links.map((link) => normalizeCitationUrl(link.url)));
|
|
683
|
-
return {
|
|
684
|
-
droppedUrls: [...droppedUrls.values()],
|
|
685
|
-
keptUrlCount: [...supportedUrls].filter((url) => keptUrls.has(url)).length,
|
|
686
|
-
links
|
|
687
|
-
};
|
|
688
|
-
}
|
|
689
|
-
function hasMergedEvidence(input) {
|
|
690
|
-
return input.codeChanges.some((change) => change.state === "merged") || input.resources.some((resource) => resource.status?.trim().toLowerCase() === "merged");
|
|
691
|
-
}
|
|
692
|
-
/** Build the text indexed for a Brief without adding transcript content. */
|
|
693
|
-
function buildBriefSearchText(brief, input) {
|
|
694
|
-
const values = [
|
|
695
|
-
input.title,
|
|
696
|
-
brief.summary,
|
|
697
|
-
brief.intent,
|
|
698
|
-
brief.outcome.text,
|
|
699
|
-
...brief.decisions.map((decision) => decision.text),
|
|
700
|
-
...brief.facts,
|
|
701
|
-
...brief.keywords,
|
|
702
|
-
...brief.links.map((link) => link.label),
|
|
703
|
-
...deterministicLinks(input).map((link) => link.label),
|
|
704
|
-
...brief.record.participants.map((participant) => participant.name),
|
|
705
|
-
...brief.record.codeChanges.map((change) => `${change.repository}#${change.number} ${change.state}`)
|
|
706
|
-
].filter((value) => Boolean(value?.trim()));
|
|
707
|
-
return [...new Set(values)].join("\n");
|
|
708
|
-
}
|
|
709
|
-
/** Generate one bounded Brief and attach only deterministic evidence links. */
|
|
710
|
-
async function generateBrief(args) {
|
|
711
|
-
const input = parseBriefInput(args.input);
|
|
712
|
-
if (!Number.isSafeInteger(args.throughIndex) || args.throughIndex < 0) throw new Error("throughIndex must be a non-negative integer");
|
|
713
|
-
const entries = inputEntries(input, args.throughIndex);
|
|
714
|
-
const record = buildBriefRecord(input, entries);
|
|
715
|
-
const sizeClass = briefSizeClass(record);
|
|
716
|
-
const caps = SIZE_CAPS[sizeClass];
|
|
717
|
-
const result = await args.completeObject({
|
|
718
|
-
maxTokens: 2500,
|
|
719
|
-
prompt: promptInput({
|
|
720
|
-
caps,
|
|
721
|
-
entries,
|
|
722
|
-
input,
|
|
723
|
-
previous: args.previous,
|
|
724
|
-
record,
|
|
725
|
-
sizeClass
|
|
726
|
-
}),
|
|
727
|
-
schema: modelBriefSchema,
|
|
728
|
-
system: args.prompt
|
|
729
|
-
});
|
|
730
|
-
const model = modelBriefSchema.parse(result.object);
|
|
731
|
-
const { droppedUrls, keptUrlCount, links } = buildEvidenceLinks({
|
|
732
|
-
entries,
|
|
733
|
-
input,
|
|
734
|
-
model,
|
|
735
|
-
previous: args.previous
|
|
736
|
-
});
|
|
737
|
-
const normalized = normalizeModelBrief({
|
|
738
|
-
assistantName: args.assistantName,
|
|
739
|
-
caps,
|
|
740
|
-
links,
|
|
741
|
-
model,
|
|
742
|
-
record
|
|
743
|
-
});
|
|
744
|
-
const mergedClaim = /\bmerged\b/i.test(`${normalized.brief.summary}\n${normalized.brief.outcome.text}`);
|
|
745
|
-
const hasLinkedEvidence = input.codeChanges.length > 0 || input.resources.length > 0;
|
|
746
|
-
return {
|
|
747
|
-
brief: normalized.brief,
|
|
748
|
-
...result.costUsd !== void 0 ? { costUsd: result.costUsd } : void 0,
|
|
749
|
-
evidence: {
|
|
750
|
-
citedUrlCount: model.urls.length,
|
|
751
|
-
codeChangeCount: input.codeChanges.length,
|
|
752
|
-
coercedDecisionKinds: normalized.coercedDecisionKinds,
|
|
753
|
-
droppedAttributionCount: normalized.droppedAttributionCount,
|
|
754
|
-
droppedRuntimeMarkerCount: normalized.droppedRuntimeMarkerCount,
|
|
755
|
-
droppedUrls,
|
|
756
|
-
keptUrlCount,
|
|
757
|
-
mergedClaimWithoutEvidence: mergedClaim && hasLinkedEvidence && !hasMergedEvidence(input),
|
|
758
|
-
resourceCount: input.resources.length
|
|
759
|
-
},
|
|
760
|
-
searchText: buildBriefSearchText(normalized.brief, input),
|
|
761
|
-
throughIndex: args.throughIndex
|
|
762
|
-
};
|
|
763
|
-
}
|
|
764
|
-
// src/chat/events/actor.ts
|
|
765
|
-
/**
|
|
766
|
-
* System author ID stamped on event mailbox messages.
|
|
767
|
-
*
|
|
768
|
-
* Keep this stable so conversation history can recognize the same system input
|
|
769
|
-
* for event Turns.
|
|
770
|
-
*
|
|
771
|
-
* TODO(dcramer): Delete this ID after resumes read event Source.kind
|
|
772
|
-
* from the Turn checkpoint instead of Message author data.
|
|
773
|
-
*/
|
|
774
|
-
const EVENT_AUTHOR_ID = "UJRNEVENT";
|
|
775
|
-
/** System Message author for event input. */
|
|
776
|
-
const EVENT_MESSAGE_AUTHOR = {
|
|
777
|
-
fullName: "System event",
|
|
778
|
-
isBot: true,
|
|
779
|
-
userId: EVENT_AUTHOR_ID,
|
|
780
|
-
userName: "junior-event"
|
|
781
|
-
};
|
|
782
|
-
/** System execution actor for every event turn. */
|
|
783
|
-
const EVENT_SYSTEM_ACTOR = {
|
|
784
|
-
platform: "system",
|
|
785
|
-
name: "event"
|
|
786
|
-
};
|
|
787
|
-
/**
|
|
788
|
-
* Whether a saved Message started a event Turn.
|
|
789
|
-
*
|
|
790
|
-
* TODO(dcramer): Delete this marker check after deployed Turn cursors all store
|
|
791
|
-
* Source and Actor. `eventType` only supports saved synthetic Slack input.
|
|
792
|
-
*/
|
|
793
|
-
function isEventConversationMessage(message) {
|
|
794
|
-
return Boolean(message.meta?.eventType) || isEventAuthorId(message.author?.userId);
|
|
795
|
-
}
|
|
796
|
-
/** Author id of an Event Message by a listed bot, which has no Identity. */
|
|
797
|
-
function eventBotAuthorId(provider, handle) {
|
|
798
|
-
return `${EVENT_AUTHOR_ID}:${provider}:${handle.toLowerCase()}`;
|
|
799
|
-
}
|
|
800
|
-
/** Whether an author id belongs to an Event Message, system or listed bot. */
|
|
801
|
-
function isEventAuthorId(id) {
|
|
802
|
-
return id === "UJRNEVENT" || Boolean(id?.startsWith(`UJRNEVENT:`));
|
|
803
|
-
}
|
|
804
|
-
// src/chat/briefs/event-entries.ts
|
|
805
|
-
const TOOL_TEXT_LIMIT = 1500;
|
|
806
|
-
function actorIdentityKey(actor) {
|
|
807
|
-
const slackUserId = actor?.slackUserId?.trim();
|
|
808
|
-
if (slackUserId) return `slack:${slackUserId}`;
|
|
809
|
-
const email = actor?.email?.trim();
|
|
810
|
-
return email ? `email:${email.toLowerCase()}` : void 0;
|
|
811
|
-
}
|
|
812
|
-
function bestActorName(actor) {
|
|
813
|
-
return actor?.fullName?.trim() || actor?.slackUserName?.trim() || actor?.email?.trim() || void 0;
|
|
814
|
-
}
|
|
815
|
-
function actorNames(events) {
|
|
816
|
-
const actors = /* @__PURE__ */ new Map();
|
|
817
|
-
for (const event of events) {
|
|
818
|
-
if (event.data.type !== "message") continue;
|
|
819
|
-
const actor = event.data.actorIdentity;
|
|
820
|
-
const key = actorIdentityKey(actor);
|
|
821
|
-
if (!key) continue;
|
|
822
|
-
const known = actors.get(key) ?? {};
|
|
823
|
-
actors.set(key, {
|
|
824
|
-
fullName: known.fullName ?? (actor?.fullName?.trim() || void 0),
|
|
825
|
-
slackUserName: known.slackUserName ?? (actor?.slackUserName?.trim() || void 0),
|
|
826
|
-
email: known.email ?? (actor?.email?.trim() || void 0)
|
|
827
|
-
});
|
|
828
|
-
}
|
|
829
|
-
const names = /* @__PURE__ */ new Map();
|
|
830
|
-
for (const [key, actor] of actors) {
|
|
831
|
-
const name = bestActorName(actor);
|
|
832
|
-
if (name) names.set(key, name);
|
|
833
|
-
}
|
|
834
|
-
return names;
|
|
835
|
-
}
|
|
836
|
-
function actorName(actor, resolvedNames) {
|
|
837
|
-
if (!actor) return void 0;
|
|
838
|
-
const key = actorIdentityKey(actor);
|
|
839
|
-
return (key ? resolvedNames.get(key) : void 0) ?? bestActorName(actor);
|
|
840
|
-
}
|
|
841
|
-
function toolText(output) {
|
|
842
|
-
if (output === void 0) return void 0;
|
|
843
|
-
const text = typeof output === "string" ? output : JSON.stringify(output, void 0, 2);
|
|
844
|
-
if (!text?.trim()) return void 0;
|
|
845
|
-
return text.length <= TOOL_TEXT_LIMIT ? text : `${text.slice(0, 1499)}…`;
|
|
846
|
-
}
|
|
847
|
-
/** Map reporting events to the entries used by every Brief input adapter. */
|
|
848
|
-
function briefEntriesFromReportEvents(events) {
|
|
849
|
-
const resolvedActorNames = actorNames(events);
|
|
850
|
-
const turnByMessageId = /* @__PURE__ */ new Map();
|
|
851
|
-
for (const event of events) if (event.data.type === "turn_lifecycle" && event.data.state === "started") for (const messageId of event.data.inputMessageIds ?? []) turnByMessageId.set(messageId, event.data.turnId);
|
|
852
|
-
const entries = [];
|
|
853
|
-
let activeTurnId;
|
|
854
|
-
for (const event of events) {
|
|
855
|
-
const data = event.data;
|
|
856
|
-
if (data.type === "turn_lifecycle") {
|
|
857
|
-
if (data.state === "started") activeTurnId = data.turnId;
|
|
858
|
-
else if (data.turnId === activeTurnId) activeTurnId = void 0;
|
|
859
|
-
continue;
|
|
860
|
-
}
|
|
861
|
-
if (data.type === "message" && data.text && data.role !== "system") {
|
|
862
|
-
const turnId = data.role === "user" ? turnByMessageId.get(data.messageId) : activeTurnId;
|
|
863
|
-
const author = actorName(data.actorIdentity, resolvedActorNames);
|
|
864
|
-
const role = data.role === "user" && (Boolean(data.eventType) || isEventAuthorId(data.actorIdentity?.slackUserId)) ? "event" : data.role;
|
|
865
|
-
entries.push({
|
|
866
|
-
index: event.seq,
|
|
867
|
-
role,
|
|
868
|
-
...author ? { author } : void 0,
|
|
869
|
-
text: data.text,
|
|
870
|
-
createdAtMs: Date.parse(event.createdAt),
|
|
871
|
-
...turnId ? { turnId } : void 0
|
|
872
|
-
});
|
|
873
|
-
continue;
|
|
874
|
-
}
|
|
875
|
-
if (data.type !== "tool_calls") continue;
|
|
876
|
-
for (const call of data.calls) {
|
|
877
|
-
const text = toolText(call.output);
|
|
878
|
-
if (!text) continue;
|
|
879
|
-
entries.push({
|
|
880
|
-
index: event.seq,
|
|
881
|
-
role: "tool",
|
|
882
|
-
author: call.name,
|
|
883
|
-
text,
|
|
884
|
-
createdAtMs: Date.parse(event.createdAt),
|
|
885
|
-
...activeTurnId ? { turnId: activeTurnId } : void 0
|
|
886
|
-
});
|
|
887
|
-
}
|
|
888
|
-
}
|
|
889
|
-
return entries;
|
|
890
|
-
}
|
|
891
|
-
// src/chat/briefs/prompt.ts
|
|
892
|
-
const BRIEF_PROMPT = `You write one durable Brief for a Conversation. The assistant wrote the entries with role \`assistant\`.
|
|
893
|
-
|
|
894
|
-
Use only facts supported by the supplied entries, evidence, or previous Brief. Do not invent names, ids, numbers, outcomes, choices, or links.
|
|
895
|
-
|
|
896
|
-
Rules:
|
|
897
|
-
- Summarize the intent and current outcome in plain prose.
|
|
898
|
-
- Keep earlier decisions unless later entries reverse them. State a reversal as a new decision.
|
|
899
|
-
- A decision is a choice made by a listed participant in this Conversation. It is not a research finding, tool result, action, observation, or suggestion. Put findings in facts or the summary.
|
|
900
|
-
- Set each decision's \`kind\` to \`stated\` when a human participant stated the choice themselves, \`confirmed\` when the assistant proposed it and a human participant explicitly accepted it, or \`assumed\` when the assistant chose while working and no participant confirmed or objected.
|
|
901
|
-
- Set a decision's \`by\` to the participant who made it, or to \`assistant\` for the assistant. Use only names in the supplied record. Set \`by\` to \`null\` when no supported attribution exists.
|
|
902
|
-
- Facts are durable one-line facts that help after the transcript expires. Prefer ids, versions, owners, constraints, and numbers. Do not list fields, recap the transcript, or include transient progress.
|
|
903
|
-
- Ignore the assistant's runtime mechanics and context tags.
|
|
904
|
-
- Never say that a code change was merged, closed, deployed, or released unless a supplied code change or resource has that status. Say opened for an open code change.
|
|
905
|
-
- Choose the outcome status that best describes where the Conversation ended.
|
|
906
|
-
- Follow the supplied size class caps. Keep the first items that matter most.
|
|
907
|
-
- Cite a URL only when its exact full string occurs in an entry, evidence, or the previous Brief. Return cited URLs in \`urls\`. Core adds code changes and resources separately.
|
|
908
|
-
- Keep the summary under 600 characters, intent under 400 characters, outcome text under 600 characters, and each other string under 400 characters.
|
|
909
|
-
`;
|
|
910
|
-
export { JUNIOR_NATIVE_EVENT_NAMESPACE as _, EVENT_SYSTEM_ACTOR as a, conversationNoteEvent as b, generateBrief as c, completeText as d, embedTexts as f, NoAudioError as g, transcribeFromUrl as h, EVENT_MESSAGE_AUTHOR as i, completeDecision as l, searchWeb as m, briefEntriesFromReportEvents as n, eventBotAuthorId as o, generateImages as p, EVENT_AUTHOR_ID as r, isEventConversationMessage as s, BRIEF_PROMPT as t, completeObject as u, agentsInstructionsUpdatedEvent as v, renderJuniorNativeConversationEvent as x, authenticationLinkedEvent as y };
|