@sentry/junior 0.283.0 → 0.285.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 (83) hide show
  1. package/dist/{adapter-D8-lqOBF.js → adapter-DN5AB4VU.js} +37 -3
  2. package/dist/{admin-Dnw5SCXp.js → admin-DOITMKnn.js} +1 -1
  3. package/dist/{agent-runner-Bj7GhysW.js → agent-runner-BsWhHe4N.js} +583 -1655
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +8 -6
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +214 -43
  8. package/dist/{app-CMBP-N43.d.ts → app-DyMs9330.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +230 -187
  11. package/dist/{assistant-reply-CdYsLbXL.js → assistant-reply-9Jip5bsr.js} +1 -1
  12. package/dist/{automation-MLWOrghe.js → automation-Mk8aaHzy.js} +2 -2
  13. package/dist/{background-compaction-queue-Bbsqx8Vm.js → background-compaction-queue-DXkLsWoH.js} +2 -2
  14. package/dist/{briefs-C4qBY-jb.js → briefs-Cl8-nK9B.js} +5 -5
  15. package/dist/{catalog-runtime-B7NRB7eH.js → catalog-runtime-Bte6jRB2.js} +1 -1
  16. package/dist/cli/chat.js +19 -16
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/init.js +3 -0
  19. package/dist/cli/main.js +3 -3
  20. package/dist/cli/plugins.js +4 -4
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +25 -4
  24. package/dist/{client-a3Ib6wxr.js → client-DDbBucBw.js} +2 -2
  25. package/dist/{config-DFVlYCeY.js → config-DqFnykQT.js} +1 -1
  26. package/dist/{connections-BtnvpBEV.js → connections-DA4LT9LL.js} +10 -10
  27. package/dist/{conversation-DdT7SNar.js → conversation-D8kVoCrP.js} +58 -6
  28. package/dist/{conversation-pending-messages-Dct5pheX.js → conversation-pending-messages-BvROq1bq.js} +1 -1
  29. package/dist/{conversation-privacy-DLq-abjU.js → conversation-privacy-D0j_h70R.js} +1 -1
  30. package/dist/{credential-sync-B4XFVcjM.js → credential-sync-hcsYatw-.js} +13 -13
  31. package/dist/{db-A_WrTY-s.d.ts → db-BhHZSuFw.d.ts} +18 -2
  32. package/dist/{executor-HPgHGAWK.js → executor-BLEMIgIZ.js} +29 -4
  33. package/dist/instrumentation.js +37 -13
  34. package/dist/{logging-2BXvW7Mp.js → logging-BfORLKoq.js} +1 -1
  35. package/dist/{message-BG1v1lXX.js → message-DqjuKzUx.js} +13 -23
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +3 -3
  38. package/dist/{oauth-callback-server-CXNZJymo.js → oauth-callback-server-CFSRzu1n.js} +2 -2
  39. package/dist/{projection-BfKkpOGQ.js → projection-DliWYrnT.js} +575 -74
  40. package/dist/{prompt-CCtaGgbI.js → prompt-BvIUzY4y.js} +8 -6
  41. package/dist/push-endpoint-CO-nomUd.js +36 -0
  42. package/dist/{registry-CLooHPAz.js → registry-rC7MCxu8.js} +1 -1
  43. package/dist/{reporting-window-B-QP9zX1.js → reporting-window-B4TwyuJo.js} +14 -14
  44. package/dist/{resolve-D3MK9oRJ.js → resolve-Biu8Qw3u.js} +3 -3
  45. package/dist/result-DxJMCX47.js +299 -0
  46. package/dist/result-event-type-DD6BAgT7.js +11 -0
  47. package/dist/{runner-Ds31u3rB.js → runner-BQJSFLKg.js} +11 -11
  48. package/dist/{sandbox-egress-signals-CLd5RPUw.js → sandbox-egress-signals-6aMxJSDn.js} +1 -1
  49. package/dist/{cadence-R7Em4RjE.js → schedule-BTp__wrw.js} +81 -1
  50. package/dist/{schema-jW3ccLjp.d.ts → schema-BUviRAs8.d.ts} +196 -220
  51. package/dist/{schema-CHNP0GfH.js → schema-BasXTvi2.js} +94 -5
  52. package/dist/{service-account-D6AMahy7.js → service-account-BI5Wgx22.js} +3 -3
  53. package/dist/{service-account-CWpTsoIM.js → service-account-CAE-_1dR.js} +3 -3
  54. package/dist/session-stop-CA-jOJ84.js +2924 -0
  55. package/dist/{skills-DuOKByQH.js → skills-B22duVJU.js} +2 -2
  56. package/dist/{spawn-CNIQGgAS.js → spawn-BB2_4VYn.js} +2 -2
  57. package/dist/{stop-DX2oOIgl.js → stop-DioIcEAu.js} +4830 -4200
  58. package/dist/{store-61mD4ZSh.js → store-B26LV6UP.js} +78 -311
  59. package/dist/{store-DAJntSEv.js → store-Dn4W7qgH.js} +30 -5
  60. package/dist/{task-queue-BE70Pb9p.js → task-queue-Bt0IoR2i.js} +3 -3
  61. package/dist/{task-runner-CmmfddSZ.js → task-runner-D8lddjzp.js} +17 -8
  62. package/dist/{thread-state-0UfRMWYd.js → thread-state-CrFk3K_7.js} +4 -4
  63. package/dist/{turn-failure-response-DKdzxJHE.js → turn-failure-response-DaJ04qVj.js} +7 -7
  64. package/dist/{turn-lifecycle-24sBZ4Ip.js → turn-lifecycle-C2mXS7AZ.js} +1 -1
  65. package/dist/{turn-session-routing-CzCnNAUO.js → turn-session-routing-CGMKrYOj.js} +10 -10
  66. package/dist/{validation-Cs_knhR8.js → validation-TzhfQABF.js} +1 -1
  67. package/dist/{version-ZMC4cXWN.js → version-DSk8CFvA.js} +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist/{viewer-CYB9T4rm.js → viewer-1Ea81s0b.js} +190 -53
  70. package/dist/{work-J1n6RQkY.js → work-ybG4_q5C.js} +238 -32
  71. package/dist/{worker-s1fCvj1z.js → worker-ccSyZRNz.js} +6 -6
  72. package/migrations/0082_push_notifications.sql +14 -0
  73. package/migrations/0083_conversation_kind.sql +11 -0
  74. package/migrations/0084_read_position_backfill.sql +25 -0
  75. package/migrations/0085_child_archived_at.sql +1 -0
  76. package/migrations/meta/0082_snapshot.json +4373 -0
  77. package/migrations/meta/0083_snapshot.json +4388 -0
  78. package/migrations/meta/0084_snapshot.json +4388 -0
  79. package/migrations/meta/0085_snapshot.json +4394 -0
  80. package/migrations/meta/_journal.json +28 -0
  81. package/package.json +7 -5
  82. package/dist/result-BPCjUefO.js +0 -483
  83. package/dist/session-stop-D8LGC3H6.js +0 -1438
@@ -1,4 +1,4 @@
1
- import { H as conversationBriefSchema, U as parseBriefInput, V as briefOutcomeStatusSchema } from "./conversation-DdT7SNar.js";
1
+ import { G as conversationBriefSchema, K as parseBriefInput, U as briefOutcomeStatusSchema } from "./conversation-D8kVoCrP.js";
2
2
  import * as z from "zod";
3
3
  // src/chat/briefs/generate.ts
4
4
  const MAX_INPUT_CHARS = 6e4;
@@ -317,9 +317,9 @@ function hasMergedEvidence(input) {
317
317
  return input.codeChanges.some((change) => change.state === "merged") || input.resources.some((resource) => resource.status?.trim().toLowerCase() === "merged");
318
318
  }
319
319
  /** Build the text indexed for a Brief without adding transcript content. */
320
- function buildBriefSearchText(brief, title) {
321
- return [
322
- title,
320
+ function buildBriefSearchText(brief, input) {
321
+ const values = [
322
+ input.title,
323
323
  brief.summary,
324
324
  brief.intent,
325
325
  brief.outcome.text,
@@ -327,9 +327,11 @@ function buildBriefSearchText(brief, title) {
327
327
  ...brief.facts,
328
328
  ...brief.keywords,
329
329
  ...brief.links.map((link) => link.label),
330
+ ...deterministicLinks(input).map((link) => link.label),
330
331
  ...brief.record.participants.map((participant) => participant.name),
331
332
  ...brief.record.codeChanges.map((change) => `${change.repository}#${change.number} ${change.state}`)
332
- ].filter((value) => Boolean(value?.trim())).join("\n");
333
+ ].filter((value) => Boolean(value?.trim()));
334
+ return [...new Set(values)].join("\n");
333
335
  }
334
336
  /** Generate one bounded Brief and attach only deterministic evidence links. */
335
337
  async function generateBrief(args) {
@@ -382,7 +384,7 @@ async function generateBrief(args) {
382
384
  mergedClaimWithoutEvidence: mergedClaim && hasLinkedEvidence && !hasMergedEvidence(input),
383
385
  resourceCount: input.resources.length
384
386
  },
385
- searchText: buildBriefSearchText(normalized.brief, input.title),
387
+ searchText: buildBriefSearchText(normalized.brief, input),
386
388
  throughIndex: args.throughIndex
387
389
  };
388
390
  }
@@ -0,0 +1,36 @@
1
+ // src/chat/notifications/push-endpoint.ts
2
+ /**
3
+ * Hosts of the browser push services. A push endpoint is a URL that the
4
+ * browser gives us, and Junior sends a POST request to it. Only these hosts
5
+ * are accepted, so a user cannot make Junior send requests to other servers.
6
+ * Add a host here when a browser uses another push service.
7
+ *
8
+ * This module has no imports so the Sentry payload filter can use it during
9
+ * SDK setup.
10
+ */
11
+ const PUSH_SERVICE_HOSTS = [
12
+ "fcm.googleapis.com",
13
+ "push.services.mozilla.com",
14
+ "push.apple.com",
15
+ "notify.windows.com"
16
+ ];
17
+ /** Return true for a known browser push service host or its subdomain. */
18
+ function isPushServiceHost(hostname) {
19
+ const host = hostname.toLowerCase();
20
+ return PUSH_SERVICE_HOSTS.some((allowed) => host === allowed || host.endsWith(`.${allowed}`));
21
+ }
22
+ /**
23
+ * Return true when the endpoint is an HTTPS URL on the default port of a
24
+ * known browser push service host or one of its subdomains.
25
+ */
26
+ function isPushServiceEndpoint(endpoint) {
27
+ let url;
28
+ try {
29
+ url = new URL(endpoint);
30
+ } catch {
31
+ return false;
32
+ }
33
+ if (url.protocol !== "https:" || url.port || url.username || url.password) return false;
34
+ return isPushServiceHost(url.hostname);
35
+ }
36
+ export { isPushServiceHost as n, isPushServiceEndpoint as t };
@@ -1,4 +1,4 @@
1
- import { b as setSpanAttributes, h as logWarn, m as logInfo } from "./logging-2BXvW7Mp.js";
1
+ import { b as setSpanAttributes, h as logWarn, m as logInfo } from "./logging-BfORLKoq.js";
2
2
  import { o as isUserActor, s as parseActorUserId } from "./actor-6jsm_v96.js";
3
3
  import { n as normalizePluginPackageNames, o as pluginRoots, t as discoverInstalledPluginPackageContent } from "./package-discovery-DJhGdS4c.js";
4
4
  import path from "node:path";
@@ -32,15 +32,6 @@ const AGENT_INVOCATION_PARENT_MAILBOX_STATUSES = [
32
32
  "skipped",
33
33
  "steered"
34
34
  ];
35
- // src/chat/conversations/web-message-id.ts
36
- /**
37
- * Build the retry-stable Message id shared by web ingress and browser sends.
38
- * Keep the existing hash and prefix so retries still address stored Messages.
39
- */
40
- async function webMessageId(args) {
41
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${args.conversationId}\u0000${args.idempotencyKey}`));
42
- return `api-msg:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 24)}`;
43
- }
44
35
  // src/chat/tools/runtime/user-input-request.ts
45
36
  const USER_INPUT_LIMITS = {
46
37
  maxButtonOptions: 5,
@@ -154,13 +145,13 @@ function answerLine(text) {
154
145
  return text.split("\n").map((line) => line.trim()).filter(Boolean).join("\n");
155
146
  }
156
147
  /**
157
- * Write an answer as the text of the person's message. Slack and the web
158
- * dashboard both send this text, so the model reads one format. The first
159
- * line names the request, and each field starts its own line.
148
+ * Write the fields of an answer, one `Label (field_id): value` line each.
149
+ * Slack, the web dashboard, and the prompt all use this text, so the model
150
+ * reads one format.
160
151
  */
161
152
  function formatUserInputAnswer(request, answer) {
162
153
  const normalized = normalizeUserInputAnswer(request, answer);
163
- const lines = [`Answer to request ${normalized.requestId}:`];
154
+ const lines = [];
164
155
  for (const field of request.fields) {
165
156
  const values = normalized.values[field.id];
166
157
  const value = values?.length ? values.join(", ") : "(no answer)";
@@ -169,6 +160,15 @@ function formatUserInputAnswer(request, answer) {
169
160
  if (normalized.other) lines.push(answerLine(`Other: ${normalized.other}`));
170
161
  return lines.join("\n");
171
162
  }
163
+ // src/chat/conversations/web-message-id.ts
164
+ /**
165
+ * Build the retry-stable Message id shared by web ingress and browser sends.
166
+ * Keep the existing hash and prefix so retries still address stored Messages.
167
+ */
168
+ async function webMessageId(args) {
169
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`${args.conversationId}\u0000${args.idempotencyKey}`));
170
+ return `api-msg:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 24)}`;
171
+ }
172
172
  // src/api/reporting-window.ts
173
173
  /** Shared UTC day/hour/six-hour windows for dashboard activity series. */
174
174
  const HOUR_MS = 36e5;
@@ -292,4 +292,4 @@ function sumUtcHoursIntoSixHours(args) {
292
292
  rows: bySix
293
293
  });
294
294
  }
295
- export { AGENT_INVOCATION_STATUSES as C, userCustomizationTextSchema as E, AGENT_INVOCATION_PARENT_MAILBOX_STATUSES as S, userCustomizationSchema as T, isEmptyUserInputAnswer as _, fillUtcSixHours as a, webMessageId as b, trailingUtcDayWindow as c, utcDayKey as d, utcHourKey as f, formatUserInputAnswer as g, buttonUserInputField as h, fillUtcHours as i, trailingUtcHourWindow as l, USER_INPUT_NOTE as m, HOUR_MS as n, startOfUtcHour as o, USER_INPUT_LIMITS as p, fillUtcDays as r, sumUtcHoursIntoSixHours as s, DAY_MS as t, trailingUtcSixHourWindow as u, normalizeUserInputAnswer as v, USER_CUSTOMIZATION_MAX_CHARS as w, AGENT_INVOCATION_MAILBOX_STATUSES as x, userInputRequestSchema as y };
295
+ export { AGENT_INVOCATION_STATUSES as C, userCustomizationTextSchema as E, AGENT_INVOCATION_PARENT_MAILBOX_STATUSES as S, userCustomizationSchema as T, formatUserInputAnswer as _, fillUtcSixHours as a, userInputRequestSchema as b, trailingUtcDayWindow as c, utcDayKey as d, utcHourKey as f, buttonUserInputField as g, USER_INPUT_NOTE as h, fillUtcHours as i, trailingUtcHourWindow as l, USER_INPUT_LIMITS as m, HOUR_MS as n, startOfUtcHour as o, webMessageId as p, fillUtcDays as r, sumUtcHoursIntoSixHours as s, DAY_MS as t, trailingUtcSixHourWindow as u, isEmptyUserInputAnswer as v, USER_CUSTOMIZATION_MAX_CHARS as w, AGENT_INVOCATION_MAILBOX_STATUSES as x, normalizeUserInputAnswer as y };
@@ -1,6 +1,6 @@
1
- import { Oa as runNonInteractiveCommand, Sa as SANDBOX_WORKSPACE_ROOT, _a as SANDBOX_COMMAND_PATH, ai as create, da as sleep, li as getSandboxProvider, si as isStale } from "./projection-BfKkpOGQ.js";
2
- import { E as withSpan, b as setSpanAttributes } from "./logging-2BXvW7Mp.js";
3
- import { r as getStateAdapter } from "./adapter-D8-lqOBF.js";
1
+ import { Di as isStale, La as SANDBOX_COMMAND_PATH, Ti as create, Va as SANDBOX_WORKSPACE_ROOT, ja as sleep, ki as getSandboxProvider, qa as runNonInteractiveCommand } from "./projection-DliWYrnT.js";
2
+ import { E as withSpan, b as setSpanAttributes } from "./logging-BfORLKoq.js";
3
+ import { r as getStateAdapter } from "./adapter-DN5AB4VU.js";
4
4
  import * as z from "zod";
5
5
  // src/chat/sandbox/resources.ts
6
6
  let configuredResources;
@@ -0,0 +1,299 @@
1
+ import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
+ import { _n as renderUntrustedTag } from "./projection-DliWYrnT.js";
3
+ import { H as SYSTEM_IDENTITY_ID } from "./viewer-1Ea81s0b.js";
4
+ import { f as credentialContextForActor } from "./registry-rC7MCxu8.js";
5
+ import { jt as listUnreportedSiblingAgents } from "./agent-runner-BsWhHe4N.js";
6
+ import { A as getAgentInvocationIdForEvents, M as getAgentInvocationIdForResult, P as getAgentInvocationResultMessageId, a as getAgentInvocation, h as markAgentInvocationParentMailboxAppended, j as getAgentInvocationIdForMessage, l as isTerminalAgentInvocation, s as getLatestAgentInvocationForConversation } from "./store-B26LV6UP.js";
7
+ import { C as isEventMailboxMetadata, T as timerWatchCredentialSubject, b as EVENT_WAIT_MS, d as getEventBatchDelayMs, n as isWatchEvent, p as parseEventMessages, s as eventReviewItemInputs, w as renderEventBatchInputs } from "./session-stop-CA-jOJ84.js";
8
+ import { r as appendAndEnqueueInboundMessage } from "./store-Dn4W7qgH.js";
9
+ import { a as resolveAgentInvocationId, i as enqueueAgentInvocation, l as createAgentInvocationFromLatest, t as createAgentInvocationWorker } from "./work-ybG4_q5C.js";
10
+ import { n as isAgentInvocationResultEventType, t as agentInvocationResultEventType } from "./result-event-type-DD6BAgT7.js";
11
+ // src/chat/agent-invocations/result.ts
12
+ var result_exports = /* @__PURE__ */ __exportAll({
13
+ createChildConversationWorker: () => createChildConversationWorker,
14
+ enqueueAgentInvocationResult: () => enqueueAgentInvocationResult,
15
+ enqueueAgentMessageToParent: () => enqueueAgentMessageToParent,
16
+ withAgentInvocationResultActors: () => withAgentInvocationResultActors
17
+ });
18
+ const AGENT_INVOCATION_EVENT_NAMESPACE = "junior";
19
+ const AGENT_INVOCATION_RESULT_MAX_LENGTH = 12e3;
20
+ /** Event type of a message that a child agent sends to its parent. */
21
+ const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
22
+ /**
23
+ * Return the Inbound message author id for results sent by one Actor.
24
+ * `selectContiguousTurnBatch` in `task-execution/worker.ts` puts messages in
25
+ * one attempt only when their author ids and sources match. Mid-Turn drains
26
+ * take only `interrupt` messages, and results are `defer`. So results never
27
+ * share a Turn and its credentials with another Actor or with watch Events.
28
+ * Keep this id unique per Actor if either rule changes.
29
+ */
30
+ function resultAuthorId(actor) {
31
+ switch (actor.platform) {
32
+ case "system": return `agent-invocation:system:${actor.name}`;
33
+ case "slack": return `agent-invocation:slack:${actor.teamId}:${actor.userId}`;
34
+ default: return `agent-invocation:${actor.platform}:${actor.userId}`;
35
+ }
36
+ }
37
+ /**
38
+ * Error messages can contain text from tools or providers, so the trusted
39
+ * summary in the mailbox metadata has only the status.
40
+ */
41
+ function trustedSummary(invocation, agent) {
42
+ switch (invocation.status) {
43
+ case "completed": return `${agent} finished its task.`;
44
+ case "blocked": return `${agent} is blocked.`;
45
+ case "failed": return `${agent} failed.`;
46
+ case "stopped": return `${agent} was stopped.`;
47
+ }
48
+ }
49
+ /**
50
+ * Render the parent agent input for one terminal agent invocation as one
51
+ * `<agent-result>`. A child agent wrote the output, so it is escaped data.
52
+ * `status` and `waiting_on` are runtime facts. The system prompt says what to
53
+ * do for each status, so the input repeats no guidance.
54
+ */
55
+ function renderResultInput(invocation, openSiblings) {
56
+ const output = (invocation.status === "completed" ? invocation.result : invocation.errorMessage).trim().slice(0, AGENT_INVOCATION_RESULT_MAX_LENGTH);
57
+ return renderUntrustedTag("agent-result", {
58
+ conversation_id: invocation.childConversationId,
59
+ name: invocation.agentName,
60
+ source: "child_agent",
61
+ status: invocation.status,
62
+ title: invocation.title,
63
+ waiting_on: openSiblings.length ? openSiblings.map(siblingLabel).join(", ") : void 0
64
+ }, "A child agent that you started", output || "(empty)");
65
+ }
66
+ function siblingLabel(sibling) {
67
+ return sibling.agentName ?? sibling.title ?? sibling.childConversationId;
68
+ }
69
+ /** Build the parent Inbound message for one terminal agent invocation. */
70
+ function buildResultInboundMessage(invocation, nowMs, openSiblings) {
71
+ const summary = trustedSummary(invocation, childAgentLabel(invocation));
72
+ const metadata = {
73
+ kind: "event",
74
+ event: {
75
+ eventKey: invocation.invocationId,
76
+ eventType: agentInvocationResultEventType(invocation.status),
77
+ identifier: invocation.invocationId,
78
+ namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
79
+ trustedSummary: summary
80
+ }
81
+ };
82
+ return {
83
+ conversationId: invocation.parentConversationId,
84
+ createdAtMs: invocation.terminalAtMs,
85
+ delivery: "defer",
86
+ inboundMessageId: getAgentInvocationResultMessageId(invocation.invocationId),
87
+ input: {
88
+ authorId: resultAuthorId(invocation.actor),
89
+ authorIdentityId: SYSTEM_IDENTITY_ID,
90
+ metadata,
91
+ text: renderResultInput(invocation, openSiblings)
92
+ },
93
+ receivedAtMs: nowMs,
94
+ source: "event"
95
+ };
96
+ }
97
+ /**
98
+ * Append one terminal agent invocation result to the parent mailbox and wake
99
+ * the parent. Repeat calls are safe.
100
+ *
101
+ * Results do not go through `admitAutomatedTurn`, so the automated-turn limit
102
+ * never drops them. Result Turns still count toward that limit.
103
+ * TODO(dcramer): Add a per-parent total invocation limit as the loop guard
104
+ * for spawn -> result -> spawn chains (#881).
105
+ */
106
+ async function enqueueAgentInvocationResult(invocation, options) {
107
+ if (invocation.parentMailboxStatus !== "pending") return;
108
+ const nowMs = options.nowMs ?? Date.now();
109
+ const openSiblings = await listUnreportedSiblingAgents(invocation.parentConversationId, invocation.childConversationId);
110
+ await appendAndEnqueueInboundMessage({
111
+ message: buildResultInboundMessage(invocation, nowMs, openSiblings),
112
+ queue: options.queue,
113
+ queueDelayMs: EVENT_WAIT_MS,
114
+ state: options.state
115
+ });
116
+ await markAgentInvocationParentMailboxAppended(invocation.invocationId, nowMs);
117
+ }
118
+ function childAgentLabel(invocation) {
119
+ return invocation.agentName ? `Child agent "${invocation.agentName}"` : "Child agent";
120
+ }
121
+ function renderMessageInput(sender, text) {
122
+ return renderUntrustedTag("agent-message", {
123
+ conversation_id: sender.childConversationId,
124
+ name: sender.agentName,
125
+ source: "child_agent",
126
+ title: sender.title
127
+ }, "A child agent that you started", text.trim());
128
+ }
129
+ /**
130
+ * Append one message from a child agent to its parent mailbox and wake the
131
+ * parent. `sender` is the open agent invocation of the child. The parent
132
+ * handles the message like a result: a root parent runs an Event Turn, and a
133
+ * child parent starts a new agent invocation. Repeat calls with the same
134
+ * `messageKey` are safe.
135
+ */
136
+ async function enqueueAgentMessageToParent(args) {
137
+ const nowMs = args.nowMs ?? Date.now();
138
+ const inboundMessageId = `agent-invocation:${args.sender.invocationId}:message:${args.messageKey}`;
139
+ const summary = `${childAgentLabel(args.sender)} sent a message.`;
140
+ const metadata = {
141
+ kind: "event",
142
+ event: {
143
+ eventKey: inboundMessageId,
144
+ eventType: AGENT_MESSAGE_EVENT_TYPE,
145
+ identifier: args.sender.invocationId,
146
+ namespace: AGENT_INVOCATION_EVENT_NAMESPACE,
147
+ trustedSummary: summary
148
+ }
149
+ };
150
+ await appendAndEnqueueInboundMessage({
151
+ message: {
152
+ conversationId: args.sender.parentConversationId,
153
+ createdAtMs: nowMs,
154
+ delivery: "defer",
155
+ inboundMessageId,
156
+ input: {
157
+ authorId: resultAuthorId(args.sender.actor),
158
+ authorIdentityId: SYSTEM_IDENTITY_ID,
159
+ metadata,
160
+ text: renderMessageInput(args.sender, args.text)
161
+ },
162
+ receivedAtMs: nowMs,
163
+ source: "event"
164
+ },
165
+ queue: args.queue,
166
+ queueDelayMs: EVENT_WAIT_MS,
167
+ state: args.state
168
+ });
169
+ }
170
+ /**
171
+ * Read the agent invocation that one result or message Event refers to: the
172
+ * finished child work for a result, or the open sender work for a message.
173
+ */
174
+ function childAgentInput(message) {
175
+ const metadata = message.input.metadata;
176
+ if (!isEventMailboxMetadata(metadata) || metadata.event.namespace !== AGENT_INVOCATION_EVENT_NAMESPACE) return;
177
+ if (metadata.event.eventType === AGENT_MESSAGE_EVENT_TYPE) return {
178
+ invocationId: metadata.event.identifier,
179
+ kind: "message"
180
+ };
181
+ return isAgentInvocationResultEventType(metadata.event.eventType) ? {
182
+ invocationId: metadata.event.identifier,
183
+ kind: "result"
184
+ } : void 0;
185
+ }
186
+ /**
187
+ * Return whether a stop after this result was sent skipped it, so it starts no
188
+ * work. A message that a child sent before its stop is still delivered.
189
+ */
190
+ function isSkippedAgentResult(input, invocation) {
191
+ return input.kind === "result" && isTerminalAgentInvocation(invocation) && invocation.parentMailboxStatus === "skipped";
192
+ }
193
+ /**
194
+ * Read the agent invocation of one result or message and check that it
195
+ * belongs to a child of the Conversation that received it.
196
+ */
197
+ async function getChildAgentInputInvocation(message, input) {
198
+ const invocation = await getAgentInvocation(input.invocationId);
199
+ if (!invocation || input.kind === "result" && !isTerminalAgentInvocation(invocation) || invocation.parentConversationId !== message.conversationId) throw new Error(`Agent invocation ${input.kind} ${input.invocationId} does not belong to ${message.conversationId}`);
200
+ return invocation;
201
+ }
202
+ /**
203
+ * Give mailbox input that reaches a child Conversation to that child: results
204
+ * and messages from its own child agents, and its own watch events. A child
205
+ * Conversation has no Location, so it cannot run an Event Turn. Each input
206
+ * starts a new agent invocation on the child instead, and that invocation
207
+ * reports to the child's parent. Returns undefined for work that is not
208
+ * mailbox input for a child Conversation.
209
+ */
210
+ async function startAgentInvocationsForChildInput(context, options) {
211
+ const messages = context.attempt.messages;
212
+ const inputs = messages.map(childAgentInput);
213
+ const isAgentInput = inputs.every((input) => input !== void 0);
214
+ const events = isAgentInput ? [] : parseEventMessages(messages);
215
+ if (messages.length === 0 || !isAgentInput && events.length === 0) return;
216
+ const latest = await getLatestAgentInvocationForConversation(context.conversationId);
217
+ if (!latest) return;
218
+ if ((latest.status === "stopped" || isTerminalAgentInvocation(latest) && latest.parentMailboxStatus === "skipped") && (isAgentInput || !messages.every(isWatchEvent))) {
219
+ await context.attempt.ack();
220
+ return { status: "completed" };
221
+ }
222
+ if (!isAgentInput) {
223
+ const delayMs = getEventBatchDelayMs(messages);
224
+ if (delayMs > 0) return {
225
+ status: "deferred",
226
+ delayMs
227
+ };
228
+ const { actor, source } = events[0];
229
+ const invocation = await createAgentInvocationFromLatest({
230
+ input: renderEventBatchInputs(messages, await eventReviewItemInputs(messages)).join("\n\n"),
231
+ invocationId: getAgentInvocationIdForEvents(messages[0].inboundMessageId),
232
+ latest,
233
+ runAs: {
234
+ actor,
235
+ credentialContext: credentialContextForActor(actor, timerWatchCredentialSubject(context.conversationId, messages)),
236
+ source
237
+ }
238
+ });
239
+ await enqueueAgentInvocation(invocation, options);
240
+ await context.attempt.ack();
241
+ return { status: "completed" };
242
+ }
243
+ for (const [index, message] of messages.entries()) {
244
+ const input = inputs[index];
245
+ const source = await getChildAgentInputInvocation(message, input);
246
+ if (isSkippedAgentResult(input, source)) continue;
247
+ const invocation = await createAgentInvocationFromLatest({
248
+ input: message.input.text.trim(),
249
+ invocationId: input.kind === "result" ? getAgentInvocationIdForResult(source.invocationId) : getAgentInvocationIdForMessage(message.inboundMessageId),
250
+ latest
251
+ });
252
+ await enqueueAgentInvocation(invocation, options);
253
+ }
254
+ await context.attempt.ack();
255
+ return { status: "completed" };
256
+ }
257
+ /**
258
+ * Build the worker for all work of a child Conversation. The caller selects
259
+ * it from the stored parent of the Conversation, never from a Turn Source. It
260
+ * starts agent invocations for child input, then runs the agent invocation
261
+ * that owns the work. Work that no agent invocation owns is an error.
262
+ */
263
+ function createChildConversationWorker(agentRunner, options) {
264
+ const invocationWorker = createAgentInvocationWorker(agentRunner, options);
265
+ return async (context) => {
266
+ const started = await startAgentInvocationsForChildInput(context, options);
267
+ if (started) return started;
268
+ const invocationId = await resolveAgentInvocationId(context);
269
+ if (!invocationId) throw new Error(`Child conversation ${context.conversationId} has no agent invocation for this work`);
270
+ return await invocationWorker(context, invocationId);
271
+ };
272
+ }
273
+ /**
274
+ * Run each agent invocation result or message as the Actor that triggered the
275
+ * child, user or system. This is on purpose: the result continues that
276
+ * Actor's work. The Actor comes from SQL, not from mailbox metadata, so the
277
+ * parent Turn has the same authority it had at spawn time. A result that a
278
+ * stop skipped is dropped. Returns undefined when no input is left.
279
+ *
280
+ * TODO(dcramer): Pass the delegated credential subject of a system Actor, such
281
+ * as a timer watch Turn, when system Turns can spawn children that need it.
282
+ */
283
+ async function withAgentInvocationResultActors(work) {
284
+ if (work.kind !== "mailbox") return work;
285
+ const kept = (await Promise.all(work.batch.map(async (entry) => {
286
+ const input = childAgentInput(entry.message);
287
+ if (!input) return entry;
288
+ const invocation = await getChildAgentInputInvocation(entry.message, input);
289
+ return isSkippedAgentResult(input, invocation) ? void 0 : {
290
+ ...entry,
291
+ actor: invocation.actor
292
+ };
293
+ }))).filter((entry) => entry !== void 0);
294
+ return kept.length > 0 ? {
295
+ kind: "mailbox",
296
+ batch: kept
297
+ } : void 0;
298
+ }
299
+ export { withAgentInvocationResultActors as a, result_exports as i, enqueueAgentInvocationResult as n, enqueueAgentMessageToParent as r, createChildConversationWorker as t };
@@ -0,0 +1,11 @@
1
+ // src/chat/agent-invocations/result-event-type.ts
2
+ const AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
3
+ /** Build the Event type of the parent message for one agent invocation result. */
4
+ function agentInvocationResultEventType(status) {
5
+ return `${AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX}${status}`;
6
+ }
7
+ /** True when an Event type names an agent invocation result. */
8
+ function isAgentInvocationResultEventType(eventType) {
9
+ return eventType.startsWith(AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX);
10
+ }
11
+ export { isAgentInvocationResultEventType as n, agentInvocationResultEventType as t };
@@ -1,14 +1,14 @@
1
- import { B as authorizationId, D as buildConversationContext, I as upsertConversationMessage, M as markConversationMessage, N as normalizeConversationText, P as recordDeliveredAssistantMessage, Ut as persistWithRetry, Z as saveTurnCheckpoint, a as loadProjection, d as recordAuthorizationCompleted, t as commitAcceptedReply, v as hydrateConversationMessages, y as persistConversationMessages } from "./projection-BfKkpOGQ.js";
2
- import { S as setTags, T as withLogContext, p as logException } from "./logging-2BXvW7Mp.js";
3
- import { F as SYSTEM_IDENTITY_ID, x as getConversationStore, y as getConversationEventStore } from "./viewer-CYB9T4rm.js";
4
- import { f as credentialContextForActor } from "./registry-CLooHPAz.js";
5
- import { j as messageCardText } from "./conversation-DdT7SNar.js";
6
- import { $ as markTurnFailed, et as startActiveTurn } from "./store-61mD4ZSh.js";
7
- import { n as getAssistantReplyText } from "./assistant-reply-CdYsLbXL.js";
8
- import { t as ConversationTurnLifecycleService } from "./turn-lifecycle-24sBZ4Ip.js";
9
- import { a as persistThreadStateById, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState } from "./thread-state-0UfRMWYd.js";
10
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-CmmfddSZ.js";
11
- import { i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response-DKdzxJHE.js";
1
+ import { F as recordDeliveredAssistantMessage, L as upsertConversationMessage, N as markConversationMessage, O as buildConversationContext, P as normalizeConversationText, Q as saveTurnCheckpoint, V as authorizationId, a as loadProjection, d as recordAuthorizationCompleted, qt as persistWithRetry, t as commitAcceptedReply, v as hydrateConversationMessages, y as persistConversationMessages } from "./projection-DliWYrnT.js";
2
+ import { S as setTags, T as withLogContext, p as logException } from "./logging-BfORLKoq.js";
3
+ import { H as SYSTEM_IDENTITY_ID, x as getConversationStore, y as getConversationEventStore } from "./viewer-1Ea81s0b.js";
4
+ import { f as credentialContextForActor } from "./registry-rC7MCxu8.js";
5
+ import { N as messageCardText } from "./conversation-D8kVoCrP.js";
6
+ import { X as markTurnFailed, Z as startActiveTurn } from "./store-B26LV6UP.js";
7
+ import { n as getAssistantReplyText } from "./assistant-reply-9Jip5bsr.js";
8
+ import { t as ConversationTurnLifecycleService } from "./turn-lifecycle-C2mXS7AZ.js";
9
+ import { a as persistThreadStateById, n as getPersistedSandboxState, o as coerceThreadConversationState, r as getPersistedThreadState } from "./thread-state-CrFk3K_7.js";
10
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-D8lddjzp.js";
11
+ import { i as completeAuthPauseTurn, l as buildDeliveredTurnStatePatch, t as finalizeFailedTurnReplyWithEvent, u as loadPendingMessageCards } from "./turn-failure-response-DaJ04qVj.js";
12
12
  import { randomUUID } from "node:crypto";
13
13
  import { createLocalSource, localDestinationSchema } from "@sentry/junior-plugin-api";
14
14
  // src/chat/local/runner.ts
@@ -1,4 +1,4 @@
1
- import { oa as sandboxEgressSignalsResponseSchema } from "./projection-BfKkpOGQ.js";
1
+ import { Ea as sandboxEgressSignalsResponseSchema } from "./projection-DliWYrnT.js";
2
2
  // src/chat/local/sandbox-egress-signals.ts
3
3
  const SANDBOX_EGRESS_SIGNALS_PATH = "/api/internal/sandbox-egress/signals";
4
4
  const LOCAL_DEV_SERVER_TIMEOUT_MS = 1e3;
@@ -1,3 +1,4 @@
1
+ import * as z from "zod";
1
2
  // src/chat/scheduled-automations/cadence.ts
2
3
  const FORMATTERS = /* @__PURE__ */ new Map();
3
4
  function getFormatter(timezone) {
@@ -252,4 +253,83 @@ function getNextRunAtMs(task, scheduledForMs, afterMs = scheduledForMs) {
252
253
  timezone
253
254
  });
254
255
  }
255
- export { resolveLocalScheduleAtMs as a, isValidTimeZone as i, getNextRunAtMs as n, getZonedDateTimeParts as r, getFirstRunAtMs as t };
256
+ // src/chat/notifications/schedule.ts
257
+ /**
258
+ * Notification hours for one user.
259
+ *
260
+ * This module imports only zod and the browser-safe cadence helpers, so the
261
+ * dashboard client bundle can use it.
262
+ */
263
+ const clockTimePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
264
+ /** Saved notification hours. Weekdays use 0 for Sunday, like `Date#getDay`. */
265
+ const notificationScheduleSchema = z.object({
266
+ /** When false, Junior sends phone notifications at any time. */
267
+ workingHoursOnly: z.boolean(),
268
+ days: z.array(z.number().int().min(0).max(6)).max(7).refine((days) => new Set(days).size === days.length, { message: "Days must be unique." }),
269
+ /** Local start time, `HH:MM`. */
270
+ start: z.string().regex(clockTimePattern),
271
+ /** Local end time, `HH:MM`. An end before the start crosses midnight. */
272
+ end: z.string().regex(clockTimePattern),
273
+ /** IANA timezone set by the user. Absent means the profile timezone. */
274
+ timezone: z.string().min(1).max(64).refine(isValidTimeZone, { message: "Unknown timezone." }).optional()
275
+ }).strict().refine((schedule) => schedule.start !== schedule.end, {
276
+ message: "Start and end must differ.",
277
+ path: ["end"]
278
+ });
279
+ /** Default hours when a user has not saved a schedule: 09:00–18:00, Mon–Fri. */
280
+ const DEFAULT_NOTIFICATION_SCHEDULE = {
281
+ workingHoursOnly: true,
282
+ days: [
283
+ 1,
284
+ 2,
285
+ 3,
286
+ 4,
287
+ 5
288
+ ],
289
+ start: "09:00",
290
+ end: "18:00"
291
+ };
292
+ function clockMinutes(value) {
293
+ const [hours, minutes] = value.split(":").map(Number);
294
+ return hours * 60 + minutes;
295
+ }
296
+ const weekdayIndex = {
297
+ Sun: 0,
298
+ Mon: 1,
299
+ Tue: 2,
300
+ Wed: 3,
301
+ Thu: 4,
302
+ Fri: 5,
303
+ Sat: 6
304
+ };
305
+ function localWeekdayAndMinutes(nowMs, timezone) {
306
+ const parts = new Intl.DateTimeFormat("en-US", {
307
+ hour: "2-digit",
308
+ hourCycle: "h23",
309
+ minute: "2-digit",
310
+ timeZone: timezone,
311
+ weekday: "short"
312
+ }).formatToParts(new Date(nowMs));
313
+ const value = (type) => parts.find((part) => part.type === type)?.value ?? "";
314
+ const weekday = weekdayIndex[value("weekday")];
315
+ if (weekday === void 0) throw new Error(`Could not read the weekday for timezone ${timezone}`);
316
+ return {
317
+ minutes: Number(value("hour")) % 24 * 60 + Number(value("minute")),
318
+ weekday
319
+ };
320
+ }
321
+ /**
322
+ * Return whether a notification may be sent now. A window that crosses
323
+ * midnight belongs to the day on which it starts.
324
+ */
325
+ function isWithinNotificationSchedule(schedule, timezone, nowMs) {
326
+ if (!schedule.workingHoursOnly) return true;
327
+ const { minutes, weekday } = localWeekdayAndMinutes(nowMs, timezone);
328
+ const start = clockMinutes(schedule.start);
329
+ const end = clockMinutes(schedule.end);
330
+ if (start < end) return schedule.days.includes(weekday) && minutes >= start && minutes < end;
331
+ if (minutes >= start) return schedule.days.includes(weekday);
332
+ if (minutes < end) return schedule.days.includes((weekday + 6) % 7);
333
+ return false;
334
+ }
335
+ export { getNextRunAtMs as a, resolveLocalScheduleAtMs as c, getFirstRunAtMs as i, isWithinNotificationSchedule as n, getZonedDateTimeParts as o, notificationScheduleSchema as r, isValidTimeZone as s, DEFAULT_NOTIFICATION_SCHEDULE as t };