Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(properties): create/edit/delete tag AI tools (#4802)
gbirmanc2eadcf1e90b
diff --git a/apps/web/src/features/property/tags/tagColors.ts b/apps/web/src/features/property/tags/tagColors.tsindex 9d020bf949..247185e3e7 100644--- a/apps/web/src/features/property/tags/tagColors.ts+++ b/apps/web/src/features/property/tags/tagColors.ts@@ -1,3 +1,6 @@+// The AI tools mirror this palette in+// crates/properties/src/inbound/toolset/tag_color.rs (TagColor::hex). Keep the+// two in sync when adding, removing, recoloring, or reordering a tag color.export const TAG_COLORS = ['#E5484D', // Red'#E54D2E', // Tomatodiff --git a/apps/web/src/lib/core/component/AI/component/tool/CreateTag.tsx b/apps/web/src/lib/core/component/AI/component/tool/CreateTag.tsxnew file mode 100644index 0000000000..105c585883--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/CreateTag.tsx@@ -0,0 +1,26 @@+import Tag from '@phosphor-icons/core/regular/tag.svg';+import { TagDot } from '@property/tags/TagDot';+import { Show } from 'solid-js';+import { BaseTool } from './BaseTool';+import { createToolRenderer } from './ToolRenderer';++const handler = createToolRenderer({+ name: 'CreateTag',+ render: (ctx) => (+ <BaseTool icon={Tag} renderContext={ctx.renderContext} type="call">+ <div class="flex min-w-0 flex-1 items-center gap-1.5">+ <span class="shrink-0">+ {ctx.response ? 'Created tag' : 'Create tag'}+ </span>+ <Show when={ctx.response?.data.color}>+ {(color) => <TagDot color={color()} />}+ </Show>+ <span class="truncate text-ink">+ {ctx.response?.data.label ?? ctx.tool.data.label}+ </span>+ </div>+ </BaseTool>+ ),+});++export const createTagHandler = handler;diff --git a/apps/web/src/lib/core/component/AI/component/tool/DeleteTag.tsx b/apps/web/src/lib/core/component/AI/component/tool/DeleteTag.tsxnew file mode 100644index 0000000000..ef7fd612e1--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/DeleteTag.tsx@@ -0,0 +1,14 @@+import Trash from '@phosphor-icons/core/regular/trash.svg';+import { BaseTool } from './BaseTool';+import { createToolRenderer } from './ToolRenderer';++const handler = createToolRenderer({+ name: 'DeleteTag',+ render: (ctx) => (+ <BaseTool icon={Trash} renderContext={ctx.renderContext} type="call">+ {ctx.response ? 'Deleted tag' : 'Delete tag'}+ </BaseTool>+ ),+});++export const deleteTagHandler = handler;diff --git a/apps/web/src/lib/core/component/AI/component/tool/EditTag.tsx b/apps/web/src/lib/core/component/AI/component/tool/EditTag.tsxnew file mode 100644index 0000000000..5baa9a46e3--- /dev/null+++ b/apps/web/src/lib/core/component/AI/component/tool/EditTag.tsx@@ -0,0 +1,32 @@+import PencilSimple from '@phosphor-icons/core/regular/pencil-simple.svg';+import { TagDot } from '@property/tags/TagDot';+import { Show } from 'solid-js';+import { BaseTool } from './BaseTool';+import { createToolRenderer } from './ToolRenderer';++const handler = createToolRenderer({+ name: 'EditTag',+ render: (ctx) => {+ const label = () => ctx.response?.data.label ?? ctx.tool.data.label;+ const color = () => ctx.response?.data.color ?? undefined;+ return (+ <BaseTool+ icon={PencilSimple}+ renderContext={ctx.renderContext}+ type="call"+ >+ <div class="flex min-w-0 flex-1 items-center gap-1.5">+ <span class="shrink-0">+ {ctx.response ? 'Edited tag' : 'Edit tag'}+ </span>+ <Show when={color()}>{(c) => <TagDot color={c()} />}</Show>+ <Show when={label()}>+ {(l) => <span class="truncate text-ink">{l()}</span>}+ </Show>+ </div>+ </BaseTool>+ );+ },+});++export const editTagHandler = handler;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.tsxindex f7872e6380..97b66b9741 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@@ -6,9 +6,12 @@ import {import { Dynamic } from 'solid-js/web';import { bashCodeExecutionHandler } from './BashCodeExecution';import { createDocumentHandler } from './CreateDocument';+import { createTagHandler } from './CreateTag';import { getCompanyHandler, listCompaniesHandler } from './Crm';+import { deleteTagHandler } from './DeleteTag';import { displayResultsHandler } from './DisplayResults';import { editDocumentHandler } from './EditDocument';+import { editTagHandler } from './EditTag';import { getThreadHandler } from './GetThread';import { listCallRecordsHandler } from './ListCallRecords';import { listEntitiesHandler } from './ListEntities';@@ -73,7 +76,10 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {DisplayResults: displayResultsHandler,ContentSearch: contentSearchHandler,CreateDocument: createDocumentHandler,+ CreateTag: createTagHandler,+ DeleteTag: deleteTagHandler,EditDocument: editDocumentHandler,+ EditTag: editTagHandler,GetThread: getThreadHandler,NameSearch: nameSearchHandler,ReadCallRecord: readCallRecordHandler,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.tsindex e10eaafb62..cc11d7ed96 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@@ -611,6 +611,100 @@ export const CreateDocumentResponse = z.object({documentId: z.string().uuid(),});+export const CreateTag = z.object({+ color: z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('red'),+ z.literal('tomato'),+ z.literal('orange'),+ z.literal('amber'),+ z.literal('yellow'),+ z.literal('green'),+ z.literal('teal'),+ z.literal('blue'),+ z.literal('indigo'),+ z.literal('purple'),+ z.literal('pink'),+ z.literal('gray'),+ ];+ 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',+ });+ }+ }),+ label: z.string(),+ scope: z+ .intersection(+ z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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',+ });+ }+ }),+ z.any().default('personal')+ )+ .optional(),+});++export const CreateTagResponse = z.object({+ color: z.union([z.string(), z.null()]).optional(),+ id: z.string().uuid(),+ label: z.string(),+ propertyDefinitionId: z.string().uuid(),+ scope: z.any().superRefine((x, ctx) => {+ const schemas = [z.literal('personal'), z.literal('team')];+ 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 DeleteTag = z.object({+ id: z.string().uuid(),+ property_definition_id: z.string().uuid(),+});++export const DeleteTagResponse = z.object({+ message: z.string(),+ success: z.boolean(),+});+export const DisplayResults = z.object({ view: z.any() });export const DisplayResultsResponse = z.object({ message: z.string() });@@ -625,6 +719,56 @@ export const EditDocumentResponse = z.object({summary: z.string(),});+export const EditTag = z.object({+ color: z+ .union([+ z.any().superRefine((x, ctx) => {+ const schemas = [+ z.literal('red'),+ z.literal('tomato'),+ z.literal('orange'),+ z.literal('amber'),+ z.literal('yellow'),+ z.literal('green'),+ z.literal('teal'),+ z.literal('blue'),+ z.literal('indigo'),+ z.literal('purple'),+ z.literal('pink'),+ z.literal('gray'),+ ];+ 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',+ });+ }+ }),+ z.null(),+ ])+ .optional(),+ id: z.string().uuid(),+ label: z.union([z.string(), z.null()]).default(null),+ property_definition_id: z.string().uuid(),+});++export const EditTagResponse = z.object({+ color: z.union([z.string(), z.null()]).optional(),+ id: z.string().uuid(),+ label: z.string(),+ propertyDefinitionId: z.string().uuid(),+ summary: z.string(),+});+export const GetCompany = z.object({ company_id: z.string().uuid() });export const GetCompanyResponse = z.object({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.tsindex f96c336ec5..6b11dcc4c5 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@@ -20,6 +20,8 @@ type ToolParserMap = {call: types.CreateDocument;response: types.CreateDocumentResponse;};+ CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };+ DeleteTag: { call: types.DeleteTag; response: types.DeleteTagResponse };DisplayResults: {call: types.DisplayResults;response: types.DisplayResultsResponse;@@ -28,6 +30,7 @@ type ToolParserMap = {call: types.EditDocument;response: types.EditDocumentResponse;};+ EditTag: { call: types.EditTag; response: types.EditTagResponse };GetCompany: { call: types.GetCompany; response: types.GetCompanyResponse };GetEntityProperties: {call: types.GetEntityProperties;@@ -134,6 +137,8 @@ const toolParserMap = {call: schemas.CreateDocument,response: schemas.CreateDocumentResponse,},+ CreateTag: { call: schemas.CreateTag, response: schemas.CreateTagResponse },+ DeleteTag: { call: schemas.DeleteTag, response: schemas.DeleteTagResponse },DisplayResults: {call: schemas.DisplayResults,response: schemas.DisplayResultsResponse,@@ -142,6 +147,7 @@ const toolParserMap = {call: schemas.EditDocument,response: schemas.EditDocumentResponse,},+ EditTag: { call: schemas.EditTag, response: schemas.EditTagResponse },GetCompany: {call: schemas.GetCompany,response: schemas.GetCompanyResponse,@@ -274,6 +280,8 @@ type ToolDataMap = {call: types.CreateDocument;response: types.CreateDocumentResponse;};+ CreateTag: { call: types.CreateTag; response: types.CreateTagResponse };+ DeleteTag: { call: types.DeleteTag; response: types.DeleteTagResponse };DisplayResults: {call: types.DisplayResults;response: types.DisplayResultsResponse;@@ -282,6 +290,7 @@ type ToolDataMap = {call: types.EditDocument;response: types.EditDocumentResponse;};+ EditTag: { call: types.EditTag; response: types.EditTagResponse };GetCompany: { call: types.GetCompany; response: types.GetCompanyResponse };GetEntityProperties: {call: types.GetEntityProperties;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.tsindex 732d047f9a..b4b815834c 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@@ -126,6 +126,22 @@ export type ContentType =| 'chat-thread'| 'chat-message'| 'project';+/**+ * A tag color from the fixed palette.+ */+export type TagColor =+ | 'red'+ | 'tomato'+ | 'orange'+ | 'amber'+ | 'yellow'+ | 'green'+ | 'teal'+ | 'blue'+ | 'indigo'+ | 'purple'+ | 'pink'+ | 'gray';/*** Where document content is, or is expected to be, read from.*/@@ -1130,6 +1146,43 @@ export interface CreateDocumentResponse {*/documentId: string;}+/**+ * Create a new tag — a colored label the user can apply to documents, emails, tasks, AI chats, and projects — in the user's personal set or their team's shared set. The set is provisioned automatically the first time a tag is created. Tags are matched by label, so call ListTags first and avoid creating one whose label duplicates an existing tag in the same set. Returns the new tag's id and its set's propertyDefinitionId, which you can pass straight to SetEntityProperty (add_option_ids) to apply the tag to an item. Use this only to create a brand-new tag; to apply an existing tag to an item, use ListTags then SetEntityProperty instead.+ */+export interface CreateTag {+ color: TagColor;+ /**+ * The tag's label, e.g. "Urgent" or "Follow-up".+ */+ label: string;+ scope?: TagScope & string;+}+/**+ * Response from the [`CreateTag`] tool.+ */+export interface CreateTagResponse {+ /**+ * The tag's color, when set.+ */+ color?: string | null;+ /**+ * The new tag's option id. Use it with SetEntityProperty to apply or remove the tag.+ */+ id: string;+ /**+ * The tag's label.+ */+ label: string;+ /**+ * The tag set's property definition id. Use it as propertyDefinitionId with SetEntityProperty.+ */+ propertyDefinitionId: string;+ scope: TagScope;+ /**+ * Human-readable summary.+ */+ summary: string;+}/*** A CRM domain attached to a company in search results.*/@@ -1193,6 +1246,32 @@ export interface CrmCompanySearchResponseItem {*/updatedAt: string;}+/**+ * Permanently delete a tag from the user's personal set or their team's shared set. This removes the tag from every item it is currently applied to, so it is destructive and cannot be undone — confirm with the user first. Both ids come from a ListTags result: `id` is the tag's option id, and `property_definition_id` is the propertyDefinitionId of the set that contains it. To simply remove a tag from a single item without deleting the tag itself, use SetEntityProperty with remove_option_ids instead.+ */+export interface DeleteTag {+ /**+ * The tag's option id (the `id` field from a ListTags result).+ */+ id: string;+ /**+ * The tag set's property definition id (the `propertyDefinitionId` of the ListTags set that contains this tag).+ */+ property_definition_id: string;+}+/**+ * Response from the [`DeleteTag`] tool.+ */+export interface DeleteTagResponse {+ /**+ * Human-readable summary.+ */+ message: string;+ /**+ * Whether the tag was deleted.+ */+ success: boolean;+}/*** Present results to the user as a rich view. The `view` argument is a dynamic-UI view object (a title plus an ordered list of widgets) following the dynamic-UI schema provided to you. The view is rendered immediately in the chat; this tool returns as soon as it is dispatched.*/@@ -1312,6 +1391,52 @@ export interface EditDocumentResponse {*/summary: string;}+/**+ * Rename or recolor an existing tag in the user's personal set or their team's shared set. The tag's id is preserved, so the change is reflected everywhere the tag is already applied — no item loses the tag. Provide the tag's `id` and its set's `property_definition_id` (both from ListTags) plus a new `label` and/or `color`; omit whichever you want to leave unchanged. This edits the tag itself; to change which tags are on a specific item, use SetEntityProperty instead.+ */+export interface EditTag {+ /**+ * A new color for the tag, chosen from the fixed tag palette. Omit to keep the current color.+ */+ color?: TagColor | null;+ /**+ * The tag's option id (the `id` field from a ListTags result).+ */+ id: string;+ /**+ * A new label for the tag. Omit to keep the current label.+ */+ label?: string | null;+ /**+ * The tag set's property definition id (the `propertyDefinitionId` of the ListTags set that contains this tag).+ */+ property_definition_id: string;+}+/**+ * Response from the [`EditTag`] tool.+ */+export interface EditTagResponse {+ /**+ * The tag's color after the edit, when set.+ */+ color?: string | null;+ /**+ * The tag's option id (unchanged).+ */+ id: string;+ /**+ * The tag's label after the edit.+ */+ label: string;+ /**+ * The tag set's property definition id.+ */+ propertyDefinitionId: string;+ /**+ * Human-readable summary.+ */+ summary: string;+}/*** A recipient for an email.*/diff --git a/crates/properties/src/inbound/toolset/create_tag.rs b/crates/properties/src/inbound/toolset/create_tag.rsnew file mode 100644index 0000000000..820f7a9413--- /dev/null+++ b/crates/properties/src/inbound/toolset/create_tag.rs@@ -0,0 +1,145 @@+//! CreateTag tool for adding a new tag to the caller's personal or team set.++use crate::domain::model::TagScope as DomainTagScope;+use crate::domain::service::PropertiesService;+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use models_properties::api::{AddPropertyOptionRequest, AddStringOptionRequest};+use models_properties::service::property_option::PropertyOptionValue;+use models_properties::service::tag_sets::TagScope;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::tag_color::TagColor;+use super::{PropertiesToolContext, caller_team_receipt_opt};++fn default_tag_scope() -> TagScope {+ TagScope::Personal+}++/// Create a new tag in the caller's personal or team set.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(+ title = "CreateTag",+ description = "Create a new tag — a colored label the user can apply to documents, emails, tasks, AI chats, and projects — in the user's personal set or their team's shared set. The set is provisioned automatically the first time a tag is created. Tags are matched by label, so call ListTags first and avoid creating one whose label duplicates an existing tag in the same set. Returns the new tag's id and its set's propertyDefinitionId, which you can pass straight to SetEntityProperty (add_option_ids) to apply the tag to an item. Use this only to create a brand-new tag; to apply an existing tag to an item, use ListTags then SetEntityProperty instead."+)]+#[serde(rename_all = "snake_case")]+pub struct CreateTag {+ #[schemars(description = "The tag's label, e.g. \"Urgent\" or \"Follow-up\".")]+ pub label: String,++ #[schemars(+ description = "The tag's color, chosen from the fixed tag palette. Pick a distinct, sensible color for the label."+ )]+ pub color: TagColor,++ #[schemars(+ description = "Which set to add the tag to: \"personal\" for the user's own private tags (the default), or \"team\" for their team's shared tags. \"team\" requires the user to belong to a team."+ )]+ #[serde(default = "default_tag_scope")]+ pub scope: TagScope,+}++/// Response from the [`CreateTag`] tool.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateTagResponse {+ /// The new tag's option id. Use it with SetEntityProperty to apply or remove the tag.+ pub id: Uuid,+ /// The tag's label.+ pub label: String,+ /// The tag's color, when set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub color: Option<String>,+ /// The tag set's property definition id. Use it as propertyDefinitionId with SetEntityProperty.+ pub property_definition_id: Uuid,+ /// Whether the tag was added to the personal or team set.+ pub scope: TagScope,+ /// Human-readable summary.+ pub summary: String,+}++#[async_trait]+impl<T, A> AsyncTool<PropertiesToolContext<T, A>> for CreateTag+where+ T: PropertiesService,+ A: EntityAccessService,+{+ type Output = CreateTagResponse;++ #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id, scope=?self.scope), err)]+ async fn call(+ &self,+ service_context: ServiceContext<PropertiesToolContext<T, A>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!("Create tag");++ let (domain_scope, team) = match self.scope {+ TagScope::Personal => (DomainTagScope::User, None),+ TagScope::Team => {+ let receipt = caller_team_receipt_opt(&service_context, &request_context)+ .await?+ .ok_or_else(|| ToolCallError {+ description: "You are not on a team, so you can't create a team tag. Create a personal tag instead.".to_string(),+ internal_error: anyhow::anyhow!("team scope without team membership"),+ })?;+ (DomainTagScope::Team, Some(receipt))+ }+ };+ let team_ref = team.as_ref();+ let user_id = &request_context.user_id;++ let tag_set = service_context+ .service+ .ensure_tag_set(user_id, team_ref, domain_scope)+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to prepare the tag set: {e}"),+ internal_error: e.into(),+ })?;++ let definition = tag_set.definition.ok_or_else(|| ToolCallError {+ description: "Failed to prepare the tag set.".to_string(),+ internal_error: anyhow::anyhow!("ensure_tag_set returned no definition"),+ })?;++ let request = AddPropertyOptionRequest::SelectString {+ option: AddStringOptionRequest {+ display_order: tag_set.options.len() as i32,+ value: self.label.clone(),+ color: Some(self.color.hex().to_string()),+ },+ };++ let option = service_context+ .service+ .add_property_option(user_id, team_ref, definition.id, &request)+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to create tag: {e}"),+ internal_error: e.into(),+ })?;++ let label = match option.value {+ PropertyOptionValue::String(s) => s,+ PropertyOptionValue::Number(n) => n.to_string(),+ };+ let scope_word = match self.scope {+ TagScope::Personal => "personal",+ TagScope::Team => "team",+ };+ let summary = format!("Created the {scope_word} tag \"{label}\".");++ Ok(CreateTagResponse {+ id: option.id,+ label,+ color: option.color,+ property_definition_id: definition.id,+ scope: self.scope,+ summary,+ })+ }+}diff --git a/crates/properties/src/inbound/toolset/delete_tag.rs b/crates/properties/src/inbound/toolset/delete_tag.rsnew file mode 100644index 0000000000..eadcfb1aa2--- /dev/null+++ b/crates/properties/src/inbound/toolset/delete_tag.rs@@ -0,0 +1,85 @@+//! DeleteTag tool for permanently removing a tag from the caller's set.++use crate::domain::service::PropertiesService;+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::{PropertiesToolContext, caller_team_receipt_opt};++/// Permanently delete a tag from the caller's personal or team set.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(+ title = "DeleteTag",+ description = "Permanently delete a tag from the user's personal set or their team's shared set. This removes the tag from every item it is currently applied to, so it is destructive and cannot be undone — confirm with the user first. Both ids come from a ListTags result: `id` is the tag's option id, and `property_definition_id` is the propertyDefinitionId of the set that contains it. To simply remove a tag from a single item without deleting the tag itself, use SetEntityProperty with remove_option_ids instead."+)]+#[serde(rename_all = "snake_case")]+pub struct DeleteTag {+ #[schemars(description = "The tag's option id (the `id` field from a ListTags result).")]+ pub id: Uuid,++ #[schemars(+ description = "The tag set's property definition id (the `propertyDefinitionId` of the ListTags set that contains this tag)."+ )]+ pub property_definition_id: Uuid,+}++/// Response from the [`DeleteTag`] tool.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct DeleteTagResponse {+ /// Whether the tag was deleted.+ pub success: bool,+ /// Human-readable summary.+ pub message: String,+}++#[async_trait]+impl<T, A> AsyncTool<PropertiesToolContext<T, A>> for DeleteTag+where+ T: PropertiesService,+ A: EntityAccessService,+{+ type Output = DeleteTagResponse;++ #[tracing::instrument(+ skip_all,+ fields(+ user_id=?request_context.user_id,+ property_definition_id=%self.property_definition_id,+ option_id=%self.id+ ),+ err+ )]+ async fn call(+ &self,+ service_context: ServiceContext<PropertiesToolContext<T, A>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!("Delete tag");++ let team = caller_team_receipt_opt(&service_context, &request_context).await?;++ service_context+ .service+ .delete_property_option(+ &request_context.user_id,+ team.as_ref(),+ self.property_definition_id,+ self.id,+ )+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to delete tag: {e}"),+ internal_error: e.into(),+ })?;++ Ok(DeleteTagResponse {+ success: true,+ message: "Tag deleted successfully.".to_string(),+ })+ }+}diff --git a/crates/properties/src/inbound/toolset/edit_tag.rs b/crates/properties/src/inbound/toolset/edit_tag.rsnew file mode 100644index 0000000000..eeb8a5cf82--- /dev/null+++ b/crates/properties/src/inbound/toolset/edit_tag.rs@@ -0,0 +1,128 @@+//! EditTag tool for renaming or recoloring an existing tag.++use crate::domain::service::PropertiesService;+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};+use async_trait::async_trait;+use entity_access::domain::ports::EntityAccessService;+use models_properties::api::UpdatePropertyOptionRequest;+use models_properties::service::property_option::PropertyOptionValue;+use schemars::JsonSchema;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use super::tag_color::TagColor;+use super::{PropertiesToolContext, caller_team_receipt_opt};++/// Rename or recolor an existing tag.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(+ title = "EditTag",+ description = "Rename or recolor an existing tag in the user's personal set or their team's shared set. The tag's id is preserved, so the change is reflected everywhere the tag is already applied — no item loses the tag. Provide the tag's `id` and its set's `property_definition_id` (both from ListTags) plus a new `label` and/or `color`; omit whichever you want to leave unchanged. This edits the tag itself; to change which tags are on a specific item, use SetEntityProperty instead."+)]+#[serde(rename_all = "snake_case")]+pub struct EditTag {+ #[schemars(description = "The tag's option id (the `id` field from a ListTags result).")]+ pub id: Uuid,++ #[schemars(+ description = "The tag set's property definition id (the `propertyDefinitionId` of the ListTags set that contains this tag)."+ )]+ pub property_definition_id: Uuid,++ #[schemars(description = "A new label for the tag. Omit to keep the current label.")]+ #[serde(default)]+ pub label: Option<String>,++ #[schemars(+ description = "A new color for the tag, chosen from the fixed tag palette. Omit to keep the current color."+ )]+ #[serde(default)]+ pub color: Option<TagColor>,+}++/// Response from the [`EditTag`] tool.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "camelCase")]+pub struct EditTagResponse {+ /// The tag's option id (unchanged).+ pub id: Uuid,+ /// The tag's label after the edit.+ pub label: String,+ /// The tag's color after the edit, when set.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub color: Option<String>,+ /// The tag set's property definition id.+ pub property_definition_id: Uuid,+ /// Human-readable summary.+ pub summary: String,+}++#[async_trait]+impl<T, A> AsyncTool<PropertiesToolContext<T, A>> for EditTag+where+ T: PropertiesService,+ A: EntityAccessService,+{+ type Output = EditTagResponse;++ #[tracing::instrument(+ skip_all,+ fields(+ user_id=?request_context.user_id,+ property_definition_id=%self.property_definition_id,+ option_id=%self.id+ ),+ err+ )]+ async fn call(+ &self,+ service_context: ServiceContext<PropertiesToolContext<T, A>>,+ request_context: RequestContext,+ ) -> ToolResult<Self::Output> {+ tracing::info!("Edit tag");++ if self.label.is_none() && self.color.is_none() {+ return Err(ToolCallError {+ description: "Provide a new label and/or color to edit the tag.".to_string(),+ internal_error: anyhow::anyhow!("edit tag with no changes"),+ });+ }++ let team = caller_team_receipt_opt(&service_context, &request_context).await?;++ let request = UpdatePropertyOptionRequest {+ value: self.label.clone(),+ color: self.color.map(|c| c.hex().to_string()),+ display_order: None,+ };++ let option = service_context+ .service+ .update_property_option(+ &request_context.user_id,+ team.as_ref(),+ self.property_definition_id,+ self.id,+ &request,+ )+ .await+ .map_err(|e| ToolCallError {+ description: format!("Failed to edit tag: {e}"),+ internal_error: e.into(),+ })?;++ let label = match option.value {+ PropertyOptionValue::String(s) => s,+ PropertyOptionValue::Number(n) => n.to_string(),+ };+ let summary = format!("Updated tag \"{label}\".");++ Ok(EditTagResponse {+ id: option.id,+ label,+ color: option.color,+ property_definition_id: self.property_definition_id,+ summary,+ })+ }+}diff --git a/crates/properties/src/inbound/toolset/mod.rs b/crates/properties/src/inbound/toolset/mod.rsindex 10174f64e8..e940b24d76 100644--- a/crates/properties/src/inbound/toolset/mod.rs+++ b/crates/properties/src/inbound/toolset/mod.rs@@ -1,17 +1,27 @@//! Toolset inbound adapter for the Properties service.+mod create_tag;+mod delete_tag;+mod edit_tag;mod get_entity_properties;mod list_tags;mod set_entity_property;+mod tag_color;#[cfg(test)]mod test;-use crate::domain::service::PropertiesService;-use ai_toolset::AsyncToolCollection;+use crate::domain::service::{PropertiesService, TeamReceipt};+use ai_toolset::{AsyncToolCollection, RequestContext, ServiceContext, ToolCallError};+use entity_access::domain::models::{+ AccessError, Entity, EntityAccessReceipt, EntityPermission, EntityType,+};use entity_access::domain::ports::EntityAccessService;use std::sync::Arc;+pub use create_tag::{CreateTag, CreateTagResponse};+pub use delete_tag::{DeleteTag, DeleteTagResponse};+pub use edit_tag::{EditTag, EditTagResponse};pub use get_entity_properties::{GetEntityProperties, GetEntityPropertiesResponse};pub use list_tags::{ListTags, ListTagsResponse};pub use set_entity_property::{SetEntityProperty, SetEntityPropertyResponse};@@ -43,6 +53,48 @@ impl<T: PropertiesService, A: EntityAccessService> PropertiesToolContext<T, A> {}}+/// Mint the caller's team-membership receipt, or `None` when they are not on a+/// team. Owner-scoped tag operations forward this to the domain, which enforces+/// ownership; passing it also lets team-owned tags satisfy the ownership check.+pub(crate) async fn caller_team_receipt_opt<T, A>(+ service_context: &ServiceContext<PropertiesToolContext<T, A>>,+ request_context: &RequestContext,+) -> Result<Option<TeamReceipt>, ToolCallError>+where+ T: PropertiesService,+ A: EntityAccessService,+{+ let Some(team_info) = service_context+ .entity_access_service+ .get_user_team(&request_context.user_id)+ .await+ .map_err(team_access_error)?+ else {+ return Ok(None);+ };++ let receipt: TeamReceipt = EntityAccessReceipt::try_new_authenticated_user(+ request_context.user_id.clone(),+ Entity {+ entity_id: team_info.team_id.to_string(),+ entity_type: EntityType::Team,+ },+ EntityPermission::TeamRole {+ role: team_info.role,+ },+ )+ .map_err(team_access_error)?;++ Ok(Some(receipt))+}++fn team_access_error(err: AccessError) -> ToolCallError {+ ToolCallError {+ description: "Failed to verify your team membership.".to_string(),+ internal_error: err.into(),+ }+}+/// Create a properties toolset.pub fn properties_toolset<T, A>() -> AsyncToolCollection<PropertiesToolContext<T, A>>where@@ -53,4 +105,7 @@ where.add_tool::<GetEntityProperties, PropertiesToolContext<T, A>>().add_tool::<SetEntityProperty, PropertiesToolContext<T, A>>().add_tool::<ListTags, PropertiesToolContext<T, A>>()+ .add_tool::<CreateTag, PropertiesToolContext<T, A>>()+ .add_tool::<EditTag, PropertiesToolContext<T, A>>()+ .add_tool::<DeleteTag, PropertiesToolContext<T, A>>()}diff --git a/crates/properties/src/inbound/toolset/tag_color.rs b/crates/properties/src/inbound/toolset/tag_color.rsnew file mode 100644index 0000000000..51a0197b1f--- /dev/null+++ b/crates/properties/src/inbound/toolset/tag_color.rs@@ -0,0 +1,59 @@+//! The fixed tag color palette the AI may choose from.+//!+//! Mirrors the frontend-owned palette in+//! `apps/web/src/features/property/tags/tagColors.ts` — keep the hex values in+//! sync. Exposing the colors as an enum keeps the AI from inventing colors the+//! tag picker can't render.++use schemars::JsonSchema;+use serde::Deserialize;++/// A tag color from the fixed palette.+#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum TagColor {+ /// Red (`#E5484D`).+ Red,+ /// Tomato (`#E54D2E`).+ Tomato,+ /// Orange (`#F76B15`).+ Orange,+ /// Amber (`#FFB224`).+ Amber,+ /// Yellow (`#F5D90A`).+ Yellow,+ /// Green (`#46A758`).+ Green,+ /// Teal (`#12A594`).+ Teal,+ /// Blue (`#0091FF`).+ Blue,+ /// Indigo (`#3E63DD`).+ Indigo,+ /// Purple (`#8E4EC6`).+ Purple,+ /// Pink (`#E93D82`).+ Pink,+ /// Gray (`#889096`).+ Gray,+}++impl TagColor {+ /// The palette hex value stored on the tag option.+ pub fn hex(self) -> &'static str {+ match self {+ TagColor::Red => "#E5484D",+ TagColor::Tomato => "#E54D2E",+ TagColor::Orange => "#F76B15",+ TagColor::Amber => "#FFB224",+ TagColor::Yellow => "#F5D90A",+ TagColor::Green => "#46A758",+ TagColor::Teal => "#12A594",+ TagColor::Blue => "#0091FF",+ TagColor::Indigo => "#3E63DD",+ TagColor::Purple => "#8E4EC6",+ TagColor::Pink => "#E93D82",+ TagColor::Gray => "#889096",+ }+ }+}diff --git a/crates/properties/src/inbound/toolset/test.rs b/crates/properties/src/inbound/toolset/test.rsindex e1c8f5829c..792492921f 100644--- a/crates/properties/src/inbound/toolset/test.rs+++ b/crates/properties/src/inbound/toolset/test.rs@@ -63,6 +63,71 @@ fn test_list_tags_schema_validation() {);}+#[test]+fn test_create_tag_schema_validation() {+ let result = generate_validated_input_schema::<CreateTag>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(validated.name, "CreateTag");+ assert!(+ validated.description.contains("Create a new tag"),+ "Description should explain that it creates a new tag"+ );++ let schema_json = serde_json::to_string(&validated.schema).unwrap();+ assert!(+ schema_json.contains("label") && schema_json.contains("color"),+ "schema should expose label and color"+ );+ assert!(+ schema_json.contains("scope"),+ "schema should expose the personal/team scope"+ );+}++#[test]+fn test_edit_tag_schema_validation() {+ let result = generate_validated_input_schema::<EditTag>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(validated.name, "EditTag");+ assert!(+ validated.description.contains("Rename or recolor"),+ "Description should explain rename/recolor"+ );++ let schema_json = serde_json::to_string(&validated.schema).unwrap();+ assert!(+ schema_json.contains("label") && schema_json.contains("color"),+ "schema should expose label and color"+ );+ assert!(+ schema_json.contains("property_definition_id"),+ "schema should require the tag set's property_definition_id"+ );+}++#[test]+fn test_delete_tag_schema_validation() {+ let result = generate_validated_input_schema::<DeleteTag>();+ assert!(result.is_ok(), "{:?}", result);++ let validated = result.unwrap();+ assert_eq!(validated.name, "DeleteTag");+ assert!(+ validated.description.contains("Permanently delete a tag"),+ "Description should explain the destructive delete"+ );++ let schema_json = serde_json::to_string(&validated.schema).unwrap();+ assert!(+ schema_json.contains("property_definition_id"),+ "schema should require the tag set's property_definition_id"+ );+}+// run `cargo test -p properties inbound::toolset::test::print_get_input_schema -- --nocapture --include-ignored`#[test]#[ignore = "prints the input schema"]