Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(channels): ask before sharing a linked item with the channel (#7851)

Wolf Mermelstein8e6a5cf9df0b
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index 9101c9f15a..4a93fc6f7f 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -115,6 +115,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [SetEntityProperty](/AI/mcp/tools/set-entity-property)
- [SetFormAccess](/AI/mcp/tools/set-form-access)
- [SetSenderPolicy](/AI/mcp/tools/set-sender-policy)
+- [ShareWithChannel](/AI/mcp/tools/share-with-channel)
- [Subagent](/AI/mcp/tools/subagent)
- [TextEditorCodeExecution](/AI/mcp/tools/text-editor-code-execution)
- [UpdateCalendarEvent](/AI/mcp/tools/update-calendar-event)
diff --git a/apps/docs/AI/mcp/tools/share-with-channel.mdx b/apps/docs/AI/mcp/tools/share-with-channel.mdx
new file mode 100644
index 0000000000..12a3618c44
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/share-with-channel.mdx
@@ -0,0 +1,18 @@
+---
+title: ShareWithChannel
+description: >-
+ Share an item with the current members of a channel by writing a channel
+ entity-access grant.
+---
+
+# ShareWithChannel
+
+Share an item with the current members of a channel by writing a channel entity-access grant. Call it only after the user agrees to share that item, or when they already asked you to share it. entityType is the stored type: calendar_event for a calendar chip, document, chat, project, database, form, call, thread, or agent_session. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `channelId` | string | Yes | Channel id whose current members should be able to view the item. |
+| `entityId` | string | Yes | Id of the item to share. For a calendar chip this is the event id in documentId. |
+| `entityType` | `"calendar_event"` \| `"document"` \| `"chat"` \| `"project"` \| `"database"` \| `"form"` \| `"call"` \| `"thread"` \| `"agent_session"` | Yes | Entity types a channel grant can cover. Values are the stored entity types. `calendar` is accepted for a calendar chip, whose stored type is `calendar_event`. |
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index 8ac49b4246..d8ec46c906 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -106,6 +106,7 @@
"AI/mcp/tools/set-entity-property",
"AI/mcp/tools/set-form-access",
"AI/mcp/tools/set-sender-policy",
+ "AI/mcp/tools/share-with-channel",
"AI/mcp/tools/subagent",
"AI/mcp/tools/text-editor-code-execution",
"AI/mcp/tools/update-calendar-event",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 924e8d7120..884601601a 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -177,6 +177,7 @@
"AI/mcp/tools/set-entity-property",
"AI/mcp/tools/set-form-access",
"AI/mcp/tools/set-sender-policy",
+ "AI/mcp/tools/share-with-channel",
"AI/mcp/tools/subagent",
"AI/mcp/tools/text-editor-code-execution",
"AI/mcp/tools/update-calendar-event",
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
index 65660d9cc2..11018f3e78 100644
--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -121,6 +121,8 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
SetEntityProperty: (whose) => `set properties in ${whose} workspace`,
SetFormAccess: (whose) => `change who can respond to ${whose} forms`,
SetSenderPolicy: (whose) => `change ${whose} email sender rules`,
+ ShareWithChannel: (whose) =>
+ `share an item from ${whose} account with a channel`,
Subagent: (whose) => `start a helper agent with ${whose} access`,
TextEditorCodeExecution: (whose) => `edit files with ${whose} access`,
UpdateCalendarEvent: (whose) => `change an event on ${whose} calendar`,
diff --git a/apps/web/src/lib/core/component/AI/component/tool/ChannelMutations.tsx b/apps/web/src/lib/core/component/AI/component/tool/ChannelMutations.tsx
index 9465318676..3f572bc4f1 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/ChannelMutations.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/ChannelMutations.tsx
@@ -1,6 +1,7 @@
import { ItemPreview } from '@core/component/ItemPreview';
import Hash from '@phosphor-icons/core/regular/hash.svg';
import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';
+import ShareNetwork from '@phosphor-icons/core/regular/share-network.svg';
import Users from '@phosphor-icons/core/regular/users.svg';
import { createSignal, For, Show, Suspense } from 'solid-js';
import { BaseTool } from './BaseTool';
@@ -196,8 +197,49 @@ const manageChannelParticipantsHandler = createToolRenderer({
},
});
+const shareWithChannelHandler = createToolRenderer({
+ name: 'ShareWithChannel',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const response = () => ctx.response?.data;
+
+ return (
+ <BaseTool
+ icon={ShareNetwork}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ expanded() && response() ? (
+ <DetailPanel
+ summary={response()!.summary}
+ details={[
+ { label: 'Type', value: response()!.entityType },
+ { label: 'Item', value: response()!.entityId },
+ ]}
+ />
+ ) : undefined
+ }
+ >
+ <div class="flex min-w-0 flex-1 items-center justify-between gap-3">
+ <span class="min-w-0 truncate">
+ {ctx.response ? 'Shared with' : 'Share with'}{' '}
+ <ChannelPreview channelId={ctx.tool.data.channelId} />
+ </span>
+ <Tool.ResultToggle
+ expanded={expanded()}
+ onToggle={() => setExpanded((value) => !value)}
+ showToggle={!!response()}
+ status={ctx.response ? 'Shared' : undefined}
+ />
+ </div>
+ </BaseTool>
+ );
+ },
+});
+
export {
createChannelHandler,
manageChannelParticipantsHandler,
renameChannelHandler,
+ shareWithChannelHandler,
};
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index c47cc6309b..a3f3deb569 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -39,6 +39,7 @@ import {
createChannelHandler,
manageChannelParticipantsHandler,
renameChannelHandler,
+ shareWithChannelHandler,
} from './ChannelMutations';
import {
dispatchCodingAgentHandler,
@@ -242,6 +243,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
SearchTools: searchToolsHandler,
SelfKnowledge: selfKnowledgeHandler,
SendChannelMessage: sendChannelMessageHandler,
+ ShareWithChannel: shareWithChannelHandler,
SendConfirmedEmail: sendConfirmedEmailHandler,
SendEmail: sendEmailHandler,
SetSenderPolicy: setSenderPolicyHandler,
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index 6d94cb0425..785fccffac 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -13242,6 +13242,73 @@ export const SetSenderPolicyResponse = z.object({
summary: z.string(),
});
+export const ShareWithChannel = z.object({
+ channelId: z.string().uuid(),
+ entityId: z.string(),
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('calendar_event'),
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('project'),
+ z.literal('database'),
+ z.literal('form'),
+ z.literal('call'),
+ z.literal('thread'),
+ z.literal('agent_session'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+});
+
+export const ShareWithChannelResponse = z.object({
+ channelId: z.string().uuid(),
+ entityId: z.string(),
+ entityType: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.literal('calendar_event'),
+ z.literal('document'),
+ z.literal('chat'),
+ z.literal('project'),
+ z.literal('database'),
+ z.literal('form'),
+ z.literal('call'),
+ z.literal('thread'),
+ z.literal('agent_session'),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ summary: z.string(),
+});
+
export const Subagent = z.object({ task: z.string() });
export const SubagentResponse = z.object({ result: z.string() });
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index a715421c50..d0279a6e26 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -343,6 +343,10 @@ type ToolParserMap = {
call: types.SetSenderPolicy;
response: types.SetSenderPolicyResponse;
};
+ ShareWithChannel: {
+ call: types.ShareWithChannel;
+ response: types.ShareWithChannelResponse;
+ };
Subagent: { call: types.Subagent; response: types.SubagentResponse };
TextEditorCodeExecution: {
call: types.TextEditorCodeExecution;
@@ -738,6 +742,10 @@ const toolParserMap = {
call: schemas.SetSenderPolicy,
response: schemas.SetSenderPolicyResponse,
},
+ ShareWithChannel: {
+ call: schemas.ShareWithChannel,
+ response: schemas.ShareWithChannelResponse,
+ },
Subagent: { call: schemas.Subagent, response: schemas.SubagentResponse },
TextEditorCodeExecution: {
call: schemas.TextEditorCodeExecution,
@@ -1111,6 +1119,10 @@ type ToolDataMap = {
call: types.SetSenderPolicy;
response: types.SetSenderPolicyResponse;
};
+ ShareWithChannel: {
+ call: types.ShareWithChannel;
+ response: types.ShareWithChannelResponse;
+ };
Subagent: { call: types.Subagent; response: types.SubagentResponse };
TextEditorCodeExecution: {
call: types.TextEditorCodeExecution;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 81c139a835..d39eb9ff92 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -4335,6 +4335,22 @@ export type GrantAccess = 'view' | 'edit';
* Where future mail from this sender lands: `signal`, `noise`, or `block`.
*/
export type ToolSenderPolicy = 'signal' | 'noise' | 'block';
+/**
+ * Entity types a channel grant can cover.
+ *
+ * Values are the stored entity types. `calendar` is accepted for a calendar
+ * chip, whose stored type is `calendar_event`.
+ */
+export type ChannelShareEntityType =
+ | 'calendar_event'
+ | 'document'
+ | 'chat'
+ | 'project'
+ | 'database'
+ | 'form'
+ | 'call'
+ | 'thread'
+ | 'agent_session';
/**
* Content of a text editor code execution response - either a result or an error
*/
@@ -12127,6 +12143,38 @@ export interface SetSenderPolicyResponse {
*/
summary: string;
}
+/**
+ * Share an item with the current members of a channel by writing a channel entity-access grant. Call it only after the user agrees to share that item, or when they already asked you to share it. entityType is the stored type: calendar_event for a calendar chip, document, chat, project, database, form, call, thread, or agent_session. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists.
+ */
+export interface ShareWithChannel {
+ /**
+ * Channel id whose current members should be able to view the item.
+ */
+ channelId: string;
+ /**
+ * Id of the item to share. For a calendar chip this is the event id in documentId.
+ */
+ entityId: string;
+ entityType: ChannelShareEntityType;
+}
+/**
+ * Confirmation that the channel grant is in place.
+ */
+export interface ShareWithChannelResponse {
+ /**
+ * Channel that received the grant.
+ */
+ channelId: string;
+ /**
+ * Shared entity id.
+ */
+ entityId: string;
+ entityType: ChannelShareEntityType;
+ /**
+ * Human-readable result.
+ */
+ summary: string;
+}
/**
* Delegate a task to a subagent that can independently use tools to research and complete it. The subagent has access to search, documents, properties, calls, and channel tools. Use this for tasks that require multiple tool calls or independent research.
*/
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 30d01f6aad..1eb25354eb 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -222,6 +222,7 @@ pub const EAGER_TOOLS: &[&str] = &[
"SearchTools",
"SelfKnowledge",
"SendChannelMessage",
+ "ShareWithChannel",
"Subagent",
"TextEditorCodeExecution",
"WebFetch",
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 4cceaa84a4..5ab3de8ce6 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -13,13 +13,14 @@ use call::inbound::toolset::CallToolContext;
use call::outbound::pg_call_repo::PgCallRepo;
use call::outbound::s3_recording_storage::S3RecordingStorage;
use channels::domain::ports::ChannelEventDispatcher;
-use channels::domain::service::{NoopChannelEventDispatcher, NoopChannelReferenceSharePermissions};
+use channels::domain::service::NoopChannelEventDispatcher;
use channels::domain::side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher};
use channels::domain::{list_service::ChannelListServiceImpl, service::ChannelServiceImpl};
use channels::inbound::toolset::ChannelToolContext;
use channels::outbound::{
connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,
contacts_dispatcher::ContactsChannelDispatcher, notification_sender::NotificationChannelSender,
+ pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions,
pg_channels_repo::PgChannelsRepo, pg_side_effect_context::PgChannelSideEffectContext,
};
use chat::domain::service::ChatServiceImpl;
@@ -206,12 +207,12 @@ pub type ToolCommsService = ChannelListServiceImpl<
/// hosts without the side-effect clients.
pub type ToolChannelEventDispatcher = std::sync::Arc<dyn ChannelEventDispatcher>;
+/// Channel reference-sharing adapter used by AI tools, including `ShareWithChannel`.
+pub type ToolChannelSharePermissions = PgChannelReferenceSharePermissions<ToolEntityAccessService>;
+
/// Type alias for the channel messages service implementation used by AI tools.
-pub type ToolChannelMessagesService = ChannelServiceImpl<
- PgChannelsRepo,
- ToolChannelEventDispatcher,
- NoopChannelReferenceSharePermissions,
->;
+pub type ToolChannelMessagesService =
+ ChannelServiceImpl<PgChannelsRepo, ToolChannelEventDispatcher, ToolChannelSharePermissions>;
/// Type alias for the channel AI tool context.
pub type ToolChannelToolContext =
@@ -420,16 +421,17 @@ pub fn build_channel_tool_context_with_dispatcher(
dispatcher: ToolChannelEventDispatcher,
messages: Arc<dyn messages::domain::api::MessageServiceApi>,
) -> ToolChannelToolContext {
+ let access = entity_access::domain::service::EntityAccessServiceImpl::new(
+ entity_access::outbound::PgAccessRepository::new(pool.clone()),
+ );
ChannelToolContext::new(
messages,
ChannelServiceImpl::with_dependencies(
PgChannelsRepo::new(pool.clone()),
dispatcher,
- NoopChannelReferenceSharePermissions,
- ),
- entity_access::domain::service::EntityAccessServiceImpl::new(
- entity_access::outbound::PgAccessRepository::new(pool),
+ PgChannelReferenceSharePermissions::new(pool, Arc::new(access.clone())),
),
+ access,
)
}
diff --git a/crates/channel_bots/src/outbound/fast_model_trigger_classifier.rs b/crates/channel_bots/src/outbound/fast_model_trigger_classifier.rs
index c5a10aeb72..66c268d213 100644
--- a/crates/channel_bots/src/outbound/fast_model_trigger_classifier.rs
+++ b/crates/channel_bots/src/outbound/fast_model_trigger_classifier.rs
@@ -17,7 +17,7 @@ static SYSTEM_PROMPT: &str = r#"You decide whether the latest message in a chann
Answer true only when the latest message is addressed to the agent, for example:
- it asks the agent a question or gives it an instruction
-- it answers a question the agent just asked
+- it answers a question the agent just asked, including a short agreement ("yes", "yeah", "please", "go ahead") to an offer to share something with the channel
- it reacts to the agent's last message in a way that invites a reply (a correction, a complaint about the agent's answer, a follow-up)
Answer false when:
@@ -118,3 +118,14 @@ impl InferredTriggerClassifier for FastModelTriggerClassifier {
Ok(output.expects_response)
}
}
+
+#[cfg(test)]
+mod test {
+ #[test]
+ fn agreeing_to_a_share_offer_expects_a_response() {
+ let prompt = super::SYSTEM_PROMPT;
+ assert!(prompt.contains("\"yes\""));
+ assert!(prompt.contains("share something with the channel"));
+ assert!(prompt.contains("\"thanks\""));
+ }
+}
diff --git a/crates/channels/src/domain/message_delivery/test.rs b/crates/channels/src/domain/message_delivery/test.rs
index 8a3cff5a0b..3c8613ecab 100644
--- a/crates/channels/src/domain/message_delivery/test.rs
+++ b/crates/channels/src/domain/message_delivery/test.rs
@@ -53,7 +53,7 @@ impl ChannelReferenceSharePermissions for Log {
_: MacroUserIdStr<'static>,
_: Uuid,
_: Vec<ReferencedShareItem>,
- ) -> Result<(), Self::Err> {
+ ) -> Result<Vec<crate::domain::models::ReferenceShareResult>, Self::Err> {
*self.shares.lock().unwrap() += 1;
anyhow::bail!("sharing temporarily unavailable")
}
diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rs
index a5a563bfb5..89ea81ddc9 100644
--- a/crates/channels/src/domain/models.rs
+++ b/crates/channels/src/domain/models.rs
@@ -754,6 +754,26 @@ impl ReferencedShareItem {
}
}
+/// Whether a referenced item was granted to a channel.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ReferenceShareOutcome {
+ /// A channel grant exists. An existing direct grant is left as it was.
+ Shared,
+ /// The actor's access is below what sharing this kind of item requires.
+ NotPermitted,
+}
+
+/// One referenced item and whether it was shared with the channel.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ReferenceShareResult {
+ /// Referenced entity id.
+ pub entity_id: String,
+ /// Referenced entity type.
+ pub entity_type: ReferencedShareItemType,
+ /// Grant outcome.
+ pub outcome: ReferenceShareOutcome,
+}
+
/// Request to add participants.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index 8f7bb8c43b..15bf76e5b7 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -6,8 +6,8 @@ use crate::domain::models::{
ChannelJoinCodeResponse, ChannelMetadata, ChannelParticipant, ChannelPreview,
ChannelPreviewRow, CreateChannelRequest, CreateChannelResponse, CreateEntityMentionOptions,
CreatedChannel, EntityMention, GetOrCreateChannelResponse, GetOrCreateDmRequest,
- GetOrCreatePrivateRequest, PatchChannelRequest, ReferencedShareItem, RemoveParticipantsRequest,
- Sender,
+ GetOrCreatePrivateRequest, PatchChannelRequest, ReferenceShareResult, ReferencedShareItem,
+ RemoveParticipantsRequest, Sender,
};
#[cfg(feature = "list")]
use crate::domain::models::{
@@ -577,6 +577,25 @@ pub trait ChannelService: Send + Sync + 'static {
}
}
+ /// Share referenced items with a channel's current members.
+ ///
+ /// The actor must already be allowed to share each item. Calendar events,
+ /// agent sessions, databases, and forms are stored as direct `entity_access`
+ /// channel grants; other items follow the same reference-sharing policy as
+ /// posting them in a message.
+ fn share_referenced_items_with_channel(
+ &self,
+ _actor: MacroUserIdStr<'static>,
+ _channel_id: Uuid,
+ _items: Vec<ReferencedShareItem>,
+ ) -> impl Future<Output = Result<Vec<ReferenceShareResult>, ChannelMutationErr>> + Send {
+ async move {
+ Err(ChannelMutationErr::NotFound(
+ "channel sharing is not configured".to_string(),
+ ))
+ }
+ }
+
/// Patch a channel.
///
/// Name-only updates are allowed for any member receipt. Converting a
@@ -877,14 +896,17 @@ pub trait ChannelReferenceSharePermissions: Send + Sync + 'static {
/// Update channel share permissions according to the referenced entity's policy.
///
/// Implementations must not grant access for an item the actor cannot already view.
- /// Agent sessions require ownership and grant view access; PDFs grant comment access,
- /// capped at the actor's own access; other references grant view.
+ /// Agent sessions require ownership and grant view access; a calendar event requires
+ /// the actor to hold it (owner or linked account) and grants view; PDFs grant comment
+ /// access, capped at the actor's own access; other references grant view. Each item
+ /// is reported as shared or not permitted. An existing direct grant is left unchanged
+ /// and still counts as shared.
fn update_channel_share_permissions_for_referenced_items(
&self,
actor: MacroUserIdStr<'static>,
channel_id: Uuid,
items: Vec<ReferencedShareItem>,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Vec<ReferenceShareResult>, Self::Err>> + Send;
}
/// Errors that can occur while mutating channels.
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index 05dedd5278..ccbe7cdec0 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -6,8 +6,8 @@ use crate::domain::{
ChannelAttachmentType, ChannelJoinCodeResponse, ChannelMetadata, ChannelParticipant,
ChannelPreview, ChannelPreviewData, ChannelType, CreateEntityMentionOptions, EntityMention,
GetOrCreateAction, GetOrCreateChannelResponse, GetOrCreateDmRequest,
- GetOrCreatePrivateRequest, ParticipantRole, PatchChannelRequest, ReferencedShareItem,
- RemoveParticipantsRequest, Sender, WithChannelId,
+ GetOrCreatePrivateRequest, ParticipantRole, PatchChannelRequest, ReferenceShareResult,
+ ReferencedShareItem, RemoveParticipantsRequest, Sender, WithChannelId,
},
ports::{
ChannelAttachmentsPage, ChannelEventDispatcher, ChannelMessagesErr, ChannelMutationErr,
@@ -72,9 +72,16 @@ impl ChannelReferenceSharePermissions for NoopChannelReferenceSharePermissions {
&self,
_actor: MacroUserIdStr<'static>,
_channel_id: Uuid,
- _items: Vec<ReferencedShareItem>,
- ) -> Result<(), Self::Err> {
- Ok(())
+ items: Vec<ReferencedShareItem>,
+ ) -> Result<Vec<ReferenceShareResult>, Self::Err> {
+ Ok(items
+ .into_iter()
+ .map(|item| ReferenceShareResult {
+ entity_id: item.entity_id().to_string(),
+ entity_type: item.entity_type(),
+ outcome: crate::domain::models::ReferenceShareOutcome::NotPermitted,
+ })
+ .collect())
}
}
@@ -1100,6 +1107,18 @@ where
ChannelServiceImpl::get_or_create_private(self, actor, req).await
}
+ async fn share_referenced_items_with_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ items: Vec<ReferencedShareItem>,
+ ) -> Result<Vec<ReferenceShareResult>, ChannelMutationErr> {
+ self.reference_share_permissions
+ .update_channel_share_permissions_for_referenced_items(actor, channel_id, items)
+ .await
+ .map_err(|error| ChannelMutationErr::Repo(error.into()))
+ }
+
async fn patch_channel(
&self,
access: EntityAccessReceipt<MemberParticipantRole>,
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 4336b71278..8a136f4dd5 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -453,9 +453,17 @@ impl ChannelReferenceSharePermissions for FakeReferenceSharing {
_actor: MacroUserIdStr<'static>,
_channel_id: Uuid,
items: Vec<ReferencedShareItem>,
- ) -> Result<(), Self::Err> {
+ ) -> Result<Vec<crate::domain::models::ReferenceShareResult>, Self::Err> {
+ let results = items
+ .iter()
+ .map(|item| crate::domain::models::ReferenceShareResult {
+ entity_id: item.entity_id().to_string(),
+ entity_type: item.entity_type(),
+ outcome: crate::domain::models::ReferenceShareOutcome::Shared,
+ })
+ .collect();
self.items.lock().unwrap().extend(items);
- Ok(())
+ Ok(results)
}
}
@@ -467,6 +475,38 @@ fn mutation_service(
ChannelServiceImpl::with_dependencies(repo, events, share)
}
+#[tokio::test]
+async fn share_referenced_items_with_channel_forwards_to_the_share_port() {
+ let share = FakeReferenceSharing::default();
+ let seen = share.items.clone();
+ let service = mutation_service(
+ FakeMutationRepo::new(Uuid::now_v7(), "macro|[email protected]"),
+ FakeEvents::default(),
+ share,
+ );
+ let channel_id = Uuid::now_v7();
+ let item = ReferencedShareItem::new(
+ Uuid::now_v7().to_string(),
+ crate::domain::models::ReferencedShareItemType::CalendarEvent,
+ );
+ let results = service
+ .share_referenced_items_with_channel(
+ macro_id("macro|[email protected]"),
+ channel_id,
+ vec![item.clone()],
+ )
+ .await
+ .expect("share port accepts the item");
+
+ assert_eq!(results.len(), 1);
+ assert_eq!(results[0].entity_id, item.entity_id());
+ assert_eq!(
+ results[0].outcome,
+ crate::domain::models::ReferenceShareOutcome::Shared
+ );
+ assert_eq!(seen.lock().unwrap().as_slice(), &[item]);
+}
+
fn macro_id(user_id: &str) -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(user_id.to_string()).unwrap()
}
diff --git a/crates/channels/src/inbound/toolset.rs b/crates/channels/src/inbound/toolset.rs
index cffc4131e7..b868fdc746 100644
--- a/crates/channels/src/inbound/toolset.rs
+++ b/crates/channels/src/inbound/toolset.rs
@@ -7,6 +7,7 @@ mod read_channel_messages;
mod read_channel_thread;
mod rename_channel;
mod send_channel_message;
+mod share_with_channel;
mod types;
#[cfg(test)]
@@ -17,6 +18,7 @@ use crate::{
inbound::toolset::{
create_channel::CreateChannel, manage_channel_participants::ManageChannelParticipants,
rename_channel::RenameChannel, send_channel_message::SendChannelMessage,
+ share_with_channel::ShareWithChannel,
},
};
use ai_toolset::{AsyncToolCollection, RequestContext, ToolCallError};
@@ -328,6 +330,7 @@ where
.add_tool::<ReadChannelMessageContext, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<ReadChannelThread, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<SendChannelMessage, ChannelToolContext<Svc, AccessSvc>>()
+ .add_tool::<ShareWithChannel, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<CreateChannel, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<RenameChannel, ChannelToolContext<Svc, AccessSvc>>()
.add_tool::<ManageChannelParticipants, ChannelToolContext<Svc, AccessSvc>>()
diff --git a/crates/channels/src/inbound/toolset/share_with_channel.rs b/crates/channels/src/inbound/toolset/share_with_channel.rs
new file mode 100644
index 0000000000..a67753ab59
--- /dev/null
+++ b/crates/channels/src/inbound/toolset/share_with_channel.rs
@@ -0,0 +1,167 @@
+//! Share one item with the current members of a channel.
+
+use super::{ChannelToolContext, channel_mutation_error};
+use crate::domain::{
+ models::{ReferenceShareOutcome, ReferencedShareItem, ReferencedShareItemType},
+ ports::ChannelService,
+};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use entity_access::domain::ports::EntityAccessService;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Entity types a channel grant can cover.
+///
+/// Values are the stored entity types. `calendar` is accepted for a calendar
+/// chip, whose stored type is `calendar_event`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum ChannelShareEntityType {
+ /// A calendar event. A calendar chip's `documentId` is this id.
+ #[serde(alias = "calendar")]
+ CalendarEvent,
+ /// A document.
+ Document,
+ /// An AI chat.
+ Chat,
+ /// A project.
+ Project,
+ /// A database.
+ Database,
+ /// A form.
+ Form,
+ /// A call.
+ Call,
+ /// An email thread.
+ #[serde(rename = "thread", alias = "email", alias = "email_thread")]
+ EmailThread,
+ /// An agent session.
+ AgentSession,
+}
+
+impl ChannelShareEntityType {
+ fn to_domain(self) -> ReferencedShareItemType {
+ match self {
+ Self::CalendarEvent => ReferencedShareItemType::CalendarEvent,
+ Self::Document => ReferencedShareItemType::Document,
+ Self::Chat => ReferencedShareItemType::Chat,
+ Self::Project => ReferencedShareItemType::Project,
+ Self::Database => ReferencedShareItemType::Database,
+ Self::Form => ReferencedShareItemType::Form,
+ Self::Call => ReferencedShareItemType::Call,
+ Self::EmailThread => ReferencedShareItemType::EmailThread,
+ Self::AgentSession => ReferencedShareItemType::AgentSession,
+ }
+ }
+
+ fn not_permitted(self) -> &'static str {
+ match self {
+ Self::CalendarEvent => {
+ "you can only share a calendar event you hold on your own calendar, and private or confidential events are not shared"
+ }
+ Self::AgentSession => "you can only share an agent session you own",
+ _ => "you need access to this item before it can be shared with the channel",
+ }
+ }
+}
+
+/// Grant the current members of a channel access to one item.
+#[derive(Debug, Clone, Deserialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+#[schemars(
+ title = "ShareWithChannel",
+ description = "Share an item with the current members of a channel by writing a channel entity-access grant. Call it only after the user agrees to share that item, or when they already asked you to share it. entityType is the stored type: calendar_event for a calendar chip, document, chat, project, database, form, call, thread, or agent_session. entityId is that item's id. A calendar event can be shared only by someone who holds it on their own calendar, and private or confidential events are refused. Sharing again is safe when a grant already exists."
+)]
+pub struct ShareWithChannel {
+ /// Channel whose current members should receive the grant.
+ #[schemars(description = "Channel id whose current members should be able to view the item.")]
+ pub channel_id: Uuid,
+ /// Id of the item to share.
+ #[schemars(
+ description = "Id of the item to share. For a calendar chip this is the event id in documentId."
+ )]
+ pub entity_id: String,
+ /// Stored entity type of the item.
+ #[schemars(
+ description = "Stored entity type: calendar_event, document, chat, project, database, form, call, thread, or agent_session."
+ )]
+ pub entity_type: ChannelShareEntityType,
+}
+
+/// Confirmation that the channel grant is in place.
+#[derive(Debug, Clone, Serialize, JsonSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ShareWithChannelResponse {
+ /// Channel that received the grant.
+ pub channel_id: Uuid,
+ /// Shared entity id.
+ pub entity_id: String,
+ /// Stored entity type that was shared.
+ pub entity_type: ChannelShareEntityType,
+ /// Human-readable result.
+ pub summary: String,
+}
+
+impl ToolAnnotated for ShareWithChannel {
+ const ANNOTATIONS: ToolAnnotations =
+ ToolAnnotations::additive("Share with channel").with_idempotent();
+}
+
+#[async_trait]
+impl<Svc, AccessSvc> AsyncTool<ChannelToolContext<Svc, AccessSvc>> for ShareWithChannel
+where
+ Svc: ChannelService,
+ AccessSvc: EntityAccessService,
+{
+ type Output = ShareWithChannelResponse;
+
+ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]
+ async fn call(
+ &self,
+ service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,
+ request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let entity_id = self.entity_id.trim();
+ if Uuid::parse_str(entity_id).is_err() {
+ return Err(ToolCallError {
+ description: "entityId must be the item's uuid".to_string(),
+ internal_error: anyhow::anyhow!("invalid share entity id"),
+ });
+ }
+ service_context
+ .require_channel_member(&request_context, self.channel_id)
+ .await?;
+
+ let item = ReferencedShareItem::new(entity_id, self.entity_type.to_domain());
+ let results = service_context
+ .service
+ .share_referenced_items_with_channel(
+ request_context.user_id.clone(),
+ self.channel_id,
+ vec![item],
+ )
+ .await
+ .map_err(|error| channel_mutation_error("share with the channel", error))?;
+ let shared = results
+ .iter()
+ .any(|result| result.outcome == ReferenceShareOutcome::Shared);
+ if !shared {
+ return Err(ToolCallError {
+ description: self.entity_type.not_permitted().to_string(),
+ internal_error: anyhow::anyhow!("reference share was not permitted"),
+ });
+ }
+
+ Ok(ShareWithChannelResponse {
+ channel_id: self.channel_id,
+ entity_id: entity_id.to_string(),
+ entity_type: self.entity_type,
+ summary: "Shared with the current members of the channel.".to_string(),
+ })
+ }
+}
diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rs
index 7c239519ee..70a82b8814 100644
--- a/crates/channels/src/inbound/toolset/test.rs
+++ b/crates/channels/src/inbound/toolset/test.rs
@@ -6,11 +6,13 @@ use super::{
parse_participants,
rename_channel::RenameChannel,
send_channel_message::SendChannelMessage,
+ share_with_channel::{ChannelShareEntityType, ShareWithChannel},
};
use crate::domain::{
models::{
AddParticipantsRequest, ChannelMetadata, ChannelType, CreateChannelRequest,
- CreateChannelResponse, PatchChannelRequest, RemoveParticipantsRequest, Sender,
+ CreateChannelResponse, PatchChannelRequest, ReferenceShareOutcome, ReferenceShareResult,
+ ReferencedShareItem, RemoveParticipantsRequest, Sender,
},
ports::{ChannelMutationErr, ChannelService},
};
@@ -227,6 +229,8 @@ struct ToolTestChannelService {
adds: Arc<Mutex<Vec<AddParticipantsCall>>>,
removes: Arc<Mutex<Vec<RemoveParticipantsCall>>>,
metadata_name: Option<String>,
+ shares: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid, Vec<ReferencedShareItem>)>>>,
+ deny_share: bool,
}
impl ToolTestChannelService {
@@ -372,6 +376,31 @@ impl ChannelService for ToolTestChannelService {
.push((actor, channel_id, req));
Ok(())
}
+
+ async fn share_referenced_items_with_channel(
+ &self,
+ actor: MacroUserIdStr<'static>,
+ channel_id: Uuid,
+ items: Vec<ReferencedShareItem>,
+ ) -> Result<Vec<ReferenceShareResult>, ChannelMutationErr> {
+ let results = items
+ .iter()
+ .map(|item| ReferenceShareResult {
+ entity_id: item.entity_id().to_string(),
+ entity_type: item.entity_type(),
+ outcome: if self.deny_share {
+ ReferenceShareOutcome::NotPermitted
+ } else {
+ ReferenceShareOutcome::Shared
+ },
+ })
+ .collect();
+ self.shares
+ .lock()
+ .expect("share lock")
+ .push((actor, channel_id, items));
+ Ok(results)
+ }
}
#[derive(Clone, Copy)]
@@ -581,6 +610,117 @@ fn rename_channel_schema_is_valid() {
assert!(!validated.description.to_lowercase().contains("admin"));
}
+#[test]
+fn share_with_channel_schema_is_valid() {
+ let result = generate_validated_input_schema::<ShareWithChannel>();
+ assert!(result.is_ok(), "{result:?}");
+ let validated = result.unwrap();
+ assert_eq!(validated.name, "ShareWithChannel");
+ assert!(validated.description.contains("entity-access"));
+ assert!(validated.description.contains("calendar_event"));
+}
+
+#[test]
+fn share_with_channel_accepts_a_calendar_chip_alias() {
+ let channel_id = Uuid::now_v7();
+ let entity_id = Uuid::now_v7();
+ let parsed: ShareWithChannel = serde_json::from_value(serde_json::json!({
+ "channelId": channel_id,
+ "entityId": entity_id,
+ "entityType": "calendar",
+ }))
+ .expect("calendar alias");
+ assert_eq!(parsed.entity_type, ChannelShareEntityType::CalendarEvent);
+ assert_eq!(parsed.entity_id, entity_id.to_string());
+}
+
+#[tokio::test]
+async fn share_with_channel_grants_the_item_for_a_member() {
+ let channel_id = Uuid::now_v7();
+ let entity_id = Uuid::now_v7();
+ let service = ToolTestChannelService::default();
+ let shares = service.shares.clone();
+ let context = ChannelToolContext::new(
+ Arc::new(RecordingMessages::default()),
+ service,
+ ToolTestAccessService::default(),
+ );
+
+ let response = ShareWithChannel {
+ channel_id,
+ entity_id: format!(" {entity_id} "),
+ entity_type: ChannelShareEntityType::CalendarEvent,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("member can share");
+
+ assert_eq!(response.channel_id, channel_id);
+ assert_eq!(response.entity_id, entity_id.to_string());
+ assert_eq!(
+ response.summary,
+ "Shared with the current members of the channel."
+ );
+ let (actor, shared_channel, items) = shares.lock().expect("share lock").pop().expect("shared");
+ assert_eq!(actor, user_id());
+ assert_eq!(shared_channel, channel_id);
+ assert_eq!(items.len(), 1);
+ assert_eq!(items[0].entity_id(), entity_id.to_string());
+ assert_eq!(
+ items[0].entity_type(),
+ crate::domain::models::ReferencedShareItemType::CalendarEvent
+ );
+}
+
+#[tokio::test]
+async fn share_with_channel_rejects_non_members() {
+ let context = ChannelToolContext::new(
+ Arc::new(RecordingMessages::default()),
+ ToolTestChannelService::default(),
+ ToolTestAccessService {
+ receipt_error: Some(ReceiptFail::Unauthorized),
+ ..ToolTestAccessService::default()
+ },
+ );
+
+ let error = ShareWithChannel {
+ channel_id: Uuid::now_v7(),
+ entity_id: Uuid::now_v7().to_string(),
+ entity_type: ChannelShareEntityType::Document,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect_err("non-member");
+
+ assert_eq!(
+ error.description,
+ "user is not a member of the requested channel"
+ );
+}
+
+#[tokio::test]
+async fn share_with_channel_reports_when_the_user_cannot_share() {
+ let context = ChannelToolContext::new(
+ Arc::new(RecordingMessages::default()),
+ ToolTestChannelService {
+ deny_share: true,
+ ..ToolTestChannelService::default()
+ },
+ ToolTestAccessService::default(),
+ );
+
+ let error = ShareWithChannel {
+ channel_id: Uuid::now_v7(),
+ entity_id: Uuid::now_v7().to_string(),
+ entity_type: ChannelShareEntityType::CalendarEvent,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect_err("not permitted");
+
+ assert!(error.description.contains("own calendar"));
+}
+
#[test]
fn manage_channel_participants_schema_is_valid() {
let result = generate_validated_input_schema::<ManageChannelParticipants>();
diff --git a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
index 848be1f505..8e5eeaf4bf 100644
--- a/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions.rs
@@ -1,7 +1,9 @@
//! Postgres adapter for channel reference share-permission side effects.
use crate::domain::{
- models::{ReferencedShareItem, ReferencedShareItemType},
+ models::{
+ ReferenceShareOutcome, ReferenceShareResult, ReferencedShareItem, ReferencedShareItemType,
+ },
ports::ChannelReferenceSharePermissions,
reference_sharing::grant_level,
};
@@ -49,7 +51,8 @@ where
actor: MacroUserIdStr<'static>,
channel_id: Uuid,
items: Vec<ReferencedShareItem>,
- ) -> Result<(), Self::Err> {
+ ) -> Result<Vec<ReferenceShareResult>, Self::Err> {
+ let mut results = Vec::with_capacity(items.len());
for item in items {
let access = self
.entity_access_service
@@ -60,9 +63,15 @@ where
)
.await
.context("failed to get user access level")?;
- share_referenced_item_with_channel(&self.pool, channel_id, &item, access).await?;
+ let outcome =
+ share_referenced_item_with_channel(&self.pool, channel_id, &item, access).await?;
+ results.push(ReferenceShareResult {
+ entity_id: item.entity_id().to_string(),
+ entity_type: item.entity_type(),
+ outcome,
+ });
}
- Ok(())
+ Ok(results)
}
}
@@ -71,15 +80,16 @@ async fn share_referenced_item_with_channel(
channel_id: Uuid,
item: &ReferencedShareItem,
sharer_access: Option<AccessLevel>,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<ReferenceShareOutcome> {
let file_type = match item.entity_type() {
ReferencedShareItemType::Document => get_document_file_type(db, item.entity_id()).await?,
_ => None,
};
- if let Some(level) = grant_level(item.entity_type(), file_type, sharer_access) {
- ensure_referenced_item_visible_to_channel(db, channel_id, item, level).await?;
- }
- Ok(())
+ let Some(level) = grant_level(item.entity_type(), file_type, sharer_access) else {
+ return Ok(ReferenceShareOutcome::NotPermitted);
+ };
+ ensure_referenced_item_visible_to_channel(db, channel_id, item, level).await?;
+ Ok(ReferenceShareOutcome::Shared)
}
async fn get_document_file_type(
diff --git a/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs b/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
index 930ec9510a..7c14a6d460 100644
--- a/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
+++ b/crates/channels/src/outbound/pg_channel_reference_share_permissions/test.rs
@@ -68,9 +68,12 @@ async fn pdf_references_never_grant_more_than_the_sharer_holds(pool: PgPool) {
);
let unshared_channel_id = Uuid::now_v7();
- share_referenced_item_with_channel(&pool, unshared_channel_id, &item, None)
- .await
- .unwrap();
+ assert_eq!(
+ share_referenced_item_with_channel(&pool, unshared_channel_id, &item, None)
+ .await
+ .unwrap(),
+ ReferenceShareOutcome::NotPermitted
+ );
assert_eq!(
document_channel_levels(&pool, PDF_DOCUMENT_ID, unshared_channel_id).await,
(None, None)
diff --git a/crates/prompt/src/channel_mention.rs b/crates/prompt/src/channel_mention.rs
index 857a71def0..f42c7c3df3 100644
--- a/crates/prompt/src/channel_mention.rs
+++ b/crates/prompt/src/channel_mention.rs
@@ -32,6 +32,20 @@ have not made the call the action has not happened. Only take actions (creating,
deleting things) that the mentioning user explicitly asked for, and because calendar invitations
go out the moment an event is created, ask in the thread before creating an event with attendees.
+When your reply links something the other people in this channel may not already be able to
+open — a calendar event, document, chat, database, form, project, call, email thread, or agent
+session — end that reply with this question and nothing after it: "Do you want me to share this with the members of the channel?" Do not share it in that same turn. Name the thing only when
+"this" would be ambiguous. Skip the question when they already asked you to share it: call
+`ShareWithChannel` then, instead of asking. Do not offer to share the channel itself, a message
+already in this channel, or something you only mentioned in passing without a chip.
+
+A later message in this thread that agrees ("yes", "yeah", "please", "go ahead", "share it")
+answers that question. Call `ShareWithChannel` for that item and this channel — `channelId` is
+the `id` on the conversation parent above; a calendar chip is entity type `calendar_event` and
+its `documentId` is the event id — then reply with only "Okay." Do not repeat the earlier answer. Agreement to a
+different question is not agreement to share. If they decline, acknowledge in a few words and
+do not share. If the tool says you cannot share it, say that plainly instead of "Okay."
+
Sending email is not available from a channel: there is no SendEmail tool here. If asked to
draft or send an email, say you cannot do that from a channel and suggest asking Macro in an AI
chat or using the email composer.
@@ -43,8 +57,29 @@ dates and times from the <current_time> block (EOD = 5:00 PM local) instead of a
user's time zone when the block names one — asking rather than silently assuming UTC when it \
does not — treats tool calls as executing immediately (no composer or pending \
confirmation to point the user at), only takes explicitly requested actions, checks before \
-creating events with attendees, and declines email drafting/sending with a pointer to AI chat \
-or the email composer.";
+creating events with attendees, declines email drafting/sending with a pointer to AI chat \
+or the email composer, and when a reply links an item the channel may not already see ends \
+by asking \"Do you want me to share this with the members of the channel?\" — then, on a yes \
+in the thread, calls ShareWithChannel and replies only \"Okay.\"";
/// The channel-mention prompt for the Macro channel bot.
pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);
+
+#[cfg(test)]
+mod test {
+ use super::PROMPT;
+
+ #[test]
+ fn a_linked_item_is_offered_to_the_channel_and_shared_only_after_yes() {
+ let instructions = PROMPT.instructions.as_ref();
+ assert!(
+ instructions.contains("Do you want me to share this with the members of the channel?")
+ );
+ assert!(instructions.contains("`ShareWithChannel`"));
+ assert!(instructions.contains("reply with only \"Okay.\""));
+ assert!(instructions.contains("calendar_event"));
+ assert!(instructions.contains("`channelId` is\nthe `id` on the conversation parent"));
+ assert!(instructions.contains("its `documentId` is the event id"));
+ assert!(PROMPT.intent.contains("ShareWithChannel"));
+ }
+}
diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rs
index 27e3a3e708..f6547d8415 100644
--- a/crates/prompt/src/lib.rs
+++ b/crates/prompt/src/lib.rs
@@ -294,6 +294,13 @@ mod tests {
assert!(preamble.contains("date/time"));
}
+ #[test]
+ fn mentions_prompt_says_a_shared_calendar_event_previews_for_channel_members() {
+ let instructions = mentions::PROMPT.instructions.as_ref();
+ assert!(instructions.contains("read-only preview"));
+ assert!(instructions.contains("Private and confidential events are never shared"));
+ }
+
#[test]
fn mentions_prompt_covers_date_and_agent_session_chips() {
let instructions = mentions::PROMPT.instructions.as_ref();
diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rs
index f4766eeeb7..1127935727 100644
--- a/crates/prompt/src/mentions.rs
+++ b/crates/prompt/src/mentions.rs
@@ -49,7 +49,7 @@ The `blockName` for a Macro database is always exactly `database` — never `md`
The `blockName` for a form is always exactly `form` — never `md` or `document`. `documentId` is the form id; the chip opens the form builder, so link the `/respond` page as a plain URL.
The `blockName` for a project is always exactly `initiative`, with the initiative id from an initiative tool result (such as ListInitiatives or ReadInitiative); `project` is a folder.
The `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.
-The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention resolves only for users who have that event on their own calendar.
+The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention opens for people who have that event on their own calendar. After it is shared with a channel, current members who do not have a copy see a read-only preview instead. Private and confidential events are never shared.
When a tool returns both a channel id and a channel message id, link the specific message using the channel message mention format. Do not link only the channel unless you are referring to the whole channel.
### People, groups, dates, agent sessions, and pull requests
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index fffcf7f626..8127101241 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -196,7 +196,13 @@ event without attendees creates the event right away (unlike AI chat, where crea
for the user to confirm a composer card). For an event with attendees the bot is prompted to
ask for confirmation in the thread first, since Google sends the invitations the moment the
event is created — no invitation goes out from the initial request. It cannot draft or send
-email at all. The bot's prompt carries the current date and time in the mentioning user's
+email at all. When that reply links something the rest of the channel may not already open
+(a calendar event, document, or similar chip), it ends by asking "Do you want me to share this
+with the members of the channel?" A yes in the thread — "yes", "please", "go ahead" — is
+enough: the bot replies "Okay." and grants current members access. It does not share before
+that yes unless the request already asked it to. A decline is not shared. Private and
+confidential calendar events stay unshared, and a calendar event can only be shared by
+someone who holds it on their own calendar. The bot's prompt carries the current date and time in the mentioning user's
own time zone (their primary calendar's), so it resolves relative times ("tomorrow at 4",
"EOD") without asking; when no calendar is connected the prompt falls back to UTC and the
bot asks before scheduling a specific clock time. Within the rollout, `@Macro` — plus
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index c9e2947b61..a433dd0d0a 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -1660,11 +1660,13 @@ that date. Coverage depends on each teammate having connected their own calendar
Google's out-of-office event type.
A calendar event mentioned in a channel message opens the calendar focused on the viewer's
-own copy of the meeting. When the sender holds the event on their own calendar, the mention
-also shares it read-only with the channel's current members: a member without a copy of their
-own sees the mention's title and time, and its hover card adds a `Shared with you · not on
+own copy of the meeting. When a person holds the event on their own calendar and posts the
+mention, it is shared read-only with the channel's current members: a member without a copy of
+their own sees the mention's title and time, and its hover card adds a `Shared with you · not on
your calendar` line with no open action. Clicking such a mention shows that hover card
-instead of opening the calendar. Private and confidential events are never shared this way.
+instead of opening the calendar. A classic `@Macro` reply that mentions an event does not share
+it by posting the chip. It asks whether to share with the channel, and a yes in that thread
+writes the same channel grant. Private and confidential events are never shared this way.
Every calendar mention's hover card shows the schedule, location, organizer and attendee
count, plus the first lines of the event description (its links open), and no last-updated
byline.