@sentry/junior 0.316.0 → 0.318.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 (124) hide show
  1. package/dist/{admin-QYiDMnsu.js → admin-UOHix_5P.js} +1 -1
  2. package/dist/{agent-runner-Cr5Fhjf-.js → agent-runner-DeYymwh2.js} +13494 -13135
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BY13DPSD.js → agent-update-delivery-DH8bx7jU.js} +5 -5
  5. package/dist/api/schema.d.ts +600 -130
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +228 -214
  8. package/dist/{app-BhvzRD__.d.ts → app-DKAOuaoC.d.ts} +33 -18
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +193 -177
  11. package/dist/{thread-context-fiMNylbg.js → auth-pause-state-f9hJM_zO.js} +6 -59
  12. package/dist/catalog-runtime-BfdAnztW.js +6 -0
  13. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  14. package/dist/{adapter-context-Bref7aPI.js → channel-access-A0de5lRv.js} +2 -42
  15. package/dist/{chat-core-engine-3dtlMku3.js → chat-core-engine-D3Wd7f5n.js} +6 -5
  16. package/dist/{child-message--2G3Ft26.js → child-message-peFWLcCZ.js} +2 -6
  17. package/dist/cli/chat.js +38 -30
  18. package/dist/cli/check.js +5 -5
  19. package/dist/cli/main.js +2 -2
  20. package/dist/cli/plugins.js +5 -4
  21. package/dist/cli/snapshot-create.js +4 -2
  22. package/dist/cli/upgrade.js +5 -3
  23. package/dist/context-BKF_5zzI.js +1833 -0
  24. package/dist/{continue-in-slack-DbQUFe_F.js → continue-in-slack-YxwMQVeR.js} +3 -3
  25. package/dist/{conversation-feed-B84pMjHo.js → conversation-feed-Cj7IuBtM.js} +3 -3
  26. package/dist/{proxy-path-BTmXDjfx.js → conversation-privacy-Cr_dNW1p.js} +2 -16
  27. package/dist/{conversation-turn-DzEpTIaf.js → conversation-turn-Bru4w_FD.js} +196 -80
  28. package/dist/{create-DUJBXr6E.js → create-Btl1y1rq.js} +12 -11
  29. package/dist/{credential-sync-JH_K9Adg.js → credential-sync-DTarZ63K.js} +20 -15
  30. package/dist/{db-DhzvUY23.js → db-of6e3sGt.js} +20724 -27256
  31. package/dist/{deployment-BhvrhQeh.js → deployment-C0qXa0FD.js} +17 -15
  32. package/dist/{engine-context-C9Nal48K.js → engine-context-C_QL_bMQ.js} +304 -56
  33. package/dist/{html-B_12WjKT.js → html-9_pS9SjY.js} +6 -2
  34. package/dist/instrumentation.js +15 -7
  35. package/dist/{job-runner-DO8nslyY.js → job-runner-B2XEvpif.js} +392 -26
  36. package/dist/{lineage-D3AZAJVe.js → lineage-nh4z9iQN.js} +1 -1
  37. package/dist/{list-B0zsb5Cp.js → list-HRP3TIRl.js} +238 -550
  38. package/dist/{logging-B8KEJegM.js → logging-BnOG0qz2.js} +4 -50
  39. package/dist/{session-stop-DponjDUZ.js → mailbox-turn-Byrry9o1.js} +4807 -7102
  40. package/dist/{list-mkB_GU8R.js → markers-CTTtJqYn.js} +171 -124
  41. package/dist/{message-B5fKDYzz.js → message-BRUuLgrY.js} +13 -24
  42. package/dist/{model-input-CuMWy37l.js → model-input-CFC62mf-.js} +3 -3
  43. package/dist/nitro.d.ts +1 -1
  44. package/dist/nitro.js +21 -7
  45. package/dist/{oauth-callback-server-B3Vvlydo.js → oauth-callback-server-CjnnUr4o.js} +2 -2
  46. package/dist/{oauth-relay-6ERrGPbA.js → oauth-relay-BvHFH0fV.js} +2 -2
  47. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  48. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  49. package/dist/profile-iHw1uu32.js +4657 -0
  50. package/dist/{transcript-CCi7323k.js → prompt-DEkStuxG.js} +92 -98
  51. package/dist/proxy-path-BHYoKZdq.js +15 -0
  52. package/dist/registry-Cl7Labpe.js +3279 -0
  53. package/dist/reports-C1d9azyV.js +195 -0
  54. package/dist/{resolve-D5JVvv6A.js → resolve-DC6zBuDV.js} +9 -29
  55. package/dist/{result-CS_7mo8a.js → result-DxewDuXb.js} +27 -118
  56. package/dist/run-conversation-Cz2ubZK-.js +337 -0
  57. package/dist/{runner-BzAES5W3.js → runner-99YxVN_r.js} +10 -18
  58. package/dist/{sandbox-egress-signals-Dwhk2Q5F.js → sandbox-egress-signals-CgoX5CTI.js} +1 -1
  59. package/dist/{schema-z5-wA6N4.js → schema-BTojNBr5.js} +48 -86
  60. package/dist/sender-actors-77zTQbSG.js +84 -0
  61. package/dist/{service-account-D6AsAtc1.js → service-account-YDCPSByj.js} +3 -1
  62. package/dist/{skills-DgJ9GBPR.js → skills-CleC0Hze.js} +6 -5
  63. package/dist/{slack-conversation-unfurl-Dq71EkhM.js → slack-conversation-unfurl-BNQLC12R.js} +7 -6
  64. package/dist/{spawn-BJWpdwhQ.js → spawn-DuZfodPa.js} +5 -5
  65. package/dist/{system-prompt-table-iIgpmslr.js → system-prompt-table-Ci6Ck4gk.js} +88 -69
  66. package/dist/{task-runner-BJae4JwE.js → task-runner-BJ9Up3bG.js} +30 -53
  67. package/dist/topics-BoCkoPJJ.js +21 -0
  68. package/dist/turn-membership-VT7XZh-L.js +856 -0
  69. package/dist/{turn-wake-BjDW7x-5.js → turn-wake-C7HeLHAM.js} +3 -4
  70. package/dist/{media-BebquhET.js → types-DCzTAA63.js} +629 -593
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-Cb9c1k9q.js +181 -0
  73. package/dist/{validation-D5WmmmhX.js → validation-BiUmWPhy.js} +1 -1
  74. package/dist/{version-CBQoanXb.js → version-VEXiEcZu.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-Cyb4kF17.js → worker-ChWYQdhm.js} +5 -4
  77. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  78. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  79. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  80. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  81. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  82. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  83. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  84. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  85. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  86. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  87. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  88. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  89. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  90. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  91. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  92. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  93. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  94. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  95. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  96. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  97. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  98. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  99. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  100. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  101. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  102. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  103. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  104. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  105. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  106. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  107. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  108. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  109. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  110. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  111. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  112. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  113. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  114. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  115. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  116. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  117. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  118. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  119. package/package.json +5 -5
  120. package/dist/people-CUtFApfL.js +0 -81
  121. package/dist/start-conversation-B-LIqqNi.js +0 -162
  122. package/dist/turn-session-routing-D15orfwy.js +0 -1309
  123. package/dist/user-customization-B27StpVQ.js +0 -9
  124. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -1,9 +1,10 @@
