From 33800acec44b01773d866a8cd856242574d4cf09 Mon Sep 17 00:00:00 2001 From: muterC <36739961+muterC@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:17:04 +0800 Subject: [PATCH 1/5] feat(teamhub): streamline room and agent approval flows --- .../agent/prompt/compact-meta-instructions.ts | 4 +- .../meta-anotherme-collaboration-compact.txt | 2 +- .../meta-anotherme-direct-compact.txt | 4 +- .../meta-general-collaboration-compact.txt | 2 +- .../meta-general-direct-compact.txt | 2 +- apps/teamhub-cli/README.md | 2 +- .../cli.help-snapshot.test.ts.snap | 34 +- .../teamhub-cli/src/business-commands.test.ts | 36 ++ apps/teamhub-cli/src/business-commands.ts | 11 +- apps/teamhub-cli/src/business-render.ts | 20 +- apps/teamhub-cli/src/command-manifest.test.ts | 2 +- apps/teamhub-cli/src/connector-approval.ts | 4 +- .../collaboration/tools/creation-schemas.ts | 49 +- .../internal/agentconnectedapps/access.go | 5 +- .../agentconnectedapps/access_test.go | 16 +- .../internal/agentcreationapproval/service.go | 19 +- .../internal/agentregistry/agent_agents.go | 19 +- .../internal/agentregistry/agent_api.go | 61 ++- ...contract_server_agent_creation_approval.go | 10 +- .../typedcard/creation_approval_decision.go | 140 +++--- .../internal/typedcard/room_creation_now.go | 166 +++++++ .../integration/agent_cli_agents_test.go | 128 +++-- .../agent_cli_collaboration_test.go | 34 +- .../mcp_creation_approval_access_test.go | 67 ++- .../integration/mcp_creation_approval_test.go | 436 +++++++----------- .../tests/integration/message_core_test.go | 15 +- .../room_member_pending_decision_test.go | 22 +- .../integration/work_item_fixture_test.go | 32 +- .../go/teamhubagentapi/openapi.gen.go | 46 +- .../src/generated/teamhub-agent-api/types.ts | 32 +- .../components/agent-collaboration.yaml | 40 +- .../openapi/teamhub-agent-api/openapi.yaml | 11 +- .../tests/teamhub-agent-api.contract.test.ts | 16 +- 33 files changed, 926 insertions(+), 561 deletions(-) create mode 100644 apps/teamhub/internal/typedcard/room_creation_now.go diff --git a/apps/node-services/src/agent/prompt/compact-meta-instructions.ts b/apps/node-services/src/agent/prompt/compact-meta-instructions.ts index 778783770..21edfa5c4 100644 --- a/apps/node-services/src/agent/prompt/compact-meta-instructions.ts +++ b/apps/node-services/src/agent/prompt/compact-meta-instructions.ts @@ -90,7 +90,7 @@ const STATIC_COMMANDS = (connectedApps: boolean): string => Add "multiple": true to allow several options. Every question must be answered. Ask an open question or a missing fact in your reply, unless a rule below asks for a card. - To show something the person looks at or uses here and now (a quick chart, dashboard, checklist or small tool), send it inline as a chat card (read the chat-card skill first); use the artifact skill only for a file to share, print, present or keep, or when a file is asked for. - For a Human-requested deck or PPT, first ask for any missing audience, style or number of slides with one question card (teamhub message ask-user), never in a plain reply, and read the slide-deck skill before starting its Task. For proactive preparation, infer the audience, style and slide count from the occasion without a question card. Build new .pptx decks with the built-in pptx skill, even when another Skill also covers presentations. -- Agents: teamhub room invite --agent-id brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "" --prompt "" adds a new teammate; teamhub agent update [--agent-id ] --prompt "..." updates an Agent you manage (or yourself when specialist). A change to an established Agent waits for approval.${connectedApps ? CONNECTED_APPS_COMMANDS_STATIC : ""} +- Agents: teamhub room invite --agent-id brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "" --prompt "" adds a new teammate; teamhub agent update [--agent-id ] --prompt "..." updates an Agent you manage (or yourself when specialist). A prompt change to an established Agent waits for approval.${connectedApps ? CONNECTED_APPS_COMMANDS_STATIC : ""} - With --operation-id, use a unique id per write; after an unknown outcome, rerun the same command with the id the error printed.`; const STATIC_ENVIRONMENT = (connectedApps: boolean): string => @@ -121,7 +121,7 @@ const DIRECT_TASKS = `Stay available: keep your own turns short and delegate hea const ROOM_TASKS = `- Delegate research and multi-step investigation to your AlterEgo so the Room isn't blocked on you: ${TASK_COMMAND}`; const DIRECT_ANOTHERME = `${DIRECT_TASKS} -- For multi-Agent work over time, find Agents your Human authorized with teamhub agent list, then propose a collaboration Room: teamhub room create --name "" --member-id (repeat per member) --content "" (--artifact-id to bring Documents). It waits for approval; then continue the work there. +- For multi-Agent work over time, find Agents your Human authorized with teamhub agent list, then create a collaboration Room: teamhub room create --name "" --member-id (repeat per member) --content "" (--artifact-id to bring Documents). It creates the Room at once; continue the work there. - When your Human asks you to start or steer work in another Room you both are in, resolve the Room name to a kind=room room: with teamhub message read --list-inboxes first if needed (ask your Human to clarify if multiple Rooms share that name), then hand it to yourself there: teamhub room handoff --inbox room: --content "", then confirm here in one line. Never ask your Human to forward a message.`; const DIRECT_SPECIALIST = `${DIRECT_TASKS} diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-compact.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-compact.txt index 61f6decc2..9b724abdd 100644 --- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-compact.txt +++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-compact.txt @@ -57,7 +57,7 @@ TeamHub commands, all run through your shell tool (teamhub --h Add "multiple": true to allow several options. Every question must be answered. Ask an open question or a missing fact in your reply, unless a rule below asks for a card. - To show something the person looks at or uses here and now (a quick chart, dashboard, checklist or small tool), send it inline as a chat card (read the chat-card skill first); use the artifact skill only for a file to share, print, present or keep, or when a file is asked for. - For a Human-requested deck or PPT, first ask for any missing audience, style or number of slides with one question card (teamhub message ask-user), never in a plain reply, and read the slide-deck skill before starting its Task. For proactive preparation, infer the audience, style and slide count from the occasion without a question card. Build new .pptx decks with the built-in pptx skill, even when another Skill also covers presentations. -- Agents: teamhub room invite --agent-id brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "" --prompt "" adds a new teammate; teamhub agent update [--agent-id ] --prompt "..." updates an Agent you manage (or yourself when specialist). A change to an established Agent waits for approval. +- Agents: teamhub room invite --agent-id brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "" --prompt "" adds a new teammate; teamhub agent update [--agent-id ] --prompt "..." updates an Agent you manage (or yourself when specialist). A prompt change to an established Agent waits for approval. - Connected apps: gmail, outlook, feishu-mail, outlook-calendar, gcal, gdrive, slack, notion, and figma have their own commands (teamhub gmail --help). For other apps, search with teamhub apps search "" and execute with teamhub apps execute --connectionId --toolSlug --toolVersion --arguments ''. Use apps listed as connected at Run start below without checking first; check teamhub apps list only if connectivity changed or a command reports no account. Never resend a write whose outcome is unknown; check the app first. - With --operation-id, use a unique id per write; after an unknown outcome, rerun the same command with the id the error printed. diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-compact.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-compact.txt index a3ba5544d..f043c65f0 100644 --- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-compact.txt +++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-compact.txt @@ -57,7 +57,7 @@ TeamHub commands, all run through your shell tool (teamhub --h Add "multiple": true to allow several options. Every question must be answered. Ask an open question or a missing fact in your reply, unless a rule below asks for a card. - To show something the person looks at or uses here and now (a quick chart, dashboard, checklist or small tool), send it inline as a chat card (read the chat-card skill first); use the artifact skill only for a file to share, print, present or keep, or when a file is asked for. - For a Human-requested deck or PPT, first ask for any missing audience, style or number of slides with one question card (teamhub message ask-user), never in a plain reply, and read the slide-deck skill before starting its Task. For proactive preparation, infer the audience, style and slide count from the occasion without a question card. Build new .pptx decks with the built-in pptx skill, even when another Skill also covers presentations. -- Agents: teamhub room invite --agent-id brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "" --prompt "" adds a new teammate; teamhub agent update [--agent-id ] --prompt "..." updates an Agent you manage (or yourself when specialist). A change to an established Agent waits for approval. +- Agents: teamhub room invite --agent-id brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "" --prompt "" adds a new teammate; teamhub agent update [--agent-id ] --prompt "..." updates an Agent you manage (or yourself when specialist). A prompt change to an established Agent waits for approval. - Connected apps: gmail, outlook, feishu-mail, outlook-calendar, gcal, gdrive, slack, notion, and figma have their own commands (teamhub gmail --help). For other apps, search with teamhub apps search "" and execute with teamhub apps execute --connectionId --toolSlug --toolVersion --arguments ''. Use apps listed as connected at Run start below without checking first; check teamhub apps list only if connectivity changed or a command reports no account. Never resend a write whose outcome is unknown; check the app first. - With --operation-id, use a unique id per write; after an unknown outcome, rerun the same command with the id the error printed. @@ -119,7 +119,7 @@ In a direct chat, keep continuity, and respond to emotion only as far as the mes ## Working with others Stay available: keep your own turns short and delegate heavier work. - Delegate non-trivial work (web research, several files, producing a document or file, a long command sequence) to your AlterEgo: teamhub task create --name "" --requirement "<brief>" (--requirement-file for a long brief). It starts at once, and up to 10 run in parallel; give each independent piece its own Task. Do quick answers and one-step lookups yourself. -- For multi-Agent work over time, find Agents your Human authorized with teamhub agent list, then propose a collaboration Room: teamhub room create --name "<name>" --member-id <actor-id> (repeat per member) --content "<self-contained brief>" (--artifact-id <document-id> to bring Documents). It waits for approval; then continue the work there. +- For multi-Agent work over time, find Agents your Human authorized with teamhub agent list, then create a collaboration Room: teamhub room create --name "<name>" --member-id <actor-id> (repeat per member) --content "<self-contained brief>" (--artifact-id <document-id> to bring Documents). It creates the Room at once; continue the work there. - When your Human asks you to start or steer work in another Room you both are in, resolve the Room name to a kind=room room:<room-id> with teamhub message read --list-inboxes first if needed (ask your Human to clarify if multiple Rooms share that name), then hand it to yourself there: teamhub room handoff --inbox room:<room-id> --content "<self-contained instruction, only what your Human would share there>", then confirm here in one line. Never ask your Human to forward a message. ## Who you answer to diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-collaboration-compact.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-collaboration-compact.txt index 511da3472..ad36703d0 100644 --- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-collaboration-compact.txt +++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-collaboration-compact.txt @@ -57,7 +57,7 @@ TeamHub commands, all run through your shell tool (teamhub <domain> <action> --h Add "multiple": true to allow several options. Every question must be answered. Ask an open question or a missing fact in your reply, unless a rule below asks for a card. - To show something the person looks at or uses here and now (a quick chart, dashboard, checklist or small tool), send it inline as a chat card (read the chat-card skill first); use the artifact skill only for a file to share, print, present or keep, or when a file is asked for. - For a Human-requested deck or PPT, first ask for any missing audience, style or number of slides with one question card (teamhub message ask-user), never in a plain reply, and read the slide-deck skill before starting its Task. For proactive preparation, infer the audience, style and slide count from the occasion without a question card. Build new .pptx decks with the built-in pptx skill, even when another Skill also covers presentations. -- Agents: teamhub room invite --agent-id <actor-id> brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "<name>" --prompt "<working instructions>" adds a new teammate; teamhub agent update [--agent-id <actor-id>] --prompt "..." updates an Agent you manage (or yourself when specialist). A change to an established Agent waits for approval. +- Agents: teamhub room invite --agent-id <actor-id> brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "<name>" --prompt "<working instructions>" adds a new teammate; teamhub agent update [--agent-id <actor-id>] --prompt "..." updates an Agent you manage (or yourself when specialist). A prompt change to an established Agent waits for approval. - Connected apps: gmail, outlook, feishu-mail, outlook-calendar, gcal, gdrive, slack, notion, and figma have their own commands (teamhub gmail --help). For other apps, search with teamhub apps search "<action in English + app>" and execute with teamhub apps execute --connectionId <id> --toolSlug <slug> --toolVersion <version> --arguments '<json>'. Use apps listed as connected at Run start below without checking first; check teamhub apps list only if connectivity changed or a command reports no account. Never resend a write whose outcome is unknown; check the app first. - With --operation-id, use a unique id per write; after an unknown outcome, rerun the same command with the id the error printed. diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-direct-compact.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-direct-compact.txt index a04db6a32..4d6d890e3 100644 --- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-direct-compact.txt +++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-general-direct-compact.txt @@ -57,7 +57,7 @@ TeamHub commands, all run through your shell tool (teamhub <domain> <action> --h Add "multiple": true to allow several options. Every question must be answered. Ask an open question or a missing fact in your reply, unless a rule below asks for a card. - To show something the person looks at or uses here and now (a quick chart, dashboard, checklist or small tool), send it inline as a chat card (read the chat-card skill first); use the artifact skill only for a file to share, print, present or keep, or when a file is asked for. - For a Human-requested deck or PPT, first ask for any missing audience, style or number of slides with one question card (teamhub message ask-user), never in a plain reply, and read the slide-deck skill before starting its Task. For proactive preparation, infer the audience, style and slide count from the occasion without a question card. Build new .pptx decks with the built-in pptx skill, even when another Skill also covers presentations. -- Agents: teamhub room invite --agent-id <actor-id> brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "<name>" --prompt "<working instructions>" adds a new teammate; teamhub agent update [--agent-id <actor-id>] --prompt "..." updates an Agent you manage (or yourself when specialist). A change to an established Agent waits for approval. +- Agents: teamhub room invite --agent-id <actor-id> brings an Agent from teamhub agent list into this Room (not a direct chat); teamhub agent create --name "<name>" --prompt "<working instructions>" adds a new teammate; teamhub agent update [--agent-id <actor-id>] --prompt "..." updates an Agent you manage (or yourself when specialist). A prompt change to an established Agent waits for approval. - Connected apps: gmail, outlook, feishu-mail, outlook-calendar, gcal, gdrive, slack, notion, and figma have their own commands (teamhub gmail --help). For other apps, search with teamhub apps search "<action in English + app>" and execute with teamhub apps execute --connectionId <id> --toolSlug <slug> --toolVersion <version> --arguments '<json>'. Use apps listed as connected at Run start below without checking first; check teamhub apps list only if connectivity changed or a command reports no account. Never resend a write whose outcome is unknown; check the app first. - With --operation-id, use a unique id per write; after an unknown outcome, rerun the same command with the id the error printed. diff --git a/apps/teamhub-cli/README.md b/apps/teamhub-cli/README.md index a2aa96092..bd694c2eb 100644 --- a/apps/teamhub-cli/README.md +++ b/apps/teamhub-cli/README.md @@ -66,7 +66,7 @@ Task completion uses only the generation, attempt and input revision accepted be The current entry points are the ones help lists. -`agent list` and `agent get --agent-id <actor-id>` show the General Agents under a Sponsor. `agent create --name <name> --prompt-file <path>` creates an Agent in the current Room, and `agent update` changes only the name, description or prompt it is given; without `--agent-id` it changes the caller. When the Sponsor must confirm, the command returns a confirmation card and exits 0; TeamHub runs it after approval and reports the result, so do not run it again. `room invite --agent-id <actor-id>` adds an existing Agent from `agent list` to the current Room at once, with the Sponsor's authority; a Direct Room or Thread keeps its members. A Task context cannot use these commands. +`agent list` and `agent get --agent-id <actor-id>` show the General Agents under a Sponsor. `agent create --name <name> --prompt-file <path>` creates an Agent at once: in a Room the Sponsor is in it joins that Room, and in the Sponsor's Direct Room it is created without joining. `agent update` changes only the name, description or prompt it is given; without `--agent-id` it changes the caller. A name or description change runs at once; a prompt change runs at once only for an uninitialized Agent in the current Room. Any other prompt change, and an `agent create` in a Room the Sponsor is not in, waits for the Sponsor: the command returns a confirmation card and exits 0; TeamHub runs it after approval and reports the result, so do not run it again. `room create --name <name> --member-id <actor-id> --content <brief>` creates a collaboration Room at once, owned by the Sponsor, with its members and first message, and hands the work to the caller in that Room. `room invite --agent-id <actor-id>` adds an existing Agent from `agent list` to the current Room at once, with the Sponsor's authority; a Direct Room or Thread keeps its members. A Task context cannot use these commands. `room handoff --inbox room:<room-id> --content <instruction>` lets Another Me, in its direct chat and in a turn its Human started by writing or deciding a card, hand that request to itself in another Room where both are members. TeamHub posts a hidden handoff there that wakes Another Me's Context in that Room, which then posts and mentions Agents itself; the direct chat never writes in that Room. Results come back with `message direct`. diff --git a/apps/teamhub-cli/src/__snapshots__/cli.help-snapshot.test.ts.snap b/apps/teamhub-cli/src/__snapshots__/cli.help-snapshot.test.ts.snap index bcfe85bc7..ae713bb08 100644 --- a/apps/teamhub-cli/src/__snapshots__/cli.help-snapshot.test.ts.snap +++ b/apps/teamhub-cli/src/__snapshots__/cli.help-snapshot.test.ts.snap @@ -41,7 +41,7 @@ Acts on the Human who owns this Agent (AnotherMe only), never on another Human. "agent create": { "help": "exit 0 teamhub agent create [flags] -Create a General Agent in this Room; a Direct Room needs the sponsor's card. +Create a General Agent of your sponsor; it joins this Room when your sponsor is a member. Options: --name <value> Stable role-oriented Agent name. @@ -53,11 +53,12 @@ Options: -h Show help. --schema Show offline input and output schemas. --operation-id <value> Stable operation identity for recovery. -Outside a Direct Room the new Agent joins this Room at once; wake it there with an Agent reference. -In a Direct Room the sponsor first approves a confirmation card in the chat; TeamHub then creates the Agent and sends you the result, or the denial and its reason. +In a Room your sponsor is in, the new Agent joins it at once; wake it there with an Agent reference. +In your sponsor's Direct Room TeamHub creates the Agent at once without adding it to that chat; the sponsor finds it in their own chat with it. +In a Room your sponsor is not in, the sponsor first approves a confirmation card; TeamHub then creates the Agent and sends you the result, or the denial and its reason. ", "schema": "exit 0 -{"command":["agent","create"],"description":"Create a General Agent in this Room; a Direct Room needs the sponsor's card.","read_only":false,"input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["name","prompt"],"properties":{"name":{"type":"string","minLength":1,"maxLength":120,"description":"Stable role-oriented display name."},"prompt":{"type":"string","minLength":1,"maxLength":50000,"description":"Complete standalone working instructions for the new Agent."},"description":{"description":"Optional Human-facing description of the Agent.","type":"string","maxLength":1000}},"additionalProperties":false,"description":"A new General Agent for the current Human sponsor; TeamHub derives its sponsor, Runtime and Room."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["applied","confirmation_pending"],"description":"applied: TeamHub made the change now. confirmation_pending: it waits for the sponsor's card."},"actor_id":{"description":"The created or changed Agent, when applied.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"room_id":{"description":"When applied, the Room a created Agent joined; when pending, the Room holding the card.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"message_id":{"description":"The confirmation card message, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"interaction_id":{"description":"The confirmation interaction, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"}},"additionalProperties":false,"description":"Result of creating or changing a General Agent."},"cli":{"usage":["teamhub agent create [flags]"],"arguments":[],"options":{"--name":{"description":"Stable role-oriented Agent name."},"--description":{"description":"Optional Human-facing description."},"--prompt":{"description":"Complete working prompt; outside code, \\\\n, \\\\t and \\\\\\\\ are decoded."},"--prompt-file":{"description":"Read the UTF-8 prompt from a file or - for stdin."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["Outside a Direct Room the new Agent joins this Room at once; wake it there with an Agent reference.","In a Direct Room the sponsor first approves a confirmation card in the chat; TeamHub then creates the Agent and sends you the result, or the denial and its reason."]}} +{"command":["agent","create"],"description":"Create a General Agent of your sponsor; it joins this Room when your sponsor is a member.","read_only":false,"input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["name","prompt"],"properties":{"name":{"type":"string","minLength":1,"maxLength":120,"description":"Stable role-oriented display name."},"prompt":{"type":"string","minLength":1,"maxLength":50000,"description":"Complete standalone working instructions for the new Agent."},"description":{"description":"Optional Human-facing description of the Agent.","type":"string","maxLength":1000}},"additionalProperties":false,"description":"A new General Agent for the current Human sponsor; TeamHub derives its sponsor, Runtime and Room."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["applied","confirmation_pending"],"description":"applied: TeamHub made the change now. confirmation_pending: it waits for the sponsor's card."},"actor_id":{"description":"The created or changed Agent, when applied.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"room_id":{"description":"When applied, the Room a created Agent joined; when pending, the Room holding the card.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"message_id":{"description":"The confirmation card message, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"interaction_id":{"description":"The confirmation interaction, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"}},"additionalProperties":false,"description":"Result of creating or changing a General Agent."},"cli":{"usage":["teamhub agent create [flags]"],"arguments":[],"options":{"--name":{"description":"Stable role-oriented Agent name."},"--description":{"description":"Optional Human-facing description."},"--prompt":{"description":"Complete working prompt; outside code, \\\\n, \\\\t and \\\\\\\\ are decoded."},"--prompt-file":{"description":"Read the UTF-8 prompt from a file or - for stdin."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["In a Room your sponsor is in, the new Agent joins it at once; wake it there with an Agent reference.","In your sponsor's Direct Room TeamHub creates the Agent at once without adding it to that chat; the sponsor finds it in their own chat with it.","In a Room your sponsor is not in, the sponsor first approves a confirmation card; TeamHub then creates the Agent and sends you the result, or the denial and its reason."]}} ", }, "agent get": { @@ -109,10 +110,10 @@ Options: -h Show help. --schema Show offline input and output schemas. --operation-id <value> Stable operation identity for recovery. -TeamHub applies the change at once only to an uninitialized Agent in this Room. Otherwise the sponsor approves a confirmation card in the chat; TeamHub then applies it and sends you the result, or the denial and its reason. +A change of only --name or --description applies at once. A prompt change applies at once only to an uninitialized Agent in this Room; otherwise the sponsor approves a confirmation card in the chat, and TeamHub then applies it and sends you the result, or the denial and its reason. ", "schema": "exit 0 -{"command":["agent","update"],"description":"Change the name, description or prompt of yourself or another General Agent of the sponsor.","read_only":false,"input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"actor_id":{"description":"Agent Actor ID to change; omit it to change yourself.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"name":{"description":"New display name.","type":"string","minLength":1,"maxLength":120},"description":{"description":"New Human-facing description.","type":"string","maxLength":1000},"prompt":{"description":"New complete working instructions.","type":"string","minLength":1,"maxLength":50000}},"additionalProperties":false,"description":"Changes to one General Agent of the current Human sponsor; omitted fields are kept."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["applied","confirmation_pending"],"description":"applied: TeamHub made the change now. confirmation_pending: it waits for the sponsor's card."},"actor_id":{"description":"The created or changed Agent, when applied.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"room_id":{"description":"When applied, the Room a created Agent joined; when pending, the Room holding the card.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"message_id":{"description":"The confirmation card message, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"interaction_id":{"description":"The confirmation interaction, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"}},"additionalProperties":false,"description":"Result of creating or changing a General Agent."},"cli":{"usage":["teamhub agent update [flags]"],"arguments":[],"options":{"--agent-id":{"description":"Agent Actor ID to change; omit it to change yourself."},"--name":{"description":"New Agent name."},"--description":{"description":"New Human-facing description."},"--prompt":{"description":"Complete working prompt; outside code, \\\\n, \\\\t and \\\\\\\\ are decoded."},"--prompt-file":{"description":"Read the UTF-8 prompt from a file or - for stdin."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["TeamHub applies the change at once only to an uninitialized Agent in this Room. Otherwise the sponsor approves a confirmation card in the chat; TeamHub then applies it and sends you the result, or the denial and its reason."]}} +{"command":["agent","update"],"description":"Change the name, description or prompt of yourself or another General Agent of the sponsor.","read_only":false,"input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"actor_id":{"description":"Agent Actor ID to change; omit it to change yourself.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"name":{"description":"New display name.","type":"string","minLength":1,"maxLength":120},"description":{"description":"New Human-facing description.","type":"string","maxLength":1000},"prompt":{"description":"New complete working instructions.","type":"string","minLength":1,"maxLength":50000}},"additionalProperties":false,"description":"Changes to one General Agent of the current Human sponsor; omitted fields are kept."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["status"],"properties":{"status":{"type":"string","enum":["applied","confirmation_pending"],"description":"applied: TeamHub made the change now. confirmation_pending: it waits for the sponsor's card."},"actor_id":{"description":"The created or changed Agent, when applied.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"room_id":{"description":"When applied, the Room a created Agent joined; when pending, the Room holding the card.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"message_id":{"description":"The confirmation card message, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"interaction_id":{"description":"The confirmation interaction, when pending.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"}},"additionalProperties":false,"description":"Result of creating or changing a General Agent."},"cli":{"usage":["teamhub agent update [flags]"],"arguments":[],"options":{"--agent-id":{"description":"Agent Actor ID to change; omit it to change yourself."},"--name":{"description":"New Agent name."},"--description":{"description":"New Human-facing description."},"--prompt":{"description":"Complete working prompt; outside code, \\\\n, \\\\t and \\\\\\\\ are decoded."},"--prompt-file":{"description":"Read the UTF-8 prompt from a file or - for stdin."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["A change of only --name or --description applies at once. A prompt change applies at once only to an uninitialized Agent in this Room; otherwise the sponsor approves a confirmation card in the chat, and TeamHub then applies it and sends you the result, or the denial and its reason."]}} ", }, "apps auto-reminders list": { @@ -2354,7 +2355,6 @@ OUTPUT Shows the actual account, plus Append receipt plus read-back verification and completeness. A fragment in a page URL does not narrow the read or edit range; databases and whole-page overwrite are out of scope. -The external write waits for the sponsor to approve a confirmation card in the chat; TeamHub then runs it and sends you the result, or the denial and its reason. Help and schema are available offline; TeamHub checks current access at execution time. EXAMPLES @@ -2365,7 +2365,7 @@ LEARN MORE teamhub notion append --schema --json ", "schema": "exit 0 -{"command":["notion","append"],"description":"Append content at the end of the page and keep the existing body.","read_only":false,"input_schema":{"type":"object","additionalProperties":false,"properties":{"pageId":{"type":"string","minLength":1},"content":{"type":"string","maxLength":1048576},"markdown":{"type":"boolean"},"account":{"type":"string","minLength":1,"maxLength":240}}},"output_schema":{"anyOf":[{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":true,"required":["action","acknowledged"],"properties":{"action":{"type":"string","minLength":1},"acknowledged":{"const":true}}}}},{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":false,"required":["action","confirmation"],"properties":{"action":{"const":"confirmation_requested"},"confirmation":{"type":"object","additionalProperties":false,"required":["status","interactionId","messageId","roomId"],"properties":{"status":{"const":"pending"},"interactionId":{"type":"string","minLength":1},"messageId":{"type":"string","minLength":1},"roomId":{"type":"string","minLength":1}}}}}}}]},"cli":{"usage":["teamhub notion append <page> [flags]"],"arguments":[],"options":{"--content":{"description":"Body text; exclusive with --file; plain text by default."},"--file":{"description":"UTF-8 body file; - reads stdin."},"--markdown":{"description":"Use the common Markdown subset validated by the backend.","boolean":true},"--account":{"description":"Select a connection ID or complete account label; when authorization is missing, an authorization card is shown in the chat."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["A fragment in a page URL does not narrow the read or edit range; databases and whole-page overwrite are out of scope.","The external write waits for the sponsor to approve a confirmation card in the chat; TeamHub then runs it and sends you the result, or the denial and its reason.","Help and schema are available offline; TeamHub checks current access at execution time."]}} +{"command":["notion","append"],"description":"Append content at the end of the page and keep the existing body.","read_only":false,"input_schema":{"type":"object","additionalProperties":false,"properties":{"pageId":{"type":"string","minLength":1},"content":{"type":"string","maxLength":1048576},"markdown":{"type":"boolean"},"account":{"type":"string","minLength":1,"maxLength":240}}},"output_schema":{"anyOf":[{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":true,"required":["action","acknowledged"],"properties":{"action":{"type":"string","minLength":1},"acknowledged":{"const":true}}}}},{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":false,"required":["action","confirmation"],"properties":{"action":{"const":"confirmation_requested"},"confirmation":{"type":"object","additionalProperties":false,"required":["status","interactionId","messageId","roomId"],"properties":{"status":{"const":"pending"},"interactionId":{"type":"string","minLength":1},"messageId":{"type":"string","minLength":1},"roomId":{"type":"string","minLength":1}}}}}}}]},"cli":{"usage":["teamhub notion append <page> [flags]"],"arguments":[],"options":{"--content":{"description":"Body text; exclusive with --file; plain text by default."},"--file":{"description":"UTF-8 body file; - reads stdin."},"--markdown":{"description":"Use the common Markdown subset validated by the backend.","boolean":true},"--account":{"description":"Select a connection ID or complete account label; when authorization is missing, an authorization card is shown in the chat."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["A fragment in a page URL does not narrow the read or edit range; databases and whole-page overwrite are out of scope.","Help and schema are available offline; TeamHub checks current access at execution time."]}} ", }, "notion create": { @@ -2394,7 +2394,6 @@ OUTPUT Shows the actual account, plus New page ID/URL and read-back verification. A fragment in a page URL does not narrow the read or edit range; databases and whole-page overwrite are out of scope. -The external write waits for the sponsor to approve a confirmation card in the chat; TeamHub then runs it and sends you the result, or the denial and its reason. Help and schema are available offline; TeamHub checks current access at execution time. EXAMPLES @@ -2405,7 +2404,7 @@ LEARN MORE teamhub notion create --schema --json ", "schema": "exit 0 -{"command":["notion","create"],"description":"Create an ordinary document under a parent page.","read_only":false,"input_schema":{"type":"object","additionalProperties":false,"properties":{"parentId":{"type":"string","minLength":1},"title":{"type":"string","minLength":1},"content":{"type":"string","maxLength":1048576},"markdown":{"type":"boolean"},"account":{"type":"string","minLength":1,"maxLength":240}}},"output_schema":{"anyOf":[{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":true,"required":["action","acknowledged"],"properties":{"action":{"type":"string","minLength":1},"acknowledged":{"const":true}}}}},{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":false,"required":["action","confirmation"],"properties":{"action":{"const":"confirmation_requested"},"confirmation":{"type":"object","additionalProperties":false,"required":["status","interactionId","messageId","roomId"],"properties":{"status":{"const":"pending"},"interactionId":{"type":"string","minLength":1},"messageId":{"type":"string","minLength":1},"roomId":{"type":"string","minLength":1}}}}}}}]},"cli":{"usage":["teamhub notion create --parent <page> --title <text> [flags]"],"arguments":[],"options":{"--content":{"description":"Body text; exclusive with --file; plain text by default."},"--file":{"description":"UTF-8 body file; - reads stdin."},"--markdown":{"description":"Use the common Markdown subset validated by the backend.","boolean":true},"--parent":{"description":"Parent page URL or UUID."},"--title":{"description":"Title of the new document."},"--account":{"description":"Select a connection ID or complete account label; when authorization is missing, an authorization card is shown in the chat."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["A fragment in a page URL does not narrow the read or edit range; databases and whole-page overwrite are out of scope.","The external write waits for the sponsor to approve a confirmation card in the chat; TeamHub then runs it and sends you the result, or the denial and its reason.","Help and schema are available offline; TeamHub checks current access at execution time."]}} +{"command":["notion","create"],"description":"Create an ordinary document under a parent page.","read_only":false,"input_schema":{"type":"object","additionalProperties":false,"properties":{"parentId":{"type":"string","minLength":1},"title":{"type":"string","minLength":1},"content":{"type":"string","maxLength":1048576},"markdown":{"type":"boolean"},"account":{"type":"string","minLength":1,"maxLength":240}}},"output_schema":{"anyOf":[{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":true,"required":["action","acknowledged"],"properties":{"action":{"type":"string","minLength":1},"acknowledged":{"const":true}}}}},{"type":"object","additionalProperties":false,"required":["account","result"],"properties":{"account":{"type":"object","additionalProperties":false,"required":["connectionId","name","displayName","identityLabel"],"properties":{"connectionId":{"type":"string","minLength":1},"name":{"type":"string","minLength":1},"displayName":{"type":"string"},"identityLabel":{"type":"string"}}},"result":{"type":"object","additionalProperties":false,"required":["action","confirmation"],"properties":{"action":{"const":"confirmation_requested"},"confirmation":{"type":"object","additionalProperties":false,"required":["status","interactionId","messageId","roomId"],"properties":{"status":{"const":"pending"},"interactionId":{"type":"string","minLength":1},"messageId":{"type":"string","minLength":1},"roomId":{"type":"string","minLength":1}}}}}}}]},"cli":{"usage":["teamhub notion create --parent <page> --title <text> [flags]"],"arguments":[],"options":{"--content":{"description":"Body text; exclusive with --file; plain text by default."},"--file":{"description":"UTF-8 body file; - reads stdin."},"--markdown":{"description":"Use the common Markdown subset validated by the backend.","boolean":true},"--parent":{"description":"Parent page URL or UUID."},"--title":{"description":"Title of the new document."},"--account":{"description":"Select a connection ID or complete account label; when authorization is missing, an authorization card is shown in the chat."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":["A fragment in a page URL does not narrow the read or edit range; databases and whole-page overwrite are out of scope.","Help and schema are available offline; TeamHub checks current access at execution time."]}} ", }, "notion edit": { @@ -3196,7 +3195,7 @@ Options: "room create": { "help": "exit 0 teamhub room create [flags] -Request Human approval for a Room and its first message. +Create a collaboration Room with its members and first message; your sponsor owns it. Options: --name <value> Proposed Room name. @@ -3216,7 +3215,7 @@ Options: --operation-id <value> Stable operation identity for recovery. ", "schema": "exit 0 -{"command":["room","create"],"description":"Request Human approval for a Room and its first message.","read_only":false,"input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["name","member_ids","initial_message_segments"],"properties":{"name":{"type":"string","description":"Name of the proposed collaboration Room.","minLength":1,"maxLength":120},"description":{"type":"string","description":"Optional description of the proposed collaboration Room.","maxLength":2000},"member_ids":{"minItems":1,"maxItems":100,"type":"array","items":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable TeamHub Actor identifier of one proposed member."},"description":"TeamHub Actors who will join the Room after approval.","uniqueItems":true},"artifacts":{"description":"Optional existing Documents delivered with the initial message after approval.","minItems":1,"maxItems":5,"type":"array","items":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable unified Document identifier delivered with the initial Room message."},"uniqueItems":true},"initial_message_segments":{"minItems":1,"maxItems":1000,"type":"array","items":{"oneOf":[{"type":"object","required":["type","content"],"properties":{"type":{"type":"string","const":"text","description":"Discriminator identifying the message segment kind."},"content":{"type":"string","description":"User-visible text carried by this segment.","minLength":1,"maxLength":50000}},"additionalProperties":false,"description":"Plain text segment. Include both fields, for example {\\"type\\":\\"text\\",\\"content\\":\\"Start here.\\"}."},{"type":"object","required":["type","content","target","target_type"],"properties":{"type":{"type":"string","const":"reference","description":"Discriminator identifying the message segment kind."},"content":{"type":"string","description":"User-visible text carried by this segment.","minLength":1,"maxLength":50000},"target":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable TeamHub Actor identifier referenced by this segment."},"target_type":{"type":"string","enum":["agent","user"],"description":"Declared Actor kind; TeamHub verifies it against the target."}},"additionalProperties":false,"description":"Actor-reference segment. Include type:\\"reference\\", content, target, and target_type; for example {\\"type\\":\\"reference\\",\\"content\\":\\"@Analyst\\",\\"target\\":\\"actor_analyst\\",\\"target_type\\":\\"agent\\"}."}],"description":"One text or Actor-reference segment of the initial message."},"description":"Ordered structured segments of the initial message created after approval."}},"additionalProperties":false,"description":"Arguments accepted by the create_room tool."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["accepted","status","creation_approval_request_id","message_id"],"properties":{"accepted":{"type":"boolean","const":true,"description":"Whether TeamHub accepted the Creation request."},"status":{"type":"string","const":"pending_approval","description":"Current state of the Creation request."},"creation_approval_request_id":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable identifier of the Creation approval request."},"message_id":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable identifier of the Human approval card message."}},"additionalProperties":false,"description":"Successful result returned by the create_room tool."},"cli":{"usage":["teamhub room create [flags]"],"arguments":[],"options":{"--name":{"description":"Proposed Room name."},"--description":{"description":"Optional description."},"--member-id":{"description":"Explicit member Actor ID; repeat for each member.","repeatable":true},"--member-ids":{"description":"Explicit member Actor ID array as JSON."},"--content":{"description":"Inline Markdown body; outside code, \\\\n, \\\\t and \\\\\\\\ are decoded."},"--file":{"description":"Read UTF-8 body from a file or - for stdin."},"--initial-message-segments":{"description":"Initial text/reference segments as a JSON array."},"--initial-message-segments-file":{"description":"Read initial-message-segments JSON from a file or - for stdin."},"--artifact-id":{"description":"Authorized existing Document ID; repeat up to five times.","repeatable":true},"--artifacts":{"description":"Authorized Document IDs as a JSON array."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":[]}} +{"command":["room","create"],"description":"Create a collaboration Room with its members and first message; your sponsor owns it.","read_only":false,"input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["name","member_ids","initial_message_segments"],"properties":{"name":{"type":"string","description":"Name of the new collaboration Room.","minLength":1,"maxLength":120},"description":{"type":"string","description":"Optional description of the new collaboration Room.","maxLength":2000},"member_ids":{"minItems":1,"maxItems":100,"type":"array","items":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable TeamHub Actor identifier of one proposed member."},"description":"TeamHub Actors who join the new Room.","uniqueItems":true},"artifacts":{"description":"Optional existing Documents delivered with the initial message.","minItems":1,"maxItems":5,"type":"array","items":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable unified Document identifier delivered with the initial Room message."},"uniqueItems":true},"initial_message_segments":{"minItems":1,"maxItems":1000,"type":"array","items":{"oneOf":[{"type":"object","required":["type","content"],"properties":{"type":{"type":"string","const":"text","description":"Discriminator identifying the message segment kind."},"content":{"type":"string","description":"User-visible text carried by this segment.","minLength":1,"maxLength":50000}},"additionalProperties":false,"description":"Plain text segment. Include both fields, for example {\\"type\\":\\"text\\",\\"content\\":\\"Start here.\\"}."},{"type":"object","required":["type","content","target","target_type"],"properties":{"type":{"type":"string","const":"reference","description":"Discriminator identifying the message segment kind."},"content":{"type":"string","description":"User-visible text carried by this segment.","minLength":1,"maxLength":50000},"target":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Stable TeamHub Actor identifier referenced by this segment."},"target_type":{"type":"string","enum":["agent","user"],"description":"Declared Actor kind; TeamHub verifies it against the target."}},"additionalProperties":false,"description":"Actor-reference segment. Include type:\\"reference\\", content, target, and target_type; for example {\\"type\\":\\"reference\\",\\"content\\":\\"@Analyst\\",\\"target\\":\\"actor_analyst\\",\\"target_type\\":\\"agent\\"}."}],"description":"One text or Actor-reference segment of the initial message."},"description":"Ordered structured segments of the new Room's initial message."}},"additionalProperties":false,"description":"Arguments accepted by the create_room tool."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","required":["accepted","status"],"properties":{"accepted":{"type":"boolean","const":true,"description":"Whether TeamHub accepted the Creation request."},"status":{"type":"string","enum":["created","pending_approval"],"description":"created when the Room exists; pending_approval only when an earlier submission's approval card still waits."},"room_id":{"description":"The created Room, when status is created.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"skipped_artifacts":{"description":"Requested Documents the new Room did not receive.","type":"array","items":{"type":"object","required":["document_id","reason"],"properties":{"document_id":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Document not delivered."},"reason":{"type":"string","description":"Why it was not delivered."}},"additionalProperties":false,"description":"A requested Document the new Room did not receive."}},"creation_approval_request_id":{"description":"The pending approval request, when status is pending_approval.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"},"message_id":{"description":"The pending approval card, when status is pending_approval.","type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$"}},"additionalProperties":false,"description":"Successful result returned by the create_room tool."},"cli":{"usage":["teamhub room create [flags]"],"arguments":[],"options":{"--name":{"description":"Proposed Room name."},"--description":{"description":"Optional description."},"--member-id":{"description":"Explicit member Actor ID; repeat for each member.","repeatable":true},"--member-ids":{"description":"Explicit member Actor ID array as JSON."},"--content":{"description":"Inline Markdown body; outside code, \\\\n, \\\\t and \\\\\\\\ are decoded."},"--file":{"description":"Read UTF-8 body from a file or - for stdin."},"--initial-message-segments":{"description":"Initial text/reference segments as a JSON array."},"--initial-message-segments-file":{"description":"Read initial-message-segments JSON from a file or - for stdin."},"--artifact-id":{"description":"Authorized existing Document ID; repeat up to five times.","repeatable":true},"--artifacts":{"description":"Authorized Document IDs as a JSON array."},"--json":{"description":"Return machine-readable JSON.","boolean":true},"--help":{"description":"Show this offline command reference.","boolean":true},"-h":{"description":"Show help.","boolean":true},"--schema":{"description":"Show offline input and output schemas.","boolean":true},"--operation-id":{"description":"Stable operation identity for recovery."}},"notes":[]}} ", }, "room handoff": { @@ -4035,7 +4034,7 @@ Options: --schema Show offline input and output schemas. teamhub agent create [flags] -Create a General Agent in this Room; a Direct Room needs the sponsor's card. +Create a General Agent of your sponsor; it joins this Room when your sponsor is a member. Options: --name <value> Stable role-oriented Agent name. @@ -4047,8 +4046,9 @@ Options: -h Show help. --schema Show offline input and output schemas. --operation-id <value> Stable operation identity for recovery. -Outside a Direct Room the new Agent joins this Room at once; wake it there with an Agent reference. -In a Direct Room the sponsor first approves a confirmation card in the chat; TeamHub then creates the Agent and sends you the result, or the denial and its reason. +In a Room your sponsor is in, the new Agent joins it at once; wake it there with an Agent reference. +In your sponsor's Direct Room TeamHub creates the Agent at once without adding it to that chat; the sponsor finds it in their own chat with it. +In a Room your sponsor is not in, the sponsor first approves a confirmation card; TeamHub then creates the Agent and sends you the result, or the denial and its reason. teamhub agent update [flags] Change the name, description or prompt of yourself or another General Agent of the sponsor. @@ -4064,7 +4064,7 @@ Options: -h Show help. --schema Show offline input and output schemas. --operation-id <value> Stable operation identity for recovery. -TeamHub applies the change at once only to an uninitialized Agent in this Room. Otherwise the sponsor approves a confirmation card in the chat; TeamHub then applies it and sends you the result, or the denial and its reason. +A change of only --name or --description applies at once. A prompt change applies at once only to an uninitialized Agent in this Room; otherwise the sponsor approves a confirmation card in the chat, and TeamHub then applies it and sends you the result, or the denial and its reason. ", "apps": "exit 0 teamhub apps list [flags] @@ -4853,7 +4853,7 @@ Options: ", "room": "exit 0 teamhub room create [flags] -Request Human approval for a Room and its first message. +Create a collaboration Room with its members and first message; your sponsor owns it. Options: --name <value> Proposed Room name. diff --git a/apps/teamhub-cli/src/business-commands.test.ts b/apps/teamhub-cli/src/business-commands.test.ts index fdb659dbb..5be57cd2c 100644 --- a/apps/teamhub-cli/src/business-commands.test.ts +++ b/apps/teamhub-cli/src/business-commands.test.ts @@ -695,6 +695,42 @@ describe("agent commands", () => { ); }); + it("creates a Room at once and names the Documents it did not deliver", async () => { + const result = await run( + [ + "room", + "create", + "--name", + "Launch", + "--member-id", + "actor_two", + "--content", + "Plan the launch.", + ], + { + accepted: true, + status: "created", + room_id: "room_new", + skipped_artifacts: [ + { document_id: "document_gone", reason: "deleted" }, + ], + }, + ); + expect(result.exitCode).toBe(0); + expect(result.path()).toBe("/api/agent/v1/creation-approval-requests"); + expect(result.stdout).toBe( + "Created Room room_new. Continue the work there; its handoff wakes you in that Room.\nNot delivered: document_gone (deleted)\n", + ); + expect( + renderBusinessResult("room create", { + accepted: true, + status: "pending_approval", + creation_approval_request_id: "approval_one", + message_id: "message_one", + }), + ).toContain("Room creation approval requested"); + }); + it("changes only the given fields and reports a pending card without failing", async () => { const result = await run( ["agent", "update", "--prompt", "Line one\\nLine two"], diff --git a/apps/teamhub-cli/src/business-commands.ts b/apps/teamhub-cli/src/business-commands.ts index 7ec828a27..6b9d28a37 100644 --- a/apps/teamhub-cli/src/business-commands.ts +++ b/apps/teamhub-cli/src/business-commands.ts @@ -260,7 +260,7 @@ const agentGet = definition( const agentCreate = definition( ["agent", "create"], "create_agent", - "Create a General Agent in this Room; a Direct Room needs the sponsor's card.", + "Create a General Agent of your sponsor; it joins this Room when your sponsor is a member.", { "--name": flag("Stable role-oriented Agent name."), "--description": flag("Optional Human-facing description."), @@ -280,8 +280,9 @@ const agentCreate = definition( approval: "confirm", unavailableInTask: agentsUnavailableInTask, notes: [ - "Outside a Direct Room the new Agent joins this Room at once; wake it there with an Agent reference.", - "In a Direct Room the sponsor first approves a confirmation card in the chat; TeamHub then creates the Agent and sends you the result, or the denial and its reason.", + "In a Room your sponsor is in, the new Agent joins it at once; wake it there with an Agent reference.", + "In your sponsor's Direct Room TeamHub creates the Agent at once without adding it to that chat; the sponsor finds it in their own chat with it.", + "In a Room your sponsor is not in, the sponsor first approves a confirmation card; TeamHub then creates the Agent and sends you the result, or the denial and its reason.", ], }, ); @@ -319,7 +320,7 @@ const agentUpdate = definition( approval: "confirm", unavailableInTask: agentsUnavailableInTask, notes: [ - "TeamHub applies the change at once only to an uninitialized Agent in this Room. Otherwise the sponsor approves a confirmation card in the chat; TeamHub then applies it and sends you the result, or the denial and its reason.", + "A change of only --name or --description applies at once. A prompt change applies at once only to an uninitialized Agent in this Room; otherwise the sponsor approves a confirmation card in the chat, and TeamHub then applies it and sends you the result, or the denial and its reason.", ], }, ); @@ -825,7 +826,7 @@ const skillPublish = definition( const roomCreate = definition( ["room", "create"], "create_room", - "Request Human approval for a Room and its first message.", + "Create a collaboration Room with its members and first message; your sponsor owns it.", { "--name": flag("Proposed Room name."), ...creationOptions, diff --git a/apps/teamhub-cli/src/business-render.ts b/apps/teamhub-cli/src/business-render.ts index ab852835b..8d33dd4a0 100644 --- a/apps/teamhub-cli/src/business-render.ts +++ b/apps/teamhub-cli/src/business-render.ts @@ -340,13 +340,23 @@ export function renderBusinessResult(command: string, result: Json): string { result.duplicate_request ? "Task already stopped" : "Task stopped", `Task ID: ${String(result.task_id)}`, ].join("\n"); - if (command === "room create") + if (command === "room create") { + if (result.status === "pending_approval") + return [ + "Room creation approval requested", + `Status: ${String(result.status)}`, + `Approval request: ${String(result.creation_approval_request_id)}`, + `Message ID: ${String(result.message_id)}`, + ].join("\n"); + const skipped = (result.skipped_artifacts as Json[] | undefined) ?? []; return [ - "Room creation approval requested", - `Status: ${String(result.status)}`, - `Approval request: ${String(result.creation_approval_request_id)}`, - `Message ID: ${String(result.message_id)}`, + `Created Room ${singleLine(result.room_id)}. Continue the work there; its handoff wakes you in that Room.`, + ...skipped.map( + (item) => + `Not delivered: ${singleLine(item.document_id)} (${singleLine(item.reason)})`, + ), ].join("\n"); + } if (command === "room collaborate") return [ `Published Room collaboration protocol`, diff --git a/apps/teamhub-cli/src/command-manifest.test.ts b/apps/teamhub-cli/src/command-manifest.test.ts index e5b1e8f28..911de2579 100644 --- a/apps/teamhub-cli/src/command-manifest.test.ts +++ b/apps/teamhub-cli/src/command-manifest.test.ts @@ -53,7 +53,7 @@ describe("command manifest", () => { Object.values(connectorWriteApproval).filter( (value) => value === "confirm", ), - ).toHaveLength(12); + ).toHaveLength(10); }); // Hosts match command prefixes, so an allowed command must never cover a diff --git a/apps/teamhub-cli/src/connector-approval.ts b/apps/teamhub-cli/src/connector-approval.ts index aa4ca83f7..c2056228a 100644 --- a/apps/teamhub-cli/src/connector-approval.ts +++ b/apps/teamhub-cli/src/connector-approval.ts @@ -31,8 +31,8 @@ export const connectorWriteApproval: Readonly<Record<string, CommandApproval>> = "outlook-calendar create": "judge", "outlook-calendar update": "judge", "outlook-calendar cancel": "judge", - "notion create": "confirm", - "notion append": "confirm", + "notion create": "judge", + "notion append": "judge", "notion edit": "confirm", "gdrive mkdir": "allow", "gdrive upload": "judge", diff --git a/apps/teamhub-cli/src/domains/collaboration/tools/creation-schemas.ts b/apps/teamhub-cli/src/domains/collaboration/tools/creation-schemas.ts index 311850d42..ad747e22d 100644 --- a/apps/teamhub-cli/src/domains/collaboration/tools/creation-schemas.ts +++ b/apps/teamhub-cli/src/domains/collaboration/tools/creation-schemas.ts @@ -133,32 +133,32 @@ const roomCreationArtifactsSchema = z ) .meta({ description: - "Existing Documents from the authorized source Room to share after approval.", + "Existing Documents from the authorized source Room to share with the new Room.", uniqueItems: true, }); export const createRoomInputSchema = z .object({ name: codePointString({ - description: "Name of the proposed collaboration Room.", + description: "Name of the new collaboration Room.", max: MAX_CREATION_TITLE_CODE_POINTS, nonBlank: true, }), description: codePointString({ - description: "Optional description of the proposed collaboration Room.", + description: "Optional description of the new collaboration Room.", max: MAX_CREATION_DESCRIPTION_CODE_POINTS, optionalEmpty: true, }).optional(), member_ids: creationMemberIdsSchema.describe( - "TeamHub Actors who will join the Room after approval.", + "TeamHub Actors who join the new Room.", ), artifacts: roomCreationArtifactsSchema .optional() .describe( - "Optional existing Documents delivered with the initial message after approval.", + "Optional existing Documents delivered with the initial message.", ), initial_message_segments: creationMessageSegmentsSchema.describe( - "Ordered structured segments of the initial message created after approval.", + "Ordered structured segments of the new Room's initial message.", ), }) .strict() @@ -183,23 +183,40 @@ export const createTaskInputSchema = z "Arguments accepted by create_task. The Task starts at once for your own AlterEgo; no approval is requested.", ); -const creationApprovalOutputShape = { +const createRoomOutputShape = { accepted: z .literal(true) .describe("Whether TeamHub accepted the Creation request."), status: z - .literal("pending_approval") - .describe("Current state of the Creation request."), - creation_approval_request_id: teamHubIdSchema.describe( - "Stable identifier of the Creation approval request.", - ), - message_id: teamHubIdSchema.describe( - "Stable identifier of the Human approval card message.", - ), + .enum(["created", "pending_approval"]) + .describe( + "created when the Room exists; pending_approval only when an earlier submission's approval card still waits.", + ), + room_id: teamHubIdSchema + .optional() + .describe("The created Room, when status is created."), + skipped_artifacts: z + .array( + z + .object({ + document_id: teamHubIdSchema.describe("Document not delivered."), + reason: z.string().describe("Why it was not delivered."), + }) + .strict() + .describe("A requested Document the new Room did not receive."), + ) + .optional() + .describe("Requested Documents the new Room did not receive."), + creation_approval_request_id: teamHubIdSchema + .optional() + .describe("The pending approval request, when status is pending_approval."), + message_id: teamHubIdSchema + .optional() + .describe("The pending approval card, when status is pending_approval."), }; export const createRoomOutputSchema = z - .object(creationApprovalOutputShape) + .object(createRoomOutputShape) .strict() .describe("Successful result returned by the create_room tool."); export type CreateRoomInput = z.output<typeof createRoomInputSchema>; diff --git a/apps/teamhub/internal/agentconnectedapps/access.go b/apps/teamhub/internal/agentconnectedapps/access.go index 33ab3893c..1f109c255 100644 --- a/apps/teamhub/internal/agentconnectedapps/access.go +++ b/apps/teamhub/internal/agentconnectedapps/access.go @@ -183,7 +183,8 @@ var readTools = map[string]bool{ // preparatory writes before a confirmed send (drafts, chats, attachments), // archives, new folders, and the writes hosts send to their // permission reviewer ("judge" in the CLI's connectorWriteApproval), which -// include paid media generation. +// include paid media generation and Notion pages created or appended to, +// which page history can undo. Notion edits replace content and stay held. var directWriteTools = map[string]bool{ "FAL_AI_SUBMIT_ASYNC_JOB": true, "FAL_AI_UPLOAD_FILE": true, @@ -204,6 +205,8 @@ var directWriteTools = map[string]bool{ "HIGGSFIELD_MCP_GENERATE_VIDEO": true, "HIGGSFIELD_MCP_MEDIA_CONFIRM": true, "HIGGSFIELD_MCP_MEDIA_UPLOAD": true, + "NOTION_ADD_MULTIPLE_PAGE_CONTENT": true, + "NOTION_CREATE_NOTION_PAGE": true, "OUTLOOK_ADD_MAIL_ATTACHMENT": true, "OUTLOOK_CALENDAR_CREATE_EVENT": true, "OUTLOOK_CANCEL_CALENDAR_EVENT": true, diff --git a/apps/teamhub/internal/agentconnectedapps/access_test.go b/apps/teamhub/internal/agentconnectedapps/access_test.go index ef97c65d6..596167357 100644 --- a/apps/teamhub/internal/agentconnectedapps/access_test.go +++ b/apps/teamhub/internal/agentconnectedapps/access_test.go @@ -206,10 +206,24 @@ var cardTools = []string{ "GMAIL_SEND_EMAIL", "GMAIL_SEND_DRAFT", "GMAIL_REPLY_TO_THREAD", "OUTLOOK_SEND_EMAIL", "OUTLOOK_SEND_DRAFT", "SLACK_SEND_MESSAGE", "SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK", - "NOTION_CREATE_NOTION_PAGE", "NOTION_ADD_MULTIPLE_PAGE_CONTENT", "NOTION_UPDATE_PAGE_MARKDOWN", + "NOTION_UPDATE_PAGE_MARKDOWN", "GITHUB_CREATE_AN_ISSUE", "GITHUB_CREATE_AN_ISSUE_COMMENT", } +// Creating or appending to a Notion page adds content that page history can +// undo, so it runs at once and the host's reviewer judges it; an edit +// replaces content and still waits for the card. +func TestAccessRunsAdditiveNotionWritesAtOnce(t *testing.T) { + for _, slug := range []string{"NOTION_CREATE_NOTION_PAGE", "NOTION_ADD_MULTIPLE_PAGE_CONTENT"} { + if accessOf(slug, nil) != accessWrite { + t.Errorf("%s must run at once", slug) + } + } + if accessOf("NOTION_UPDATE_PAGE_MARKDOWN", nil) != accessConfirm { + t.Error("NOTION_UPDATE_PAGE_MARKDOWN replaces content and must wait for confirmation") + } +} + func TestAccessListsKeepConfirmedWritesHeld(t *testing.T) { for _, slug := range cardTools { if accessOf(slug, nil) != accessConfirm { diff --git a/apps/teamhub/internal/agentcreationapproval/service.go b/apps/teamhub/internal/agentcreationapproval/service.go index 4c69920e3..2a72c2669 100644 --- a/apps/teamhub/internal/agentcreationapproval/service.go +++ b/apps/teamhub/internal/agentcreationapproval/service.go @@ -76,9 +76,13 @@ type AvailableAgentPage struct { NextCursor string } +// Result is a submitted Room creation: the created Room's response body, or, +// for a submission replayed from before Rooms were created at once, its +// pending approval card. type Result struct { CreationApprovalRequestID string MessageID string + Created json.RawMessage Replay bool } @@ -168,6 +172,8 @@ func (s *Service) ListAvailableAgents( }, nil } +// Submit creates the Agent's requested Room at once, owned by its Sponsor, +// after authorizing the caller and freezing the Room it asked for. func (s *Service) Submit( ctx context.Context, token string, @@ -189,7 +195,7 @@ func (s *Service) Submit( if err != nil { return Result{}, err } - created, err := s.cards.CreateCreationApprovalRequestInTx(ctx, tx, typedcard.CreationApprovalInTxInput{ + created, err := s.cards.CreateRoomInTx(ctx, tx, typedcard.CreationApprovalInTxInput{ RoomID: resolved.roomID, AgentManagementID: resolved.authorization.AgentID, ExpectedAgentActorID: resolved.authorization.AgentActorID, ExpectedTenantID: resolved.authorization.TenantID, @@ -225,10 +231,13 @@ func (s *Service) Submit( if err := tx.Commit(ctx); err != nil { return Result{}, err } - return Result{ - CreationApprovalRequestID: created.DecisionID, - MessageID: created.MessageID, Replay: created.Replay, - }, nil + if created.DecisionID != "" { + return Result{ + CreationApprovalRequestID: created.DecisionID, + MessageID: created.MessageID, Replay: created.Replay, + }, nil + } + return Result{Created: created.Body, Replay: created.Replay}, nil } func (s *Service) authorizeSubmission( diff --git a/apps/teamhub/internal/agentregistry/agent_agents.go b/apps/teamhub/internal/agentregistry/agent_agents.go index 99e92bcab..906703a6a 100644 --- a/apps/teamhub/internal/agentregistry/agent_agents.go +++ b/apps/teamhub/internal/agentregistry/agent_agents.go @@ -111,14 +111,21 @@ func ValidAgentProfileChange(change AgentProfileChange) bool { // CreateSponsorAgent registers a General Agent of the Sponsor with the // caller's Runtime, exactly like a Web creation. key makes it idempotent. func (s *Service) CreateSponsorAgent(ctx context.Context, accountID, tenantID, callerActorID string, change AgentProfileChange, key string) (string, error) { + actorID, _, err := s.createSponsorAgent(ctx, accountID, tenantID, callerActorID, change, key) + return actorID, err +} + +// createSponsorAgent is CreateSponsorAgent that also reports whether key +// replayed an earlier creation. +func (s *Service) createSponsorAgent(ctx context.Context, accountID, tenantID, callerActorID string, change AgentProfileChange, key string) (string, bool, error) { caller, err := s.queries.GetAgentRegistrationByActor(ctx, store.GetAgentRegistrationByActorParams{ ActorID: callerActorID, TenantID: tenantID, }) if err != nil { - return "", err + return "", false, err } if caller.Status != "active" { - return "", collaboration.ErrAgentSponsorRequired + return "", false, collaboration.ErrAgentSponsorRequired } agentType, visibility := httpapi.CreatableAgentTypeGeneral, httpapi.AgentVisibilityScopeSponsor result, err := s.ExecuteTenantAgentRegistration(ctx, accountID, tenantID, httpapi.TenantAgentCreateRequest{ @@ -126,16 +133,16 @@ func (s *Service) CreateSponsorAgent(ctx context.Context, accountID, tenantID, c Runtime: agentRuntimeConfig(agentRegistrationFromRow(caller)), AgentType: &agentType, VisibilityScope: &visibility, }, key) if err != nil { - return "", err + return "", false, err } var created httpapi.TenantAgent if err := json.Unmarshal(result.Body, &created); err != nil { - return "", err + return "", false, err } if created.Actor.Id == "" { - return "", errors.New("created Agent has no Actor") + return "", false, errors.New("created Agent has no Actor") } - return created.Actor.Id, nil + return created.Actor.Id, result.Replay, nil } // AgentChangeRequest is the stored change a decision runs. diff --git a/apps/teamhub/internal/agentregistry/agent_api.go b/apps/teamhub/internal/agentregistry/agent_api.go index e18a539d7..d1804a5c7 100644 --- a/apps/teamhub/internal/agentregistry/agent_api.go +++ b/apps/teamhub/internal/agentregistry/agent_api.go @@ -8,6 +8,7 @@ import ( "github.com/simplexai-labs/linger/apps/teamhub/internal/agentauth" "github.com/simplexai-labs/linger/apps/teamhub/internal/collaboration" "github.com/simplexai-labs/linger/apps/teamhub/internal/idempotency" + "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation" "github.com/simplexai-labs/linger/apps/teamhub/internal/store" "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard" api "github.com/simplexai-labs/linger/contracts-go/teamhubagentapi" @@ -54,9 +55,11 @@ func (s *Service) GetSponsorAgent(ctx context.Context, authorizer agentauth.Auth } // UpdateSponsorAgent changes the profile of the caller, or of another -// General Agent of its Sponsor. The change runs at once only while the -// target is still uninitialized and in the caller's Room; otherwise the -// Sponsor must confirm it. +// General Agent of its Sponsor. A change of only the name or description runs +// at once, since it changes no behavior. A prompt change runs at once only +// while the target is still uninitialized and in the caller's Room; otherwise +// the Sponsor must confirm it, since a prompt is what an injected instruction +// would rewrite to persist. func (s *Service) UpdateSponsorAgent(ctx context.Context, authorizer agentauth.Authorizer, token string, request api.AgentUpdateAgentRequest, change AgentProfileChange) (AgentChange, error) { caller, err := authorizer.Authorize(ctx, token, "update_agent") if err != nil { @@ -113,7 +116,8 @@ func (s *Service) UpdateSponsorAgent(ctx context.Context, authorizer agentauth.A return AgentChange{}, err } } - if !member || !collaboration.IsUninitializedAgentProfile(target.registration.Instructions) { + profileOnly := change.Instructions == nil + if auth.RoomID == "" || (!profileOnly && (!member || !collaboration.IsUninitializedAgentProfile(target.registration.Instructions))) { if err := tx.Rollback(ctx); err != nil { return AgentChange{}, err } @@ -146,8 +150,9 @@ func (s *Service) UpdateSponsorAgent(ctx context.Context, authorizer agentauth.A } // CreateSponsorGeneralAgent creates a General Agent of the caller's Sponsor -// and adds it to the caller's Room when it can join; otherwise the Sponsor -// must confirm the creation. +// and adds it to the caller's Room when it can join. In the Sponsor's own +// Direct Room, where only the Sponsor can have asked, it creates the Agent +// without joining it; anywhere else the Sponsor must confirm the creation. func (s *Service) CreateSponsorGeneralAgent(ctx context.Context, authorizer agentauth.Authorizer, token string, request api.AgentCreateAgentRequest, change AgentProfileChange) (AgentChange, error) { tx, err := s.pool.Begin(ctx) if err != nil { @@ -174,31 +179,40 @@ func (s *Service) CreateSponsorGeneralAgent(ctx context.Context, authorizer agen } // The new Agent joins the caller's Room only when it can: a Direct Room has // fixed members, and the Sponsor is the one who admits it. - joinable := false + direct, sponsorMember := false, false if auth.RoomID != "" { - direct, err := queries.IsTenantDirectRoom(ctx, store.IsTenantDirectRoomParams{RoomID: auth.RoomID, TenantID: auth.TenantID}) + direct, err = queries.IsTenantDirectRoom(ctx, store.IsTenantDirectRoomParams{RoomID: auth.RoomID, TenantID: auth.TenantID}) if err != nil { return AgentChange{}, err } - sponsorMember, err := queries.IsActiveRoomMember(ctx, store.IsActiveRoomMemberParams{RoomID: auth.RoomID, TenantID: auth.TenantID, ActorID: auth.SponsorActorID}) + sponsorMember, err = queries.IsActiveRoomMember(ctx, store.IsActiveRoomMemberParams{RoomID: auth.RoomID, TenantID: auth.TenantID, ActorID: auth.SponsorActorID}) if err != nil { return AgentChange{}, err } - joinable = !direct && sponsorMember } if err := tx.Commit(ctx); err != nil { return AgentChange{}, err } - if !joinable { + joinable := !direct && sponsorMember + sponsorDirect := direct && sponsorMember + if !joinable && !sponsorDirect { return AgentChange{Auth: auth, Confirm: &typedcard.AgentChangeDecision{ Request: typedcard.AgentChangeRequest{Change: agentChangeRequestOf(change)}, View: agentCreateCard(change), }}, nil } - actorID, err := s.CreateSponsorAgent(ctx, accountID, auth.TenantID, auth.AgentActorID, change, "agent-create:"+request.InvocationId) + actorID, replay, err := s.createSponsorAgent(ctx, accountID, auth.TenantID, auth.AgentActorID, change, "agent-create:"+request.InvocationId) if err != nil { return AgentChange{}, err } + if sponsorDirect { + if err := s.settleDirectRoomCreation(ctx, accountID, auth, actorID, replay); err != nil { + return AgentChange{}, err + } + return AgentChange{Auth: auth, Status: http.StatusOK, Created: &api.AgentAgentChangeResponse{ + Status: api.AgentChangeApplied, ActorId: &actorID, + }}, nil + } if _, _, err := s.collaboration.PutRoomMember(ctx, accountID, auth.RoomID, actorID, httpapi.Member, collaboration.AddedByAgent{ActorID: auth.AgentActorID, Created: true}); err != nil { return AgentChange{}, err } @@ -207,6 +221,29 @@ func (s *Service) CreateSponsorGeneralAgent(ctx context.Context, authorizer agen }}, nil } +// settleDirectRoomCreation finishes a creation in the Sponsor's Direct Room +// as an approved creation card does: it opens the new Agent's own Direct Room, +// which the sidebar lists it by, and announces the Agent where it was asked +// for. A replayed creation was already announced. +func (s *Service) settleDirectRoomCreation(ctx context.Context, accountID string, auth agentauth.Authorization, actorID string, replay bool) error { + if _, err := s.collaboration.OpenDirectRoom(ctx, accountID, auth.TenantID, actorID); err != nil { + return err + } + if replay { + return nil + } + actors := make([]store.Actor, 0, 2) + for _, id := range []string{auth.AgentActorID, actorID} { + actor, err := s.queries.GetActor(ctx, store.GetActorParams{ID: id, TenantID: auth.TenantID}) + if err != nil { + return err + } + actors = append(actors, actor) + } + _, err := messagecreation.CreateNotice(ctx, s.queries, auth.TenantID, auth.RoomID, actors[0], messagecreation.AgentCreated(actors[1], nil)) + return err +} + // AddSponsorAgentToRoom adds an existing Agent to the caller's Room with its // Sponsor's authority, as the Sponsor could from the Web. It reports the Room's // newly admitted Agents, empty when the Agent already was a member. diff --git a/apps/teamhub/internal/app/contract_server_agent_creation_approval.go b/apps/teamhub/internal/app/contract_server_agent_creation_approval.go index 9a0f6f027..79b8fb931 100644 --- a/apps/teamhub/internal/app/contract_server_agent_creation_approval.go +++ b/apps/teamhub/internal/app/contract_server_agent_creation_approval.go @@ -92,10 +92,14 @@ func (a *App) submitAgentCreationApprovalRequest(c *gin.Context) { if a.writeAgentCreationApprovalError(c, err) { return } + if result.Created != nil { + c.Data(http.StatusOK, "application/json", result.Created) + return + } c.JSON(http.StatusOK, teamhubagentapi.AgentCreationApprovalResponse{ - Accepted: true, Status: "pending_approval", - CreationApprovalRequestId: result.CreationApprovalRequestID, - MessageId: result.MessageID, + Accepted: true, Status: teamhubagentapi.PendingApproval, + CreationApprovalRequestId: &result.CreationApprovalRequestID, + MessageId: &result.MessageID, }) } func agentCreationApprovalRequestToDomain( diff --git a/apps/teamhub/internal/typedcard/creation_approval_decision.go b/apps/teamhub/internal/typedcard/creation_approval_decision.go index 9f6628553..1dc3073d7 100644 --- a/apps/teamhub/internal/typedcard/creation_approval_decision.go +++ b/apps/teamhub/internal/typedcard/creation_approval_decision.go @@ -70,13 +70,80 @@ type roomCreationApproval struct { // share, posts its initial message and handoff, and reports the result in // the origin Room. It returns those Messages and the created Room. func (a roomCreationApproval) approve(ctx context.Context, tx pgx.Tx, queries *store.Queries) (decisionOutcome, string, error) { - decisionOwner, accountID := a.owner, a.accountID + decisionOwner := a.owner + room, err := createSnapshotRoom(ctx, tx, queries, snapshotRoomSpec{ + tenantID: a.tenantID, originRoomID: a.originRoomID, agentActorID: a.agentActorID, accountID: a.accountID, + owner: decisionOwner, snapshot: a.snapshot, bindingKey: "room-create-artifacts:" + a.decisionID, + }) + if err != nil { + return decisionOutcome{}, "", err + } + snapshot, agent, delivered, skipped := room.snapshot, room.agent, room.delivered, room.skipped + created := room.created + // The decision recorded decided_at in this transaction; the handoff carries it. + var decidedAt time.Time + if err := tx.QueryRow(ctx, `SELECT decided_at FROM decisions WHERE id=$1`, a.decisionID).Scan(&decidedAt); err != nil { + return decisionOutcome{}, "", err + } + // The handoff shares the initial message's transaction and Room topic, so the + // requesting Agent's new Room Context accepts both in one batch and wakes once. + handoff, err := persistRoomCreationHandoffMessage( + ctx, queries, a.tenantID, created.Room.ID, decisionOwner, agent, + a.decisionID, a.cardMessageID, a.originRoomID, snapshot.Description, delivered, decidedAt, + ) + if err != nil { + return decisionOutcome{}, "", err + } + if _, err := messagecreation.Publish(ctx, queries, handoff); err != nil { + return decisionOutcome{}, "", err + } + resultMessage, err := persistDecisionResultMessage( + ctx, queries, a.tenantID, a.originRoomID, a.cardMessageID, + decisionOwner, fmt.Sprintf("Collaboration request approved. Room \"%s\" (%s) was created.", snapshot.Name, created.Room.ID), + ) + if err != nil { + return decisionOutcome{}, "", err + } + runtimeMessage, err := persistCreationApprovalRuntimeMessage( + ctx, queries, a.tenantID, a.originRoomID, a.cardMessageID, + decisionOwner, agent, a.decisionID, created.Room.ID, snapshot.Name, delivered, skipped, + ) + if err != nil { + return decisionOutcome{}, "", err + } + return decisionOutcome{messages: []messagecreation.Persisted{resultMessage, runtimeMessage}}, created.Room.ID, nil +} + +// snapshotRoomSpec names a frozen Room creation and who creates it: the +// requesting Agent as creator and owner as the new Room's owner. +type snapshotRoomSpec struct { + tenantID, originRoomID, agentActorID, accountID string + owner store.Actor + snapshot json.RawMessage + // bindingKey makes the Documents' Room bindings idempotent. + bindingKey string +} + +// snapshotRoom is a Room created from a frozen snapshot, with the Documents +// it received and those it skipped. +type snapshotRoom struct { + created roomcreation.Result + snapshot RoomCreationSnapshot + agent store.Actor + delivered []RoomCreationArtifactSnapshot + skipped []roomCreationSkippedArtifact +} + +// createSnapshotRoom creates the frozen Room with the Documents its owner may +// still share and posts its initial message as the requesting Agent. +func createSnapshotRoom(ctx context.Context, tx pgx.Tx, queries *store.Queries, spec snapshotRoomSpec) (snapshotRoom, error) { + owner, accountID := spec.owner, spec.accountID var snapshot RoomCreationSnapshot - if err := json.Unmarshal(a.snapshot, &snapshot); err != nil || snapshot.OriginRoomID != a.originRoomID { - return decisionOutcome{}, "", ErrConflict + if err := json.Unmarshal(spec.snapshot, &snapshot); err != nil || snapshot.OriginRoomID != spec.originRoomID { + return snapshotRoom{}, ErrConflict } if _, _, err := roomCreationArtifactReferences(snapshot.Artifacts); err != nil { - return decisionOutcome{}, "", err + return snapshotRoom{}, err } delivered := make([]RoomCreationArtifactSnapshot, 0, len(snapshot.Artifacts)) skipped := make([]roomCreationSkippedArtifact, 0) @@ -88,9 +155,9 @@ func (a roomCreationApproval) approve(ctx context.Context, tx pgx.Tx, queries *s reviews := make(map[string]*document.RoomCreationArtifactReview, len(artifactsToReview)) for _, artifact := range artifactsToReview { review, reason, err := document.LockRoomCreationArtifactInTransaction(ctx, tx, - accountID, a.tenantID, artifact.DocumentID, artifact.DocumentVersionID, artifact.DocumentRevisionID) + accountID, spec.tenantID, artifact.DocumentID, artifact.DocumentVersionID, artifact.DocumentRevisionID) if err != nil { - return decisionOutcome{}, "", err + return snapshotRoom{}, err } reasons[artifact.DocumentID] = reason reviews[artifact.DocumentID] = review @@ -102,31 +169,31 @@ func (a roomCreationApproval) approve(ctx context.Context, tx pgx.Tx, queries *s artifactDocumentIDs = append(artifactDocumentIDs, artifact.DocumentID) } if err := document.Lock(ctx, tx, artifactDocumentIDs); err != nil { - return decisionOutcome{}, "", err + return snapshotRoom{}, err } - agent, err := creationDecisionAgent(ctx, queries, a.tenantID, a.agentActorID) + agent, err := creationDecisionAgent(ctx, queries, spec.tenantID, spec.agentActorID) if err != nil { - return decisionOutcome{}, "", err + return snapshotRoom{}, err } created, err := roomcreation.Create(ctx, queries, roomcreation.Spec{ - TenantID: a.tenantID, Name: snapshot.Name, Description: snapshot.Description, - Creator: agent, Owner: decisionOwner, - MemberActorIDs: creationRoomMemberIDs(snapshot.MemberIDs, agent.ID, decisionOwner.ID), + TenantID: spec.tenantID, Name: snapshot.Name, Description: snapshot.Description, + Creator: agent, Owner: owner, + MemberActorIDs: creationRoomMemberIDs(snapshot.MemberIDs, agent.ID, owner.ID), AgentsAuthorized: true, }) if err != nil { - return decisionOutcome{}, "", mapCreationDecisionError(err) + return snapshotRoom{}, mapCreationDecisionError(err) } for _, artifact := range artifactsToReview { if reasons[artifact.DocumentID] != "" { continue } reason, err := reviews[artifact.DocumentID].BindToRoom(ctx, document.EnsureRoomBindingsInTransactionInput{ - AccountID: accountID, TenantID: a.tenantID, RoomID: created.Room.ID, InitiatedByActorID: decisionOwner.ID, - IdempotencyKey: "room-create-artifacts:" + a.decisionID, Role: "manager", + AccountID: accountID, TenantID: spec.tenantID, RoomID: created.Room.ID, InitiatedByActorID: owner.ID, + IdempotencyKey: spec.bindingKey, Role: "manager", }) if err != nil { - return decisionOutcome{}, "", mapCreationDecisionError(err) + return snapshotRoom{}, mapCreationDecisionError(err) } reasons[artifact.DocumentID] = reason } @@ -139,50 +206,19 @@ func (a roomCreationApproval) approve(ctx context.Context, tx pgx.Tx, queries *s } _, artifactVersionIDs, err := roomCreationArtifactReferences(delivered) if err != nil { - return decisionOutcome{}, "", err + return snapshotRoom{}, err } content, err := messagecreation.Normalize(roomCreationInitialSegments(snapshot.InitialMessageSegments, skipped)) if err != nil { - return decisionOutcome{}, "", ErrConflict + return snapshotRoom{}, ErrConflict } if _, err := messagecreation.Create(ctx, queries, messagecreation.Draft{ - TenantID: a.tenantID, RoomID: created.Room.ID, Author: agent, Content: content, + TenantID: spec.tenantID, RoomID: created.Room.ID, Author: agent, Content: content, AttachmentVersionIDs: artifactVersionIDs, AttachmentRule: messagecreation.DocumentCardAttachments, }); err != nil { - return decisionOutcome{}, "", mapCreationDecisionError(err) - } - // The decision recorded decided_at in this transaction; the handoff carries it. - var decidedAt time.Time - if err := tx.QueryRow(ctx, `SELECT decided_at FROM decisions WHERE id=$1`, a.decisionID).Scan(&decidedAt); err != nil { - return decisionOutcome{}, "", err + return snapshotRoom{}, mapCreationDecisionError(err) } - // The handoff shares the initial message's transaction and Room topic, so the - // requesting Agent's new Room Context accepts both in one batch and wakes once. - handoff, err := persistRoomCreationHandoffMessage( - ctx, queries, a.tenantID, created.Room.ID, decisionOwner, agent, - a.decisionID, a.cardMessageID, a.originRoomID, snapshot.Description, delivered, decidedAt, - ) - if err != nil { - return decisionOutcome{}, "", err - } - if _, err := messagecreation.Publish(ctx, queries, handoff); err != nil { - return decisionOutcome{}, "", err - } - resultMessage, err := persistDecisionResultMessage( - ctx, queries, a.tenantID, a.originRoomID, a.cardMessageID, - decisionOwner, fmt.Sprintf("Collaboration request approved. Room \"%s\" (%s) was created.", snapshot.Name, created.Room.ID), - ) - if err != nil { - return decisionOutcome{}, "", err - } - runtimeMessage, err := persistCreationApprovalRuntimeMessage( - ctx, queries, a.tenantID, a.originRoomID, a.cardMessageID, - decisionOwner, agent, a.decisionID, created.Room.ID, snapshot.Name, delivered, skipped, - ) - if err != nil { - return decisionOutcome{}, "", err - } - return decisionOutcome{messages: []messagecreation.Persisted{resultMessage, runtimeMessage}}, created.Room.ID, nil + return snapshotRoom{created: created, snapshot: snapshot, agent: agent, delivered: delivered, skipped: skipped}, nil } func persistCreationApprovalRuntimeMessage( diff --git a/apps/teamhub/internal/typedcard/room_creation_now.go b/apps/teamhub/internal/typedcard/room_creation_now.go new file mode 100644 index 000000000..f0464ea93 --- /dev/null +++ b/apps/teamhub/internal/typedcard/room_creation_now.go @@ -0,0 +1,166 @@ +package typedcard + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/jackc/pgx/v5" + "github.com/simplexai-labs/linger/apps/teamhub/internal/idempotency" + "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation" + "github.com/simplexai-labs/linger/apps/teamhub/internal/store" +) + +// RoomCreated is the response body of a Room an Agent created at once. +type RoomCreated struct { + Accepted bool `json:"accepted"` + Status string `json:"status"` + RoomID string `json:"room_id"` + SkippedArtifacts []roomCreationSkippedArtifact `json:"skipped_artifacts"` +} + +// RoomCreatedStatus is the status of a Room created without an approval card. +const RoomCreatedStatus = "created" + +// CreateRoomInTx creates an Agent's requested Room at once in the caller's +// transaction, owned by the Agent's Sponsor, with the same snapshot, +// Documents, initial message and handoff an approved creation card makes. A +// retried submission replays its response. +func (s *Service) CreateRoomInTx(ctx context.Context, tx pgx.Tx, input CreationApprovalInTxInput) (CreateResult, error) { + command, err := normalizeCreationApprovalSubmission(input.Submission) + if err != nil { + return CreateResult{}, err + } + if s == nil || tx == nil || input.RoomID == "" || input.AgentManagementID == "" || + strings.TrimSpace(input.IdempotencyOperation) == "" || len(input.IdempotencyOperation) > 300 || + len(input.CallerInputHash) != sha256.Size { + return CreateResult{}, ErrInvalid + } + operation := strings.TrimSpace(input.IdempotencyOperation) + queries := store.New(tx) + if err := queries.AcquireAdvisoryTransactionLock(ctx, "room-membership|"+input.RoomID); err != nil { + return CreateResult{}, err + } + source, err := queries.ResolveCreationApprovalAgentSource(ctx, store.ResolveCreationApprovalAgentSourceParams{ + RoomID: input.RoomID, AgentManagementID: input.AgentManagementID, + }) + if errors.Is(err, pgx.ErrNoRows) { + return CreateResult{}, ErrNotFound + } + if err != nil { + return CreateResult{}, err + } + if input.ExpectedAgentActorID != "" && source.AgentActorID != input.ExpectedAgentActorID || + input.ExpectedTenantID != "" && source.TenantID != input.ExpectedTenantID { + return CreateResult{}, ErrForbidden + } + key := idempotency.AgentKey(source.AgentActorID, operation, command.SubmissionID) + if err := idempotency.Lock(ctx, tx, key); err != nil { + return CreateResult{}, err + } + // A submission made before Rooms were created at once replays its card. + if replay, found, err := lookupCreationApprovalReplay( + ctx, queries, source.AgentActorID, operation, command.SubmissionID, input.CallerInputHash, + ); err != nil || found { + return replay, err + } + record, found, err := idempotency.Lookup(ctx, tx, key, input.CallerInputHash) + if errors.Is(err, idempotency.ErrConflict) { + return CreateResult{}, ErrIdempotencyConflict + } + if err != nil { + return CreateResult{}, err + } + if found { + return CreateResult{Status: record.Status, Body: record.Body, Replay: true}, nil + } + owner, err := queries.GetActor(ctx, store.GetActorParams{ID: source.CreatedByActorID, TenantID: source.TenantID}) + if err != nil { + return CreateResult{}, err + } + if !owner.AccountID.Valid { + return CreateResult{}, ErrForbidden + } + if input.BeforeCreate != nil { + if err := input.BeforeCreate(ctx, queries, CreationApprovalSource{ + TenantID: source.TenantID, AgentActorID: source.AgentActorID, + AgentManagementID: input.AgentManagementID, CreatedByActorID: source.CreatedByActorID, + DecisionOwner: owner, + }, &command); err != nil { + return CreateResult{}, err + } + if command, err = normalizeCreationApprovalSubmission(command); err != nil { + return CreateResult{}, err + } + } + room, err := createSnapshotRoom(ctx, tx, queries, snapshotRoomSpec{ + tenantID: source.TenantID, originRoomID: input.RoomID, agentActorID: source.AgentActorID, + accountID: owner.AccountID.String, owner: owner, snapshot: command.FulfillmentSnapshot, + bindingKey: "room-create-artifacts:" + operation + ":" + command.SubmissionID, + }) + if err != nil { + return CreateResult{}, err + } + roomID := room.created.Room.ID + text, err := roomCreatedHandoffText(input.RoomID, roomID, room.snapshot.Description, room.delivered) + if err != nil { + return CreateResult{}, err + } + // The handoff shares the initial message's transaction and Room topic, so + // the Agent's new Room Context accepts both in one batch and wakes once. + handoff, err := messagecreation.CardHandoff(ctx, queries, messagecreation.Draft{ + TenantID: source.TenantID, RoomID: roomID, Author: owner, HumanWaiting: true, + }, room.agent, text) + if err != nil { + return CreateResult{}, err + } + if _, err := messagecreation.Publish(ctx, queries, handoff); err != nil { + return CreateResult{}, err + } + body, err := json.Marshal(RoomCreated{Accepted: true, Status: RoomCreatedStatus, RoomID: roomID, SkippedArtifacts: room.skipped}) + if err != nil { + return CreateResult{}, err + } + if err := idempotency.Save(ctx, tx, key, input.CallerInputHash, idempotency.Record{ + ResourceID: roomID, Status: http.StatusOK, Body: body, + }); err != nil { + return CreateResult{}, err + } + return CreateResult{Status: http.StatusOK, Body: body}, nil +} + +// roomCreatedHandoffText hands the requested work to the Agent inside the Room +// it created. Like an approved creation's handoff it carries no origin Room +// messages and no skipped Documents. +func roomCreatedHandoffText(originRoomID, roomID string, description *string, delivered []RoomCreationArtifactSnapshot) (string, error) { + var purpose *string + if description != nil { + if trimmed := strings.TrimSpace(*description); trimmed != "" { + purpose = &trimmed + } + } + if delivered == nil { + delivered = []RoomCreationArtifactSnapshot{} + } + payload, err := json.Marshal(struct { + Kind string `json:"kind"` + OriginRoomID string `json:"origin_room_id"` + OriginInboxID string `json:"origin_room_inbox_id"` + RoomInboxID string `json:"room_inbox_id"` + Purpose *string `json:"purpose,omitempty"` + DeliveredItems []RoomCreationArtifactSnapshot `json:"delivered_artifacts"` + }{"room_creation_handoff", originRoomID, "room:" + originRoomID, "room:" + roomID, purpose, delivered}) + if err != nil { + return "", err + } + prompt := fmt.Sprintf(`<room-handoff-pattern> +You created this Room. Continue the requested work here and reply only to the Inbox +room:%s. Origin Room messages are not copied into this Room. Read delivered_artifacts +with teamhub docs get <document-id> and this Room's history with teamhub message read. +</room-handoff-pattern>`, roomID) + return " Room creation handoff=" + string(payload) + "\n" + prompt, nil +} diff --git a/apps/teamhub/tests/integration/agent_cli_agents_test.go b/apps/teamhub/tests/integration/agent_cli_agents_test.go index 5fb90feca..274b99ca3 100644 --- a/apps/teamhub/tests/integration/agent_cli_agents_test.go +++ b/apps/teamhub/tests/integration/agent_cli_agents_test.go @@ -177,26 +177,43 @@ func TestAgentCLIManagesSponsorAgents(t *testing.T) { t.Fatalf("initialization notices=%d", got) } - // Changing an established identity, even one's own, waits for the Sponsor. + // Renaming changes no behavior, so it runs at once, even for an + // established identity. status, body = inRoom.post("agents/updates", map[string]any{"invocation_id": agentInvocation("rename"), "name": "Planner"}) var rename agentChangeResult decode(t, body, &rename) - if status != http.StatusOK || rename.Status != "confirmation_pending" { + if status != http.StatusOK || rename.Status != "applied" || rename.ActorID != caller.Actor.ID { t.Fatalf("rename=%d %s", status, body) } if replay, again := inRoom.post("agents/updates", map[string]any{"invocation_id": agentInvocation("rename"), "name": "Planner"}); replay != http.StatusOK || !bytes.Equal(again, body) { t.Fatalf("replay=%d %s want %s", replay, again, body) } - decideAgentChange(t, env, alice, rename, map[string]any{"decision": "approve"}, "succeeded") if got := countRows(t, env, `SELECT count(*) FROM actors WHERE id=$1 AND display_name='Planner'`, caller.Actor.ID); got != 1 { - t.Fatal("approved rename was not applied") + t.Fatal("rename was not applied") } if got := roomNotices(t, env, roomID, "agent_profile_changed", `{"initialized":false,"instructions_changed":false,"changes":[{"field":"name","after":"Planner"}]}`); got != 1 { - t.Fatalf("approved rename notices=%d", got) + t.Fatalf("rename notices=%d", got) + } + // Changing an established prompt, even one's own, waits for the Sponsor. + status, body = inRoom.post("agents/updates", map[string]any{"invocation_id": agentInvocation("reprompt"), "prompt": "Plan the work in small steps."}) + var reprompt agentChangeResult + decode(t, body, &reprompt) + if status != http.StatusOK || reprompt.Status != "confirmation_pending" { + t.Fatalf("prompt change=%d %s", status, body) + } + if replay, again := inRoom.post("agents/updates", map[string]any{"invocation_id": agentInvocation("reprompt"), "prompt": "Plan the work in small steps."}); replay != http.StatusOK || !bytes.Equal(again, body) { + t.Fatalf("replay=%d %s want %s", replay, again, body) + } + decideAgentChange(t, env, alice, reprompt, map[string]any{"decision": "approve"}, "succeeded") + if got := countRows(t, env, `SELECT count(*) FROM agent_registrations WHERE actor_id=$1 AND instructions='Plan the work in small steps.'`, caller.Actor.ID); got != 1 { + t.Fatal("approved prompt change was not applied") + } + if got := roomNotices(t, env, roomID, "agent_profile_changed", `{"initialized":false,"instructions_changed":true}`); got != 1 { + t.Fatalf("approved prompt change notices=%d", got) } // The card raced against initialization was opened at the old revision. decideAgentChange(t, env, alice, raced, map[string]any{"decision": "approve"}, "failed") - if got := roomNotices(t, env, roomID, "agent_profile_changed", ""); got != 2 { + if got := roomNotices(t, env, roomID, "agent_profile_changed", ""); got != 3 { t.Fatalf("a failed change posted a notice: %d", got) } // The Sponsor's own Web edit announces nothing. @@ -206,7 +223,7 @@ func TestAgentCLIManagesSponsorAgents(t *testing.T) { } status, _, body = env.request(alice, http.MethodPatch, "/v0/tenants/"+acmeTenant+"/agents/"+caller.Actor.ID, map[string]any{"expected_configuration_revision": revision, "description": "Plans the work."}, "web-description-edit") - if status != http.StatusOK || roomNotices(t, env, roomID, "agent_profile_changed", "") != 2 { + if status != http.StatusOK || roomNotices(t, env, roomID, "agent_profile_changed", "") != 3 { t.Fatalf("Web edit=%d %s", status, body) } @@ -255,7 +272,9 @@ func TestAgentCLIManagesSponsorAgents(t *testing.T) { t.Fatalf("list as a General Agent=%d %s", status, body) } - // In the Sponsor's Direct Room nobody can join, so creation needs the card. + // In the Sponsor's Direct Room only the Sponsor can have asked, so the + // Agent is created at once; nobody can join a Direct Room, so it opens + // with its own direct Room instead. status, _, body = env.request(alice, http.MethodPost, "/v0/tenants/"+acmeTenant+"/direct-rooms", map[string]any{"peer_actor_id": caller.Actor.ID}, "") var direct struct { ID string `json:"id"` @@ -265,39 +284,31 @@ func TestAgentCLIManagesSponsorAgents(t *testing.T) { t.Fatalf("open Direct Room=%d %s", status, body) } directRoomID := direct.ID - status, body = agent.in("room", directRoomID).post("agents", map[string]any{"invocation_id": agentInvocation("create-critic"), "name": "Critic", "prompt": "Challenge every claim."}) - var critic agentChangeResult - decode(t, body, &critic) - if status != http.StatusOK || critic.Status != "confirmation_pending" || critic.RoomID != directRoomID { - t.Fatalf("create in Direct Room=%d %s", status, body) - } - decideAgentChange(t, env, alice, critic, map[string]any{"decision": "deny", "comment": "Not now"}, "denied") - if got := countRows(t, env, `SELECT count(*) FROM actors WHERE display_name='Critic' AND tenant_id=$1`, acmeTenant); got != 0 { - t.Fatal("a denied creation created an Agent") - } - // An approved creation is announced once in the card's Room, naming the approver. - status, body = agent.in("room", directRoomID).post("agents", map[string]any{"invocation_id": agentInvocation("create-editor"), "name": "Editor", "prompt": "Edit for clarity."}) + inDirect := agent.in("room", directRoomID) + status, body = inDirect.post("agents", map[string]any{"invocation_id": agentInvocation("create-editor"), "name": "Editor", "prompt": "Edit for clarity."}) var editor agentChangeResult decode(t, body, &editor) - if status != http.StatusOK || editor.Status != "confirmation_pending" { - t.Fatalf("create Editor=%d %s", status, body) + if status != http.StatusOK || editor.Status != "applied" || editor.ActorID == "" || editor.RoomID != "" { + t.Fatalf("create in Direct Room=%d %s", status, body) } - decideAgentChange(t, env, alice, editor, map[string]any{"decision": "approve"}, "succeeded") - if got := roomNotices(t, env, directRoomID, "agent_created", `{"agent":{"display_name":"Editor"},"approved_by":{"id":"actor_acme_alice"}}`); got != 1 { - t.Fatalf("approved creation notices=%d", got) + if replay, again := inDirect.post("agents", map[string]any{"invocation_id": agentInvocation("create-editor"), "name": "Editor", "prompt": "Edit for clarity."}); replay != http.StatusOK || !bytes.Equal(again, body) { + t.Fatalf("Direct Room create replay=%d %s", replay, again) } - // The approved Agent opens with the Sponsor's direct Room, which lists it - // in the sidebar; a rerun of the decision reopens that Room. - var editorID string - if err := env.pool.QueryRow(t.Context(), `SELECT id FROM actors WHERE tenant_id=$1 AND display_name='Editor' AND kind='agent'`, acmeTenant).Scan(&editorID); err != nil { - t.Fatal(err) + editorID := editor.ActorID + if got := countRows(t, env, `SELECT count(*) FROM messages WHERE room_id=$1 AND author_actor_id=$2 AND message_kind='room_notice' + AND notice @> jsonb_build_object('type','agent_created','agent',jsonb_build_object('id',$3::text)) AND NOT notice ? 'approved_by'`, + directRoomID, caller.Actor.ID, editorID); got != 1 { + t.Fatalf("Direct Room creation notices=%d", got) + } + if got := countRows(t, env, `SELECT count(*) FROM active_room_members WHERE room_id=$1 AND actor_id=$2`, directRoomID, editorID); got != 0 { + t.Fatal("created Agent joined the Sponsor's Direct Room") } - editorRooms := func() int { + agentDirectRooms := func(agentID string) int { return countRows(t, env, `SELECT count(*) FROM rooms room JOIN active_room_members member ON member.room_id=room.id AND member.actor_id=$2 - WHERE room.tenant_id=$1 AND room.direct_human_actor_id='actor_acme_alice' AND room.direct_agent_actor_id=$2`, acmeTenant, editorID) + WHERE room.tenant_id=$1 AND room.direct_human_actor_id='actor_acme_alice' AND room.direct_agent_actor_id=$2`, acmeTenant, agentID) } - if got := editorRooms(); got != 1 { - t.Fatalf("approved Agent direct Rooms=%d want=1", got) + if got := agentDirectRooms(editorID); got != 1 { + t.Fatalf("created Agent direct Rooms=%d want=1", got) } status, _, body = env.request(alice, http.MethodGet, "/v0/tenants/"+acmeTenant+"/rooms", nil, "") var listed struct { @@ -317,18 +328,59 @@ func TestAgentCLIManagesSponsorAgents(t *testing.T) { if status != http.StatusOK || sidebar != 1 { t.Fatalf("Sponsor room list status=%d direct Editor Rooms=%d body=%s", status, sidebar, body) } - claim := typedcard.ClaimedDecision{ID: editor.InteractionID} + + // In a Room the Sponsor is not in, someone else asked, so creation needs + // the Sponsor's card, which goes to the Sponsor's Direct Room. + elsewhereID := createPrivateRoom(t, env, alice, "Without the Sponsor", "agent-cli-elsewhere-room") + if status, body := putRoomMember(t, env, alice, elsewhereID, caller.Actor.ID, "member"); status != http.StatusOK { + t.Fatalf("membership=%d %s", status, body) + } + if _, err := env.pool.Exec(t.Context(), `DELETE FROM room_members WHERE room_id=$1 AND actor_id='actor_acme_alice'`, elsewhereID); err != nil { + t.Fatal(err) + } + elsewhere := agent.in("room", elsewhereID) + status, body = elsewhere.post("agents", map[string]any{"invocation_id": agentInvocation("create-critic"), "name": "Critic", "prompt": "Challenge every claim."}) + var critic agentChangeResult + decode(t, body, &critic) + if status != http.StatusOK || critic.Status != "confirmation_pending" || critic.RoomID != directRoomID { + t.Fatalf("create without the Sponsor=%d %s", status, body) + } + decideAgentChange(t, env, alice, critic, map[string]any{"decision": "deny", "comment": "Not now"}, "denied") + if got := countRows(t, env, `SELECT count(*) FROM actors WHERE display_name='Critic' AND tenant_id=$1`, acmeTenant); got != 0 { + t.Fatal("a denied creation created an Agent") + } + // An approved creation is announced once in the card's Room, naming the approver. + status, body = elsewhere.post("agents", map[string]any{"invocation_id": agentInvocation("create-reviewer"), "name": "Reviewer", "prompt": "Review for accuracy."}) + var reviewer agentChangeResult + decode(t, body, &reviewer) + if status != http.StatusOK || reviewer.Status != "confirmation_pending" { + t.Fatalf("create Reviewer=%d %s", status, body) + } + decideAgentChange(t, env, alice, reviewer, map[string]any{"decision": "approve"}, "succeeded") + if got := roomNotices(t, env, directRoomID, "agent_created", `{"agent":{"display_name":"Reviewer"},"approved_by":{"id":"actor_acme_alice"}}`); got != 1 { + t.Fatalf("approved creation notices=%d", got) + } + // The approved Agent opens with the Sponsor's direct Room; a rerun of the + // decision reopens that Room. + var reviewerID string + if err := env.pool.QueryRow(t.Context(), `SELECT id FROM actors WHERE tenant_id=$1 AND display_name='Reviewer' AND kind='agent'`, acmeTenant).Scan(&reviewerID); err != nil { + t.Fatal(err) + } + if got := agentDirectRooms(reviewerID); got != 1 { + t.Fatalf("approved Agent direct Rooms=%d want=1", got) + } + claim := typedcard.ClaimedDecision{ID: reviewer.InteractionID} if err := env.pool.QueryRow(t.Context(), `SELECT kind, tenant_id, room_id, requested_by_actor_id, decider_actor_id, request FROM decisions WHERE id=$1`, - editor.InteractionID).Scan(&claim.Kind, &claim.TenantID, &claim.RoomID, &claim.RequestedByActorID, &claim.DeciderActorID, &claim.Request); err != nil { + reviewer.InteractionID).Scan(&claim.Kind, &claim.TenantID, &claim.RoomID, &claim.RequestedByActorID, &claim.DeciderActorID, &claim.Request); err != nil { t.Fatal(err) } logger := slog.New(slog.DiscardHandler) registry := agentregistry.New(env.pool, nil, collaboration.New(env.pool, nil, nil, nil, nil, logger), nil, logger) replayed, err := registry.RunAgentChangeDecision(t.Context(), claim) - if err != nil || replayed.Status != "succeeded" || replayed.Data.(map[string]string)["actor_id"] != editorID { + if err != nil || replayed.Status != "succeeded" || replayed.Data.(map[string]string)["actor_id"] != reviewerID { t.Fatalf("replayed decision=%+v err=%v", replayed, err) } - if got := editorRooms(); got != 1 { + if got := agentDirectRooms(reviewerID); got != 1 { t.Fatalf("direct Rooms after replay=%d want=1", got) } } diff --git a/apps/teamhub/tests/integration/agent_cli_collaboration_test.go b/apps/teamhub/tests/integration/agent_cli_collaboration_test.go index d069ece88..dd7fb6899 100644 --- a/apps/teamhub/tests/integration/agent_cli_collaboration_test.go +++ b/apps/teamhub/tests/integration/agent_cli_collaboration_test.go @@ -1,6 +1,8 @@ package integration_test import ( + "bytes" + "encoding/json" "errors" "net/http" "strings" @@ -120,28 +122,36 @@ func TestAgentCLICollaborationUsesCurrentBusinessRoleWithoutInvocation(t *testin t.Fatal(err) } }) - t.Run("Room approval is persisted before Human decision", func(t *testing.T) { + // CLI writes start no Runs; the created Room's handoff below wakes the Agent there. + if n := countRows(t, env, `SELECT count(*) FROM agent_local_runs`); n != 0 { + t.Fatalf("created %d lifecycle records", n) + } + t.Run("Room is created at once and replays", func(t *testing.T) { service := agentcreationapproval.New(env.pool, contexts, typedcard.New(env.pool)) - segments := []messagecreation.Segment{{Type: "text", Content: "Independent Room approval"}} + segments := []messagecreation.Segment{{Type: "text", Content: "Independent Room creation"}} input := agentcreationapproval.Input{RequestKind: "room_creation", InvocationID: "agent-invocation-sha256:" + strings.Repeat("c", 64), - RoomCaller: &agentcreationapproval.RoomCallerInput{Name: "CLI pending room", MemberIDs: []string{"actor_acme_alice", "actor_acme_official"}, InitialMessageSegments: segments}, - RoomEffective: &agentcreationapproval.RoomEffectivePayload{Name: "CLI pending room", MemberIDs: []string{"actor_acme_alice", "actor_acme_official"}, InitialMessageSegments: segments}, + RoomCaller: &agentcreationapproval.RoomCallerInput{Name: "CLI created room", MemberIDs: []string{"actor_acme_alice", "actor_acme_official"}, InitialMessageSegments: segments}, + RoomEffective: &agentcreationapproval.RoomEffectivePayload{Name: "CLI created room", MemberIDs: []string{"actor_acme_alice", "actor_acme_official"}, InitialMessageSegments: segments}, } result, err := service.Submit(ctx, issued.AccessToken, input) - if err != nil || result.CreationApprovalRequestID == "" { - t.Fatalf("room approval: %+v %v", result, err) + var created typedcard.RoomCreated + if err == nil && result.Created != nil { + err = json.Unmarshal(result.Created, &created) + } + if err != nil || created.Status != typedcard.RoomCreatedStatus || created.RoomID == "" || result.CreationApprovalRequestID != "" { + t.Fatalf("room creation: %+v %s %v", result, result.Created, err) } replay, err := service.Submit(ctx, issued.AccessToken, input) - if err != nil || !replay.Replay || replay.CreationApprovalRequestID != result.CreationApprovalRequestID { + if err != nil || !replay.Replay || !bytes.Equal(replay.Created, result.Created) { t.Fatalf("room replay: %+v %v", replay, err) } - if n := countRows(t, env, `SELECT count(*) FROM rooms WHERE name='CLI pending room'`); n != 0 { - t.Fatalf("created %d rooms before approval", n) + if n := countRows(t, env, `SELECT count(*) FROM rooms WHERE name='CLI created room' AND id=$1`, created.RoomID); n != 1 { + t.Fatalf("created %d rooms", n) + } + if n := countRows(t, env, `SELECT count(*) FROM decisions WHERE kind='room_creation'`); n != 0 { + t.Fatalf("posted %d approval cards", n) } }) - if n := countRows(t, env, `SELECT count(*) FROM agent_local_runs`); n != 0 { - t.Fatalf("created %d lifecycle records", n) - } } // The Room's Humans never see the Agent-only team.md announcement, so each diff --git a/apps/teamhub/tests/integration/mcp_creation_approval_access_test.go b/apps/teamhub/tests/integration/mcp_creation_approval_access_test.go index 8ea1b5db6..018627724 100644 --- a/apps/teamhub/tests/integration/mcp_creation_approval_access_test.go +++ b/apps/teamhub/tests/integration/mcp_creation_approval_access_test.go @@ -12,19 +12,20 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgconn" - "github.com/simplexai-labs/linger/apps/teamhub/internal/agentauth" - "github.com/simplexai-labs/linger/apps/teamhub/internal/agentcreationapproval" "github.com/simplexai-labs/linger/apps/teamhub/internal/document" + "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation" "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard" ) -// These subcases reuse the real MCP proposal and approval chain's private DB. -// The approver is the Space's only Human, who reads and shares every active -// Document, so an artifact is skipped only when its Document or frozen content -// is gone; approval holds the Document and the Human steady until it commits. +// These subcases decide pending Room creation cards, which Agents posted +// before TeamHub created their Rooms at once, in the vertical slice's private +// DB. The approver is the Space's only Human, who reads and shares every +// active Document, so an artifact is skipped only when its Document or frozen +// content is gone; approval holds the Document and the Human steady until it +// commits. func assertRoomCreationApprovalAccessTransactions(t *testing.T, env *testEnv, alice *http.Client, - service *agentcreationapproval.Service, token string, - roomInput agentcreationapproval.Input, documentID, otherDocumentID string, + sourceRoomID string, artifacts []typedcard.RoomCreationArtifactSnapshot, segments []messagecreation.Segment, + documentID, otherDocumentID string, ) { decisions := typedcard.New(env.pool) exec := func(t *testing.T, query string, args ...any) { @@ -33,37 +34,35 @@ func assertRoomCreationApprovalAccessTransactions(t *testing.T, env *testEnv, al t.Fatal(err) } } - sourceRoomID := strings.TrimPrefix(roomInput.SourceInboxIDs[0], "room:") - submit := func(t *testing.T, artifacts ...string) agentcreationapproval.Result { + // submit posts a card for the default artifacts, or for one file artifact + // and the filename its card segment shows. + submit := func(t *testing.T, file ...string) typedcard.CreateResult { t.Helper() - input := roomInput - caller, effective := *input.RoomCaller, *input.RoomEffective - caller.Name = "Access transaction " + mcpCreationInvocationID(t.Name())[24:56] - effective.Name = caller.Name - if len(artifacts) > 0 { - caller.Artifacts, effective.Artifacts = artifacts, artifacts - } - input.RoomCaller, input.RoomEffective = &caller, &effective - input.InvocationID = mcpCreationInvocationID(t.Name()) - // The requesting Meta sends its source Room Context. - roomCtx := agentauth.WithTarget(t.Context(), "room", sourceRoomID) - pending, err := service.Submit(roomCtx, token, input) - if err != nil { - t.Fatal(err) + frozen, frozenSegments := artifacts, segments + if len(file) == 3 { + frozen = []typedcard.RoomCreationArtifactSnapshot{{DocumentID: file[0], DocumentVersionID: file[1]}} + frozenSegments = []messagecreation.Segment{ + {Type: "text", Content: "Start the approved Room."}, {Type: "text", Content: "\n"}, + {Type: "document", Content: file[2], DocumentID: file[0], Presentation: "card"}, + } } - return pending + key := mcpCreationInvocationID(t.Name())[24:56] + return postRoomCreationCard(t, env, roomCreationApprovalInputFor(t, typedcard.RoomCreationSnapshot{ + OriginRoomID: sourceRoomID, Name: "Access transaction " + key, MemberIDs: []string{"actor_acme_official"}, + Artifacts: frozen, InitialMessageSegments: frozenSegments, + }, key)) } - decide := func(ctx context.Context, pending agentcreationapproval.Result) (typedcard.CreateResult, error) { - return decisions.DecideDecision(ctx, "account_alice", pending.CreationApprovalRequestID, + decide := func(ctx context.Context, pending typedcard.CreateResult) (typedcard.CreateResult, error) { + return decisions.DecideDecision(ctx, "account_alice", pending.DecisionID, typedcard.DecisionAnswerCommand{Decision: "approve", ExpectedVersion: 1}) } - assertDelivered := func(t *testing.T, pending agentcreationapproval.Result, artifactIDs ...string) string { + assertDelivered := func(t *testing.T, pending typedcard.CreateResult, artifactIDs ...string) string { t.Helper() var roomID, runtimeBody string if err := env.pool.QueryRow(t.Context(), `SELECT request.result->'data'->>'created_room_id',message.body FROM decisions request JOIN messages message ON message.card_context_message_id=request.message_id AND message.message_kind='agent_runtime' AND message.human_waiting WHERE request.id=$1 AND request.status='succeeded'`, - pending.CreationApprovalRequestID).Scan(&roomID, &runtimeBody); err != nil { + pending.DecisionID).Scan(&roomID, &runtimeBody); err != nil { t.Fatal(err) } if len(artifactIDs) == 0 { @@ -127,7 +126,7 @@ func assertRoomCreationApprovalAccessTransactions(t *testing.T, env *testEnv, al } return pid } - asyncDecision := func(t *testing.T, pending agentcreationapproval.Result) <-chan error { + asyncDecision := func(t *testing.T, pending typedcard.CreateResult) <-chan error { results := make(chan error, 1) ctx, cancel := context.WithTimeout(t.Context(), 15*time.Second) t.Cleanup(cancel) @@ -146,7 +145,7 @@ func assertRoomCreationApprovalAccessTransactions(t *testing.T, env *testEnv, al } var artifact uploadedDocumentRef decode(t, body, &artifact) - pending := submit(t, artifact.ID) + pending := submit(t, artifact.ID, artifact.CurrentVersion.ID, "trash-wait.txt") roomBarrier := barrier(t) result := asyncDecision(t, pending) // The approval has reviewed and locked every artifact before the Room insert. @@ -239,13 +238,13 @@ func assertRoomCreationApprovalAccessTransactions(t *testing.T, env *testEnv, al for i, table := range facts { before[i] = countRows(t, env, "SELECT count(*) FROM "+table) } - triggerTable, condition := "document_context_bindings", "NEW.document_id='"+otherDocumentID+"' AND NEW.room_id<>'"+roomInput.SourceInboxIDs[0][5:]+"'" + triggerTable, condition := "document_context_bindings", "NEW.document_id='"+otherDocumentID+"' AND NEW.room_id<>'"+sourceRoomID+"'" if failure == "notification" { triggerTable = "messages" condition = "NEW.message_kind='agent_runtime' AND NEW.card_context_message_id='" + pending.MessageID + "'" } if failure == "handoff" { - handoffDigest := sha256.Sum256([]byte("room-creation-handoff:" + pending.CreationApprovalRequestID)) + handoffDigest := sha256.Sum256([]byte("room-creation-handoff:" + pending.DecisionID)) triggerTable = "messages" condition = fmt.Sprintf("NEW.id='message_%x'", handoffDigest[:16]) } @@ -277,7 +276,7 @@ func assertRoomCreationApprovalAccessTransactions(t *testing.T, env *testEnv, al } } if got := countRows(t, env, `SELECT count(*) FROM decisions request JOIN message_cards card ON card.message_id=request.message_id - WHERE request.id=$1 AND request.status='pending' AND request.result IS NULL AND card.version=1`, pending.CreationApprovalRequestID); got != 1 { + WHERE request.id=$1 AND request.status='pending' AND request.result IS NULL AND card.version=1`, pending.DecisionID); got != 1 { t.Fatal("approval/card state did not roll back") } }) diff --git a/apps/teamhub/tests/integration/mcp_creation_approval_test.go b/apps/teamhub/tests/integration/mcp_creation_approval_test.go index c42bb9290..681024e0b 100644 --- a/apps/teamhub/tests/integration/mcp_creation_approval_test.go +++ b/apps/teamhub/tests/integration/mcp_creation_approval_test.go @@ -1,6 +1,7 @@ package integration_test import ( + "bytes" "crypto/sha256" "encoding/json" "errors" @@ -164,88 +165,44 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { } } - roomName := "Approved MCP Room " + suffix + roomName := "Created MCP Room " + suffix roomInput := agentcreationapproval.Input{ RequestKind: "room_creation", RoomCaller: &agentcreationapproval.RoomCallerInput{ Name: roomName, MemberIDs: []string{"actor_acme_official"}, Artifacts: []string{nativeArtifactID, roomArtifact.ID}, - InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Start the approved Room."}}, + InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Start the new Room."}}, }, RoomEffective: &agentcreationapproval.RoomEffectivePayload{ Name: roomName, MemberIDs: []string{"actor_acme_official"}, Artifacts: []string{nativeArtifactID, roomArtifact.ID}, - InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Start the approved Room."}}, + InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Start the new Room."}}, }, SourceInboxIDs: []string{"room:" + originRoomID}, InvocationID: mcpCreationInvocationID(suffix + ":room"), } // The requesting Meta sends its Room Context, as its CLI configuration does. - pendingRoom, err := service.Submit(agentauth.WithTarget(t.Context(), "room", originRoomID), token, roomInput) + roomCtx := agentauth.WithTarget(t.Context(), "room", originRoomID) + roomsBefore := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) + createdRoom, err := service.Submit(roomCtx, token, roomInput) if err != nil { - t.Fatalf("submit Room Creation approval: %v", err) + t.Fatalf("create Room: %v", err) } - assertMcpCreationPendingFacts(t, env, pendingRoom, "room_creation", originRoomID) - var frozenRoomSnapshotJSON []byte - if err := env.pool.QueryRow(t.Context(), ` - SELECT request->'fulfillment_snapshot' FROM decisions WHERE id=$1 - `, pendingRoom.CreationApprovalRequestID).Scan(&frozenRoomSnapshotJSON); err != nil { - t.Fatal(err) + created := decodeRoomCreated(t, createdRoom) + createdRoomID := created.RoomID + if len(created.SkippedArtifacts) != 0 { + t.Fatalf("created Room skipped=%s", createdRoom.Created) } - var frozenRoomSnapshot typedcard.RoomCreationSnapshot - if err := json.Unmarshal(frozenRoomSnapshotJSON, &frozenRoomSnapshot); err != nil { - t.Fatal(err) + if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != roomsBefore+1 { + t.Fatalf("Room count=%d want=%d", got, roomsBefore+1) } - if len(frozenRoomSnapshot.Artifacts) != 2 || - frozenRoomSnapshot.Artifacts[0].DocumentID != nativeArtifactID || - frozenRoomSnapshot.Artifacts[0].DocumentRevisionID != nativeRevisionID || - frozenRoomSnapshot.Artifacts[0].DocumentVersionID != "" || - frozenRoomSnapshot.Artifacts[1].DocumentID != roomArtifact.ID || - frozenRoomSnapshot.Artifacts[1].DocumentVersionID != roomArtifact.CurrentVersion.ID || - frozenRoomSnapshot.Artifacts[1].DocumentRevisionID != "" || - len(frozenRoomSnapshot.InitialMessageSegments) != 5 || - frozenRoomSnapshot.InitialMessageSegments[2].Type != "document" || - frozenRoomSnapshot.InitialMessageSegments[2].DocumentID != nativeArtifactID || - frozenRoomSnapshot.InitialMessageSegments[4].Type != "document" || - frozenRoomSnapshot.InitialMessageSegments[4].DocumentID != roomArtifact.ID { - t.Fatalf("frozen Room Creation snapshot=%+v", frozenRoomSnapshot) - } - status, _, replacementBody := requestUnifiedDocumentVersionUpload( - t, env, alice, roomArtifact.ID, "mcp-creation-room-artifact-v2-"+suffix, - map[string]string{ - "expected_current_version_id": roomArtifact.CurrentVersion.ID, - "filename": "room-brief-v2.txt", "representation_format": "plain_text", "media_type": "text/plain", - }, - "room-brief-v2.txt", []byte("newer Room brief v2\n"), - ) - if status != http.StatusCreated { - t.Fatalf("replace Room Creation artifact status=%d body=%s", status, replacementBody) + // The Sponsor owns the Room; no approval card is posted. + if got := countRows(t, env, `SELECT count(*) FROM rooms room JOIN room_members member ON member.room_id=room.id + WHERE room.id=$1 AND room.name=$2 AND member.actor_id='actor_acme_alice' AND member.role='owner'`, createdRoomID, roomName); got != 1 { + t.Fatalf("created Room owned by the Sponsor=%d want=1", got) } - var replacementVersion struct { - ID string `json:"id"` - } - decode(t, replacementBody, &replacementVersion) - if replacementVersion.ID == "" || replacementVersion.ID == roomArtifact.CurrentVersion.ID { - t.Fatalf("replacement Room Creation Version=%+v", replacementVersion) - } - - roomsBeforeRoomApproval := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) - status, _, body := env.request(alice, http.MethodPost, - "/v0/decisions/"+pendingRoom.CreationApprovalRequestID, - map[string]any{"decision": "approve", "expected_version": int64(1)}, "") - if status != http.StatusOK { - t.Fatalf("approve Room Creation status=%d body=%s", status, body) - } - var createdRoomID string - if err := env.pool.QueryRow(t.Context(), ` - SELECT room.id FROM decisions request - JOIN rooms room ON room.id=request.result->'data'->>'created_room_id' AND room.tenant_id=request.tenant_id - WHERE request.id=$1 AND request.status='succeeded' AND room.name=$2 - `, pendingRoom.CreationApprovalRequestID, roomName).Scan(&createdRoomID); err != nil { - t.Fatalf("load approved Room Creation: %v", err) - } - if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != roomsBeforeRoomApproval+1 { - t.Fatalf("approved Room count=%d want=%d", got, roomsBeforeRoomApproval+1) + if got := countRows(t, env, `SELECT count(*) FROM decisions WHERE room_id=$1`, originRoomID); got != 0 { + t.Fatalf("Room creation posted %d cards", got) } var initialMessageID string var initialSegmentsJSON []byte @@ -259,7 +216,7 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { if err := json.Unmarshal(initialSegmentsJSON, &initialSegments); err != nil { t.Fatal(err) } - if len(initialSegments) != 5 || initialSegments[0].Content != "Start the approved Room." || + if len(initialSegments) != 5 || initialSegments[0].Content != "Start the new Room." || initialSegments[1].Type != "text" || initialSegments[1].Content != "\n" || initialSegments[2].Type != "document" || initialSegments[2].Content != nativeArtifactTitle || initialSegments[2].DocumentID != nativeArtifactID || initialSegments[2].DocumentVersionID != "" || @@ -268,7 +225,7 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { initialSegments[4].Type != "document" || initialSegments[4].Content != "room-brief-v1.txt" || initialSegments[4].DocumentID != roomArtifact.ID || initialSegments[4].DocumentVersionID != "" || initialSegments[4].Presentation != "card" { - t.Fatalf("approved Room initial segments=%+v", initialSegments) + t.Fatalf("created Room initial segments=%+v", initialSegments) } var attachedDocumentID, attachedVersionID, fileBindingRole, nativeBindingRole string if err := env.pool.QueryRow(t.Context(), `SELECT @@ -285,174 +242,72 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { } if attachedDocumentID != roomArtifact.ID || attachedVersionID != roomArtifact.CurrentVersion.ID || fileBindingRole != "manager" || nativeBindingRole != "manager" { - t.Fatalf("approved Room artifact document=%s version=%s file binding=%s native binding=%s", + t.Fatalf("created Room artifact document=%s version=%s file binding=%s native binding=%s", attachedDocumentID, attachedVersionID, fileBindingRole, nativeBindingRole) } - var runtimeMessageID, runtimeMessageBody string - var runtimeSegmentsJSON []byte - if err := env.pool.QueryRow(t.Context(), ` - SELECT id,body,segments FROM messages - WHERE room_id=$1 AND message_kind='agent_runtime' AND card_context_message_id=$2 - `, originRoomID, pendingRoom.MessageID).Scan( - &runtimeMessageID, &runtimeMessageBody, &runtimeSegmentsJSON, - ); err != nil { - t.Fatal(err) - } - if !strings.Contains(runtimeMessageBody, `"creation_approval_request_id":"`+pendingRoom.CreationApprovalRequestID+`"`) || - !strings.Contains(runtimeMessageBody, `"created_room_id":"`+createdRoomID+`"`) { - t.Fatalf("Room Creation runtime body=%q", runtimeMessageBody) - } - if !strings.Contains(runtimeMessageBody, `"created_room_inbox_id":"room:`+createdRoomID+`"`) || - !strings.Contains(runtimeMessageBody, `"created_room_name":"`+roomName+`"`) || - !strings.Contains(runtimeMessageBody, `"skipped_artifacts":[]`) || - !strings.Contains(runtimeMessageBody, `<room-communication-pattern>`) { - t.Fatalf("Room approval address/delivery missing: %s", runtimeMessageBody) - } - if got := countRows(t, env, `SELECT count(*) FROM messages WHERE room_id=$1 - AND card_context_message_id=$2 AND message_kind='conversation' - AND body LIKE '%'||$3||'%' AND body LIKE '%'||$4||'%'`, originRoomID, pendingRoom.MessageID, roomName, createdRoomID); got != 1 { - t.Fatal("visible Room result must include the name and ID fallback") - } _, sendErr := newAgentSendService(t, env.pool, contexts).Send( - agentauth.WithTarget(t.Context(), "room", originRoomID), token, + roomCtx, token, agentSendInput("room:"+createdRoomID, mcpCreationInvocationID(suffix+":cross-room-send"), agentsendmessage.PreparedSegment{Type: "text", Content: "Must be forbidden."})) if !errors.Is(sendErr, agentsendmessage.ErrForbidden) { t.Fatalf("cross-room send error=%v want Forbidden", sendErr) } - var deliveryPayload struct { - Delivered []struct { - typedcard.RoomCreationArtifactSnapshot - Reason string `json:"reason"` - } `json:"delivered_artifacts"` - } - payloadText := strings.SplitN(strings.SplitN(runtimeMessageBody, "result=", 2)[1], "\n", 2)[0] - if err := json.Unmarshal([]byte(payloadText), &deliveryPayload); err != nil { - t.Fatal(err) - } - if len(deliveryPayload.Delivered) != len(frozenRoomSnapshot.Artifacts) { - t.Fatalf("delivered=%+v", deliveryPayload) - } - for i, artifact := range deliveryPayload.Delivered { - if artifact.RoomCreationArtifactSnapshot != frozenRoomSnapshot.Artifacts[i] || artifact.Reason != "delivered" { - t.Fatalf("delivered=%+v", deliveryPayload) - } - } - var runtimeSegments []messagecreation.Segment - if err := json.Unmarshal(runtimeSegmentsJSON, &runtimeSegments); err != nil { - t.Fatal(err) - } - if len(runtimeSegments) != 2 || runtimeSegments[0].Type != "reference" || - runtimeSegments[0].Target != "actor_acme_official" || runtimeSegments[0].TargetType != "agent" { - t.Fatalf("Room Creation runtime segments=%+v", runtimeSegments) - } - if got := countRows(t, env, ` - SELECT count(*) FROM messages - WHERE id=$1 AND 'actor_acme_official'=ANY(mentioned_actor_ids) - `, runtimeMessageID); got != 1 { - t.Fatalf("Room Creation runtime mentions=%d want=1", got) - } - if got := countRows(t, env, ` - SELECT count(*) FROM messages - WHERE room_id=$1 AND card_context_message_id=$2 AND message_kind='conversation' - `, originRoomID, pendingRoom.MessageID); got != 1 { - t.Fatalf("Room Creation visible result messages=%d want=1", got) - } - assertHumanVisibleMessageIDs(t, env, alice, originRoomID, runtimeMessageID, false) - assertRoomCreationHandoff(t, env, createdRoomID, originRoomID, pendingRoom, "", + assertRoomCreationHandoff(t, env, createdRoomID, originRoomID, nil, "", []string{nativeArtifactID, roomArtifact.ID}) - // A repeated decision carries a stale card version. - status, _, repeatedDecisionBody := env.request(alice, http.MethodPost, - "/v0/decisions/"+pendingRoom.CreationApprovalRequestID, - map[string]any{"decision": "approve", "expected_version": int64(1)}, "") - if status != http.StatusConflict { - t.Fatalf("repeated Room decision status=%d body=%s", status, repeatedDecisionBody) + // A retried submission replays the Room it created. + replayed, err := service.Submit(roomCtx, token, roomInput) + if err != nil || !replayed.Replay || !bytes.Equal(replayed.Created, createdRoom.Created) { + t.Fatalf("replayed Room creation=%+v err=%v", replayed, err) } - if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != roomsBeforeRoomApproval+1 { - t.Fatalf("repeated Room decision duplicated Room: got=%d want=%d", got, roomsBeforeRoomApproval+1) - } - if got := countRows(t, env, ` - SELECT count(*) FROM messages - WHERE room_id=$1 AND message_kind='agent_runtime' AND card_context_message_id=$2 - `, originRoomID, pendingRoom.MessageID); got != 1 { - t.Fatalf("Room decision replay runtime messages=%d want=1", got) + if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != roomsBefore+1 { + t.Fatalf("replayed Room creation duplicated Room: got=%d want=%d", got, roomsBefore+1) } if got := countRows(t, env, `SELECT jsonb_array_length(attachments) FROM messages WHERE id=$1`, initialMessageID); got != 1 { - t.Fatalf("Room decision replay attachments=%d want=1", got) + t.Fatalf("replayed Room creation attachments=%d want=1", got) } - assertRoomCreationHandoff(t, env, createdRoomID, originRoomID, pendingRoom, "", + assertRoomCreationHandoff(t, env, createdRoomID, originRoomID, nil, "", []string{nativeArtifactID, roomArtifact.ID}) - status, _, revokedArtifactBody := requestUnifiedDocumentMultipart( + // A Document no longer in the origin Room cannot be shared, so no Room is created. + status, _, otherArtifactBody := requestUnifiedDocumentMultipart( t, env, alice, "/v0/rooms/"+originRoomID+"/documents/uploads", - "mcp-creation-revoked-artifact-"+suffix, + "mcp-creation-other-artifact-"+suffix, map[string]string{ - "filename": "revoked-brief.txt", "representation_format": "plain_text", "media_type": "text/plain", + "filename": "other-brief.txt", "representation_format": "plain_text", "media_type": "text/plain", }, - "revoked-brief.txt", []byte("revoke before approval\n"), + "other-brief.txt", []byte("trashed before creation\n"), ) if status != http.StatusCreated { - t.Fatalf("upload revoked Room artifact status=%d body=%s", status, revokedArtifactBody) - } - var revokedArtifact uploadedDocumentRef - decode(t, revokedArtifactBody, &revokedArtifact) - revokedRoomName := "Revoked Artifact MCP Room " + suffix - revokedCaller := *roomInput.RoomCaller - revokedCaller.Name = revokedRoomName - revokedCaller.Artifacts = []string{revokedArtifact.ID} - revokedEffective := *roomInput.RoomEffective - revokedEffective.Name = revokedRoomName - revokedEffective.Artifacts = []string{revokedArtifact.ID} - revokedRoomInput := roomInput - revokedRoomInput.RoomCaller = &revokedCaller - revokedRoomInput.RoomEffective = &revokedEffective - revokedRoomInput.InvocationID = mcpCreationInvocationID(suffix + ":room-revoked-artifact") - pendingRevokedRoom, err := service.Submit(agentauth.WithTarget(t.Context(), "room", originRoomID), token, revokedRoomInput) - if err != nil { - t.Fatalf("submit revoked-artifact Room Creation approval: %v", err) + t.Fatalf("upload other Room artifact status=%d body=%s", status, otherArtifactBody) } - status, _, body = env.request( - alice, http.MethodDelete, "/v0/documents/"+revokedArtifact.ID, nil, + var otherArtifact uploadedDocumentRef + decode(t, otherArtifactBody, &otherArtifact) + status, _, body := env.request( + alice, http.MethodDelete, "/v0/documents/"+otherArtifact.ID, nil, "mcp-creation-trash-artifact-"+suffix, ) if status != http.StatusNoContent { - t.Fatalf("trash pending Room artifact status=%d body=%s", status, body) - } - roomsBeforeRevokedApproval := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) - status, _, body = env.request(alice, http.MethodPost, - "/v0/decisions/"+pendingRevokedRoom.CreationApprovalRequestID, - map[string]any{"decision": "approve", "expected_version": int64(1)}, - "mcp-creation-revoked-room-decision-"+suffix) - if status != http.StatusOK { - t.Fatalf("approve deleted-artifact Room status=%d body=%s", status, body) - } - if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != roomsBeforeRevokedApproval+1 { - t.Fatalf("deleted-artifact approval Rooms=%d want=%d", got, roomsBeforeRevokedApproval+1) - } - var skippedRoomID, skippedRuntimeBody string - if err := env.pool.QueryRow(t.Context(), `SELECT request.result->'data'->>'created_room_id',message.body - FROM decisions request JOIN messages message - ON message.card_context_message_id=request.message_id AND message.message_kind='agent_runtime' - WHERE request.id=$1 AND request.status='succeeded'`, pendingRevokedRoom.CreationApprovalRequestID).Scan(&skippedRoomID, &skippedRuntimeBody); err != nil { - t.Fatal(err) - } - if !strings.Contains(skippedRuntimeBody, `"skipped_artifacts":[{"document_id":"`+revokedArtifact.ID+`","reason":"document_unavailable"}]`) || - !strings.Contains(skippedRuntimeBody, `"delivered_artifacts":[]`) { - t.Fatalf("skipped runtime=%s", skippedRuntimeBody) + t.Fatalf("trash Room artifact status=%d body=%s", status, body) } - if got := countRows(t, env, `SELECT count(*) FROM document_context_bindings WHERE room_id=$1 AND document_id=$2`, skippedRoomID, revokedArtifact.ID); got != 0 { - t.Fatalf("skipped bindings=%d", got) + trashedCaller, trashedEffective := *roomInput.RoomCaller, *roomInput.RoomEffective + trashedCaller.Name, trashedEffective.Name = "Trashed Artifact MCP Room "+suffix, "Trashed Artifact MCP Room "+suffix + trashedCaller.Artifacts, trashedEffective.Artifacts = []string{otherArtifact.ID}, []string{otherArtifact.ID} + trashedInput := roomInput + trashedInput.RoomCaller, trashedInput.RoomEffective = &trashedCaller, &trashedEffective + trashedInput.InvocationID = mcpCreationInvocationID(suffix + ":room-trashed-artifact") + roomsBeforeTrashed := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) + if _, err := service.Submit(roomCtx, token, trashedInput); err == nil { + t.Fatal("a Room with a trashed artifact was created") } - if got := countRows(t, env, `SELECT count(*) FROM messages WHERE room_id=$1 AND (segments::text LIKE '%'||$2||'%' OR attachments @> jsonb_build_array(jsonb_build_object('document_id',$2::text)))`, skippedRoomID, revokedArtifact.ID); got != 0 { - t.Fatalf("skipped artifact messages=%d", got) + if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != roomsBeforeTrashed { + t.Fatalf("trashed-artifact Rooms=%d want=%d", got, roomsBeforeTrashed) } - assertRoomCreationHandoff(t, env, skippedRoomID, originRoomID, pendingRevokedRoom, "", nil, revokedArtifact.ID) - // Frozen Versions/Revisions and approval snapshots are immutable. Exercise - // unavailable or mismatched historical content at the Document guard itself. + // Frozen Versions/Revisions are immutable. Exercise unavailable or + // mismatched historical content at the Document guard itself. for _, contentCase := range []struct{ documentID, versionID, revisionID, tenantID, reason string }{ - {roomArtifact.ID, revokedArtifact.CurrentVersion.ID, "", acmeTenant, "frozen_content_unavailable"}, + {roomArtifact.ID, otherArtifact.CurrentVersion.ID, "", acmeTenant, "frozen_content_unavailable"}, {nativeArtifactID, "", "revision_missing", acmeTenant, "frozen_content_unavailable"}, } { tx, err := env.pool.Begin(t.Context()) @@ -466,45 +321,84 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { t.Fatalf("content review reason=%q want=%q err=%v", reason, contentCase.reason, reviewErr) } } - assertRoomCreationApprovalAccessTransactions(t, env, alice, service, token, roomInput, + frozenArtifacts := []typedcard.RoomCreationArtifactSnapshot{ + {DocumentID: nativeArtifactID, DocumentRevisionID: nativeRevisionID}, + {DocumentID: roomArtifact.ID, DocumentVersionID: roomArtifact.CurrentVersion.ID}, + } + frozenSegments := []messagecreation.Segment{ + {Type: "text", Content: "Start the approved Room."}, + {Type: "text", Content: "\n"}, + {Type: "document", Content: nativeArtifactTitle, DocumentID: nativeArtifactID, Presentation: "card"}, + {Type: "text", Content: "\n"}, + {Type: "document", Content: "room-brief-v1.txt", DocumentID: roomArtifact.ID, Presentation: "card"}, + } + pendingCard := func(t *testing.T, name string, description *string) typedcard.CreateResult { + t.Helper() + return postRoomCreationCard(t, env, roomCreationApprovalInputFor(t, typedcard.RoomCreationSnapshot{ + OriginRoomID: originRoomID, Name: name, Description: description, MemberIDs: []string{"actor_acme_official"}, + Artifacts: frozenArtifacts, InitialMessageSegments: frozenSegments, + }, mcpCreationInvocationID(t.Name())[24:56])) + } + assertRoomCreationApprovalAccessTransactions(t, env, alice, originRoomID, frozenArtifacts, frozenSegments, roomArtifact.ID, nativeArtifactID) - t.Run("handoff carries the frozen description as purpose", func(t *testing.T) { - purpose := "Plan the launch with the approved brief." + t.Run("handoff carries the description as purpose", func(t *testing.T) { + purpose := "Plan the launch with the brief." caller, effective := *roomInput.RoomCaller, *roomInput.RoomEffective caller.Name, effective.Name = "Purpose MCP Room "+suffix, "Purpose MCP Room "+suffix caller.Description, effective.Description = &purpose, &purpose input := roomInput input.RoomCaller, input.RoomEffective = &caller, &effective input.InvocationID = mcpCreationInvocationID(suffix + ":room-purpose") - pending, err := service.Submit(agentauth.WithTarget(t.Context(), "room", originRoomID), token, input) + result, err := service.Submit(roomCtx, token, input) if err != nil { t.Fatal(err) } - httpStatus, _, response := env.request(alice, http.MethodPost, - "/v0/decisions/"+pending.CreationApprovalRequestID, - map[string]any{"decision": "approve", "expected_version": 1}, "purpose-room-"+suffix) + assertRoomCreationHandoff(t, env, decodeRoomCreated(t, result).RoomID, originRoomID, nil, purpose, + []string{nativeArtifactID, roomArtifact.ID}) + }) + t.Run("an earlier pending card creates its Room on approval", func(t *testing.T) { + pending := pendingCard(t, "Approved MCP Room "+suffix, nil) + before := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) + httpStatus, _, response := env.request(alice, http.MethodPost, "/v0/decisions/"+pending.DecisionID, + map[string]any{"decision": "approve", "expected_version": int64(1)}, "approve-room-"+suffix) if httpStatus != http.StatusOK { - t.Fatalf("purpose approval status=%d body=%s", httpStatus, response) + t.Fatalf("approve status=%d body=%s", httpStatus, response) } - var purposeRoomID string - if err := env.pool.QueryRow(t.Context(), `SELECT result->'data'->>'created_room_id' FROM decisions WHERE id=$1 AND status='succeeded'`, - pending.CreationApprovalRequestID).Scan(&purposeRoomID); err != nil { + var approvedRoomID, runtimeBody string + if err := env.pool.QueryRow(t.Context(), `SELECT request.result->'data'->>'created_room_id',message.body + FROM decisions request JOIN messages message + ON message.card_context_message_id=request.message_id AND message.message_kind='agent_runtime' + WHERE request.id=$1 AND request.status='succeeded'`, pending.DecisionID).Scan(&approvedRoomID, &runtimeBody); err != nil { t.Fatal(err) } - assertRoomCreationHandoff(t, env, purposeRoomID, originRoomID, pending, purpose, + if !strings.Contains(runtimeBody, `"created_room_id":"`+approvedRoomID+`"`) || + !strings.Contains(runtimeBody, `"skipped_artifacts":[]`) || + !strings.Contains(runtimeBody, `<room-communication-pattern>`) { + t.Fatalf("approval runtime=%s", runtimeBody) + } + if got := countRows(t, env, `SELECT count(*) FROM messages WHERE room_id=$1 + AND card_context_message_id=$2 AND message_kind='conversation' + AND body LIKE '%'||$3||'%'`, originRoomID, pending.MessageID, approvedRoomID); got != 1 { + t.Fatal("visible Room result must include the Room ID") + } + assertRoomCreationHandoff(t, env, approvedRoomID, originRoomID, &pending, "", []string{nativeArtifactID, roomArtifact.ID}) - }) - t.Run("denial creates no Room or document delivery", func(t *testing.T) { - input := roomInput - input.InvocationID = mcpCreationInvocationID(suffix + ":room-denied") - pending, err := service.Submit(agentauth.WithTarget(t.Context(), "room", originRoomID), token, input) - if err != nil { - t.Fatal(err) + // A repeated decision carries a stale card version. + httpStatus, _, response = env.request(alice, http.MethodPost, "/v0/decisions/"+pending.DecisionID, + map[string]any{"decision": "approve", "expected_version": int64(1)}, "") + if httpStatus != http.StatusConflict { + t.Fatalf("repeated decision status=%d body=%s", httpStatus, response) + } + if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != before+1 { + t.Fatalf("approved Rooms=%d want=%d", got, before+1) } + }) + t.Run("denying an earlier pending card creates no Room or document delivery", func(t *testing.T) { + pending := pendingCard(t, "Denied MCP Room "+suffix, nil) roomCount := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) bindingCount := countRows(t, env, `SELECT count(*) FROM document_context_bindings WHERE tenant_id=$1`, acmeTenant) httpStatus, _, response := env.request(alice, http.MethodPost, - "/v0/decisions/"+pending.CreationApprovalRequestID, + "/v0/decisions/"+pending.DecisionID, map[string]any{"decision": "deny", "expected_version": 1, "comment": "Use the existing Room."}, "deny-room-"+suffix) if httpStatus != http.StatusOK { t.Fatalf("deny status=%d body=%s", httpStatus, response) @@ -512,49 +406,45 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { if countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) != roomCount || countRows(t, env, `SELECT count(*) FROM document_context_bindings WHERE tenant_id=$1`, acmeTenant) != bindingCount { t.Fatal("denial created Room or Binding") } - if got := countRows(t, env, `SELECT count(*) FROM decisions WHERE id=$1 AND status='denied' AND result IS NULL`, pending.CreationApprovalRequestID); got != 1 { + if got := countRows(t, env, `SELECT count(*) FROM decisions WHERE id=$1 AND status='denied' AND result IS NULL`, pending.DecisionID); got != 1 { t.Fatal("denial result invalid") } if got := countRows(t, env, `SELECT count(*) FROM messages WHERE card_context_message_id=$1 AND message_kind='agent_runtime'`, pending.MessageID); got != 0 { t.Fatal("denial sent approval notification") } - handoffDigest := sha256.Sum256([]byte("room-creation-handoff:" + pending.CreationApprovalRequestID)) + handoffDigest := sha256.Sum256([]byte("room-creation-handoff:" + pending.DecisionID)) if got := countRows(t, env, `SELECT count(*) FROM messages WHERE id=$1`, fmt.Sprintf("message_%x", handoffDigest[:16])); got != 0 { t.Fatal("denial sent a Room Creation handoff") } }) - } -func assertMcpCreationPendingFacts( - t *testing.T, - env *testEnv, - result agentcreationapproval.Result, - requestKind, roomID string, -) { +// decodeRoomCreated reads the Room a submission created at once. +func decodeRoomCreated(t *testing.T, result agentcreationapproval.Result) typedcard.RoomCreated { t.Helper() - if got := countRows(t, env, ` - SELECT count(*) - FROM decisions request - JOIN message_cards card ON card.message_id=request.message_id - WHERE request.id=$1 AND request.message_id=$2 AND request.room_id=$3 - AND request.kind=$4 AND request.status='pending' - AND card.version=1 AND card.work_item_id IS NULL - -- The request owns its idempotency; no receipt pins the credential. - AND NOT EXISTS (SELECT 1 FROM command_replays receipt WHERE receipt.resource_id=request.id) - `, result.CreationApprovalRequestID, result.MessageID, roomID, requestKind); got != 1 { - t.Fatalf("pending %s request/card rows=%d want=1", requestKind, got) + var created typedcard.RoomCreated + if result.Created == nil { + t.Fatalf("submission was not created at once: %+v", result) + } + if err := json.Unmarshal(result.Created, &created); err != nil { + t.Fatal(err) } + if !created.Accepted || created.Status != typedcard.RoomCreatedStatus || created.RoomID == "" { + t.Fatalf("created Room=%s", result.Created) + } + return created } -// assertRoomCreationHandoff checks the single Agent handoff appended to an -// approved Room: derived ID, no cross-Room card context, one Mention for the -// requesting Agent, request facts, and only delivered Document references. +// assertRoomCreationHandoff checks the single Agent handoff appended to a +// created Room: no cross-Room card context, one Mention for the requesting +// Agent, request facts, and only delivered Document references. For a Room an +// approval card created, approval names it, and the handoff also carries an ID +// derived from the request and the decision's facts. func assertRoomCreationHandoff( t *testing.T, env *testEnv, roomID, originRoomID string, - pending agentcreationapproval.Result, + approval *typedcard.CreateResult, wantPurpose string, wantDocumentIDs []string, forbidden ...string, @@ -572,9 +462,11 @@ func assertRoomCreationHandoff( `, roomID).Scan(&id, &body, &segments, &cardContextEmpty); err != nil { t.Fatal(err) } - digest := sha256.Sum256([]byte("room-creation-handoff:" + pending.CreationApprovalRequestID)) - if want := fmt.Sprintf("message_%x", digest[:16]); id != want { - t.Fatalf("handoff ID=%s want request-derived %s", id, want) + if approval != nil { + digest := sha256.Sum256([]byte("room-creation-handoff:" + approval.DecisionID)) + if want := fmt.Sprintf("message_%x", digest[:16]); id != want { + t.Fatalf("handoff ID=%s want request-derived %s", id, want) + } } if !cardContextEmpty { t.Fatal("handoff must not set a cross-Room card_context") @@ -620,27 +512,35 @@ func assertRoomCreationHandoff( if err := json.Unmarshal([]byte(payloadText), &payload); err != nil { t.Fatalf("handoff payload %q: %v", payloadText, err) } - if payload.Kind != "room_creation_handoff" || payload.RequestID != pending.CreationApprovalRequestID || - payload.CardMessageID != pending.MessageID || payload.OriginRoomID != originRoomID || + if payload.Kind != "room_creation_handoff" || payload.OriginRoomID != originRoomID || payload.OriginInboxID != "room:"+originRoomID || payload.RoomInboxID != "room:"+roomID { t.Fatalf("handoff payload=%+v", payload) } - // Decision facts must equal the persisted decision, not a separately sampled clock. - var requestStatus, decidedBy string - var decidedAt time.Time - if err := env.pool.QueryRow(t.Context(), ` - SELECT status,decided_by_actor_id,decided_at FROM decisions WHERE id=$1 - `, pending.CreationApprovalRequestID).Scan(&requestStatus, &decidedBy, &decidedAt); err != nil { - t.Fatal(err) - } - payloadDecidedAt, err := time.Parse(time.RFC3339Nano, payload.DecidedAt) - if err != nil || !strings.HasSuffix(payload.DecidedAt, "Z") { - t.Fatalf("handoff decided_at=%q must be RFC3339 UTC: %v", payload.DecidedAt, err) - } - if requestStatus != "succeeded" || payload.Decision != "approved" || payload.DecidedBy != decidedBy || - !payloadDecidedAt.Equal(decidedAt) { - t.Fatalf("handoff decision=%q decided_by=%q decided_at=%s want %q %q %s", - payload.Decision, payload.DecidedBy, payload.DecidedAt, requestStatus, decidedBy, decidedAt.UTC().Format(time.RFC3339Nano)) + if approval == nil { + if payload.RequestID != "" || payload.CardMessageID != "" || payload.Decision != "" || payload.DecidedBy != "" || payload.DecidedAt != "" { + t.Fatalf("handoff of a Room created at once names a decision: %+v", payload) + } + } else { + if payload.RequestID != approval.DecisionID || payload.CardMessageID != approval.MessageID { + t.Fatalf("handoff payload=%+v", payload) + } + // Decision facts must equal the persisted decision, not a separately sampled clock. + var requestStatus, decidedBy string + var decidedAt time.Time + if err := env.pool.QueryRow(t.Context(), ` + SELECT status,decided_by_actor_id,decided_at FROM decisions WHERE id=$1 + `, approval.DecisionID).Scan(&requestStatus, &decidedBy, &decidedAt); err != nil { + t.Fatal(err) + } + payloadDecidedAt, err := time.Parse(time.RFC3339Nano, payload.DecidedAt) + if err != nil || !strings.HasSuffix(payload.DecidedAt, "Z") { + t.Fatalf("handoff decided_at=%q must be RFC3339 UTC: %v", payload.DecidedAt, err) + } + if requestStatus != "succeeded" || payload.Decision != "approved" || payload.DecidedBy != decidedBy || + !payloadDecidedAt.Equal(decidedAt) { + t.Fatalf("handoff decision=%q decided_by=%q decided_at=%s want %q %q %s", + payload.Decision, payload.DecidedBy, payload.DecidedAt, requestStatus, decidedBy, decidedAt.UTC().Format(time.RFC3339Nano)) + } } if wantPurpose == "" { if payload.Purpose != nil || strings.Contains(payloadText, `"purpose"`) { diff --git a/apps/teamhub/tests/integration/message_core_test.go b/apps/teamhub/tests/integration/message_core_test.go index c2de8f26d..bd2a564ff 100644 --- a/apps/teamhub/tests/integration/message_core_test.go +++ b/apps/teamhub/tests/integration/message_core_test.go @@ -10,11 +10,9 @@ import ( "time" "github.com/simplexai-labs/linger/apps/teamhub/internal/agentauth" - "github.com/simplexai-labs/linger/apps/teamhub/internal/agentcreationapproval" "github.com/simplexai-labs/linger/apps/teamhub/internal/agentsendmessage" "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation" "github.com/simplexai-labs/linger/apps/teamhub/internal/store" - "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard" ) // An Agent's Thread reply refreshes the parent timeline's Thread summary, as a @@ -146,20 +144,11 @@ func TestMessageCreatedPayloadIsOneShapeForEveryWriter(t *testing.T) { t.Fatalf("Agent Message result=%+v err=%v", sent, err) } - // An AnotherMe asks its Human to approve a Room: a typed card Message. + // A pending Room creation card is a typed card Message. if _, err := env.pool.Exec(ctx, `UPDATE agent_registrations SET agent_type='anotherme',receives_all_messages=true,represented_human_actor_id='actor_acme_alice' WHERE actor_id='actor_acme_official'`); err != nil { t.Fatal(err) } - segments := []messagecreation.Segment{{Type: "text", Content: "Payload Room approval"}} - members := []string{"actor_acme_alice", "actor_acme_official"} - approval, err := agentcreationapproval.New(env.pool, contexts, typedcard.New(env.pool)).Submit(ctx, issued.AccessToken, agentcreationapproval.Input{ - RequestKind: "room_creation", InvocationID: "agent-invocation-sha256:" + strings.Repeat("d", 64), - RoomCaller: &agentcreationapproval.RoomCallerInput{Name: "Payload room " + suffix, MemberIDs: members, InitialMessageSegments: segments}, - RoomEffective: &agentcreationapproval.RoomEffectivePayload{Name: "Payload room " + suffix, MemberIDs: members, InitialMessageSegments: segments}, - }) - if err != nil || approval.CreationApprovalRequestID == "" { - t.Fatalf("Room approval result=%+v err=%v", approval, err) - } + pendingRoomCreationCard(t, env, roomID, "payload-"+suffix) events, _ := humanRoomEventsAfter(t, env, alice, roomID, start.LatestRoomSeq) announced := map[string]map[string]any{} diff --git a/apps/teamhub/tests/integration/room_member_pending_decision_test.go b/apps/teamhub/tests/integration/room_member_pending_decision_test.go index 6944b61e1..10d18497a 100644 --- a/apps/teamhub/tests/integration/room_member_pending_decision_test.go +++ b/apps/teamhub/tests/integration/room_member_pending_decision_test.go @@ -3,14 +3,8 @@ package integration_test import ( "net/http" "strconv" - "strings" "testing" "time" - - "github.com/simplexai-labs/linger/apps/teamhub/internal/agentauth" - "github.com/simplexai-labs/linger/apps/teamhub/internal/agentcreationapproval" - "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation" - "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard" ) // A pending creation approval keeps its decision owner and the requesting @@ -18,24 +12,14 @@ import ( // who does not own the decision may not take it. A denial tells the Room why. func TestRoomMemberRemovalWaitsForPendingCreationApproval(t *testing.T) { allowParallelIntegrationTest(t) - env, alice, issued, roomID := newAgentCLIIdentity(t) + env, alice, _, roomID := newAgentCLIIdentity(t) bob := seedPeerHuman(t, env) suffix := strconv.FormatInt(time.Now().UnixNano(), 36) if _, err := env.pool.Exec(t.Context(), `UPDATE agent_registrations SET agent_type='anotherme',receives_all_messages=true,represented_human_actor_id='actor_acme_alice',visibility_scope='sponsor' WHERE actor_id='actor_acme_official'`); err != nil { t.Fatal(err) } - segments := []messagecreation.Segment{{Type: "text", Content: "Plan the launch"}} - members := []string{"actor_acme_alice", "actor_acme_official"} - approval, err := agentcreationapproval.New(env.pool, agentauth.New(env.pool), typedcard.New(env.pool)).Submit( - agentauth.WithTarget(t.Context(), "room", roomID), issued.AccessToken, - agentcreationapproval.Input{ - RequestKind: "room_creation", InvocationID: "agent-invocation-sha256:" + strings.Repeat("e", 64), - RoomCaller: &agentcreationapproval.RoomCallerInput{Name: "Launch room " + suffix, MemberIDs: members, InitialMessageSegments: segments}, - RoomEffective: &agentcreationapproval.RoomEffectivePayload{Name: "Launch room " + suffix, MemberIDs: members, InitialMessageSegments: segments}, - }) - if err != nil || approval.CreationApprovalRequestID == "" { - t.Fatalf("Room approval result=%+v err=%v", approval, err) - } + card := pendingRoomCreationCard(t, env, roomID, "member-removal-"+suffix) + approval := struct{ CreationApprovalRequestID, MessageID string }{card.DecisionID, card.MessageID} decide := func(client *http.Client, decision map[string]any, key string) (int, []byte) { status, _, body := env.request(client, http.MethodPost, "/v0/decisions/"+approval.CreationApprovalRequestID, decision, key) diff --git a/apps/teamhub/tests/integration/work_item_fixture_test.go b/apps/teamhub/tests/integration/work_item_fixture_test.go index 4a730c48c..77b18bdb0 100644 --- a/apps/teamhub/tests/integration/work_item_fixture_test.go +++ b/apps/teamhub/tests/integration/work_item_fixture_test.go @@ -65,38 +65,56 @@ func createWorkRoomFixture(t *testing.T, env *testEnv, owner *http.Client, workI // request in originRoomID; key keeps its submission distinct. func roomCreationApprovalInput(t *testing.T, originRoomID, key string) typedcard.CreationApprovalInTxInput { t.Helper() - proposal := typedcard.RoomCreationSnapshot{OriginRoomID: originRoomID, Name: "Acceptance file release", + return roomCreationApprovalInputFor(t, typedcard.RoomCreationSnapshot{OriginRoomID: originRoomID, Name: "Acceptance file release", MemberIDs: []string{"actor_acme_alice", "actor_acme_official"}, InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Review after generating the report"}}, - } + }, key) +} + +// roomCreationApprovalInputFor is the official Agent's request for the Room +// that proposal freezes, as TeamHub froze it for an approval card. +func roomCreationApprovalInputFor(t *testing.T, proposal typedcard.RoomCreationSnapshot, key string) typedcard.CreationApprovalInTxInput { + t.Helper() encoded, err := json.Marshal(proposal) if err != nil { t.Fatal(err) } hash := sha256.Sum256(encoded) return typedcard.CreationApprovalInTxInput{ - RoomID: originRoomID, AgentManagementID: acmeOfficialAgentManagementID, IdempotencyOperation: "test-room-creation:" + key, CallerInputHash: hash[:], + RoomID: proposal.OriginRoomID, AgentManagementID: acmeOfficialAgentManagementID, IdempotencyOperation: "test-room-creation:" + key, CallerInputHash: hash[:], Submission: typedcard.CreationApprovalSubmission{SubmissionID: "room-creation-" + key, CallerInput: encoded, EffectivePayload: encoded, FulfillmentSnapshot: encoded}, } } -// createPendingRoomCreationApproval submits the official Agent's create_room -// request in originRoomID and returns its pending creation approval. +// createPendingRoomCreationApproval posts a pending Room creation card for +// the official Agent in originRoomID and returns its decision. func createPendingRoomCreationApproval(t *testing.T, env *testEnv, originRoomID, suffix string) string { + t.Helper() + return pendingRoomCreationCard(t, env, originRoomID, suffix).DecisionID +} + +// pendingRoomCreationCard posts a pending Room creation card, as Agents did +// before TeamHub created their Rooms at once; such cards can still be decided. +func pendingRoomCreationCard(t *testing.T, env *testEnv, originRoomID, suffix string) typedcard.CreateResult { + t.Helper() + return postRoomCreationCard(t, env, roomCreationApprovalInput(t, originRoomID, suffix)) +} + +func postRoomCreationCard(t *testing.T, env *testEnv, input typedcard.CreationApprovalInTxInput) typedcard.CreateResult { t.Helper() tx, err := env.pool.Begin(t.Context()) if err != nil { t.Fatal(err) } defer tx.Rollback(t.Context()) - created, err := typedcard.New(env.pool).CreateCreationApprovalRequestInTx(t.Context(), tx, roomCreationApprovalInput(t, originRoomID, suffix)) + created, err := typedcard.New(env.pool).CreateCreationApprovalRequestInTx(t.Context(), tx, input) if err != nil { t.Fatalf("request Room creation: %v", err) } if err := tx.Commit(t.Context()); err != nil { t.Fatal(err) } - return created.DecisionID + return created } // denyRoomCreationApproval denies a pending creation approval as decider. diff --git a/contracts/generated/go/teamhubagentapi/openapi.gen.go b/contracts/generated/go/teamhubagentapi/openapi.gen.go index 7b9475a28..6b6597b8a 100644 --- a/contracts/generated/go/teamhubagentapi/openapi.gen.go +++ b/contracts/generated/go/teamhubagentapi/openapi.gen.go @@ -368,6 +368,24 @@ func (e AgentContextMemberKind) Valid() bool { } } +// Defines values for AgentCreationApprovalResponseStatus. +const ( + Created AgentCreationApprovalResponseStatus = "created" + PendingApproval AgentCreationApprovalResponseStatus = "pending_approval" +) + +// Valid indicates whether the value is a known member of the AgentCreationApprovalResponseStatus enum. +func (e AgentCreationApprovalResponseStatus) Valid() bool { + switch e { + case Created: + return true + case PendingApproval: + return true + default: + return false + } +} + // Defines values for AgentDocumentCommentAuthorKind. const ( AgentDocumentCommentAuthorKindAgent AgentDocumentCommentAuthorKind = "agent" @@ -2027,21 +2045,30 @@ type AgentCreateTeamMdResponse struct { // AgentCreationActorIds Duplicate-free TeamHub Actor identifiers in caller-supplied order. type AgentCreationActorIds = []Id -// AgentCreationApprovalResponse Durable pending Room creation approval request. +// AgentCreationApprovalResponse A submitted Room creation. TeamHub creates the Room at once, owned by the Agent's Sponsor; a submission replayed from an earlier pending approval card still reports that card. type AgentCreationApprovalResponse struct { // Accepted Whether TeamHub accepted and durably persisted the Creation request. Accepted bool `json:"accepted"` // CreationApprovalRequestId Opaque, case-sensitive identifier. Clients must not infer type or time from it. - CreationApprovalRequestId Id `json:"creation_approval_request_id"` + CreationApprovalRequestId *Id `json:"creation_approval_request_id,omitempty"` // MessageId Opaque, case-sensitive identifier. Clients must not infer type or time from it. - MessageId Id `json:"message_id"` + MessageId *Id `json:"message_id,omitempty"` - // Status Initial lifecycle state while awaiting a Human decision. - Status string `json:"status"` + // RoomId Opaque, case-sensitive identifier. Clients must not infer type or time from it. + RoomId *Id `json:"room_id,omitempty"` + + // SkippedArtifacts Requested Documents not delivered to the created Room, each with the reason; present when status is created. + SkippedArtifacts *[]AgentRoomCreationSkippedArtifact `json:"skipped_artifacts,omitempty"` + + // Status created when the Room exists; pending_approval for a replayed submission whose approval card still awaits a Human decision. + Status AgentCreationApprovalResponseStatus `json:"status"` } +// AgentCreationApprovalResponseStatus created when the Room exists; pending_approval for a replayed submission whose approval card still awaits a Human decision. +type AgentCreationApprovalResponseStatus string + // AgentCreationMessageSegment One structured initial message segment accepted by a Creation request. Every segment must include its type discriminator. Document and file segments remain excluded because the destination Room does not exist yet; create_room delivers existing Documents through its separate artifacts field. type AgentCreationMessageSegment struct { union json.RawMessage @@ -2701,6 +2728,15 @@ type AgentRoomCreationEffectivePayload struct { Name string `json:"name"` } +// AgentRoomCreationSkippedArtifact A requested Document the created Room did not receive. +type AgentRoomCreationSkippedArtifact struct { + // DocumentId Opaque, case-sensitive identifier. Clients must not infer type or time from it. + DocumentId Id `json:"document_id"` + + // Reason Why the Document was not delivered. + Reason string `json:"reason"` +} + // AgentRoomHandoffRequest The Room to hand the Human's request to and the instruction the AnotherMe's Context there carries out. The caller, its direct chat and its Human are derived by TeamHub, never accepted from the caller. type AgentRoomHandoffRequest struct { // HandoffId Opaque, case-sensitive identifier. Clients must not infer type or time from it. diff --git a/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts b/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts index 18a7601c1..24c283f6c 100644 --- a/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts +++ b/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts @@ -454,8 +454,8 @@ export interface paths { get?: never; put?: never; /** - * Submit one Room creation request for Human approval - * @description Resolves the Agent and Tenant exclusively from the Agent credential, re-authorizes create_room in the caller's Room Context, and atomically stores the exact caller input separately from the canonical effective payload. TeamHub revalidates every derived value before freezing the immutable approval snapshot; caller identity is intentionally absent from the request body. + * Create one Room the Agent requested + * @description Resolves the Agent and Tenant exclusively from the Agent credential, re-authorizes create_room in the caller's Room Context, revalidates every derived value, and creates the Room at once, owned by the Agent's Sponsor, with its initial message and the Agent's handoff. Caller identity is intentionally absent from the request body. */ post: operations["submitAgentCreationApprovalRequest"]; delete?: never; @@ -2285,7 +2285,13 @@ export interface components { /** @description Canonical Room payload frozen independently from caller input. */ effective_payload: components["schemas"]["AgentRoomCreationEffectivePayload"]; }; - /** @description Durable pending Room creation approval request. */ + /** @description A requested Document the created Room did not receive. */ + AgentRoomCreationSkippedArtifact: { + document_id: components["schemas"]["Id"]; + /** @description Why the Document was not delivered. */ + reason: string; + }; + /** @description A submitted Room creation. TeamHub creates the Room at once, owned by the Agent's Sponsor; a submission replayed from an earlier pending approval card still reports that card. */ AgentCreationApprovalResponse: { /** * @description Whether TeamHub accepted and durably persisted the Creation request. @@ -2293,14 +2299,18 @@ export interface components { */ accepted: true; /** - * @description Initial lifecycle state while awaiting a Human decision. - * @constant + * @description created when the Room exists; pending_approval for a replayed submission whose approval card still awaits a Human decision. + * @enum {string} */ - status: "pending_approval"; - /** @description Stable identifier of the Creation approval request fact. */ - creation_approval_request_id: components["schemas"]["Id"]; - /** @description Stable identifier of the Human approval card message. */ - message_id: components["schemas"]["Id"]; + status: "created" | "pending_approval"; + /** @description The created Room, present when status is created. */ + room_id?: components["schemas"]["Id"]; + /** @description Requested Documents not delivered to the created Room, each with the reason; present when status is created. */ + skipped_artifacts?: components["schemas"]["AgentRoomCreationSkippedArtifact"][]; + /** @description Stable identifier of the Creation approval request; present when status is pending_approval. */ + creation_approval_request_id?: components["schemas"]["Id"]; + /** @description Stable identifier of the Human approval card message; present when status is pending_approval. */ + message_id?: components["schemas"]["Id"]; }; /** @description One delegated Task created and started immediately for the calling Agent's own AlterEgo. The origin Room is the caller's Room Context; no Human approval is requested. */ AgentCreateTaskRequest: { @@ -3973,7 +3983,7 @@ export interface operations { }; }; responses: { - /** @description The durable pending Creation approval request and active Manifest attestation. */ + /** @description The created Room, or the pending approval card of a replayed earlier submission. */ 200: { headers: { [name: string]: unknown; diff --git a/contracts/openapi/components/agent-collaboration.yaml b/contracts/openapi/components/agent-collaboration.yaml index 9db7c7633..472aa1a53 100644 --- a/contracts/openapi/components/agent-collaboration.yaml +++ b/contracts/openapi/components/agent-collaboration.yaml @@ -852,13 +852,14 @@ components: description: Canonical Room payload frozen independently from caller input. AgentCreationApprovalResponse: type: object - description: Durable pending Room creation approval request. + description: >- + A submitted Room creation. TeamHub creates the Room at once, owned by the Agent's + Sponsor; a submission replayed from an earlier pending approval card still reports + that card. additionalProperties: false required: - accepted - status - - creation_approval_request_id - - message_id properties: accepted: type: boolean @@ -866,14 +867,39 @@ components: description: Whether TeamHub accepted and durably persisted the Creation request. status: type: string - const: pending_approval - description: Initial lifecycle state while awaiting a Human decision. + enum: [created, pending_approval] + description: >- + created when the Room exists; pending_approval for a replayed submission whose + approval card still awaits a Human decision. + room_id: + $ref: "./common.yaml#/components/schemas/Id" + description: The created Room, present when status is created. + skipped_artifacts: + type: array + description: >- + Requested Documents not delivered to the created Room, each with the reason; + present when status is created. + items: + $ref: "#/components/schemas/AgentRoomCreationSkippedArtifact" creation_approval_request_id: $ref: "./common.yaml#/components/schemas/Id" - description: Stable identifier of the Creation approval request fact. + description: Stable identifier of the Creation approval request; present when status is pending_approval. message_id: $ref: "./common.yaml#/components/schemas/Id" - description: Stable identifier of the Human approval card message. + description: Stable identifier of the Human approval card message; present when status is pending_approval. + AgentRoomCreationSkippedArtifact: + type: object + description: A requested Document the created Room did not receive. + additionalProperties: false + required: + - document_id + - reason + properties: + document_id: + $ref: "./common.yaml#/components/schemas/Id" + reason: + type: string + description: Why the Document was not delivered. AgentCreateTaskRequest: type: object description: >- diff --git a/contracts/openapi/teamhub-agent-api/openapi.yaml b/contracts/openapi/teamhub-agent-api/openapi.yaml index af3921d7f..05a586b05 100644 --- a/contracts/openapi/teamhub-agent-api/openapi.yaml +++ b/contracts/openapi/teamhub-agent-api/openapi.yaml @@ -316,13 +316,12 @@ paths: post: tags: [Agent Business API] operationId: submitAgentCreationApprovalRequest - summary: Submit one Room creation request for Human approval + summary: Create one Room the Agent requested description: >- Resolves the Agent and Tenant exclusively from the Agent credential, re-authorizes - create_room in the caller's Room Context, and atomically stores the exact caller input - separately from the canonical effective payload. TeamHub revalidates every derived value before freezing - the immutable approval snapshot; caller identity is intentionally absent from the - request body. + create_room in the caller's Room Context, revalidates every derived value, and + creates the Room at once, owned by the Agent's Sponsor, with its initial message and + the Agent's handoff. Caller identity is intentionally absent from the request body. security: - agentBearer: [] x-deadline-ms: 5000 @@ -334,7 +333,7 @@ paths: $ref: "../components/agent-collaboration.yaml#/components/schemas/AgentRoomCreationApprovalRequest" responses: "200": - description: The durable pending Creation approval request and active Manifest attestation. + description: The created Room, or the pending approval card of a replayed earlier submission. content: application/json: schema: diff --git a/contracts/tests/teamhub-agent-api.contract.test.ts b/contracts/tests/teamhub-agent-api.contract.test.ts index ac3a983f2..d420e33e4 100644 --- a/contracts/tests/teamhub-agent-api.contract.test.ts +++ b/contracts/tests/teamhub-agent-api.contract.test.ts @@ -186,15 +186,15 @@ describe("TeamHub Agent API contract", () => { expect(schemas.AgentCreationApprovalResponse).toMatchObject({ additionalProperties: false, - required: [ - "accepted", - "status", - "creation_approval_request_id", - "message_id", - ], + required: ["accepted", "status"], properties: { accepted: { const: true }, - status: { const: "pending_approval" }, + status: { enum: ["created", "pending_approval"] }, + skipped_artifacts: { + items: { + $ref: "#/components/schemas/AgentRoomCreationSkippedArtifact", + }, + }, }, }); expect( @@ -205,6 +205,8 @@ describe("TeamHub Agent API contract", () => { [ "accepted", "status", + "room_id", + "skipped_artifacts", "creation_approval_request_id", "message_id", ].sort(), From 06700f615c3c69d4660c1f3b9c9cb77ad2a6e51e Mon Sep 17 00:00:00 2001 From: muterC <36739961+muterC@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:18:27 +0800 Subject: [PATCH 2/5] fix(voice): restore Carina for live calls --- apps/voice-runtime/README.md | 2 +- apps/voice-runtime/src/live-agent.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/voice-runtime/README.md b/apps/voice-runtime/README.md index 822080c06..116acc81b 100644 --- a/apps/voice-runtime/README.md +++ b/apps/voice-runtime/README.md @@ -14,5 +14,5 @@ Commands, conventions and boundaries are in [AGENTS.md](./AGENTS.md). ## Running and configuration - `node dist/main.js start` starts the ASR worker; `start --recorder` starts the recording worker from the same image. Set the log level with the LiveKit CLI's `--log-level`; `start` defaults to `info`. -- Required environment variables: `TEAMHUB_BASE_URL`, `LINGER_SECRET_SEED`. `LIVEKIT_URL`, `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET` are optional and have defaults. The transcription workers need `SONIOX_API_KEY`, and ASR uses Soniox only; the Live worker needs only `XAI_API_KEY`, and the user's captions come from Grok's own transcription, not from Soniox. Live uses `grok-voice-3.0` with the `ursa` voice. Recording transcripts always separate speakers; dictation does not. `HTTPS_PROXY` (or `https_proxy`) is an HTTP CONNECT proxy for the Soniox and xAI websockets only, with the key sent on the connection; `NO_PROXY` exempts hosts (a bare `example.com` also covers its subdomains, as in Go and curl), and loopback is always direct. A `socks5://` proxy is not supported and is ignored. Node verifies TLS against its bundled CA list and `NODE_EXTRA_CA_CERTS`, not the macOS Keychain or the Windows certificate store, so an `https://` proxy whose certificate comes from a corporate CA installed only in the system fails with `network_tls`. LiveKit and TeamHub connections never use the proxy. +- Required environment variables: `TEAMHUB_BASE_URL`, `LINGER_SECRET_SEED`. `LIVEKIT_URL`, `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET` are optional and have defaults. The transcription workers need `SONIOX_API_KEY`, and ASR uses Soniox only; the Live worker needs only `XAI_API_KEY`, and the user's captions come from Grok's own transcription, not from Soniox. Live uses `grok-voice-3.0` with the `carina` voice. Recording transcripts always separate speakers; dictation does not. `HTTPS_PROXY` (or `https_proxy`) is an HTTP CONNECT proxy for the Soniox and xAI websockets only, with the key sent on the connection; `NO_PROXY` exempts hosts (a bare `example.com` also covers its subdomains, as in Go and curl), and loopback is always direct. A `socks5://` proxy is not supported and is ignored. Node verifies TLS against its bundled CA list and `NODE_EXTRA_CA_CERTS`, not the macOS Keychain or the Windows certificate store, so an `https://` proxy whose certificate comes from a corporate CA installed only in the system fails with `network_tls`. LiveKit and TeamHub connections never use the proxy. - The health port is `VOICE_WORKER_PORT` (`4324` when unset; node-services gives each worker a free port): in the image (`NODE_ENV=production`) it listens on every interface, and when run directly on a machine only on loopback. Each worker takes at most 16 sessions. The LiveKit address and key pair come from `LIVEKIT_URL`, `LIVEKIT_API_KEY` and `LIVEKIT_API_SECRET`; unset, they default to the local deployment in `apps/teamhub/deployments/voice` (`ws://127.0.0.1:17880`, `devkey` and its development secret), the same as TeamHub's defaults. In Compose, `LIVEKIT_URL` is `ws://livekit:7880`. The Soniox model and language hints are code constants. diff --git a/apps/voice-runtime/src/live-agent.ts b/apps/voice-runtime/src/live-agent.ts index 07bdc3d28..5e20b9367 100644 --- a/apps/voice-runtime/src/live-agent.ts +++ b/apps/voice-runtime/src/live-agent.ts @@ -25,7 +25,7 @@ export default defineAgent({ proxy: config.providerProxy, audioTransport: config.xaiLiveAudioTransport, model: "grok-voice-3.0", - voice: "ursa", + voice: "carina", reasoningEffort: "high", setup, }), From 54fc846d2be364d4c4320d60dcb8150d418f279a Mon Sep 17 00:00:00 2001 From: muterC <36739961+muterC@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:53:43 +0800 Subject: [PATCH 3/5] fix(teamhub): enforce sponsor admission for immediate room creation --- apps/teamhub-cli/README.md | 2 +- .../typedcard/creation_approval_decision.go | 6 ++- .../integration/mcp_creation_approval_test.go | 40 ++++++++++++++++++- .../src/generated/teamhub-agent-api/types.ts | 2 +- .../openapi/teamhub-agent-api/openapi.yaml | 3 +- 5 files changed, 47 insertions(+), 6 deletions(-) diff --git a/apps/teamhub-cli/README.md b/apps/teamhub-cli/README.md index bd694c2eb..a425063c1 100644 --- a/apps/teamhub-cli/README.md +++ b/apps/teamhub-cli/README.md @@ -66,7 +66,7 @@ Task completion uses only the generation, attempt and input revision accepted be The current entry points are the ones help lists. -`agent list` and `agent get --agent-id <actor-id>` show the General Agents under a Sponsor. `agent create --name <name> --prompt-file <path>` creates an Agent at once: in a Room the Sponsor is in it joins that Room, and in the Sponsor's Direct Room it is created without joining. `agent update` changes only the name, description or prompt it is given; without `--agent-id` it changes the caller. A name or description change runs at once; a prompt change runs at once only for an uninitialized Agent in the current Room. Any other prompt change, and an `agent create` in a Room the Sponsor is not in, waits for the Sponsor: the command returns a confirmation card and exits 0; TeamHub runs it after approval and reports the result, so do not run it again. `room create --name <name> --member-id <actor-id> --content <brief>` creates a collaboration Room at once, owned by the Sponsor, with its members and first message, and hands the work to the caller in that Room. `room invite --agent-id <actor-id>` adds an existing Agent from `agent list` to the current Room at once, with the Sponsor's authority; a Direct Room or Thread keeps its members. A Task context cannot use these commands. +`agent list` and `agent get --agent-id <actor-id>` show the General Agents under a Sponsor. `agent create --name <name> --prompt-file <path>` creates an Agent at once: in a Room the Sponsor is in it joins that Room, and in the Sponsor's Direct Room it is created without joining. `agent update` changes only the name, description or prompt it is given; without `--agent-id` it changes the caller. A name or description change runs at once; a prompt change runs at once only for an uninitialized Agent in the current Room. Any other prompt change, and an `agent create` in a Room the Sponsor is not in, waits for the Sponsor: the command returns a confirmation card and exits 0; TeamHub runs it after approval and reports the result, so do not run it again. `room create --name <name> --member-id <actor-id> --content <brief>` creates a collaboration Room at once, owned by the Sponsor, with its members and first message, and hands the work to the caller in that Room. Each Agent added at creation must have the same Sponsor as the caller. `room invite --agent-id <actor-id>` adds an existing Agent from `agent list` to the current Room at once, with the Sponsor's authority; a Direct Room or Thread keeps its members. A Task context cannot use these commands. `room handoff --inbox room:<room-id> --content <instruction>` lets Another Me, in its direct chat and in a turn its Human started by writing or deciding a card, hand that request to itself in another Room where both are members. TeamHub posts a hidden handoff there that wakes Another Me's Context in that Room, which then posts and mentions Agents itself; the direct chat never writes in that Room. Results come back with `message direct`. diff --git a/apps/teamhub/internal/typedcard/creation_approval_decision.go b/apps/teamhub/internal/typedcard/creation_approval_decision.go index 1dc3073d7..2269c3779 100644 --- a/apps/teamhub/internal/typedcard/creation_approval_decision.go +++ b/apps/teamhub/internal/typedcard/creation_approval_decision.go @@ -74,6 +74,7 @@ func (a roomCreationApproval) approve(ctx context.Context, tx pgx.Tx, queries *s room, err := createSnapshotRoom(ctx, tx, queries, snapshotRoomSpec{ tenantID: a.tenantID, originRoomID: a.originRoomID, agentActorID: a.agentActorID, accountID: a.accountID, owner: decisionOwner, snapshot: a.snapshot, bindingKey: "room-create-artifacts:" + a.decisionID, + humanApproved: true, }) if err != nil { return decisionOutcome{}, "", err @@ -120,6 +121,7 @@ type snapshotRoomSpec struct { tenantID, originRoomID, agentActorID, accountID string owner store.Actor snapshot json.RawMessage + humanApproved bool // bindingKey makes the Documents' Room bindings idempotent. bindingKey string } @@ -179,7 +181,7 @@ func createSnapshotRoom(ctx context.Context, tx pgx.Tx, queries *store.Queries, TenantID: spec.tenantID, Name: snapshot.Name, Description: snapshot.Description, Creator: agent, Owner: owner, MemberActorIDs: creationRoomMemberIDs(snapshot.MemberIDs, agent.ID, owner.ID), - AgentsAuthorized: true, + AgentsAuthorized: spec.humanApproved, }) if err != nil { return snapshotRoom{}, mapCreationDecisionError(err) @@ -392,6 +394,8 @@ func creationDecisionAgent( func mapCreationDecisionError(err error) error { switch { + case errors.Is(err, roomcreation.ErrAgentSponsorRequired): + return ErrForbidden case errors.Is(err, roomcreation.ErrInvalid), errors.Is(err, roomcreation.ErrNotFound), errors.Is(err, roomcreation.ErrAgentUnavailable), errors.Is(err, messagecreation.ErrInvalid), errors.Is(err, messagecreation.ErrInvalidReference), diff --git a/apps/teamhub/tests/integration/mcp_creation_approval_test.go b/apps/teamhub/tests/integration/mcp_creation_approval_test.go index 681024e0b..35dd5e2a6 100644 --- a/apps/teamhub/tests/integration/mcp_creation_approval_test.go +++ b/apps/teamhub/tests/integration/mcp_creation_approval_test.go @@ -169,12 +169,12 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { roomInput := agentcreationapproval.Input{ RequestKind: "room_creation", RoomCaller: &agentcreationapproval.RoomCallerInput{ - Name: roomName, MemberIDs: []string{"actor_acme_official"}, + Name: roomName, MemberIDs: []string{"actor_acme_official", discussionAgentActorID}, Artifacts: []string{nativeArtifactID, roomArtifact.ID}, InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Start the new Room."}}, }, RoomEffective: &agentcreationapproval.RoomEffectivePayload{ - Name: roomName, MemberIDs: []string{"actor_acme_official"}, + Name: roomName, MemberIDs: []string{"actor_acme_official", discussionAgentActorID}, Artifacts: []string{nativeArtifactID, roomArtifact.ID}, InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Start the new Room."}}, }, @@ -201,6 +201,9 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { WHERE room.id=$1 AND room.name=$2 AND member.actor_id='actor_acme_alice' AND member.role='owner'`, createdRoomID, roomName); got != 1 { t.Fatalf("created Room owned by the Sponsor=%d want=1", got) } + if got := countRows(t, env, `SELECT count(*) FROM room_members WHERE room_id=$1 AND actor_id=$2 AND role='member'`, createdRoomID, discussionAgentActorID); got != 1 { + t.Fatalf("invited Agent memberships=%d want=1", got) + } if got := countRows(t, env, `SELECT count(*) FROM decisions WHERE room_id=$1`, originRoomID); got != 0 { t.Fatalf("Room creation posted %d cards", got) } @@ -417,6 +420,39 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { t.Fatal("denial sent a Room Creation handoff") } }) + t.Run("only a Human-approved snapshot admits an Agent with a different Sponsor", func(t *testing.T) { + seedPeerHumanActor(t, env.pool) + if _, err := env.pool.Exec(t.Context(), `UPDATE agent_registrations SET created_by_actor_id='actor_acme_bob' WHERE actor_id=$1`, workspaceAgentActorID); err != nil { + t.Fatal(err) + } + snapshot := typedcard.RoomCreationSnapshot{ + OriginRoomID: originRoomID, Name: "Agent admission " + suffix, MemberIDs: []string{workspaceAgentActorID}, + InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Start the discussion."}}, + } + input := roomCreationApprovalInputFor(t, snapshot, mcpCreationInvocationID(t.Name())[24:56]) + cards := typedcard.New(env.pool) + tx, err := env.pool.Begin(t.Context()) + if err != nil { + t.Fatal(err) + } + _, err = cards.CreateRoomInTx(t.Context(), tx, input) + if rollbackErr := tx.Rollback(t.Context()); rollbackErr != nil { + t.Fatal(rollbackErr) + } + if !errors.Is(err, typedcard.ErrForbidden) { + t.Fatalf("immediate admission error = %v, want ErrForbidden", err) + } + + pending := postRoomCreationCard(t, env, input) + if _, err := cards.DecideDecision(t.Context(), "account_alice", pending.DecisionID, + typedcard.DecisionAnswerCommand{Decision: "approve", ExpectedVersion: 1}); err != nil { + t.Fatal(err) + } + if got := countRows(t, env, `SELECT count(*) FROM decisions d JOIN room_members m ON m.room_id=d.result->'data'->>'created_room_id' + WHERE d.id=$1 AND m.actor_id=$2 AND m.role='member'`, pending.DecisionID, workspaceAgentActorID); got != 1 { + t.Fatalf("approved Agent memberships=%d want=1", got) + } + }) } // decodeRoomCreated reads the Room a submission created at once. diff --git a/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts b/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts index 24c283f6c..940ae6068 100644 --- a/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts +++ b/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts @@ -455,7 +455,7 @@ export interface paths { put?: never; /** * Create one Room the Agent requested - * @description Resolves the Agent and Tenant exclusively from the Agent credential, re-authorizes create_room in the caller's Room Context, revalidates every derived value, and creates the Room at once, owned by the Agent's Sponsor, with its initial message and the Agent's handoff. Caller identity is intentionally absent from the request body. + * @description Resolves the Agent and Tenant exclusively from the Agent credential, re-authorizes create_room in the caller's Room Context, revalidates every derived value, and creates the Room at once, owned by the Agent's Sponsor, with its initial message and the Agent's handoff. Each Agent added to the new Room must have the same Sponsor as the caller. Caller identity is intentionally absent from the request body. */ post: operations["submitAgentCreationApprovalRequest"]; delete?: never; diff --git a/contracts/openapi/teamhub-agent-api/openapi.yaml b/contracts/openapi/teamhub-agent-api/openapi.yaml index 05a586b05..5e7cd2831 100644 --- a/contracts/openapi/teamhub-agent-api/openapi.yaml +++ b/contracts/openapi/teamhub-agent-api/openapi.yaml @@ -321,7 +321,8 @@ paths: Resolves the Agent and Tenant exclusively from the Agent credential, re-authorizes create_room in the caller's Room Context, revalidates every derived value, and creates the Room at once, owned by the Agent's Sponsor, with its initial message and - the Agent's handoff. Caller identity is intentionally absent from the request body. + the Agent's handoff. Each Agent added to the new Room must have the same Sponsor as the caller. + Caller identity is intentionally absent from the request body. security: - agentBearer: [] x-deadline-ms: 5000 From 1a0f300842b2cec4c01c72008d955032428ce412 Mon Sep 17 00:00:00 2001 From: muterC <36739961+muterC@users.noreply.github.com> Date: Thu, 26 Nov 2026 23:54:12 +0800 Subject: [PATCH 4/5] fix(teamhub): recover agent creation notices on retry --- .../internal/agentregistry/agent_agents.go | 19 ++---- .../internal/agentregistry/agent_api.go | 58 ++++++++++++------- .../internal/store/agent_registration.sql.go | 22 +++++++ .../store/queries/agent_registration.sql | 8 +++ .../integration/agent_cli_agents_test.go | 44 +++++++++++++- 5 files changed, 113 insertions(+), 38 deletions(-) diff --git a/apps/teamhub/internal/agentregistry/agent_agents.go b/apps/teamhub/internal/agentregistry/agent_agents.go index 906703a6a..99e92bcab 100644 --- a/apps/teamhub/internal/agentregistry/agent_agents.go +++ b/apps/teamhub/internal/agentregistry/agent_agents.go @@ -111,21 +111,14 @@ func ValidAgentProfileChange(change AgentProfileChange) bool { // CreateSponsorAgent registers a General Agent of the Sponsor with the // caller's Runtime, exactly like a Web creation. key makes it idempotent. func (s *Service) CreateSponsorAgent(ctx context.Context, accountID, tenantID, callerActorID string, change AgentProfileChange, key string) (string, error) { - actorID, _, err := s.createSponsorAgent(ctx, accountID, tenantID, callerActorID, change, key) - return actorID, err -} - -// createSponsorAgent is CreateSponsorAgent that also reports whether key -// replayed an earlier creation. -func (s *Service) createSponsorAgent(ctx context.Context, accountID, tenantID, callerActorID string, change AgentProfileChange, key string) (string, bool, error) { caller, err := s.queries.GetAgentRegistrationByActor(ctx, store.GetAgentRegistrationByActorParams{ ActorID: callerActorID, TenantID: tenantID, }) if err != nil { - return "", false, err + return "", err } if caller.Status != "active" { - return "", false, collaboration.ErrAgentSponsorRequired + return "", collaboration.ErrAgentSponsorRequired } agentType, visibility := httpapi.CreatableAgentTypeGeneral, httpapi.AgentVisibilityScopeSponsor result, err := s.ExecuteTenantAgentRegistration(ctx, accountID, tenantID, httpapi.TenantAgentCreateRequest{ @@ -133,16 +126,16 @@ func (s *Service) createSponsorAgent(ctx context.Context, accountID, tenantID, c Runtime: agentRuntimeConfig(agentRegistrationFromRow(caller)), AgentType: &agentType, VisibilityScope: &visibility, }, key) if err != nil { - return "", false, err + return "", err } var created httpapi.TenantAgent if err := json.Unmarshal(result.Body, &created); err != nil { - return "", false, err + return "", err } if created.Actor.Id == "" { - return "", false, errors.New("created Agent has no Actor") + return "", errors.New("created Agent has no Actor") } - return created.Actor.Id, result.Replay, nil + return created.Actor.Id, nil } // AgentChangeRequest is the stored change a decision runs. diff --git a/apps/teamhub/internal/agentregistry/agent_api.go b/apps/teamhub/internal/agentregistry/agent_api.go index d1804a5c7..4e3d74ded 100644 --- a/apps/teamhub/internal/agentregistry/agent_api.go +++ b/apps/teamhub/internal/agentregistry/agent_api.go @@ -168,15 +168,6 @@ func (s *Service) CreateSponsorGeneralAgent(ctx context.Context, authorizer agen if err != nil { return AgentChange{}, err } - count, err := queries.CountSponsorGeneralAgents(ctx, store.CountSponsorGeneralAgentsParams{ - TenantID: auth.TenantID, SponsorActorID: auth.SponsorActorID, - }) - if err == nil && count >= MaxSponsorGeneralAgents { - err = ErrAgentLimitReached - } - if err != nil { - return AgentChange{}, err - } // The new Agent joins the caller's Room only when it can: a Direct Room has // fixed members, and the Sponsor is the one who admits it. direct, sponsorMember := false, false @@ -190,23 +181,32 @@ func (s *Service) CreateSponsorGeneralAgent(ctx context.Context, authorizer agen return AgentChange{}, err } } + if !sponsorMember { + count, err := queries.CountSponsorGeneralAgents(ctx, store.CountSponsorGeneralAgentsParams{ + TenantID: auth.TenantID, SponsorActorID: auth.SponsorActorID, + }) + if err != nil { + return AgentChange{}, err + } + if count >= MaxSponsorGeneralAgents { + return AgentChange{}, ErrAgentLimitReached + } + } if err := tx.Commit(ctx); err != nil { return AgentChange{}, err } - joinable := !direct && sponsorMember - sponsorDirect := direct && sponsorMember - if !joinable && !sponsorDirect { + if !sponsorMember { return AgentChange{Auth: auth, Confirm: &typedcard.AgentChangeDecision{ Request: typedcard.AgentChangeRequest{Change: agentChangeRequestOf(change)}, View: agentCreateCard(change), }}, nil } - actorID, replay, err := s.createSponsorAgent(ctx, accountID, auth.TenantID, auth.AgentActorID, change, "agent-create:"+request.InvocationId) + actorID, err := s.CreateSponsorAgent(ctx, accountID, auth.TenantID, auth.AgentActorID, change, "agent-create:"+request.InvocationId) if err != nil { return AgentChange{}, err } - if sponsorDirect { - if err := s.settleDirectRoomCreation(ctx, accountID, auth, actorID, replay); err != nil { + if direct { + if err := s.settleDirectRoomCreation(ctx, accountID, auth, actorID); err != nil { return AgentChange{}, err } return AgentChange{Auth: auth, Status: http.StatusOK, Created: &api.AgentAgentChangeResponse{ @@ -224,24 +224,38 @@ func (s *Service) CreateSponsorGeneralAgent(ctx context.Context, authorizer agen // settleDirectRoomCreation finishes a creation in the Sponsor's Direct Room // as an approved creation card does: it opens the new Agent's own Direct Room, // which the sidebar lists it by, and announces the Agent where it was asked -// for. A replayed creation was already announced. -func (s *Service) settleDirectRoomCreation(ctx context.Context, accountID string, auth agentauth.Authorization, actorID string, replay bool) error { +// for. Registration and opening the Direct Room can both outlive a failed notice. +func (s *Service) settleDirectRoomCreation(ctx context.Context, accountID string, auth agentauth.Authorization, actorID string) error { if _, err := s.collaboration.OpenDirectRoom(ctx, accountID, auth.TenantID, actorID); err != nil { return err } - if replay { - return nil + tx, err := s.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + queries := store.New(tx) + // The Room lock serializes concurrent retries. The published notice also + // identifies a completed creation whose registration key was written earlier. + if err := queries.LockTenantDeliveryRooms(ctx, store.LockTenantDeliveryRoomsParams{TenantID: auth.TenantID, RoomIds: []string{auth.RoomID}}); err != nil { + return err + } + published, err := queries.HasAgentCreationNotice(ctx, store.HasAgentCreationNoticeParams{RoomID: auth.RoomID, AuthorActorID: auth.AgentActorID, AgentActorID: actorID}) + if err != nil || published { + return err } actors := make([]store.Actor, 0, 2) for _, id := range []string{auth.AgentActorID, actorID} { - actor, err := s.queries.GetActor(ctx, store.GetActorParams{ID: id, TenantID: auth.TenantID}) + actor, err := queries.GetActor(ctx, store.GetActorParams{ID: id, TenantID: auth.TenantID}) if err != nil { return err } actors = append(actors, actor) } - _, err := messagecreation.CreateNotice(ctx, s.queries, auth.TenantID, auth.RoomID, actors[0], messagecreation.AgentCreated(actors[1], nil)) - return err + if _, err := messagecreation.CreateNotice(ctx, queries, auth.TenantID, auth.RoomID, actors[0], messagecreation.AgentCreated(actors[1], nil)); err != nil { + return err + } + return tx.Commit(ctx) } // AddSponsorAgentToRoom adds an existing Agent to the caller's Room with its diff --git a/apps/teamhub/internal/store/agent_registration.sql.go b/apps/teamhub/internal/store/agent_registration.sql.go index 8b294ec52..3feff36ed 100644 --- a/apps/teamhub/internal/store/agent_registration.sql.go +++ b/apps/teamhub/internal/store/agent_registration.sql.go @@ -894,6 +894,28 @@ func (q *Queries) GetVisibleAgentAvatarImage(ctx context.Context, arg GetVisible return i, err } +const hasAgentCreationNotice = `-- name: HasAgentCreationNotice :one +SELECT EXISTS ( + SELECT 1 FROM messages + WHERE room_id=$1::text AND author_actor_id=$2::text + AND message_kind='room_notice' AND room_seq IS NOT NULL + AND notice->>'type'='agent_created' AND notice->'agent'->>'id'=$3::text +) +` + +type HasAgentCreationNoticeParams struct { + RoomID string `json:"room_id"` + AuthorActorID string `json:"author_actor_id"` + AgentActorID string `json:"agent_actor_id"` +} + +func (q *Queries) HasAgentCreationNotice(ctx context.Context, arg HasAgentCreationNoticeParams) (bool, error) { + row := q.db.QueryRow(ctx, hasAgentCreationNotice, arg.RoomID, arg.AuthorActorID, arg.AgentActorID) + var exists bool + err := row.Scan(&exists) + return exists, err +} + const hasPendingAgentLocalWork = `-- name: HasPendingAgentLocalWork :one SELECT EXISTS ( SELECT 1 FROM agent_execution_contexts context diff --git a/apps/teamhub/internal/store/queries/agent_registration.sql b/apps/teamhub/internal/store/queries/agent_registration.sql index 7ea5c4e3a..24b38c5d2 100644 --- a/apps/teamhub/internal/store/queries/agent_registration.sql +++ b/apps/teamhub/internal/store/queries/agent_registration.sql @@ -263,6 +263,14 @@ WHERE actor_id=sqlc.arg(actor_id)::text AND status='active' AND configuration_revision=sqlc.arg(expected_revision)::bigint; +-- name: HasAgentCreationNotice :one +SELECT EXISTS ( + SELECT 1 FROM messages + WHERE room_id=sqlc.arg(room_id)::text AND author_actor_id=sqlc.arg(author_actor_id)::text + AND message_kind='room_notice' AND room_seq IS NOT NULL + AND notice->>'type'='agent_created' AND notice->'agent'->>'id'=sqlc.arg(agent_actor_id)::text +); + -- name: CountSponsorGeneralAgents :one SELECT count(*)::bigint FROM agent_registrations diff --git a/apps/teamhub/tests/integration/agent_cli_agents_test.go b/apps/teamhub/tests/integration/agent_cli_agents_test.go index 274b99ca3..ecef9e91a 100644 --- a/apps/teamhub/tests/integration/agent_cli_agents_test.go +++ b/apps/teamhub/tests/integration/agent_cli_agents_test.go @@ -285,13 +285,47 @@ func TestAgentCLIManagesSponsorAgents(t *testing.T) { } directRoomID := direct.ID inDirect := agent.in("room", directRoomID) - status, body = inDirect.post("agents", map[string]any{"invocation_id": agentInvocation("create-editor"), "name": "Editor", "prompt": "Edit for clarity."}) + createEditor := map[string]any{"invocation_id": agentInvocation("create-editor"), "name": "Editor", "prompt": "Edit for clarity."} + // A publication failure lands after registration and after the notice row + // would be inserted. The retry must publish exactly once for the same Agent. + if _, err := env.pool.Exec(t.Context(), `CREATE FUNCTION reject_created_notice() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'injected notice event failure'; END $$; + CREATE TRIGGER reject_created_notice BEFORE INSERT ON room_events FOR EACH ROW + WHEN (NEW.payload #>> '{message,notice,type}' = 'agent_created') EXECUTE FUNCTION reject_created_notice()`); err != nil { + t.Fatal(err) + } + status, body = inDirect.post("agents", createEditor) + if status != http.StatusInternalServerError { + t.Fatalf("injected notice failure=%d %s", status, body) + } + if got := roomNotices(t, env, directRoomID, "agent_created", ""); got != 0 { + t.Fatalf("unpublished notices after failed creation=%d", got) + } + var registeredID string + if err := env.pool.QueryRow(t.Context(), `SELECT id FROM actors WHERE tenant_id=$1 AND kind='agent' AND display_name='Editor'`, acmeTenant).Scan(®isteredID); err != nil { + t.Fatal(err) + } + if _, err := env.pool.Exec(t.Context(), "DROP TRIGGER reject_created_notice ON room_events; DROP FUNCTION reject_created_notice()"); err != nil { + t.Fatal(err) + } + directHeaders := headers.Clone() + directHeaders.Set("X-TeamHub-Context-Id", directRoomID) + for range 2 { + if err := startAsyncJSONRequestWithHeaders(results, "retry-create-editor", env.server.Client(), http.MethodPost, env.server.URL+"/api/agent/v1/agents", "", createEditor, directHeaders); err != nil { + t.Fatal(err) + } + } + first, second := <-results, <-results + if first.err != nil || second.err != nil || first.status != http.StatusOK || second.status != http.StatusOK || !bytes.Equal(first.body, second.body) { + t.Fatalf("concurrent Direct Room retries=%d %s (%v), %d %s (%v)", first.status, first.body, first.err, second.status, second.body, second.err) + } + status, body = first.status, first.body var editor agentChangeResult decode(t, body, &editor) - if status != http.StatusOK || editor.Status != "applied" || editor.ActorID == "" || editor.RoomID != "" { + if status != http.StatusOK || editor.Status != "applied" || editor.ActorID != registeredID || editor.RoomID != "" { t.Fatalf("create in Direct Room=%d %s", status, body) } - if replay, again := inDirect.post("agents", map[string]any{"invocation_id": agentInvocation("create-editor"), "name": "Editor", "prompt": "Edit for clarity."}); replay != http.StatusOK || !bytes.Equal(again, body) { + if replay, again := inDirect.post("agents", createEditor); replay != http.StatusOK || !bytes.Equal(again, body) { t.Fatalf("Direct Room create replay=%d %s", replay, again) } editorID := editor.ActorID @@ -300,6 +334,10 @@ func TestAgentCLIManagesSponsorAgents(t *testing.T) { directRoomID, caller.Actor.ID, editorID); got != 1 { t.Fatalf("Direct Room creation notices=%d", got) } + if got := countRows(t, env, `SELECT count(*) FROM room_events WHERE room_id=$1 AND event_type='message.created' + AND payload #>> '{message,notice,type}'='agent_created' AND payload #>> '{message,notice,agent,id}'=$2`, directRoomID, editorID); got != 1 { + t.Fatalf("Direct Room creation events=%d", got) + } if got := countRows(t, env, `SELECT count(*) FROM active_room_members WHERE room_id=$1 AND actor_id=$2`, directRoomID, editorID); got != 0 { t.Fatal("created Agent joined the Sponsor's Direct Room") } From 7591c43c02dbabfa57a4d33737cd749ec701684a Mon Sep 17 00:00:00 2001 From: muterC <36739961+muterC@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:03:39 +0800 Subject: [PATCH 5/5] refactor(teamhub): retire the legacy room approval writer --- .../internal/typedcard/creation_approval.go | 126 ------------------ .../typedcard/creation_approval_decision.go | 69 +++++----- .../typedcard/creation_approval_test.go | 6 +- .../internal/typedcard/room_creation_now.go | 35 +---- .../integration/mcp_creation_approval_test.go | 29 ++++ .../room_message_batch_hydration_test.go | 9 +- .../integration/work_item_fixture_test.go | 60 ++++++++- 7 files changed, 129 insertions(+), 205 deletions(-) diff --git a/apps/teamhub/internal/typedcard/creation_approval.go b/apps/teamhub/internal/typedcard/creation_approval.go index 1d2d7ad21..2c674e0f2 100644 --- a/apps/teamhub/internal/typedcard/creation_approval.go +++ b/apps/teamhub/internal/typedcard/creation_approval.go @@ -3,16 +3,12 @@ package typedcard import ( "bytes" "context" - "crypto/sha256" "encoding/json" "errors" "fmt" - "net/http" "strings" "github.com/jackc/pgx/v5" - "github.com/simplexai-labs/linger/apps/teamhub/internal/idempotency" - idgen "github.com/simplexai-labs/linger/apps/teamhub/internal/ids" "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation" "github.com/simplexai-labs/linger/apps/teamhub/internal/store" ) @@ -53,121 +49,6 @@ type CreationApprovalBeforeCreate func( *CreationApprovalSubmission, ) error -// CreateCreationApprovalRequestInTx posts a Room creation decision for the -// requesting Agent's creator in the caller's transaction. A retried -// submission replays its card. -func (s *Service) CreateCreationApprovalRequestInTx( - ctx context.Context, - tx pgx.Tx, - input CreationApprovalInTxInput, -) (CreateResult, error) { - command, err := normalizeCreationApprovalSubmission(input.Submission) - if err != nil { - return CreateResult{}, err - } - if s == nil || tx == nil || input.RoomID == "" || input.AgentManagementID == "" || - strings.TrimSpace(input.IdempotencyOperation) == "" || len(input.IdempotencyOperation) > 300 || - len(input.CallerInputHash) != sha256.Size { - return CreateResult{}, ErrInvalid - } - operation := strings.TrimSpace(input.IdempotencyOperation) - queries := store.New(tx) - if err := queries.AcquireAdvisoryTransactionLock(ctx, "room-membership|"+input.RoomID); err != nil { - return CreateResult{}, err - } - source, err := queries.ResolveCreationApprovalAgentSource(ctx, store.ResolveCreationApprovalAgentSourceParams{ - RoomID: input.RoomID, AgentManagementID: input.AgentManagementID, - }) - if errors.Is(err, pgx.ErrNoRows) { - return CreateResult{}, ErrNotFound - } - if err != nil { - return CreateResult{}, err - } - if input.ExpectedAgentActorID != "" && source.AgentActorID != input.ExpectedAgentActorID || - input.ExpectedTenantID != "" && source.TenantID != input.ExpectedTenantID { - return CreateResult{}, ErrForbidden - } - if err := idempotency.Lock(ctx, tx, idempotency.AgentKey(source.AgentActorID, operation, command.SubmissionID)); err != nil { - return CreateResult{}, err - } - if replay, found, err := lookupCreationApprovalReplay( - ctx, queries, source.AgentActorID, operation, command.SubmissionID, input.CallerInputHash, - ); err != nil || found { - return replay, err - } - author := store.Actor{ - ID: source.AgentActorID, TenantID: source.TenantID, Kind: source.AgentKind, - DisplayName: source.AgentDisplayName, AccountID: source.AgentAccountID, - Handle: source.AgentHandle, CreatedAt: source.AgentCreatedAt, - } - decisionOwner := store.Actor{ - ID: source.CreatedByActorID, TenantID: source.TenantID, Kind: "human", - } - decisionOwner, err = queries.GetActor(ctx, store.GetActorParams{ID: decisionOwner.ID, TenantID: source.TenantID}) - if err != nil { - return CreateResult{}, err - } - if input.BeforeCreate != nil { - if err := input.BeforeCreate(ctx, queries, CreationApprovalSource{ - TenantID: source.TenantID, AgentActorID: source.AgentActorID, - AgentManagementID: input.AgentManagementID, CreatedByActorID: source.CreatedByActorID, - DecisionOwner: decisionOwner, - }, &command); err != nil { - return CreateResult{}, err - } - if command, err = normalizeCreationApprovalSubmission(command); err != nil { - return CreateResult{}, err - } - } - var snapshot RoomCreationSnapshot - if err := json.Unmarshal(command.FulfillmentSnapshot, &snapshot); err != nil { - return CreateResult{}, ErrInvalid - } - view, err := json.Marshal(roomCreationProposalValue(snapshot)) - if err != nil { - return CreateResult{}, err - } - request, err := json.Marshal(command) - if err != nil { - return CreateResult{}, err - } - content, err := messagecreation.Normalize([]messagecreation.Segment{{Type: "text", Content: roomCreationTitle(snapshot.Name)}}) - if err != nil { - return CreateResult{}, err - } - message, err := messagecreation.Persist(ctx, queries, messagecreation.Draft{ - TenantID: source.TenantID, RoomID: input.RoomID, Author: author, Content: content, - Card: &messagecreation.Card{DecisionOwnerActorID: decisionOwner.ID, CardType: "personal_notice", Intent: "decision_requested"}, - }) - if err != nil { - return CreateResult{}, err - } - decisionID := idgen.New("decision") - // A Room creation waits until it is decided. - if _, err := queries.InsertDecision(ctx, store.InsertDecisionParams{ - ID: decisionID, TenantID: source.TenantID, RoomID: input.RoomID, MessageID: message.Message.ID, - Kind: DecisionKindRoomCreation, RequestedByActorID: author.ID, DeciderActorID: decisionOwner.ID, - Request: request, View: view, - }); err != nil { - return CreateResult{}, err - } - published, err := publishCardMessage(ctx, queries, message) - if err != nil { - return CreateResult{}, err - } - if err := idempotency.Save(ctx, tx, idempotency.AgentKey(author.ID, operation, command.SubmissionID), - input.CallerInputHash, idempotency.Record{ - ResourceID: published.Message.ID, Status: http.StatusCreated, Body: published.Payload, - }); err != nil { - return CreateResult{}, err - } - return CreateResult{ - Status: http.StatusCreated, Body: published.Payload, MessageID: published.Message.ID, - DecisionID: decisionID, - }, nil -} - func roomCreationTitle(name string) string { return fmt.Sprintf("Request to create a collaboration room: %s", name) } @@ -245,10 +126,3 @@ type roomCreationProposal struct { MemberIDs []string `json:"member_ids"` InitialMessageSegments []messagecreation.Segment `json:"initial_message_segments"` } - -func roomCreationProposalValue(snapshot RoomCreationSnapshot) roomCreationProposal { - return roomCreationProposal{ - OriginRoomID: snapshot.OriginRoomID, Name: snapshot.Name, Description: snapshot.Description, - MemberIDs: snapshot.MemberIDs, InitialMessageSegments: snapshot.InitialMessageSegments, - } -} diff --git a/apps/teamhub/internal/typedcard/creation_approval_decision.go b/apps/teamhub/internal/typedcard/creation_approval_decision.go index 2269c3779..35bc1d1c8 100644 --- a/apps/teamhub/internal/typedcard/creation_approval_decision.go +++ b/apps/teamhub/internal/typedcard/creation_approval_decision.go @@ -258,9 +258,9 @@ func persistRoomCreationHandoffMessage( delivered []RoomCreationArtifactSnapshot, decidedAt time.Time, ) (messagecreation.Persisted, error) { - text, err := roomCreationHandoffText( - requestID, cardMessageID, originRoomID, roomID, description, delivered, decisionOwner.ID, decidedAt, - ) + text, err := roomCreationHandoffText(originRoomID, roomID, description, delivered, &roomHandoffApproval{ + requestID: requestID, cardMessageID: cardMessageID, decidedBy: decisionOwner.ID, decidedAt: decidedAt, + }) if err != nil { return messagecreation.Persisted{}, err } @@ -275,48 +275,55 @@ func roomCreationHandoffMessageID(requestID string) string { return "message_" + hex.EncodeToString(digest[:16]) } -func roomCreationHandoffText( - requestID, cardMessageID, originRoomID, roomID string, - description *string, - delivered []RoomCreationArtifactSnapshot, - decidedByActorID string, - decidedAt time.Time, -) (string, error) { - var purpose *string - if description != nil { - if trimmed := strings.TrimSpace(*description); trimmed != "" { - purpose = &trimmed - } - } +type roomHandoffApproval struct { + requestID, cardMessageID, decidedBy string + decidedAt time.Time +} + +func roomCreationHandoffText(originRoomID, roomID string, description *string, delivered []RoomCreationArtifactSnapshot, approval *roomHandoffApproval) (string, error) { if delivered == nil { delivered = []RoomCreationArtifactSnapshot{} } - payload, err := json.Marshal(struct { + payload := struct { Kind string `json:"kind"` - RequestID string `json:"creation_approval_request_id"` - CardMessageID string `json:"approval_card_message_id"` + RequestID *string `json:"creation_approval_request_id,omitempty"` + CardMessageID *string `json:"approval_card_message_id,omitempty"` OriginRoomID string `json:"origin_room_id"` OriginInboxID string `json:"origin_room_inbox_id"` RoomInboxID string `json:"room_inbox_id"` - Purpose *string `json:"purpose,omitempty"` + Purpose string `json:"purpose,omitempty"` DeliveredItems []RoomCreationArtifactSnapshot `json:"delivered_artifacts"` - Decision string `json:"decision"` - DecidedBy string `json:"decided_by"` - DecidedAt time.Time `json:"decided_at"` + Decision string `json:"decision,omitempty"` + DecidedBy *string `json:"decided_by,omitempty"` + DecidedAt *time.Time `json:"decided_at,omitempty"` }{ - "room_creation_handoff", requestID, cardMessageID, originRoomID, "room:" + originRoomID, "room:" + roomID, - purpose, delivered, "approved", decidedByActorID, decidedAt.UTC(), - }) - if err != nil { - return "", err + Kind: "room_creation_handoff", OriginRoomID: originRoomID, OriginInboxID: "room:" + originRoomID, + RoomInboxID: "room:" + roomID, DeliveredItems: delivered, } - prompt := fmt.Sprintf(`<room-handoff-pattern> + if description != nil { + payload.Purpose = strings.TrimSpace(*description) + } + prompt := `<room-handoff-pattern> +You created this Room. Continue the requested work here and reply only to the Inbox +room:%s. Origin Room messages are not copied into this Room. Read delivered_artifacts +with teamhub docs get <document-id> and this Room's history with teamhub message read. +</room-handoff-pattern>` + if approval != nil { + decidedAt := approval.decidedAt.UTC() + payload.RequestID, payload.CardMessageID = &approval.requestID, &approval.cardMessageID + payload.Decision, payload.DecidedBy, payload.DecidedAt = "approved", &approval.decidedBy, &decidedAt + prompt = `<room-handoff-pattern> This Room was created by approval of your request. Continue the requested work here and reply only to the Inbox room:%s. Origin Room messages are not copied into this Room. Read delivered_artifacts with teamhub docs get <document-id> and this Room's history with teamhub message read. -</room-handoff-pattern>`, roomID) - return " Room creation handoff=" + string(payload) + "\n" + prompt, nil +</room-handoff-pattern>` + } + encoded, err := json.Marshal(payload) + if err != nil { + return "", err + } + return " Room creation handoff=" + string(encoded) + "\n" + fmt.Sprintf(prompt, roomID), nil } type roomCreationSkippedArtifact struct { diff --git a/apps/teamhub/internal/typedcard/creation_approval_test.go b/apps/teamhub/internal/typedcard/creation_approval_test.go index b1b9d20a7..1a4d278af 100644 --- a/apps/teamhub/internal/typedcard/creation_approval_test.go +++ b/apps/teamhub/internal/typedcard/creation_approval_test.go @@ -14,6 +14,7 @@ func TestRoomCreationHandoffTextCarriesRequestFactsAndDeliveredDocumentsOnly(t * blank := " " delivered := []RoomCreationArtifactSnapshot{{DocumentID: "doc-ok", DocumentVersionID: "version-1"}} decidedAt := time.Date(2026, 10, 22, 17, 39, 0, 123456000, time.FixedZone("CST", 8*60*60)) + approval := &roomHandoffApproval{requestID: "request-1", cardMessageID: "card-1", decidedBy: "actor-owner", decidedAt: decidedAt} for _, test := range []struct { name string description *string @@ -24,8 +25,7 @@ func TestRoomCreationHandoffTextCarriesRequestFactsAndDeliveredDocumentsOnly(t * {"blank description", &blank, ""}, } { t.Run(test.name, func(t *testing.T) { - text, err := roomCreationHandoffText("request-1", "card-1", "room-origin", "room-new", test.description, delivered, - "actor-owner", decidedAt) + text, err := roomCreationHandoffText("room-origin", "room-new", test.description, delivered, approval) if err != nil { t.Fatal(err) } @@ -67,7 +67,7 @@ func TestRoomCreationHandoffTextCarriesRequestFactsAndDeliveredDocumentsOnly(t * } }) } - empty, err := roomCreationHandoffText("request-2", "card-2", "room-origin", "room-new", nil, nil, "actor-owner", decidedAt) + empty, err := roomCreationHandoffText("room-origin", "room-new", nil, nil, approval) if err != nil || !strings.Contains(empty, `"delivered_artifacts":[]`) { t.Fatalf("empty handoff=%q err=%v", empty, err) } diff --git a/apps/teamhub/internal/typedcard/room_creation_now.go b/apps/teamhub/internal/typedcard/room_creation_now.go index f0464ea93..273397a83 100644 --- a/apps/teamhub/internal/typedcard/room_creation_now.go +++ b/apps/teamhub/internal/typedcard/room_creation_now.go @@ -5,7 +5,6 @@ import ( "crypto/sha256" "encoding/json" "errors" - "fmt" "net/http" "strings" @@ -106,7 +105,7 @@ func (s *Service) CreateRoomInTx(ctx context.Context, tx pgx.Tx, input CreationA return CreateResult{}, err } roomID := room.created.Room.ID - text, err := roomCreatedHandoffText(input.RoomID, roomID, room.snapshot.Description, room.delivered) + text, err := roomCreationHandoffText(input.RoomID, roomID, room.snapshot.Description, room.delivered, nil) if err != nil { return CreateResult{}, err } @@ -132,35 +131,3 @@ func (s *Service) CreateRoomInTx(ctx context.Context, tx pgx.Tx, input CreationA } return CreateResult{Status: http.StatusOK, Body: body}, nil } - -// roomCreatedHandoffText hands the requested work to the Agent inside the Room -// it created. Like an approved creation's handoff it carries no origin Room -// messages and no skipped Documents. -func roomCreatedHandoffText(originRoomID, roomID string, description *string, delivered []RoomCreationArtifactSnapshot) (string, error) { - var purpose *string - if description != nil { - if trimmed := strings.TrimSpace(*description); trimmed != "" { - purpose = &trimmed - } - } - if delivered == nil { - delivered = []RoomCreationArtifactSnapshot{} - } - payload, err := json.Marshal(struct { - Kind string `json:"kind"` - OriginRoomID string `json:"origin_room_id"` - OriginInboxID string `json:"origin_room_inbox_id"` - RoomInboxID string `json:"room_inbox_id"` - Purpose *string `json:"purpose,omitempty"` - DeliveredItems []RoomCreationArtifactSnapshot `json:"delivered_artifacts"` - }{"room_creation_handoff", originRoomID, "room:" + originRoomID, "room:" + roomID, purpose, delivered}) - if err != nil { - return "", err - } - prompt := fmt.Sprintf(`<room-handoff-pattern> -You created this Room. Continue the requested work here and reply only to the Inbox -room:%s. Origin Room messages are not copied into this Room. Read delivered_artifacts -with teamhub docs get <document-id> and this Room's history with teamhub message read. -</room-handoff-pattern>`, roomID) - return " Room creation handoff=" + string(payload) + "\n" + prompt, nil -} diff --git a/apps/teamhub/tests/integration/mcp_creation_approval_test.go b/apps/teamhub/tests/integration/mcp_creation_approval_test.go index 35dd5e2a6..db2b63f5e 100644 --- a/apps/teamhub/tests/integration/mcp_creation_approval_test.go +++ b/apps/teamhub/tests/integration/mcp_creation_approval_test.go @@ -359,6 +359,35 @@ func TestAgentCreationApprovalPostgreSQLVerticalSlice(t *testing.T) { assertRoomCreationHandoff(t, env, decodeRoomCreated(t, result).RoomID, originRoomID, nil, purpose, []string{nativeArtifactID, roomArtifact.ID}) }) + t.Run("replaying a pending Room submission returns its original card", func(t *testing.T) { + snapshot := typedcard.RoomCreationSnapshot{ + OriginRoomID: originRoomID, Name: "Pending retry", MemberIDs: []string{"actor_acme_official"}, + InitialMessageSegments: []messagecreation.Segment{{Type: "text", Content: "Discuss the plan."}}, + } + input := roomCreationApprovalInputFor(t, snapshot, "pending-retry") + pending := postRoomCreationCard(t, env, input) + before := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) + tx, err := env.pool.Begin(t.Context()) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback(t.Context()) + cards := typedcard.New(env.pool) + replay, err := cards.CreateRoomInTx(t.Context(), tx, input) + if err != nil || !replay.Replay || replay.DecisionID != pending.DecisionID || replay.MessageID != pending.MessageID { + t.Fatalf("pending card replay=%+v, err=%v; want decision %s and message %s", replay, err, pending.DecisionID, pending.MessageID) + } + snapshot.Name = "Changed proposal" + if _, err := cards.CreateRoomInTx(t.Context(), tx, roomCreationApprovalInputFor(t, snapshot, "pending-retry")); !errors.Is(err, typedcard.ErrIdempotencyConflict) { + t.Fatalf("reuse with a changed proposal: got %v, want ErrIdempotencyConflict", err) + } + if err := tx.Commit(t.Context()); err != nil { + t.Fatal(err) + } + if got := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant); got != before { + t.Fatalf("pending card replay changed Room count from %d to %d", before, got) + } + }) t.Run("an earlier pending card creates its Room on approval", func(t *testing.T) { pending := pendingCard(t, "Approved MCP Room "+suffix, nil) before := countRows(t, env, `SELECT count(*) FROM rooms WHERE tenant_id=$1`, acmeTenant) diff --git a/apps/teamhub/tests/integration/room_message_batch_hydration_test.go b/apps/teamhub/tests/integration/room_message_batch_hydration_test.go index 0ccb47f2a..4793e2bbc 100644 --- a/apps/teamhub/tests/integration/room_message_batch_hydration_test.go +++ b/apps/teamhub/tests/integration/room_message_batch_hydration_test.go @@ -14,7 +14,6 @@ import ( "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/simplexai-labs/linger/apps/teamhub/internal/config" - "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard" ) func TestRoomMessageCardHydrationQueryCountIsConstantAtLimit200(t *testing.T) { @@ -107,8 +106,7 @@ func newRoomMessageQueryCountEnv(t *testing.T, tracer pgx.QueryTracer) (*testEnv return env, env.login("alice", alicePassword) } -// seedQueryCountCards commits count pending create_room approval cards through -// the live creation approval writer. +// seedQueryCountCards stores pending approval cards for a Room message history. func seedQueryCountCards(t *testing.T, env *testEnv, roomID, suffix string, count int) { t.Helper() tx, err := env.pool.Begin(t.Context()) @@ -116,11 +114,8 @@ func seedQueryCountCards(t *testing.T, env *testEnv, roomID, suffix string, coun t.Fatal(err) } defer tx.Rollback(context.Background()) - cards := typedcard.New(env.pool) for index := range count { - if _, err := cards.CreateCreationApprovalRequestInTx(t.Context(), tx, roomCreationApprovalInput(t, roomID, fmt.Sprintf("query-count-%s-%d", suffix, index))); err != nil { - t.Fatalf("seed query-count card %d: %v", index, err) - } + seedLegacyRoomCreationCardInTx(t, tx, roomCreationApprovalInput(t, roomID, fmt.Sprintf("query-count-%s-%d", suffix, index))) } if err := tx.Commit(t.Context()); err != nil { t.Fatal(err) diff --git a/apps/teamhub/tests/integration/work_item_fixture_test.go b/apps/teamhub/tests/integration/work_item_fixture_test.go index 77b18bdb0..5641ce14e 100644 --- a/apps/teamhub/tests/integration/work_item_fixture_test.go +++ b/apps/teamhub/tests/integration/work_item_fixture_test.go @@ -6,6 +6,9 @@ import ( "net/http" "testing" + "github.com/jackc/pgx/v5" + "github.com/simplexai-labs/linger/apps/teamhub/internal/idempotency" + "github.com/simplexai-labs/linger/apps/teamhub/internal/ids" "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation" "github.com/simplexai-labs/linger/apps/teamhub/internal/store" "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard" @@ -107,16 +110,65 @@ func postRoomCreationCard(t *testing.T, env *testEnv, input typedcard.CreationAp t.Fatal(err) } defer tx.Rollback(t.Context()) - created, err := typedcard.New(env.pool).CreateCreationApprovalRequestInTx(t.Context(), tx, input) - if err != nil { - t.Fatalf("request Room creation: %v", err) - } + created := seedLegacyRoomCreationCardInTx(t, tx, input) if err := tx.Commit(t.Context()); err != nil { t.Fatal(err) } return created } +// seedLegacyRoomCreationCardInTx writes the decision, published card and replay +// record that can still exist together after an upgrade to immediate Room creation. +func seedLegacyRoomCreationCardInTx(t *testing.T, tx pgx.Tx, input typedcard.CreationApprovalInTxInput) typedcard.CreateResult { + t.Helper() + ctx := t.Context() + queries := store.New(tx) + agent, err := queries.GetActor(ctx, store.GetActorParams{TenantID: acmeTenant, ID: "actor_acme_official"}) + if err != nil { + t.Fatal(err) + } + var proposal typedcard.RoomCreationSnapshot + decode(t, input.Submission.FulfillmentSnapshot, &proposal) + // Only the decision request stored the artifacts. + proposal.Artifacts = nil + content, err := messagecreation.Normalize([]messagecreation.Segment{{Type: "text", Content: "Request to create a collaboration room: " + proposal.Name}}) + if err != nil { + t.Fatal(err) + } + const ownerID = "actor_acme_alice" + message, err := messagecreation.Persist(ctx, queries, messagecreation.Draft{ + TenantID: acmeTenant, RoomID: input.RoomID, Author: agent, Content: content, + Card: &messagecreation.Card{DecisionOwnerActorID: ownerID, CardType: "personal_notice", Intent: "decision_requested"}, + }) + if err != nil { + t.Fatal(err) + } + decisionID := ids.New("decision") + if _, err := queries.InsertDecision(ctx, store.InsertDecisionParams{ + ID: decisionID, TenantID: acmeTenant, RoomID: input.RoomID, MessageID: message.Message.ID, + Kind: typedcard.DecisionKindRoomCreation, RequestedByActorID: agent.ID, DeciderActorID: ownerID, + Request: mustJSON(t, input.Submission), View: mustJSON(t, proposal), + }); err != nil { + t.Fatal(err) + } + card, found, err := typedcard.SnapshotCard(ctx, queries, message.Message.ID) + if err != nil || !found { + t.Fatalf("snapshot pending Room creation card: found=%t err=%v", found, err) + } + message.Card = card + published, err := messagecreation.Publish(ctx, queries, message) + if err != nil { + t.Fatal(err) + } + key := idempotency.AgentKey(agent.ID, input.IdempotencyOperation, input.Submission.SubmissionID) + if err := idempotency.Save(ctx, tx, key, input.CallerInputHash, idempotency.Record{ + ResourceID: message.Message.ID, Status: http.StatusCreated, Body: published.Payload, + }); err != nil { + t.Fatal(err) + } + return typedcard.CreateResult{Status: http.StatusCreated, Body: published.Payload, MessageID: message.Message.ID, DecisionID: decisionID} +} + // denyRoomCreationApproval denies a pending creation approval as decider. func denyRoomCreationApproval(t *testing.T, env *testEnv, decider *http.Client, requestID, suffix string) { t.Helper()