1
- import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData } from "./sentry-CPbZjomA.js";
2
- import { i as getCurrentConversationPrivacy, n as redactSandboxEgressProxyPath } from "./proxy-path-BTmXDjfx.js";
1
+ import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData, u as sentry_exports } from "./sentry-CPbZjomA.js";
2
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-Cr_dNW1p.js";
3
3
  import { n as isPushServiceHost } from "./push-endpoint-CO-nomUd.js";
4
+ import { n as redactSandboxEgressProxyPath } from "./proxy-path-BHYoKZdq.js";
4
5
  import { n as promoteHttpRouteName, r as routeNameMiddleware, t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
5
6
  import { t as consumePrivateTraceResultMarker } from "./private-trace-result-CE7_lEdq.js";
6
- import { _ as getDeploymentServiceVersion, v as getDeploymentTelemetryAttributes } from "./deployment-BhvrhQeh.js";
7
+ import { _ as getDeploymentTelemetryAttributes, g as getDeploymentServiceVersion } from "./deployment-C0qXa0FD.js";
7
8
  import { performance } from "node:perf_hooks";
8
9
  import { subscribe, unsubscribe } from "node:diagnostics_channel";
9
10
  // src/chat/pi/gateway-request-timing.ts
@@ -300,6 +301,13 @@ function scrubPrivateSentryLog(log) {
300
301
  return log;
301
302
  }
302
303
  // src/instrumentation.ts
304
+ const RATE_LIMIT_HEADERS = [
305
+ "x-ratelimit-limit",
306
+ "x-ratelimit-remaining",
307
+ "x-ratelimit-reset",
308
+ "x-ratelimit-resource",
309
+ "x-ratelimit-used"
310
+ ];
303
311
  const MANUAL_GEN_AI_INTEGRATIONS = /* @__PURE__ */ new Set([
304
312
  "Anthropic_AI",
305
313
  "Google_GenAI",
@@ -350,7 +358,7 @@ function getBrowserSentryConfig() {
350
358
  baggage: trace.baggage,
351
359
  dsn,
352
360
  environment: getEnvironment(),
353
- release: getDeploymentServiceVersion(),
361
+ release: getDeploymentServiceVersion(process.env),
354
362
  sentryTrace: trace["sentry-trace"],
355
363
  tracesSampleRate: getTracesSampleRate()
356
364
  };
@@ -360,8 +368,8 @@ function initSentry() {
360
368
  if (getClient()) return;
361
369
  const dsn = process.env["SENTRY_DSN"];
362
370
  const enableLogs = getBoolean(process.env["SENTRY_ENABLE_LOGS"], Boolean(dsn || process.env["SENTRY_SPOTLIGHT"]?.trim()));
363
- const serviceVersion = getDeploymentServiceVersion();
364
- const deploymentSpanAttributes = getDeploymentTelemetryAttributes();
371
+ const serviceVersion = getDeploymentServiceVersion(process.env);
372
+ const deploymentSpanAttributes = getDeploymentTelemetryAttributes(process.env);
365
373
  init({
366
374
  dsn,
367
375
  environment: getEnvironment(),
@@ -394,7 +402,7 @@ function initSentry() {
394
402
  beforeSend: scrubPrivateSentryEvent,
395
403
  beforeSendLog: enableLogs ? scrubPrivateSentryLog : () => null,
396
404
  beforeSendSpan: scrubPrivateSentrySpan,
397
- integrations: (defaultIntegrations) => defaultIntegrations.filter((integration) => !MANUAL_GEN_AI_INTEGRATIONS.has(integration.name) && integration.name !== "Dedupe")
405
+ integrations: (defaultIntegrations) => [...defaultIntegrations.filter((integration) => !MANUAL_GEN_AI_INTEGRATIONS.has(integration.name) && integration.name !== "Dedupe" && integration.name !== "NodeFetch"), sentry_exports.nativeNodeFetchIntegration({ headersToSpanAttributes: { responseHeaders: RATE_LIMIT_HEADERS } })]
398
406
  });
399
407
  getGlobalScope().setAttributes(deploymentSpanAttributes);
400
408
  getGlobalScope().addEventProcessor((event) => event.type === "feedback" ? scrubPrivateSentryEvent(event) : event);
@@ -1,18 +1,18 @@
1
- import { $i as getVercelConversationWorkQueue, Dr as buildSandboxEgressNetworkPolicy, Eu as juniorSpaceConfigurations, Gn as create, Gu as workspaceSnapshotFinishedEvent, Hn as loadSnapshotsForProfile, Pd as sleep, Pn as getWorkspace, Tu as juniorConversations, Un as setWorkspaceSnapshot, V as slackMention, Vn as invalidateReadySnapshot, Wn as setWorkspaceSnapshotBuild, Xn as getSandboxProvider, Zd as ToolInputError, a as getDb, aa as QUEUE_SIGNATURE_MAX_AGE_MS, br as createSandboxEgressCredentialToken, ca as getQueueProvider, cp as withLock, dr as WorkspaceSnapshotNotReadyError, id as findMatchingWatches, nf as getStateAdapter, oa as signQueueMessage, od as isQuietEvent, of as credentialContextForActor, pr as isWorkspaceSnapshotNotReadyError, q as createPluginHookRunner, qn as isStale, rd as deliverWatch, sa as verifyQueueMessage, sp as fenceLock, sr as isAbortError, xn as getTurnRequestDeadline, yi as SANDBOX_RUNTIME } from "./db-DhzvUY23.js";
2
- import { h as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC } from "./package-discovery-BI6T_RkD.js";
3
- import { M as SANDBOX_WORKSPACE_ROOT, k as SANDBOX_REPOS_ROOT } from "./transcript-CCi7323k.js";
4
- import { m as logInfo, p as logException } from "./logging-B8KEJegM.js";
5
- import { cn as isValidTimeZone, sn as getZonedDateTimeParts } from "./media-BebquhET.js";
6
- import { ln as enqueueEventNotification, na as validateConfigValue, ra as configValueSchema, sn as addQuietEventNote, ta as validateConfigKey, yn as resolveEventAuthor } from "./session-stop-DponjDUZ.js";
7
- import { B as zodToolDefinition, H as juniorToolOutputSchema, z as zodTool } from "./turn-session-routing-D15orfwy.js";
8
- import { t as resolveEventMentions } from "./people-CUtFApfL.js";
9
- import { i as postinstall, r as dependencies, s as getSandboxResources } from "./resolve-D5JVvv6A.js";
1
+ import { a as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC } from "./topics-BoCkoPJJ.js";
2
+ import { T as withLock, n as credentialContextForActor, w as fenceLock, y as getStateAdapter } from "./context-BKF_5zzI.js";
3
+ import { $n as resolveEventMentions, Br as QUEUE_SIGNATURE_MAX_AGE_MS, Hr as verifyQueueMessage, Ji as createSandboxCapability, Nr as getVercelConversationWorkQueue, Oo as deliverWatch, Pi as slackMention, Ui as createPluginModel, Ur as getQueueProvider, Vi as createPluginDecider, Vr as signQueueMessage, Vs as sleep, Wi as createPluginModelCostRecorder, Xi as withPluginHookSpan, a as getDb, au as ToolInputError, gf as juniorSpaceConfigurations, go as workspaceSnapshotFinishedEvent, hf as juniorConversations, jo as isQuietEvent, jt as juniorToolOutputSchema, ko as findMatchingWatches, ou as isToolInputError, qi as basePluginContext, qs as readActorIdentity, rs as createPluginAnnotations, ur as getTurnRequestDeadline, wt as getRegistrations } from "./db-of6e3sGt.js";
4
+ import { Fn as isValidTimeZone, Pn as getZonedDateTimeParts } from "./types-DCzTAA63.js";
5
+ import { f as logException, m as logWarn, p as logInfo } from "./logging-BnOG0qz2.js";
6
+ import { c as SANDBOX_REPOS_ROOT, d as SANDBOX_WORKSPACE_ROOT, s as SANDBOX_JUNIOR_ROOT } from "./prompt-DEkStuxG.js";
7
+ import { $t as invalidateReadySnapshot, B as resolveEventAuthor, Qt as workspaceRepoCheckoutPath, Wt as getWorkspace, ci as configValueSchema, en as loadSnapshotsForProfile, j as enqueueEventNotification, k as addQuietEventNote, nn as setWorkspaceSnapshotBuild, oi as validateConfigKey, si as validateConfigValue, tn as setWorkspaceSnapshot } from "./mailbox-turn-Byrry9o1.js";
8
+ import { E as createSandboxEgressCredentialToken, _ as WorkspaceSnapshotNotReadyError, j as buildSandboxEgressNetworkPolicy, o as getSandboxProvider, p as isAbortError, r as isStale, t as create, u as SANDBOX_RUNTIME, y as isWorkspaceSnapshotNotReadyError } from "./profile-iHw1uu32.js";
9
+ import { i as postinstall, o as getSandboxResources, r as dependencies } from "./resolve-DC6zBuDV.js";
10
10
  import * as z from "zod";
11
11
  import path from "node:path";
12
- import { createHash, randomUUID } from "node:crypto";
13
- import { eventSchema } from "@sentry/junior-plugin-api";
14
12
  import { and, asc, eq, sql } from "drizzle-orm";
15
13
  import { alias } from "drizzle-orm/pg-core";
14
+ import { escapeTagTextAndQuotes, eventSchema, objectAnnotationSchema, renderInlineTag } from "@sentry/junior-plugin-api";
15
+ import { createHash, randomUUID } from "node:crypto";
16
16
  import { structuredPatch } from "diff";
17
17
  // src/chat/spaces/configuration.ts
18
18
  /**
@@ -59,8 +59,8 @@ async function unsetSpaceConfiguration(spaceId, key) {
59
59
  await getDb().delete(juniorSpaceConfigurations).where(and(eq(juniorSpaceConfigurations.spaceId, spaceId), eq(juniorSpaceConfigurations.key, key)));
60
60
  }
61
61
  /**
62
- * Return the id of the Space that a Conversation's root is in, if any. A
63
- * child is in the Space of its root.
62
+ * Return the id of the Space that a Conversation's root is in, if any. In a
63
+ * Space, the root is the Space's Lead.
64
64
  */
65
65
  async function readConversationSpaceId(conversationId) {
66
66
  const [row] = await getDb().select({ spaceId: rootConversation.spaceId }).from(juniorConversations).innerJoin(rootConversation, eq(rootConversation.conversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
@@ -77,6 +77,111 @@ async function readConversationSpaceConfiguration(conversationId) {
77
77
  }).from(juniorConversations).innerJoin(rootConversation, eq(rootConversation.conversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).innerJoin(juniorSpaceConfigurations, eq(juniorSpaceConfigurations.spaceId, rootConversation.spaceId)).where(eq(juniorConversations.conversationId, conversationId));
78
78
  return Object.fromEntries(rows.map((row) => [row.key, configValueSchema.parse(JSON.parse(row.value))]));
79
79
  }
80
+ // src/chat/tool-support/zod-tool.ts
81
+ function isContentOnlyToolResult(value) {
82
+ return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
83
+ }
84
+ function isStructuredToolResultEnvelope(value) {
85
+ return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
86
+ }
87
+ function parseToolContent(content) {
88
+ for (const item of content) if (!item || typeof item !== "object" || (item.type === "text" ? typeof item.text !== "string" : item.type === "image" ? typeof item.data !== "string" || typeof item.mimeType !== "string" : true)) throw new TypeError("zodTool() content must contain valid text or image items.");
89
+ return content;
90
+ }
91
+ function formatZodPath(path) {
92
+ return path.length > 0 ? path.map(String).join(".") : "root";
93
+ }
94
+ function formatToolInputError(error) {
95
+ return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
96
+ }
97
+ /** Parse tool input with its Zod schema, as a model-repairable error on failure. */
98
+ function parseToolInput(schema, args) {
99
+ const result = schema.safeParse(args);
100
+ if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
101
+ return result.data;
102
+ }
103
+ /** Declare the static definition of a Zod tool once, for the registry and its factory. */
104
+ function zodToolDefinition(definition) {
105
+ return definition;
106
+ }
107
+ function zodTool(definition) {
108
+ const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
109
+ let modelInputSchema;
110
+ try {
111
+ modelInputSchema = z.toJSONSchema(inputSchema);
112
+ } catch (error) {
113
+ throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
114
+ }
115
+ let modelOutputSchema;
116
+ if (outputSchema) try {
117
+ modelOutputSchema = z.toJSONSchema(outputSchema);
118
+ } catch (error) {
119
+ throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
120
+ }
121
+ return {
122
+ ...toolDef,
123
+ inputSchema: modelInputSchema,
124
+ ...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
125
+ prepareArguments(args) {
126
+ return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
127
+ },
128
+ ...execute ? { async execute(input, options) {
129
+ const result = await execute(input, options);
130
+ if (!outputSchema) {
131
+ if (isContentOnlyToolResult(result)) return result;
132
+ throw new TypeError("zodTool() content-only tools must return { content } without details.");
133
+ }
134
+ if (isStructuredToolResultEnvelope(result)) return {
135
+ content: parseToolContent(result.content),
136
+ details: outputSchema.parse(result.details)
137
+ };
138
+ return outputSchema.parse(result);
139
+ } } : void 0
140
+ };
141
+ }
142
+ // src/chat/conversations/annotation-results.ts
143
+ /** Save object annotations and retain returned facts in the tool result. */
144
+ async function saveObjectAnnotations(conversationId, plugin, value) {
145
+ const annotations = objectAnnotationSchema.array().parse(value);
146
+ await getDb().transaction(async (db) => {
147
+ const store = createPluginAnnotations({
148
+ conversationId,
149
+ plugin,
150
+ db
151
+ });
152
+ for (const annotation of annotations) {
153
+ await store.upsert(annotation);
154
+ await store.remove("resource_link", annotation.key);
155
+ }
156
+ });
157
+ return annotations.map((annotation) => ({
158
+ ...annotation,
159
+ plugin
160
+ }));
161
+ }
162
+ /**
163
+ * Save annotations from a successful plugin tool result and attach their cards.
164
+ * An Annotation marks work that the Conversation did, so a read-only tool must
165
+ * not return one: looking up an object does not link it.
166
+ */
167
+ async function annotateToolResult(conversationId, plugin, result, options) {
168
+ if (typeof result !== "object" || result === null) return result;
169
+ if ("isError" in result && result.isError === true) return result;
170
+ const details = "details" in result && typeof result.details === "object" && result.details !== null ? result.details : result;
171
+ if ("timed_out" in details && details.timed_out === true || "isError" in details && details.isError === true || !("objectAnnotations" in details) || !Array.isArray(details.objectAnnotations)) return result;
172
+ if (options.readOnly) throw new Error(`Read-only ${plugin} tool returned objectAnnotations. Return them only from tools that change the object.`);
173
+ const cards = await saveObjectAnnotations(conversationId, plugin, details.objectAnnotations);
174
+ const { objectAnnotations: _annotations, ...rest } = details;
175
+ const annotated = {
176
+ ...rest,
177
+ objectCards: cards
178
+ };
179
+ if (details !== result) return {
180
+ ...result,
181
+ details: annotated
182
+ };
183
+ return annotated;
184
+ }
80
185
  // src/chat/sandbox/file-utils.ts
81
186
  /** Normalize model-supplied numeric knobs before they reach filesystem tools. */
82
187
  function positiveInteger(value) {
@@ -260,7 +365,6 @@ const bashToolDefinition = zodToolDefinition({
260
365
  openWorldHint: false,
261
366
  readOnlyHint: false
262
367
  },
263
- approvalMode: "auto",
264
368
  description: "Run a bash command inside the isolated sandbox workspace. Use this for repository inspection/execution tasks that need shell access. Do not use for network-sensitive or destructive actions unless explicitly required.",
265
369
  inputSchema: z.object({
266
370
  command: z.string().min(1).describe("Bash command to run inside the sandbox."),
@@ -363,15 +467,6 @@ function createWriteFileTool() {
363
467
  }
364
468
  });
365
469
  }
366
- // src/chat/tools/system-time.ts
367
- const systemTimeInputSchema = z.object({ timezone: z.string().trim().min(1).optional().describe("Optional IANA timezone, for example America/Los_Angeles. When set, iso_local and timezone_offset_minutes are for that zone.") });
368
- const systemTimeOutputSchema = juniorToolOutputSchema.extend({
369
- unix_ms: z.number().describe("Current time in epoch milliseconds, for millisecond inputs."),
370
- iso_utc: z.string(),
371
- iso_local: z.string(),
372
- timezone: z.string().nullable(),
373
- timezone_offset_minutes: z.number()
374
- });
375
470
  const systemTimeToolDefinition = zodToolDefinition({
376
471
  description: "Return current system time in UTC and optional local IANA timezone formats. Use when the user asks for current time/date context. Pass timezone when the answer should be in a known IANA zone such as America/Los_Angeles.",
377
472
  annotations: {
@@ -380,8 +475,14 @@ const systemTimeToolDefinition = zodToolDefinition({
380
475
  openWorldHint: false,
381
476
  readOnlyHint: true
382
477
  },
383
- inputSchema: systemTimeInputSchema,
384
- outputSchema: systemTimeOutputSchema,
478
+ inputSchema: z.object({ timezone: z.string().trim().min(1).optional().describe("Optional IANA timezone, for example America/Los_Angeles. When set, iso_local and timezone_offset_minutes are for that zone.") }),
479
+ outputSchema: juniorToolOutputSchema.extend({
480
+ unix_ms: z.number().describe("Current time in epoch milliseconds, for millisecond inputs."),
481
+ iso_utc: z.string(),
482
+ iso_local: z.string(),
483
+ timezone: z.string().nullable(),
484
+ timezone_offset_minutes: z.number()
485
+ }),
385
486
  privateTraceResult: (result) => ({
386
487
  unix_ms: result.unix_ms,
387
488
  iso_utc: result.iso_utc,
@@ -437,6 +538,271 @@ function getTimeZoneOffsetMinutes(timestampMs, timezone) {
437
538
  const asUtcMs = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
438
539
  return Math.round((timestampMs - asUtcMs) / 6e4);
439
540
  }
541
+ // src/chat/tool-support/plugin-tool-denied-error.ts
542
+ const NOT_RUN_LINE = "This action was blocked by policy and was not executed.";
543
+ const RAN_LINE = "This action ran, but policy rejected its result. Its changes may still be in place.";
544
+ const PLUGIN_DENIAL_INSTRUCTIONS = ["Do not retry it or reach the same result through a workaround or another tool.", "Stop and explain what was blocked and why."].join("\n");
545
+ /** Expected tool failure when a plugin hook refuses a tool call by policy. */
546
+ var PluginToolDeniedError = class extends Error {
547
+ /** `ran` is true when an after-execution hook rejected the result. */
548
+ constructor(reason, options = {}) {
549
+ super(`${options.ran ? RAN_LINE : NOT_RUN_LINE}\n${PLUGIN_DENIAL_INSTRUCTIONS}\nReason: ${reason}`);
550
+ this.name = "PluginToolDeniedError";
551
+ }
552
+ };
553
+ // src/chat/plugins/after-tool-hooks.ts
554
+ /** Render a nudge as the marked text the agent reads. */
555
+ function renderToolResultNudge(nudge) {
556
+ return renderInlineTag("plugin-note", escapeTagTextAndQuotes(nudge.message), { plugin: nudge.pluginName });
557
+ }
558
+ async function activeWorkspace(sandbox) {
559
+ const id = sandbox.workspaceId();
560
+ const workspace = id ? await getWorkspace(getDb(), id) : void 0;
561
+ if (!workspace) return void 0;
562
+ return {
563
+ name: workspace.name,
564
+ repos: workspace.repos.map((repo) => ({
565
+ path: workspaceRepoCheckoutPath(repo.repo),
566
+ provider: repo.provider,
567
+ repo: repo.repo
568
+ }))
569
+ };
570
+ }
571
+ /**
572
+ * Run each plugin's `afterToolExecute` hook in registration order. A denial
573
+ * throws `PluginToolDeniedError` and skips later hooks. An abort stops the
574
+ * checks and keeps the tool result.
575
+ */
576
+ async function runAfterToolExecuteHooks(args) {
577
+ const hooked = args.plugins.filter((plugin) => plugin.hooks?.afterToolExecute);
578
+ if (hooked.length === 0) return [];
579
+ const { signal } = args.tool;
580
+ const sandbox = createSandboxCapability(args.sandbox.workspace, signal);
581
+ let workspace;
582
+ try {
583
+ workspace = await activeWorkspace(args.sandbox);
584
+ } catch (error) {
585
+ logException(error, "agent.plugin.after_tool_execute.failed", { "gen_ai.tool.name": args.tool.name });
586
+ return [];
587
+ }
588
+ const nudges = [];
589
+ for (const plugin of hooked) {
590
+ if (signal?.aborted) break;
591
+ const pluginName = plugin.manifest.name;
592
+ const onCost = createPluginModelCostRecorder({
593
+ ...args.turn,
594
+ pluginName,
595
+ source: "afterToolExecute",
596
+ toolName: args.tool.name
597
+ });
598
+ let denial;
599
+ try {
600
+ await withPluginHookSpan(pluginName, "afterToolExecute", async () => await plugin.hooks.afterToolExecute({
601
+ ...basePluginContext(plugin),
602
+ decider: createPluginDecider(pluginName, {
603
+ onCost,
604
+ signal
605
+ }),
606
+ decision: {
607
+ deny(reason) {
608
+ denial = reason;
609
+ },
610
+ nudge(message) {
611
+ nudges.push({
612
+ message,
613
+ pluginName
614
+ });
615
+ }
616
+ },
617
+ model: createPluginModel(pluginName, plugin.model, {
618
+ onCost,
619
+ signal
620
+ }),
621
+ sandbox,
622
+ ...signal ? { signal } : void 0,
623
+ tool: {
624
+ input: args.tool.input,
625
+ name: args.tool.name
626
+ },
627
+ ...workspace ? { workspace } : void 0
628
+ }));
629
+ } catch (error) {
630
+ if (signal?.aborted) break;
631
+ const attributes = {
632
+ "app.plugin.name": pluginName,
633
+ "gen_ai.tool.name": args.tool.name
634
+ };
635
+ if (isToolInputError(error)) logWarn("agent.plugin.after_tool_execute.failed", {
636
+ ...attributes,
637
+ "error.type": "tool_input_error"
638
+ });
639
+ else logException(error, "agent.plugin.after_tool_execute.failed", attributes);
640
+ continue;
641
+ }
642
+ if (denial !== void 0) throw new PluginToolDeniedError(denial, { ran: true });
643
+ }
644
+ return nudges;
645
+ }
646
+ // src/chat/plugins/hooks/runner.ts
647
+ function normalizeEnv(value) {
648
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return {};
649
+ const env = {};
650
+ for (const [key, rawValue] of Object.entries(value)) if (typeof rawValue === "string") env[key] = rawValue;
651
+ return env;
652
+ }
653
+ /** Create one runner over runtime hook plugins registered by the app. */
654
+ function createPluginHookRunner(input = {}) {
655
+ const loaded = getRegistrations();
656
+ return {
657
+ async afterToolExecute(tool) {
658
+ if (!input.toolRun) return [];
659
+ const { sandbox, ...turn } = input.toolRun;
660
+ return await runAfterToolExecuteHooks({
661
+ plugins: loaded,
662
+ sandbox: sandbox(),
663
+ tool,
664
+ turn
665
+ });
666
+ },
667
+ async afterMcpTool(tool) {
668
+ const cards = [];
669
+ for (const plugin of loaded) {
670
+ if (plugin.manifest.name !== tool.provider) continue;
671
+ const hook = plugin.hooks?.afterMcpTool;
672
+ if (!hook) continue;
673
+ const annotations = tool.conversationId ? createPluginAnnotations({
674
+ conversationId: tool.conversationId,
675
+ db: getDb(),
676
+ plugin: plugin.manifest.name
677
+ }) : void 0;
678
+ try {
679
+ const result = await hook({
680
+ ...basePluginContext(plugin),
681
+ ...tool.conversationId ? { conversationId: tool.conversationId } : void 0,
682
+ ...annotations ? { annotations } : void 0,
683
+ result: {
684
+ content: tool.content,
685
+ structuredContent: tool.structuredContent
686
+ },
687
+ tool: {
688
+ arguments: tool.arguments,
689
+ name: tool.toolName
690
+ }
691
+ });
692
+ if (result && tool.conversationId) cards.push(...await saveObjectAnnotations(tool.conversationId, plugin.manifest.name, result.objectAnnotations));
693
+ } catch (error) {
694
+ logWarn("agent.plugin.after_mcp_tool.failed", {
695
+ "app.plugin.name": plugin.manifest.name,
696
+ "gen_ai.tool.name": tool.toolName,
697
+ "exception.message": error instanceof Error ? error.message : String(error)
698
+ });
699
+ }
700
+ }
701
+ return cards;
702
+ },
703
+ async prepareWorkspace(sandbox, repos, signal) {
704
+ const preparers = new Set(loaded.filter((plugin) => plugin.hooks?.workspacePrepare).map((plugin) => plugin.manifest.name));
705
+ const unhandledProviders = [...new Set(repos.map((repo) => repo.provider).filter((provider) => !preparers.has(provider)))].sort();
706
+ if (unhandledProviders.length > 0) throw new Error(`Workspace repository providers have no preparation hook: ${unhandledProviders.join(", ")}`);
707
+ const selectedRepos = repos.map((repo) => ({
708
+ provider: repo.provider,
709
+ repo: repo.repo,
710
+ path: workspaceRepoCheckoutPath(repo.repo)
711
+ }));
712
+ const paths = /* @__PURE__ */ new Set();
713
+ for (const entry of selectedRepos) {
714
+ const key = entry.path.toLowerCase();
715
+ if (paths.has(key)) throw new Error(`Workspace checkout path collision: ${entry.path}`);
716
+ paths.add(key);
717
+ }
718
+ const sandboxCapability = createSandboxCapability(sandbox, signal);
719
+ const finalizers = [];
720
+ for (const plugin of loaded) {
721
+ const hook = plugin.hooks?.workspacePrepare;
722
+ if (!hook) continue;
723
+ const selected = selectedRepos.filter((repo) => repo.provider === plugin.manifest.name).map((repo) => ({
724
+ path: repo.path,
725
+ repo: repo.repo
726
+ }));
727
+ if (selected.length === 0) continue;
728
+ const finalize = await hook({
729
+ ...basePluginContext(plugin),
730
+ repos: selected,
731
+ sandbox: sandboxCapability
732
+ });
733
+ if (finalize) finalizers.push(finalize);
734
+ }
735
+ return async () => {
736
+ for (const finalize of finalizers) await finalize();
737
+ };
738
+ },
739
+ async prepareSandbox(sandbox) {
740
+ const sandboxCapability = createSandboxCapability(sandbox);
741
+ for (const plugin of loaded) {
742
+ const pluginName = plugin.manifest.name;
743
+ const hook = plugin.hooks?.sandboxPrepare;
744
+ if (!hook) continue;
745
+ logInfo("agent.plugin.sandbox_preparation.started", { "app.plugin.name": pluginName });
746
+ await withPluginHookSpan(pluginName, "sandboxPrepare", async () => await hook({
747
+ ...basePluginContext(plugin),
748
+ actor: input.actor,
749
+ sandbox: sandboxCapability
750
+ }));
751
+ }
752
+ },
753
+ async beforeToolExecute(tool) {
754
+ const env = {};
755
+ let nextInput = { ...tool.input };
756
+ const actors = input.actors?.() ?? (input.actor ? [input.actor] : []);
757
+ for (const plugin of loaded) {
758
+ const pluginName = plugin.manifest.name;
759
+ const hook = plugin.hooks?.beforeToolExecute;
760
+ if (!hook) continue;
761
+ let replacement;
762
+ let blocked;
763
+ await withPluginHookSpan(pluginName, "beforeToolExecute", async () => await hook({
764
+ ...basePluginContext(plugin),
765
+ actor: input.actor,
766
+ actors,
767
+ tool: {
768
+ name: tool.name,
769
+ input: nextInput
770
+ },
771
+ users: { resolveActor: async () => input.actor ? await readActorIdentity(input.actor) : void 0 },
772
+ juniorRoot: SANDBOX_JUNIOR_ROOT,
773
+ env: {
774
+ get(key) {
775
+ return env[key] ?? normalizeEnv(nextInput["env"])[key];
776
+ },
777
+ set(key, value) {
778
+ env[key] = value;
779
+ }
780
+ },
781
+ decision: {
782
+ deny(reason) {
783
+ blocked = new PluginToolDeniedError(reason);
784
+ },
785
+ redirect(message) {
786
+ blocked = new ToolInputError(message);
787
+ },
788
+ replaceInput(input) {
789
+ replacement = input;
790
+ }
791
+ }
792
+ }));
793
+ if (blocked) throw blocked;
794
+ if (replacement !== void 0) {
795
+ if (typeof replacement !== "object" || replacement === null || Array.isArray(replacement)) throw new Error(`Plugin "${pluginName}" replaced tool input with a non-object value`);
796
+ nextInput = { ...replacement };
797
+ }
798
+ }
799
+ return {
800
+ input: nextInput,
801
+ env
802
+ };
803
+ }
804
+ };
805
+ }
440
806
  // src/chat/events/ingest.ts
441
807
  /** Match a normalized event and enqueue notifications into conversations. */
442
808
  async function ingestEvent(input, options) {
@@ -1136,4 +1502,4 @@ async function ensureWorkspaceSnapshotBuild(input) {
1136
1502
  else await sendWorkspaceSnapshotJob(message);
1137
1503
  return "building";
1138
1504
  }
1139
- export { setSpaceConfiguration as A, isMissingPathError as C, listSpaceConfiguration as D, resolveWorkspacePath as E, readConversationSpaceConfiguration as O, validateAndApplyTextEdits as S, positiveInteger as T, buildCompactDiff as _, prepareWorkspaceSnapshot as a, restoreLineEndings as b, systemTimeToolDefinition as c, createReadFileTool as d, readFileToolDefinition as f, createBashTool as g, bashToolDefinition as h, requireReadyWorkspaceSnapshot as i, unsetSpaceConfiguration as j, readConversationSpaceId as k, createWriteFileTool as l, editFileToolDefinition as m, processWorkspaceSnapshotJob as n, ingestEvent as o, createEditFileTool as p, verifyWorkspaceSnapshotJobMessage as r, createSystemTimeTool as s, ensureWorkspaceSnapshotBuild as t, writeFileToolDefinition as u, detectLineEnding as v, normalizeToLf as w, stripBom as x, prepareTextReplacementArguments as y };
1505
+ export { annotateToolResult as A, restoreLineEndings as C, normalizeToLf as D, isMissingPathError as E, listSpaceConfiguration as F, readConversationSpaceConfiguration as I, readConversationSpaceId as L, parseToolInput as M, zodTool as N, positiveInteger as O, zodToolDefinition as P, setSpaceConfiguration as R, prepareTextReplacementArguments as S, validateAndApplyTextEdits as T, editFileToolDefinition as _, prepareWorkspaceSnapshot as a, buildCompactDiff as b, renderToolResultNudge as c, systemTimeToolDefinition as d, createWriteFileTool as f, createEditFileTool as g, readFileToolDefinition as h, requireReadyWorkspaceSnapshot as i, saveObjectAnnotations as j, resolveWorkspacePath as k, PluginToolDeniedError as l, createReadFileTool as m, processWorkspaceSnapshotJob as n, ingestEvent as o, writeFileToolDefinition as p, verifyWorkspaceSnapshotJobMessage as r, createPluginHookRunner as s, ensureWorkspaceSnapshotBuild as t, createSystemTimeTool as u, bashToolDefinition as v, stripBom as w, detectLineEnding as x, createBashTool as y, unsetSpaceConfiguration as z };
@@ -1,4 +1,4 @@
1
- import { Ds as conversationKindFromRow, Tu as juniorConversations, a as getDb } from "./db-DhzvUY23.js";
1
+ import { J as conversationKindFromRow, a as getDb, hf as juniorConversations } from "./db-of6e3sGt.js";
2
2
  import { desc, eq, sql } from "drizzle-orm";
3
3
  // src/chat/conversations/lineage.ts
4
4
  /**