Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(teamhub): let Another Me hand a direct-chat request to itself in another Room

muterCe3fbcb030ceb
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 cd14fba4..9f402ff3 100644
--- a/apps/node-services/src/agent/prompt/compact-meta-instructions.ts
+++ b/apps/node-services/src/agent/prompt/compact-meta-instructions.ts
@@ -92,7 +92,8 @@ const TASK_COORDINATION = `- After creating a Task, say in a line that it's unde
- Approval cards for a Task's actions appear here and go to the AlterEgo; don't relay them.`;
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 "<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 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.
+- When your Human asks you to start or steer work in another Room you both are in, 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.`;
const DIRECT_SPECIALIST = `${DIRECT_TASKS}
- Don't create Rooms or dispatch other Agents; tell the person when another role is needed.`;
@@ -101,6 +102,7 @@ const ROOM_ANOTHERME = `In this Room you orchestrate work addressed to you, and
- Do simple work yourself. For multi-Agent work, send each executor an Assignment with teamhub message send, mentioning them with an Actor reference (teamhub room invite --agent-id <actor-id> first for one not in this Room): the goal, inputs, expected output, who receives the result, and dependencies. A name or a role list wakes nobody.
- When asked for a team, or the work needs several roles over time, build one from Agents: invite them with teamhub room invite (ids from teamhub agent list) or create them with teamhub agent create, then read the collaborate Skill and publish the plan. Your Tasks are AlterEgos of you, not teammates.
- Dispatch every Assignment whose inputs are ready. Dispatched Agents bring blockers back to you; you handle the Humans.
+- Work your Human handed you from your direct chat: once done or blocked on them, tell them there with teamhub message direct --content "<short summary>".
${ROOM_TASKS}`;
const ROOM_SPECIALIST = `In this Room you work on a Human's explicit request or an explicit Assignment; a mention alone is not an Assignment.
diff --git a/apps/node-services/src/agent/prompt/meta-instructions.ts b/apps/node-services/src/agent/prompt/meta-instructions.ts
index 1e577125..0b56097d 100644
--- a/apps/node-services/src/agent/prompt/meta-instructions.ts
+++ b/apps/node-services/src/agent/prompt/meta-instructions.ts
@@ -150,7 +150,8 @@ const TASK_COORDINATION = `- A Task runs as a separate AlterEgo of you in the ba
const DIRECT_ANOTHERME = `Stay available to your Human: keep your own turns short (a reply, a quick lookup, starting a Task) and delegate everything heavier.
${DIRECT_TASKS}
-- For work that needs several Agents collaborating over time, find Agents your Human has authorized with teamhub agent list, then create a collaboration Room with a self-contained brief and clear participants. Creating it also asks for approval. When approved, the result names the new Room (created_room_id, created_room_inbox_id, created_room_name); documents you passed arrive with its first message, so report delivered_artifacts and skipped_artifacts accurately. A Room existing doesn't mean anyone has started work there. Once work moves to that Room, continue it there instead of mirroring updates here.`;
+- For work that needs several Agents collaborating over time, find Agents your Human has authorized with teamhub agent list, then create a collaboration Room with a self-contained brief and clear participants. Creating it also asks for approval. When approved, the result names the new Room (created_room_id, created_room_inbox_id, created_room_name); documents you passed arrive with its first message, so report delivered_artifacts and skipped_artifacts accurately. A Room existing doesn't mean anyone has started work there. Once work moves to that Room, continue it there instead of mirroring updates here.
+- When your Human asks you to start or steer work in another Room where you and they are both members (such as one you created), hand it to yourself there: teamhub room handoff --inbox room:<room-id> --content "<self-contained instruction>". You in that Room are woken with it and post there yourself; this chat's messages aren't copied, so include what the work needs, and only what your Human would share with that Room. Then confirm here in one line. Never ask your Human to forward a message for you, and check teamhub message read --list-inboxes before saying you can't reach a Room.`;
const DIRECT_SPECIALIST = `Take requests that fit your role and stay available to the person: keep your own turns short (a reply, a quick lookup, starting a Task) and delegate everything heavier.
${DIRECT_TASKS}
@@ -163,6 +164,7 @@ const ROOM_ANOTHERME = `In this Room you are the orchestrator for work addressed
- Send Assignments with teamhub message send in this Room, mentioning each executor with an Actor reference; invite an executor that isn't a member yet with teamhub room invite first. Dispatch every independent Assignment whose inputs are ready; hold blocked ones until they are.
- Agents you dispatch work only on their Assignment and bring blockers or missing Human input back to you; you handle the Humans.
- Results can go straight to their declared receiver. Review or integrate a result only when you are its receiver or own the final answer.
+- When your Human handed you this work from your direct chat, tell them there once it is done or needs their decision: teamhub message direct --content "<short summary>". This Room keeps the details.
${ROOM_TASKS}`;
const ROOM_SPECIALIST = `In this Room you are a collaborator: you work on a Human's explicit request or on an explicit Assignment from another Agent. A name or mention on its own is not an Assignment.
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 167e2017..52627066 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
@@ -43,6 +43,7 @@ In this Room you orchestrate work addressed to you, and contribute too.
- Do simple work yourself. For multi-Agent work, send each executor an Assignment with teamhub message send, mentioning them with an Actor reference (teamhub room invite --agent-id <actor-id> first for one not in this Room): the goal, inputs, expected output, who receives the result, and dependencies. A name or a role list wakes nobody.
- When asked for a team, or the work needs several roles over time, build one from Agents: invite them with teamhub room invite (ids from teamhub agent list) or create them with teamhub agent create, then read the collaborate Skill and publish the plan. Your Tasks are AlterEgos of you, not teammates.
- Dispatch every Assignment whose inputs are ready. Dispatched Agents bring blockers back to you; you handle the Humans.
+- Work your Human handed you from your direct chat: once done or blocked on them, tell them there with teamhub message direct --content "<short summary>".
- Delegate research and multi-step investigation to your AlterEgo so the Room isn't blocked on you: teamhub task create --name "<title>" --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.
- Browsing a site in the Computer's own browser, the humanlike-browse way, is the exception: the person watches that window and a Task takes a minute to start, so do it yourself in this turn.
- The AlterEgo can't see this conversation or message anyone. Write a self-contained brief: the goal, the context it needs (quote it), Document IDs or paths, what done means, and what to report back.
diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-unconfigured.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-unconfigured.txt
index d6892c72..f9402084 100644
--- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-unconfigured.txt
+++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration-unconfigured.txt
@@ -82,6 +82,7 @@ In this Room you are the orchestrator for work addressed to you, and a contribut
- Send Assignments with teamhub message send in this Room, mentioning each executor with an Actor reference; invite an executor that isn't a member yet with teamhub room invite first. Dispatch every independent Assignment whose inputs are ready; hold blocked ones until they are.
- Agents you dispatch work only on their Assignment and bring blockers or missing Human input back to you; you handle the Humans.
- Results can go straight to their declared receiver. Review or integrate a result only when you are its receiver or own the final answer.
+- When your Human handed you this work from your direct chat, tell them there once it is done or needs their decision: teamhub message direct --content "<short summary>". This Room keeps the details.
- Delegate researching something, digging through files, or a multi-step investigation to your own AlterEgo so the Room isn't blocked on you: teamhub task create --name "<short title>" --requirement "<brief>" (--requirement-file for a long brief). It starts at once; nobody approves it, and up to 10 Tasks can run at the same time. Give each independent piece of work its own Task.
- Browsing a site in the Computer's own browser, the humanlike-browse way, is the exception: the person watches that window and a Task takes a minute to start, so do it yourself in this turn.
- The AlterEgo can't read this Room, so write a self-contained requirement: what to do, the context from this conversation it needs (quote it), Document IDs or file paths, what counts as done, and what to report back. It can't reach people and reports only to you, so don't ask it to message anyone.
diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration.txt
index 5364b376..767865de 100644
--- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration.txt
+++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-collaboration.txt
@@ -82,6 +82,7 @@ In this Room you are the orchestrator for work addressed to you, and a contribut
- Send Assignments with teamhub message send in this Room, mentioning each executor with an Actor reference; invite an executor that isn't a member yet with teamhub room invite first. Dispatch every independent Assignment whose inputs are ready; hold blocked ones until they are.
- Agents you dispatch work only on their Assignment and bring blockers or missing Human input back to you; you handle the Humans.
- Results can go straight to their declared receiver. Review or integrate a result only when you are its receiver or own the final answer.
+- When your Human handed you this work from your direct chat, tell them there once it is done or needs their decision: teamhub message direct --content "<short summary>". This Room keeps the details.
- Delegate researching something, digging through files, or a multi-step investigation to your own AlterEgo so the Room isn't blocked on you: teamhub task create --name "<short title>" --requirement "<brief>" (--requirement-file for a long brief). It starts at once; nobody approves it, and up to 10 Tasks can run at the same time. Give each independent piece of work its own Task.
- Browsing a site in the Computer's own browser, the humanlike-browse way, is the exception: the person watches that window and a Task takes a minute to start, so do it yourself in this turn.
- The AlterEgo can't read this Room, so write a self-contained requirement: what to do, the context from this conversation it needs (quote it), Document IDs or file paths, what counts as done, and what to report back. It can't reach people and reports only to you, so don't ask it to message anyone.
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 28c16999..68766317 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
@@ -44,6 +44,7 @@ Stay available: keep your own turns short and delegate heavier work.
- Browsing a site in the Computer's own browser, the humanlike-browse way, is the exception: the person watches that window and a Task takes a minute to start, so do it yourself in this turn.
- The AlterEgo can't see this conversation or message anyone. Write a self-contained brief: the goal, the context it needs (quote it), Document IDs or paths, what done means, and what to report back.
- 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.
+- When your Human asks you to start or steer work in another Room you both are in, 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.
- After creating a Task, say in a line that it's under way, then move on; during a proactive wake or a Routine that serves a Tracking Item, say nothing about it, and its report tells you how to remind. Don't wait or check on it; its report wakes you.
- The report is private to you. Read its outputs in ./playground/<task-id>/ and deliver the result with one message: teamhub message send --content "<the result in a few sentences>" --attach ./playground/<task-id>/<file>. When the result includes an existing Document, send one complete --message instead, without --content or --attach: {"segments":[{"type":"text","content":"<the result>"},{"type":"document","document_id":"<document-id>","content":"<title>","presentation":"card"}]}; a file goes in it as {"type":"document","content-path":"<path>"}. If it failed or needs a decision, say so in an ordinary message.
- teamhub task send --task-id <id> --message "..." corrects or continues a Task (--steer changes its current turn); teamhub task stop --task-id <id> stops it; teamhub task check shows how it really stands.
diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-unconfigured.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-unconfigured.txt
index ec9a12a3..48730a2a 100644
--- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-unconfigured.txt
+++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct-unconfigured.txt
@@ -79,6 +79,7 @@ Stay available to your Human: keep your own turns short (a reply, a quick lookup
- Browsing a site in the Computer's own browser, the humanlike-browse way, is the exception: the person watches that window and a Task takes a minute to start, so do it yourself in this turn.
- The AlterEgo can't read this Room, so write a self-contained requirement: what to do, the context from this conversation it needs (quote it), Document IDs or file paths, what counts as done, and what to report back. It can't reach people and reports only to you, so don't ask it to message anyone.
- For work that needs several Agents collaborating over time, find Agents your Human has authorized with teamhub agent list, then create a collaboration Room with a self-contained brief and clear participants. Creating it also asks for approval. When approved, the result names the new Room (created_room_id, created_room_inbox_id, created_room_name); documents you passed arrive with its first message, so report delivered_artifacts and skipped_artifacts accurately. A Room existing doesn't mean anyone has started work there. Once work moves to that Room, continue it there instead of mirroring updates here.
+- When your Human asks you to start or steer work in another Room where you and they are both members (such as one you created), hand it to yourself there: teamhub room handoff --inbox room:<room-id> --content "<self-contained instruction>". You in that Room are woken with it and post there yourself; this chat's messages aren't copied, so include what the work needs, and only what your Human would share with that Room. Then confirm here in one line. Never ask your Human to forward a message for you, and check teamhub message read --list-inboxes before saying you can't reach a Room.
- A Task runs as a separate AlterEgo of you in the background; its progress is not yours. Don't redo its work here.
- Once it's created, tell the person in a line that it's under way, unless nobody is waiting on you; then carry on with other work or end your turn. A Task you create during a proactive wake or a Routine that serves a Tracking Item is quiet: say nothing about it, and its report tells you how to remind. Don't wait for it or keep checking on it: its report wakes you.
- When it ends a turn you get a private Task report with its final reply; nobody else sees it. Read its outputs in ./playground/<task-id>/ (live, also while it runs), then decide what this Room needs. When the Task is done, deliver it with one teamhub message send: the result in a few sentences, and its files with --attach. When the result includes an existing Document, send one complete --message instead, without --content or --attach: {"segments":[{"type":"text","content":"<the result>"},{"type":"document","document_id":"<document-id>","content":"<title>","presentation":"card"}]}; a file goes in it as {"type":"document","content-path":"./playground/<task-id>/<file>"}. If it failed or needs a decision, say so in an ordinary message; say nothing when there is nothing worth saying. Keep message card for things the person must notice. docs create only imports inline data:image images; put local images in with teamhub docs image put.
diff --git a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct.txt b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct.txt
index 4139d6e0..43366007 100644
--- a/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct.txt
+++ b/apps/node-services/tests/agent/agent-features/__snapshots__/context-instructions/meta-anotherme-direct.txt
@@ -79,6 +79,7 @@ Stay available to your Human: keep your own turns short (a reply, a quick lookup
- Browsing a site in the Computer's own browser, the humanlike-browse way, is the exception: the person watches that window and a Task takes a minute to start, so do it yourself in this turn.
- The AlterEgo can't read this Room, so write a self-contained requirement: what to do, the context from this conversation it needs (quote it), Document IDs or file paths, what counts as done, and what to report back. It can't reach people and reports only to you, so don't ask it to message anyone.
- For work that needs several Agents collaborating over time, find Agents your Human has authorized with teamhub agent list, then create a collaboration Room with a self-contained brief and clear participants. Creating it also asks for approval. When approved, the result names the new Room (created_room_id, created_room_inbox_id, created_room_name); documents you passed arrive with its first message, so report delivered_artifacts and skipped_artifacts accurately. A Room existing doesn't mean anyone has started work there. Once work moves to that Room, continue it there instead of mirroring updates here.
+- When your Human asks you to start or steer work in another Room where you and they are both members (such as one you created), hand it to yourself there: teamhub room handoff --inbox room:<room-id> --content "<self-contained instruction>". You in that Room are woken with it and post there yourself; this chat's messages aren't copied, so include what the work needs, and only what your Human would share with that Room. Then confirm here in one line. Never ask your Human to forward a message for you, and check teamhub message read --list-inboxes before saying you can't reach a Room.
- A Task runs as a separate AlterEgo of you in the background; its progress is not yours. Don't redo its work here.
- Once it's created, tell the person in a line that it's under way, unless nobody is waiting on you; then carry on with other work or end your turn. A Task you create during a proactive wake or a Routine that serves a Tracking Item is quiet: say nothing about it, and its report tells you how to remind. Don't wait for it or keep checking on it: its report wakes you.
- When it ends a turn you get a private Task report with its final reply; nobody else sees it. Read its outputs in ./playground/<task-id>/ (live, also while it runs), then decide what this Room needs. When the Task is done, deliver it with one teamhub message send: the result in a few sentences, and its files with --attach. When the result includes an existing Document, send one complete --message instead, without --content or --attach: {"segments":[{"type":"text","content":"<the result>"},{"type":"document","document_id":"<document-id>","content":"<title>","presentation":"card"}]}; a file goes in it as {"type":"document","content-path":"./playground/<task-id>/<file>"}. If it failed or needs a decision, say so in an ordinary message; say nothing when there is nothing worth saying. Keep message card for things the person must notice. docs create only imports inline data:image images; put local images in with teamhub docs image put.
diff --git a/apps/teamhub-cli/README.md b/apps/teamhub-cli/README.md
index df21db8a..e1692a02 100644
--- a/apps/teamhub-cli/README.md
+++ b/apps/teamhub-cli/README.md
@@ -46,6 +46,8 @@ 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.
+`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`.
+
```bash
teamhub room invite --agent-id <actor-id> --json
teamhub agent create --name 'Reviewer' --description 'Checks patches' --prompt-file ./reviewer.md --json
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 0da789dc..7b9a17ab 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
@@ -2590,6 +2590,28 @@ Options:
",
"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","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","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}},"required":["type","content"],"additionalProperties":false,"description":"Plain text segment. Include both fields, for example {\\"type\\":\\"text\\",\\"content\\":\\"Start here.\\"}."},{"type":"object","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."}},"required":["type","content","target","target_type"],"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."}},"required":["name","member_ids","initial_message_segments"],"additionalProperties":false,"description":"Arguments accepted by the create_room tool."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","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."}},"required":["accepted","status","creation_approval_request_id","message_id"],"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": {
+ "help": "exit 0
+teamhub room handoff [flags]
+Hand your Human's request from your direct chat to yourself in another Room you both are in.
+
+Options:
+ --inbox <value> room:<room-id> of another Room where you and your Human are both members.
+ --content <value> Inline Markdown body; outside code, \\n, \\t and \\\\ are decoded.
+ --file <value> Read UTF-8 body from a file or - for stdin.
+ --json Return machine-readable JSON.
+ --help Show this offline command reference.
+ -h Show help.
+ --schema Show offline input and output schemas.
+ --operation-id <value> Stable operation identity for recovery.
+Only Another Me, from its direct chat with its Human, in a turn the Human started by writing to it or deciding one of its cards.
+The instruction is hidden from that Room. You there are woken with it, read that Room, and post and @ the Agents yourself; the direct chat's messages are not copied.
+Results come back to the direct chat through teamhub message direct.
+",
+ "schema": "exit 0
+{"command":["room","handoff"],"description":"Hand your Human's request from your direct chat to yourself in another Room you both are in.","read_only":false,"input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"room_id":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Another Room where you and your Human are both members."},"instruction":{"type":"string","minLength":1,"maxLength":8000,"description":"Self-contained instruction for you in that Room; hidden from its timeline."}},"required":["room_id","instruction"],"additionalProperties":false,"description":"Arguments accepted by the hand_off_to_room tool."},"output_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{"duplicate_request":{"type":"boolean","description":"Whether TeamHub returned an earlier handoff of this operation."},"reason":{"description":"Public explanation of a committed replay.","type":"string","minLength":1},"accepted":{"type":"boolean","const":true,"description":"Whether TeamHub posted the handoff."},"inbox_id":{"type":"string","pattern":"^room:[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Inbox of the Room that received the handoff."},"handoff_id":{"type":"string","minLength":1,"maxLength":64,"pattern":"^[A-Za-z0-9][A-Za-z0-9_-]*$","description":"Identifier of the hidden handoff."}},"required":["duplicate_request","accepted","inbox_id","handoff_id"],"additionalProperties":false,"description":"Successful result returned by the hand_off_to_room tool."},"cli":{"usage":["teamhub room handoff [flags]"],"arguments":[],"options":{"--inbox":{"description":"room:<room-id> of another Room where you and your Human are both members."},"--content":{"description":"Inline Markdown body; outside code, \\\\n, \\\\t and \\\\\\\\ are decoded."},"--file":{"description":"Read UTF-8 body 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":["Only Another Me, from its direct chat with its Human, in a turn the Human started by writing to it or deciding one of its cards.","The instruction is hidden from that Room. You there are woken with it, read that Room, and post and @ the Agents yourself; the direct chat's messages are not copied.","Results come back to the direct chat through teamhub message direct."]}}
",
},
"room invite": {
@@ -4094,6 +4116,22 @@ Options:
The Agent joins at once with your sponsor's authority; wake it there with an Agent reference.
A Direct Room or Thread keeps its members; create a collaboration Room with teamhub room create instead.
+teamhub room handoff [flags]
+Hand your Human's request from your direct chat to yourself in another Room you both are in.
+
+Options:
+ --inbox <value> room:<room-id> of another Room where you and your Human are both members.
+ --content <value> Inline Markdown body; outside code, \\n, \\t and \\\\ are decoded.
+ --file <value> Read UTF-8 body from a file or - for stdin.
+ --json Return machine-readable JSON.
+ --help Show this offline command reference.
+ -h Show help.
+ --schema Show offline input and output schemas.
+ --operation-id <value> Stable operation identity for recovery.
+Only Another Me, from its direct chat with its Human, in a turn the Human started by writing to it or deciding one of its cards.
+The instruction is hidden from that Room. You there are woken with it, read that Room, and post and @ the Agents yourself; the direct chat's messages are not copied.
+Results come back to the direct chat through teamhub message direct.
+
teamhub room protocol [flags]
Read the current collaboration protocol of the configured Room.
diff --git a/apps/teamhub-cli/src/business-commands.ts b/apps/teamhub-cli/src/business-commands.ts
index 6fcf0f7a..f642dcf2 100644
--- a/apps/teamhub-cli/src/business-commands.ts
+++ b/apps/teamhub-cli/src/business-commands.ts
@@ -827,6 +827,40 @@ const roomInvite = definition(
],
},
);
+const roomHandoff = definition(
+ ["room", "handoff"],
+ "hand_off_to_room",
+ "Hand your Human's request from your direct chat to yourself in another Room you both are in.",
+ {
+ "--inbox": flag(
+ "room:<room-id> of another Room where you and your Human are both members.",
+ ),
+ ...bodyOptions,
+ },
+ async (args, reader) => {
+ assertPositionals(args, 0);
+ const room = /^room:([A-Za-z0-9][A-Za-z0-9_-]*)$/u.exec(
+ requiredOption(args, "--inbox"),
+ );
+ if (!room) invalid("--inbox accepts only a room: address.");
+ return {
+ input: await validate("hand_off_to_room", {
+ room_id: room[1],
+ instruction: await markdownBodySource(args, reader),
+ }),
+ };
+ },
+ {
+ defaultTarget: "room",
+ unavailableInTask:
+ "A Task cannot hand off work. Say in your final reply which Room should take it; the Meta that started the Task can hand it off.",
+ notes: [
+ "Only Another Me, from its direct chat with its Human, in a turn the Human started by writing to it or deciding one of its cards.",
+ "The instruction is hidden from that Room. You there are woken with it, read that Room, and post and @ the Agents yourself; the direct chat's messages are not copied.",
+ "Results come back to the direct chat through teamhub message direct.",
+ ],
+ },
+);
const roomProtocol = definition(
["room", "protocol"],
"get_team_md",
@@ -1285,6 +1319,7 @@ export const businessCommandDefinitions: readonly CommandDefinition[] = [
collaborate,
roomMembers,
roomInvite,
+ roomHandoff,
roomProtocol,
taskCreate,
taskCheck,
diff --git a/apps/teamhub-cli/src/business-render.ts b/apps/teamhub-cli/src/business-render.ts
index 242c5390..ab852835 100644
--- a/apps/teamhub-cli/src/business-render.ts
+++ b/apps/teamhub-cli/src/business-render.ts
@@ -197,6 +197,8 @@ export function renderBusinessResult(command: string, result: Json): string {
return result.added
? `Added Agent ${singleLine(result.actor_id)} to Room ${singleLine(result.room_id)}. Wake it with an Agent reference in that Room.`
: `Agent ${singleLine(result.actor_id)} is already a member of Room ${singleLine(result.room_id)}.`;
+ if (command === "room handoff")
+ return `${result.duplicate_request === true ? "Already handed off" : "Handed off"} to you in ${singleLine(result.inbox_id)}; you there carry it out. Confirm to your Human in one line.`;
if (command === "room protocol")
return result.published === false
? "No team.md collaboration protocol has been published in this Room yet."
diff --git a/apps/teamhub-cli/src/business-routes.ts b/apps/teamhub-cli/src/business-routes.ts
index 3ce9810d..1710bc30 100644
--- a/apps/teamhub-cli/src/business-routes.ts
+++ b/apps/teamhub-cli/src/business-routes.ts
@@ -21,6 +21,7 @@ export const routesByToolName: Readonly<Record<string, TeamHubApiPostPath>> = {
stop_task: "/api/agent/v1/tasks/stop",
create_team_md: "/api/agent/v1/team-md",
add_room_member: "/api/agent/v1/room-members/add",
+ hand_off_to_room: "/api/agent/v1/room-handoffs",
get_room_members: "/api/agent/v1/room-members/query",
get_team_md: "/api/agent/v1/team-md/query",
list_available_agents: "/api/agent/v1/available-agents",
diff --git a/apps/teamhub-cli/src/cli.openapi.test.ts b/apps/teamhub-cli/src/cli.openapi.test.ts
index 98e1ee6d..4b704181 100644
--- a/apps/teamhub-cli/src/cli.openapi.test.ts
+++ b/apps/teamhub-cli/src/cli.openapi.test.ts
@@ -199,6 +199,13 @@ async function respond(request: Request): Promise<Response> {
room_created: true,
duplicate_request: false,
});
+ if (endpoint.endsWith("/room-handoffs"))
+ return Response.json({
+ accepted: true,
+ inbox_id: "room:room_two",
+ handoff_id: "message_handoff",
+ duplicate_request: false,
+ });
if (endpoint.endsWith("/emoji-reactions"))
return Response.json({
accepted: true,
diff --git a/apps/teamhub-cli/src/command-schema-loader.test.ts b/apps/teamhub-cli/src/command-schema-loader.test.ts
index 0ef23358..07ea9584 100644
--- a/apps/teamhub-cli/src/command-schema-loader.test.ts
+++ b/apps/teamhub-cli/src/command-schema-loader.test.ts
@@ -23,6 +23,7 @@ const loadable = [
"get_personal_profile",
"get_room_members",
"get_team_md",
+ "hand_off_to_room",
"list_available_agents",
"list_connected_apps",
"list_routines",
diff --git a/apps/teamhub-cli/src/command-schema-loader.ts b/apps/teamhub-cli/src/command-schema-loader.ts
index 12200a57..da16cd70 100644
--- a/apps/teamhub-cli/src/command-schema-loader.ts
+++ b/apps/teamhub-cli/src/command-schema-loader.ts
@@ -107,6 +107,9 @@ export async function loadAgentCommandSchema(
.runRoutineSchema;
case "search_app_tools":
return (await import("./domains/apps/tools.js")).searchAppToolsSchema;
+ case "hand_off_to_room":
+ return (await import("./domains/collaboration/tools/room-handoff.js"))
+ .roomHandoffSchema;
case "send_direct_message":
return (
await import("./domains/collaboration/tools/send-direct-message.js")
diff --git a/apps/teamhub-cli/src/domains/collaboration/tools/room-handoff.ts b/apps/teamhub-cli/src/domains/collaboration/tools/room-handoff.ts
new file mode 100644
index 00000000..15d5d53e
--- /dev/null
+++ b/apps/teamhub-cli/src/domains/collaboration/tools/room-handoff.ts
@@ -0,0 +1,46 @@
+import { z } from "zod";
+import { teamHubIdSchema } from "../message-segments.js";
+
+export const roomHandoffInputSchema = z
+ .object({
+ room_id: teamHubIdSchema.describe(
+ "Another Room where you and your Human are both members.",
+ ),
+ instruction: z
+ .string()
+ .min(1)
+ .max(8000)
+ .refine((value) => value.trim() !== "", "Instruction must not be blank.")
+ .describe(
+ "Self-contained instruction for you in that Room; hidden from its timeline.",
+ ),
+ })
+ .strict()
+ .describe("Arguments accepted by the hand_off_to_room tool.");
+
+export const roomHandoffOutputSchema = z
+ .object({
+ duplicate_request: z
+ .boolean()
+ .describe(
+ "Whether TeamHub returned an earlier handoff of this operation.",
+ ),
+ reason: z
+ .string()
+ .min(1)
+ .optional()
+ .describe("Public explanation of a committed replay."),
+ accepted: z.literal(true).describe("Whether TeamHub posted the handoff."),
+ inbox_id: z
+ .string()
+ .regex(/^room:[A-Za-z0-9][A-Za-z0-9_-]*$/u)
+ .describe("Inbox of the Room that received the handoff."),
+ handoff_id: teamHubIdSchema.describe("Identifier of the hidden handoff."),
+ })
+ .strict()
+ .describe("Successful result returned by the hand_off_to_room tool.");
+
+export const roomHandoffSchema = {
+ input: roomHandoffInputSchema,
+ output: roomHandoffOutputSchema,
+};
diff --git a/apps/teamhub-cli/src/test-support/command-examples.ts b/apps/teamhub-cli/src/test-support/command-examples.ts
index a9e97f8d..973b6559 100644
--- a/apps/teamhub-cli/src/test-support/command-examples.ts
+++ b/apps/teamhub-cli/src/test-support/command-examples.ts
@@ -110,6 +110,12 @@ export const commandExamples: Record<string, string[]> = {
list_available_agents: ["--limit", "10"],
get_agent: ["--agent-id", "actor_agent"],
add_room_member: ["--agent-id", "actor_agent"],
+ hand_off_to_room: [
+ "--inbox",
+ "room:room_two",
+ "--content",
+ "Plan the offsite with the travel Agents and tell me the result.",
+ ],
create_agent: [
"--name",
"Reviewer",
diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.md
index d6486581..bff3e418 100644
--- a/apps/teamhub/AGENTS.md
+++ b/apps/teamhub/AGENTS.md
@@ -101,6 +101,19 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.
Document reads are live-latest and mutations retain CAS. CLI business
operations use current Agent/resource authority, not Context/Run prerequisites.
+- An Agent writes only in its Context Room. To act in another Room, an
+ AnotherMe in its direct chat uses Room handoff (`internal/agentroomhandoff`,
+ `teamhub room handoff`): TeamHub posts a hidden `agent_runtime` message,
+ authored by the Human and mentioning the AnotherMe, in another live Room
+ where both are members, and it wakes the AnotherMe's Context there, which
+ then speaks for itself. Only a Run whose inputs carry a message the Human
+ wrote, or a card they decided, in the direct chat may hand off
+ (`X-TeamHub-Run-Id`); proactive wakes, Routines and Task callbacks may not,
+ because they often carry outside content. A refusal names its reason in an
+ error issue, which the CLI shows the Agent. The handoff body is hidden from the Web timeline but other
+ Agents in that Room can read it. Results come back through
+ `send_direct_message`.
+
- Go generates only types for the contracts TeamHub serves. Mount each
operation in the caller's route table in `internal/app/routes_*.go`;
`TestRoutesMountEveryContractOperationExactlyOnce` fails on a missing,
diff --git a/apps/teamhub/internal/agentauth/agentauth.go b/apps/teamhub/internal/agentauth/agentauth.go
index 5d68c73d..e8cd4ff1 100644
--- a/apps/teamhub/internal/agentauth/agentauth.go
+++ b/apps/teamhub/internal/agentauth/agentauth.go
@@ -55,7 +55,7 @@ const TaskContextForbiddenMessage = "A Task cannot send messages, create Documen
// speaks and publishes; the AlterEgo reports through its final reply.
func taskContextBlocked(tool string) bool {
switch tool {
- case "send_message", "send_message_sequence", "send_direct_message", "send_emoji", "ask_user", "show_fragment",
+ case "send_message", "send_message_sequence", "send_direct_message", "hand_off_to_room", "send_emoji", "ask_user", "show_fragment",
"create_document", "create_room", "create_team_md",
"create_task", "check_task", "send_task", "stop_task":
return true
@@ -219,7 +219,7 @@ func authorizeAgentPrincipal(ctx context.Context, tx pgx.Tx, token, action strin
// service independently enforces the action's current permissions.
func businessAction(action string) bool {
switch action {
- case "apply_document_semantic_mutation", "ask_user", "check_task", "create_document", "create_task", "create_room", "create_routine", "create_team_md", "delete_routine", "enable_routine", "get_document_comment_thread", "list_available_agents", "list_routines", "pause_routine", "replace_document_comment_text", "reply_document_comment", "run_routine", "send_direct_message", "send_emoji", "send_message", "send_message_sequence", "send_task", "show_fragment", "stop_task", "upload_artifact_tree", "upload_artifacts",
+ case "apply_document_semantic_mutation", "ask_user", "check_task", "create_document", "create_task", "create_room", "create_routine", "create_team_md", "delete_routine", "enable_routine", "get_document_comment_thread", "hand_off_to_room", "list_available_agents", "list_routines", "pause_routine", "replace_document_comment_text", "reply_document_comment", "run_routine", "send_direct_message", "send_emoji", "send_message", "send_message_sequence", "send_task", "show_fragment", "stop_task", "upload_artifact_tree", "upload_artifacts",
"add_room_member", "create_agent", "get_agent", "update_agent", "list_connected_apps", "search_app_tools", "execute_app_tool", "manage_auto_reminders",
"get_personal_profile", "write_personal_profile", "start_personal_profile_build", "get_account_profile", "update_account_profile",
"request_browser_connection", "read_computer_permissions", "request_computer_permission":
@@ -256,6 +256,9 @@ func businessCapability(i Authorization, action string) bool {
return i.AgentType == "anotherme" && i.UserArtifactOwnerActorID != "" && i.Target.Kind != "document"
case "send_message_sequence":
return i.AgentType == "anotherme" && i.ParticipantTaskID == "" && i.Target.Kind != "document"
+ case "hand_off_to_room":
+ // From an AnotherMe's Meta in a Room; the service requires its direct chat.
+ return i.AgentType == "anotherme" && i.ParticipantTaskID == "" && i.Target.Kind == "room" && i.RoomID != ""
case "create_task", "check_task", "send_task", "stop_task", "create_room", "create_team_md", "show_fragment":
return i.ParticipantTaskID == "" && i.Target.Kind != "document"
case "get_document_comment_thread", "reply_document_comment", "replace_document_comment_text":
diff --git a/apps/teamhub/internal/agentroomhandoff/service.go b/apps/teamhub/internal/agentroomhandoff/service.go
new file mode 100644
index 00000000..b2e866fa
--- /dev/null
+++ b/apps/teamhub/internal/agentroomhandoff/service.go
@@ -0,0 +1,308 @@
+// Package agentroomhandoff hands a Human's request from the direct chat with
+// their AnotherMe to that AnotherMe's Context in another Room. An Agent writes
+// only in its Context Room, so the direct chat never posts in the other Room:
+// it leaves a hidden handoff there that wakes the AnotherMe's own Context,
+// which then decides what to say to that Room.
+package agentroomhandoff
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "regexp"
+ "strings"
+ "time"
+ "unicode/utf8"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentauth"
+ "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"
+)
+
+const (
+ toolName = "hand_off_to_room"
+ idempotencyOperation = "hand_off_to_room"
+ // MaxInstructionRunes bounds the instruction the receiving Context reads.
+ MaxInstructionRunes = 8000
+)
+
+var (
+ // ErrInvalid reports a malformed request.
+ ErrInvalid = errors.New("Room handoff input is invalid")
+ // ErrNotFromDirectChat reports a caller that is not an AnotherMe Meta in
+ // its direct chat with its Human.
+ ErrNotFromDirectChat = fmt.Errorf("%w: only an AnotherMe hands off from its direct chat", agentauth.ErrForbidden)
+ // ErrNotRequestedByHuman reports a Run that nothing the Human did in the
+ // direct chat started, such as a proactive wake, Routine or Task report.
+ ErrNotRequestedByHuman = fmt.Errorf("%w: only a turn the Human started hands off", agentauth.ErrForbidden)
+ // ErrRoomUnavailable reports a target Room that is missing, being
+ // deleted, the direct chat itself, or lacks the AnotherMe or its Human.
+ ErrRoomUnavailable = errors.New("Room handoff target is unavailable")
+ // ErrIdempotencyConflict reports an invocation reused with other input.
+ ErrIdempotencyConflict = errors.New("Room handoff invocation was reused with different input")
+ // ErrUnavailable reports a receipt that no longer matches current facts.
+ ErrUnavailable = errors.New("Room handoff service is unavailable")
+
+ invocationPattern = regexp.MustCompile(`^agent-invocation-sha256:[a-f0-9]{64}$`)
+ roomIDPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$`)
+)
+
+// Input is one handoff request.
+type Input struct {
+ InvocationID string
+ RoomID string
+ Instruction string
+}
+
+// Result is the handoff in the target Room.
+type Result struct {
+ InboxID string
+ HandoffID string
+ Replay bool
+}
+
+type receipt struct {
+ InboxID string `json:"inbox_id"`
+ HandoffID string `json:"handoff_id"`
+}
+
+// Service posts Room handoffs.
+type Service struct {
+ pool *pgxpool.Pool
+ authorizer *agentauth.Service
+ now func() time.Time
+}
+
+// New builds the Service.
+func New(pool *pgxpool.Pool, authorizer *agentauth.Service) *Service {
+ return &Service{pool: pool, authorizer: authorizer, now: time.Now}
+}
+
+// HandOff posts the handoff in input.RoomID, or returns the receipt of the
+// same invocation.
+func (s *Service) HandOff(ctx context.Context, token string, input Input) (Result, error) {
+ instruction := strings.TrimSpace(input.Instruction)
+ if !invocationPattern.MatchString(input.InvocationID) || !roomIDPattern.MatchString(input.RoomID) ||
+ instruction == "" || utf8.RuneCountInString(instruction) > MaxInstructionRunes {
+ return Result{}, ErrInvalid
+ }
+ if s == nil || s.pool == nil || s.authorizer == nil {
+ return Result{}, ErrUnavailable
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return Result{}, err
+ }
+ defer func() { _ = tx.Rollback(ctx) }()
+ authorization, err := s.authorizer.AuthorizeInTx(ctx, tx, token, toolName)
+ if err != nil {
+ return Result{}, err
+ }
+ queries := store.New(tx)
+ human := authorization.UserArtifactOwnerActorID
+ directRoomID, err := directChat(ctx, queries, authorization)
+ if err != nil {
+ return Result{}, err
+ }
+
+ requestHash := sha256.Sum256([]byte(input.RoomID + "\x00" + instruction))
+ key := idempotency.AgentKey(authorization.AgentActorID, idempotencyOperation,
+ agentauth.IdempotencyKey(idempotencyOperation, input.InvocationID))
+ if err := idempotency.Lock(ctx, tx, key); err != nil {
+ return Result{}, err
+ }
+ record, found, err := idempotency.Lookup(ctx, tx, key, requestHash[:])
+ if errors.Is(err, idempotency.ErrConflict) {
+ return Result{}, ErrIdempotencyConflict
+ }
+ if err != nil {
+ return Result{}, err
+ }
+ if found {
+ var stored receipt
+ if json.Unmarshal(record.Body, &stored) != nil || record.InvocationID != input.InvocationID ||
+ stored.HandoffID != record.ResourceID || stored.InboxID != "room:"+input.RoomID {
+ return Result{}, ErrUnavailable
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return Result{}, err
+ }
+ return Result{InboxID: stored.InboxID, HandoffID: stored.HandoffID, Replay: true}, nil
+ }
+
+ if err := requireHumanRequest(ctx, queries, authorization, directRoomID, human); err != nil {
+ return Result{}, err
+ }
+ humanActor, agentActor, err := targetMembers(ctx, queries, authorization, directRoomID, input.RoomID)
+ if err != nil {
+ return Result{}, err
+ }
+ handoffID := handoffMessageID(authorization.AgentActorID, input.InvocationID)
+ text, err := handoffText(handoffID, directRoomID, input.RoomID, instruction, human, s.now())
+ if err != nil {
+ return Result{}, err
+ }
+ // The Human speaks the hidden message so the AnotherMe does not ignore it
+ // as its own; the mention wakes only that AnotherMe's Context.
+ persisted, err := messagecreation.CardHandoff(ctx, queries, messagecreation.Draft{
+ ID: handoffID, TenantID: authorization.TenantID, RoomID: input.RoomID, Author: humanActor,
+ }, agentActor, text)
+ if err != nil {
+ return Result{}, err
+ }
+ if _, err := messagecreation.Publish(ctx, queries, persisted); err != nil {
+ return Result{}, err
+ }
+ stored := receipt{InboxID: "room:" + input.RoomID, HandoffID: handoffID}
+ body, err := json.Marshal(stored)
+ if err != nil {
+ return Result{}, err
+ }
+ if err := idempotency.Save(ctx, tx, key, requestHash[:], idempotency.Record{
+ ResourceID: handoffID, Status: http.StatusOK, Body: body, InvocationID: input.InvocationID,
+ }); err != nil {
+ return Result{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return Result{}, err
+ }
+ return Result{InboxID: stored.InboxID, HandoffID: handoffID}, nil
+}
+
+// directChat returns the caller's Context Room when it is the AnotherMe's
+// live direct chat with its Human.
+func directChat(ctx context.Context, queries *store.Queries, authorization agentauth.Authorization) (string, error) {
+ human := authorization.UserArtifactOwnerActorID
+ if authorization.AgentType != "anotherme" || authorization.ParticipantTaskID != "" ||
+ authorization.Target.Kind != "room" || authorization.RoomID == "" || human == "" {
+ return "", ErrNotFromDirectChat
+ }
+ direct, err := queries.GetDirectRoomByPair(ctx, store.GetDirectRoomByPairParams{
+ TenantID: authorization.TenantID, HumanActorID: human, AgentActorID: authorization.AgentActorID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return "", ErrNotFromDirectChat
+ }
+ if err != nil {
+ return "", err
+ }
+ if direct.ID != authorization.RoomID || direct.DeletionStartedAt.Valid {
+ return "", ErrNotFromDirectChat
+ }
+ return direct.ID, nil
+}
+
+// requireHumanRequest admits only the Run the request names when it carries
+// a message the Human wrote, or a card they decided, in the direct chat. A
+// proactive wake, Routine or Task callback runs there too, often on content
+// from outside (mail, events, documents), and must not reach other Rooms.
+func requireHumanRequest(
+ ctx context.Context,
+ queries *store.Queries,
+ authorization agentauth.Authorization,
+ directRoomID, human string,
+) error {
+ runID := messagecreation.RunClaim(ctx)
+ if runID == "" {
+ return ErrNotRequestedByHuman
+ }
+ started, err := queries.IsRunStartedByDirectChatHuman(ctx, store.IsRunStartedByDirectChatHumanParams{
+ RoomID: directRoomID, RunID: runID, TenantID: authorization.TenantID,
+ AgentActorID: authorization.AgentActorID, HumanActorID: human,
+ })
+ if err != nil {
+ return err
+ }
+ if !started {
+ return ErrNotRequestedByHuman
+ }
+ return nil
+}
+
+// targetMembers locks the live target Room and returns its Human and
+// AnotherMe members, key-share locked until the handoff commits.
+func targetMembers(
+ ctx context.Context,
+ queries *store.Queries,
+ authorization agentauth.Authorization,
+ directRoomID, roomID string,
+) (store.Actor, store.Actor, error) {
+ if roomID == directRoomID {
+ return store.Actor{}, store.Actor{}, ErrRoomUnavailable
+ }
+ if thread, err := queries.GetThreadRoomByRoomID(ctx, roomID); err == nil && thread.RoomID == roomID {
+ return store.Actor{}, store.Actor{}, ErrRoomUnavailable
+ } else if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ return store.Actor{}, store.Actor{}, err
+ }
+ active, err := queries.LockActiveRoomForMutation(ctx, roomID)
+ if errors.Is(err, pgx.ErrNoRows) || err == nil && active != roomID {
+ return store.Actor{}, store.Actor{}, ErrRoomUnavailable
+ }
+ if err != nil {
+ return store.Actor{}, store.Actor{}, err
+ }
+ member := func(actorID, kind string) (store.Actor, error) {
+ actor, err := queries.GetRoomActorMember(ctx, store.GetRoomActorMemberParams{RoomID: roomID, ActorID: actorID})
+ if errors.Is(err, pgx.ErrNoRows) {
+ return store.Actor{}, ErrRoomUnavailable
+ }
+ if err != nil {
+ return store.Actor{}, err
+ }
+ if actor.TenantID != authorization.TenantID || actor.Kind != kind {
+ return store.Actor{}, ErrRoomUnavailable
+ }
+ return actor, nil
+ }
+ humanActor, err := member(authorization.UserArtifactOwnerActorID, "human")
+ if err != nil {
+ return store.Actor{}, store.Actor{}, err
+ }
+ agentActor, err := member(authorization.AgentActorID, "agent")
+ if err != nil {
+ return store.Actor{}, store.Actor{}, err
+ }
+ return humanActor, agentActor, nil
+}
+
+// handoffMessageID derives the hidden message from the invocation, so one
+// invocation posts at most one handoff.
+func handoffMessageID(agentActorID, invocationID string) string {
+ digest := sha256.Sum256([]byte("room-handoff:" + agentActorID + ":" + invocationID))
+ return "message_" + hex.EncodeToString(digest[:16])
+}
+
+func handoffText(handoffID, directRoomID, roomID, instruction, humanActorID string, requestedAt time.Time) (string, error) {
+ payload, err := json.Marshal(struct {
+ Kind string `json:"kind"`
+ HandoffID string `json:"handoff_id"`
+ OriginRoomID string `json:"origin_room_id"`
+ OriginInboxID string `json:"origin_room_inbox_id"`
+ RoomInboxID string `json:"room_inbox_id"`
+ Instruction string `json:"instruction"`
+ RequestedBy string `json:"requested_by"`
+ RequestedAt time.Time `json:"requested_at"`
+ }{
+ "room_handoff", handoffID, directRoomID, "room:" + directRoomID, "room:" + roomID,
+ instruction, humanActorID, requestedAt.UTC(),
+ })
+ if err != nil {
+ return "", err
+ }
+ prompt := fmt.Sprintf(`<room-handoff-pattern>
+Your Human asked for this in your direct chat, and you there handed it to you here. Carry out the
+instruction in this Room: read this Room's history with teamhub message read, then post here and
+mention each Agent who should act. Reply only to the Inbox room:%s. Messages of the direct chat are
+not copied into this Room. When the work is done or needs your Human's decision, tell them with
+teamhub message direct. Never hand this work back.
+</room-handoff-pattern>`, roomID)
+ return " Room handoff=" + string(payload) + "\n" + prompt, nil
+}
diff --git a/apps/teamhub/internal/app/app.go b/apps/teamhub/internal/app/app.go
index af7c7915..e19ebcd8 100644
--- a/apps/teamhub/internal/app/app.go
+++ b/apps/teamhub/internal/app/app.go
@@ -39,6 +39,7 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentcreationapproval"
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentdirectmessage"
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentdocument"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentroomhandoff"
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"
"github.com/simplexai-labs/linger/apps/teamhub/internal/agentsendmessage"
artifactstore "github.com/simplexai-labs/linger/apps/teamhub/internal/artifact"
@@ -142,6 +143,7 @@ type App struct {
mcpContexts mcpContextService
agentAuth agentauth.Authorizer
agentDirectMessages agentDirectMessageService
+ agentRoomHandoffs agentRoomHandoffService
agentDocumentCreations agentDocumentCreateService
agentDocumentComments agentDocumentCommentService
agentDocumentSemanticMutations agentDocumentSemanticService
@@ -634,6 +636,7 @@ func (a *App) registerAgentTools(cfg config.Config, deps Deps, agentAuthorizatio
a.agentDocumentCreations = agentdocument.NewCreateTool(agentAuthorization, a.documents)
a.agentDocumentSemanticMutations = agentdocument.NewSemanticTool(agentAuthorization, a.documents)
a.agentDirectMessages = agentdirectmessage.New(a.pool, agentAuthorization)
+ a.agentRoomHandoffs = agentroomhandoff.New(a.pool, agentAuthorization)
messageSender := agentsendmessage.New(a.pool, agentAuthorization, a.documents, a.artifacts)
a.agentSendMessages = messageSender
a.registerPermissionReview(cfg.PermissionReview, models, deps.PermissionJudge)
diff --git a/apps/teamhub/internal/app/contract_server_agent_room_handoff.go b/apps/teamhub/internal/app/contract_server_agent_room_handoff.go
new file mode 100644
index 00000000..dfbe8052
--- /dev/null
+++ b/apps/teamhub/internal/app/contract_server_agent_room_handoff.go
@@ -0,0 +1,79 @@
+package app
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentauth"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentroomhandoff"
+ teamhubagentapi "github.com/simplexai-labs/linger/contracts-go/teamhubagentapi"
+)
+
+const agentRoomHandoffRequestMaxBytes = 64 << 10
+
+type agentRoomHandoffService interface {
+ HandOff(context.Context, string, agentroomhandoff.Input) (agentroomhandoff.Result, error)
+}
+
+func (a *App) handOffAgentRoomWork(c *gin.Context) {
+ token, ok := a.agentCommandBearer(c)
+ if !ok {
+ return
+ }
+ var request teamhubagentapi.AgentRoomHandoffRequest
+ body := http.MaxBytesReader(c.Writer, c.Request.Body, agentRoomHandoffRequestMaxBytes)
+ if err := decodeStrictJSON(body, &request, "request body must contain one JSON object"); err != nil {
+ a.writeAgentAPIError(c, http.StatusBadRequest, teamhubagentapi.AgentApiErrorCodeInvalidRequest, "Room handoff request is invalid")
+ return
+ }
+ result, err := a.agentRoomHandoffs.HandOff(c.Request.Context(), token, agentroomhandoff.Input{
+ InvocationID: request.InvocationId, RoomID: request.RoomId, Instruction: request.Instruction,
+ })
+ if a.writeAgentRoomHandoffError(c, err) {
+ return
+ }
+ c.JSON(http.StatusOK, agentMessageReceipt(gin.H{"accepted": true, "inbox_id": result.InboxID, "handoff_id": result.HandoffID}, result.Replay,
+ "This operation was already completed. The original handoff is returned; nothing new was posted."))
+}
+
+// writeRoomHandoffRefusal carries the refusal's reason in a model-safe issue,
+// which the CLI shows the Agent, so it can tell the Human what really
+// happened instead of guessing.
+func (a *App) writeRoomHandoffRefusal(c *gin.Context, code teamhubagentapi.AgentApiErrorCode, path, reason, message string) {
+ a.writeAgentAPIErrorWithIssues(c, http.StatusForbidden, code, "Room handoff was refused",
+ []teamhubagentapi.AgentApiErrorIssue{{Path: path, Code: reason, Message: message}})
+}
+
+func (a *App) writeAgentRoomHandoffError(c *gin.Context, err error) bool {
+ if err == nil {
+ return false
+ }
+ switch {
+ case errors.Is(err, agentroomhandoff.ErrInvalid), errors.Is(err, agentauth.ErrInvalid):
+ a.writeAgentAPIError(c, http.StatusBadRequest, teamhubagentapi.AgentApiErrorCodeInvalidRequest, "Room handoff request is invalid")
+ case errors.Is(err, agentauth.ErrCredentialInvalid):
+ a.writeAgentAPIError(c, http.StatusUnauthorized, teamhubagentapi.AgentApiErrorCodeAgentCredentialInvalid, "Agent credential is invalid or expired")
+ case errors.Is(err, agentroomhandoff.ErrNotRequestedByHuman):
+ a.writeRoomHandoffRefusal(c, teamhubagentapi.AgentApiErrorCodeOperationForbidden, "run", "not_requested_by_human",
+ "Hand off only in a turn your Human started in this direct chat, by writing to you or deciding one of your cards. In a proactive wake, Routine or Task report, tell your Human here and let them ask.")
+ case errors.Is(err, agentroomhandoff.ErrNotFromDirectChat), errors.Is(err, agentauth.ErrForbidden):
+ a.writeRoomHandoffRefusal(c, teamhubagentapi.AgentApiErrorCodeOperationForbidden, "context", "not_direct_chat",
+ "Only Another Me hands off, from its direct chat with its Human. In any other Room, work in that Room itself.")
+ case errors.Is(err, agentroomhandoff.ErrRoomUnavailable):
+ a.writeRoomHandoffRefusal(c, teamhubagentapi.AgentApiErrorCodeForbidden, "room_id", "room_unavailable",
+ "The target must be another live Room, not a Thread or this chat, where both you and your Human are members; teamhub message read --list-inboxes lists your Rooms.")
+ case errors.Is(err, agentroomhandoff.ErrIdempotencyConflict):
+ a.writeAgentAPIError(c, http.StatusConflict, teamhubagentapi.AgentApiErrorCodeIdempotencyConflict, "Room handoff invocation was reused with different input")
+ case errors.Is(err, agentroomhandoff.ErrUnavailable):
+ a.writeAgentAPIError(c, http.StatusServiceUnavailable, teamhubagentapi.AgentApiErrorCodeDependencyUnavailable, "Room handoff service is unavailable")
+ default:
+ if a.logger != nil {
+ a.logger.Error("agent.room_handoff_failed", "request_id", c.GetString("request_id"), "error_type", fmt.Sprintf("%T", err))
+ }
+ a.writeAgentAPIError(c, http.StatusInternalServerError, teamhubagentapi.AgentApiErrorCodeInternalError, "Room handoff service could not complete the request")
+ }
+ return true
+}
diff --git a/apps/teamhub/internal/app/routes_agent_api.go b/apps/teamhub/internal/app/routes_agent_api.go
index d813d489..f7e617e7 100644
--- a/apps/teamhub/internal/app/routes_agent_api.go
+++ b/apps/teamhub/internal/app/routes_agent_api.go
@@ -47,6 +47,7 @@ func (a *App) agentAPIRoutes() []contractRoute {
route(http.MethodPost, "/api/agent/v1/personal-profile/builds", nil, a.startAgentPersonalProfileBuild),
route(http.MethodPost, "/api/agent/v1/personal-profile/revisions", nil, a.writeAgentPersonalProfile),
route(http.MethodPost, "/api/agent/v1/presentation-sequences", nil, a.sendAgentPresentationSequence),
+ route(http.MethodPost, "/api/agent/v1/room-handoffs", nil, a.handOffAgentRoomWork),
route(http.MethodPost, "/api/agent/v1/room-members/add", nil, a.addAgentRoomMember),
route(http.MethodPost, "/api/agent/v1/room-members/query", nil, a.getAgentRoomMembers),
route(http.MethodPost, "/api/agent/v1/routines", nil, a.createAgentRoutine),
diff --git a/apps/teamhub/internal/store/queries/room_handoff.sql b/apps/teamhub/internal/store/queries/room_handoff.sql
new file mode 100644
index 00000000..8bf1cd49
--- /dev/null
+++ b/apps/teamhub/internal/store/queries/room_handoff.sql
@@ -0,0 +1,34 @@
+-- name: IsRunStartedByDirectChatHuman :one
+-- Whether the Agent's running Run in its direct chat carries something the
+-- Human did there: a Message they wrote, or the result of a card they
+-- decided themselves. TeamHub also writes Messages in the Human's name with a
+-- card's context, such as a reminder about a card still pending, so a card's
+-- context alone proves nothing; its decision must name the Human. Quiet
+-- wakes, Routine fires and Task callbacks carry neither. A Room input names
+-- the Messages it carries in payload invocationMessageIds.
+SELECT EXISTS (
+ SELECT 1
+ FROM agent_local_runs run
+ JOIN agent_execution_contexts context ON context.context_key=run.context_key
+ JOIN agent_local_run_inputs relation ON relation.run_id=run.run_id
+ JOIN agent_runtime_inputs input
+ ON input.context_key=relation.context_key AND input.input_id=relation.input_id
+ JOIN messages message ON message.room_id=sqlc.arg(room_id)::text
+ AND (input.source_message_id=message.id
+ OR jsonb_typeof(input.payload->'invocationMessageIds')='array'
+ AND input.payload->'invocationMessageIds' @> to_jsonb(message.id))
+ WHERE run.run_id=sqlc.arg(run_id)::text AND run.status='running'
+ AND run.status_room_id=sqlc.arg(room_id)::text
+ AND context.tenant_id=sqlc.arg(tenant_id)::text
+ AND context.agent_actor_id=sqlc.arg(agent_actor_id)::text
+ AND message.author_actor_id=sqlc.arg(human_actor_id)::text
+ AND (
+ message.message_kind='conversation' AND message.card_context_message_id IS NULL
+ OR EXISTS (
+ SELECT 1 FROM decisions decision
+ WHERE decision.message_id=message.card_context_message_id
+ AND decision.room_id=message.room_id
+ AND decision.decided_by_actor_id=sqlc.arg(human_actor_id)::text
+ )
+ )
+)::boolean;
diff --git a/apps/teamhub/internal/store/room_handoff.sql.go b/apps/teamhub/internal/store/room_handoff.sql.go
new file mode 100644
index 00000000..4756d032
--- /dev/null
+++ b/apps/teamhub/internal/store/room_handoff.sql.go
@@ -0,0 +1,67 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.29.0
+// source: room_handoff.sql
+
+package store
+
+import (
+ "context"
+)
+
+const isRunStartedByDirectChatHuman = `-- name: IsRunStartedByDirectChatHuman :one
+SELECT EXISTS (
+ SELECT 1
+ FROM agent_local_runs run
+ JOIN agent_execution_contexts context ON context.context_key=run.context_key
+ JOIN agent_local_run_inputs relation ON relation.run_id=run.run_id
+ JOIN agent_runtime_inputs input
+ ON input.context_key=relation.context_key AND input.input_id=relation.input_id
+ JOIN messages message ON message.room_id=$1::text
+ AND (input.source_message_id=message.id
+ OR jsonb_typeof(input.payload->'invocationMessageIds')='array'
+ AND input.payload->'invocationMessageIds' @> to_jsonb(message.id))
+ WHERE run.run_id=$2::text AND run.status='running'
+ AND run.status_room_id=$1::text
+ AND context.tenant_id=$3::text
+ AND context.agent_actor_id=$4::text
+ AND message.author_actor_id=$5::text
+ AND (
+ message.message_kind='conversation' AND message.card_context_message_id IS NULL
+ OR EXISTS (
+ SELECT 1 FROM decisions decision
+ WHERE decision.message_id=message.card_context_message_id
+ AND decision.room_id=message.room_id
+ AND decision.decided_by_actor_id=$5::text
+ )
+ )
+)::boolean
+`
+
+type IsRunStartedByDirectChatHumanParams struct {
+ RoomID string `json:"room_id"`
+ RunID string `json:"run_id"`
+ TenantID string `json:"tenant_id"`
+ AgentActorID string `json:"agent_actor_id"`
+ HumanActorID string `json:"human_actor_id"`
+}
+
+// Whether the Agent's running Run in its direct chat carries something the
+// Human did there: a Message they wrote, or the result of a card they
+// decided themselves. TeamHub also writes Messages in the Human's name with a
+// card's context, such as a reminder about a card still pending, so a card's
+// context alone proves nothing; its decision must name the Human. Quiet
+// wakes, Routine fires and Task callbacks carry neither. A Room input names
+// the Messages it carries in payload invocationMessageIds.
+func (q *Queries) IsRunStartedByDirectChatHuman(ctx context.Context, arg IsRunStartedByDirectChatHumanParams) (bool, error) {
+ row := q.db.QueryRow(ctx, isRunStartedByDirectChatHuman,
+ arg.RoomID,
+ arg.RunID,
+ arg.TenantID,
+ arg.AgentActorID,
+ arg.HumanActorID,
+ )
+ var column_1 bool
+ err := row.Scan(&column_1)
+ return column_1, err
+}
diff --git a/apps/teamhub/tests/integration/agent_room_handoff_test.go b/apps/teamhub/tests/integration/agent_room_handoff_test.go
new file mode 100644
index 00000000..fc186f9f
--- /dev/null
+++ b/apps/teamhub/tests/integration/agent_room_handoff_test.go
@@ -0,0 +1,251 @@
+package integration_test
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"
+)
+
+// From its direct chat, in a turn its Human's own message started, a Human's
+// AnotherMe hands that request to its Context in another Room where both are
+// members: TeamHub posts one hidden handoff that wakes it there. Any other
+// caller, turn or Room is refused and posts nothing.
+func TestAgentRoomHandoffWakesAnotherMeInItsHumansRoom(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ env, alice, issued, roomID := newAgentCLIIdentity(t)
+ status, _, body := env.request(alice, http.MethodPost, "/v0/tenants/"+acmeTenant+"/direct-rooms", map[string]any{"peer_actor_id": "actor_acme_official"}, "")
+ if status != http.StatusOK && status != http.StatusCreated {
+ t.Fatalf("create direct chat=%d %s", status, body)
+ }
+ var direct struct {
+ ID string `json:"id"`
+ }
+ decode(t, body, &direct)
+ withoutAliceID := createPrivateRoom(t, env, alice, "Room without Alice", "handoff-without-alice")
+ if code, body := putRoomMember(t, env, alice, withoutAliceID, "actor_acme_official", "member"); code != http.StatusOK {
+ t.Fatalf("add Agent to %s: %d %s", withoutAliceID, code, body)
+ }
+ if _, err := env.pool.Exec(t.Context(), `DELETE FROM room_members WHERE room_id=$1 AND actor_id='actor_acme_alice'`, withoutAliceID); err != nil {
+ t.Fatal(err)
+ }
+ otherRoomID := createPrivateRoom(t, env, alice, "Other Room with Alice", "handoff-other-room")
+ if code, body := putRoomMember(t, env, alice, otherRoomID, "actor_acme_official", "member"); code != http.StatusOK {
+ t.Fatalf("add Agent to %s: %d %s", otherRoomID, code, body)
+ }
+
+ // A Context runs one Run at a time: a quiet wake's, a reminder about a
+ // card still pending, the result of a card Alice answered, then her typed
+ // request. Everything but the request is hidden and authored by Alice;
+ // only the answered card is something she did.
+ const requested, woken, reminded, answered = "run_handoff_requested", "run_handoff_woken", "run_handoff_reminded", "run_handoff_answered"
+ handOff := func(contextID, runID, targetRoomID, invocation string) (int, map[string]any) {
+ t.Helper()
+ return postRoomHandoff(t, env, issued.AccessToken, contextID, runID, map[string]any{
+ "invocation_id": "agent-invocation-sha256:" + semanticDigest([]byte("room-handoff-"+invocation)),
+ "room_id": targetRoomID,
+ "instruction": "Plan the December offsite with the travel Agents and tell Alice the result.",
+ })
+ }
+ // A refusal names its reason in an issue the CLI shows the Agent.
+ refused := func(name string, code int, want, reason, contextID, runID, targetRoomID, invocation string) {
+ t.Helper()
+ got, body := handOff(contextID, runID, targetRoomID, invocation)
+ envelope, _ := body["error"].(map[string]any)
+ issues, _ := envelope["issues"].([]any)
+ issue := map[string]any{}
+ if len(issues) == 1 {
+ issue, _ = issues[0].(map[string]any)
+ }
+ if got != code || agentProfileErrorCode(body) != want || issue["code"] != reason {
+ t.Fatalf("%s=%d %v, want %d %s %s", name, got, body, code, want, reason)
+ }
+ }
+ endRun := func(runID string) {
+ t.Helper()
+ for _, statement := range []string{
+ `DELETE FROM agent_local_run_inputs WHERE run_id=$1`,
+ `DELETE FROM agent_runtime_inputs WHERE local_run_id=$1`,
+ `DELETE FROM agent_local_runs WHERE run_id=$1`,
+ } {
+ if _, err := env.pool.Exec(t.Context(), statement, runID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ handoffs := func(roomID string) int {
+ return countRows(t, env, `SELECT count(*) FROM messages WHERE room_id=$1 AND message_kind='agent_runtime'
+ AND body LIKE '%"kind":"room_handoff"%'`, roomID)
+ }
+
+ refused("general Agent", http.StatusForbidden, "operation_forbidden", "not_direct_chat", direct.ID, requested, roomID, "general")
+ if _, err := env.pool.Exec(t.Context(), `UPDATE agent_registrations SET agent_type='anotherme',represented_human_actor_id='actor_acme_alice' WHERE actor_id='actor_acme_official'`); err != nil {
+ t.Fatal(err)
+ }
+ refused("from a collaboration Room", http.StatusForbidden, "operation_forbidden", "not_direct_chat", otherRoomID, requested, roomID, "collaboration")
+ refused("without a Run", http.StatusForbidden, "operation_forbidden", "not_requested_by_human", direct.ID, "", roomID, "no-run")
+ seedDirectChatRun(t, env, direct.ID, woken, "message_handoff_wake", "agent_runtime", noCard)
+ refused("in a wake's Run", http.StatusForbidden, "operation_forbidden", "not_requested_by_human", direct.ID, woken, roomID, "wake")
+ endRun(woken)
+ seedDirectChatRun(t, env, direct.ID, reminded, "message_handoff_reminder", "agent_runtime", cardPending)
+ refused("in a pending card reminder's Run", http.StatusForbidden, "operation_forbidden", "not_requested_by_human", direct.ID, reminded, roomID, "reminder")
+ endRun(reminded)
+ if n := handoffs(roomID) + handoffs(withoutAliceID) + handoffs(direct.ID); n != 0 {
+ t.Fatalf("refused handoffs persisted: %d", n)
+ }
+
+ seedDirectChatRun(t, env, direct.ID, answered, "message_handoff_answer", "agent_runtime", cardDecided)
+ if code, body := handOff(direct.ID, answered, roomID, "answered"); code != http.StatusOK || body["accepted"] != true {
+ t.Fatalf("handoff after Alice answered a card=%d %v", code, body)
+ }
+ endRun(answered)
+ seedDirectChatRun(t, env, direct.ID, requested, "message_handoff_request", "conversation", noCard)
+ refused("in a Run of another Room", http.StatusForbidden, "operation_forbidden", "not_direct_chat", otherRoomID, requested, roomID, "other-run")
+ refused("to a Room without the Human", http.StatusForbidden, "forbidden", "room_unavailable", direct.ID, requested, withoutAliceID, "without-alice")
+ refused("to the direct chat", http.StatusForbidden, "forbidden", "room_unavailable", direct.ID, requested, direct.ID, "direct")
+ if n := handoffs(withoutAliceID) + handoffs(direct.ID); n != 0 {
+ t.Fatalf("refused handoffs persisted: %d", n)
+ }
+
+ code, first := handOff(direct.ID, requested, roomID, "accepted")
+ if code != http.StatusOK || first["accepted"] != true || first["duplicate_request"] != false || first["inbox_id"] != "room:"+roomID {
+ t.Fatalf("handoff=%d %v", code, first)
+ }
+ code, replay := handOff(direct.ID, requested, roomID, "accepted")
+ if code != http.StatusOK || replay["duplicate_request"] != true || replay["handoff_id"] != first["handoff_id"] {
+ t.Fatalf("handoff replay=%d %v first=%v", code, replay, first)
+ }
+ var author string
+ var mentioned []string
+ var text string
+ if err := env.pool.QueryRow(t.Context(), `SELECT author_actor_id,mentioned_actor_ids,body FROM messages WHERE id=$1 AND room_id=$2 AND message_kind='agent_runtime'`,
+ first["handoff_id"], roomID).Scan(&author, &mentioned, &text); err != nil {
+ t.Fatalf("read handoff: %v", err)
+ }
+ if author != "actor_acme_alice" || len(mentioned) != 1 || mentioned[0] != "actor_acme_official" ||
+ !strings.Contains(text, "Plan the December offsite") || !strings.Contains(text, `"origin_room_id":"`+direct.ID+`"`) {
+ t.Fatalf("handoff author=%s mentioned=%v body=%s", author, mentioned, text)
+ }
+ if n := handoffs(roomID); n != 2 {
+ t.Fatalf("handoffs in the Human's Room=%d, want 2", n)
+ }
+ // The hidden handoff wakes the AnotherMe's Context in that Room.
+ disposition := func(agentActorID string) string {
+ var value string
+ if err := env.pool.QueryRow(t.Context(), `SELECT disposition FROM agent_inbox_message_disposition($1,$2,'',$3,$4)`,
+ acmeTenant, agentActorID, "room:"+roomID, first["handoff_id"]).Scan(&value); err != nil {
+ t.Fatalf("disposition for %s: %v", agentActorID, err)
+ }
+ return value
+ }
+ if got := disposition("actor_acme_official"); got != "notify" {
+ t.Fatalf("AnotherMe disposition=%s, want notify", got)
+ }
+ if n := countRows(t, env, `SELECT count(*) FROM messages WHERE room_id=$1 AND author_actor_id='actor_acme_official'`, roomID); n != 0 {
+ t.Fatalf("the direct chat wrote %d messages in the other Room", n)
+ }
+}
+
+// Decision states of the card a seeded message carries the context of.
+const (
+ noCard = ""
+ cardDecided = "answered"
+ cardPending = "pending"
+)
+
+// seedDirectChatRun records a running Run of the fixture Agent's Context in
+// the direct chat whose initial input carries one new message of the given
+// kind from Alice. With a card state, the message carries the context of a
+// question card the Agent posted: one Alice answered, or one still pending,
+// which TeamHub's own reminders carry in her name.
+func seedDirectChatRun(t *testing.T, env *testEnv, directID, runID, messageID, kind, card string) {
+ t.Helper()
+ ensured, err := agentruntimestate.New(env.pool).EnsureContext(t.Context(), agentruntimestate.EnsureContextInput{TargetResidency: "active",
+ Ref: agentruntimestate.ContextRef{Kind: "meta", AgentID: acmeOfficialAgentManagementID, RoomID: directID},
+ })
+ if err != nil {
+ t.Fatalf("ensure Context: %v", err)
+ }
+ key := ensured.Context.ContextKey
+ cardID := ""
+ if card != noCard {
+ cardID = messageID + "_card"
+ decided := card == cardDecided
+ for _, statement := range []struct {
+ query string
+ args []any
+ }{
+ {`INSERT INTO messages(id,tenant_id,room_id,author_actor_id,body,segments,message_kind)
+ VALUES($1,$2,$3,'actor_acme_official','Where should we go?','[{"type":"text","content":"Where should we go?"}]'::jsonb,'conversation')`,
+ []any{cardID, acmeTenant, directID}},
+ {`INSERT INTO message_cards(message_id,tenant_id,room_id,decision_owner_actor_id,card_type,intent)
+ VALUES($1,$2,$3,'actor_acme_alice','personal_notice','decision_requested')`,
+ []any{cardID, acmeTenant, directID}},
+ {`INSERT INTO decisions(id,tenant_id,room_id,message_id,kind,requested_by_actor_id,decider_actor_id,
+ status,request,view,answer,decided_at,decided_by_actor_id,finished_at)
+ VALUES($1,$2,$3,$4,'question','actor_acme_official','actor_acme_alice',
+ CASE WHEN $5 THEN 'answered' ELSE 'pending' END,'{}'::jsonb,
+ '{"prompt":"Where?","questions":[{"id":"q1","prompt":"Where?","input":"radio","options":[{"id":"o1","label":"Lake"}]}]}'::jsonb,
+ CASE WHEN $5 THEN '{"decision":"submit","answers":{"q1":"Lake"}}'::jsonb END,
+ CASE WHEN $5 THEN clock_timestamp() END,
+ CASE WHEN $5 THEN 'actor_acme_alice' END,
+ CASE WHEN $5 THEN clock_timestamp() END)`,
+ []any{"decision_" + cardID, acmeTenant, directID, cardID, decided}},
+ } {
+ if _, err := env.pool.Exec(t.Context(), statement.query, statement.args...); err != nil {
+ t.Fatalf("seed card %s: %v", cardID, err)
+ }
+ }
+ }
+ for _, statement := range []struct {
+ query string
+ args []any
+ }{
+ {`INSERT INTO messages(id,tenant_id,room_id,author_actor_id,body,segments,message_kind,card_context_message_id)
+ VALUES($1,$2,$3,'actor_acme_alice','Please plan it','[{"type":"text","content":"Please plan it"}]'::jsonb,$4,NULLIF($5,''))`,
+ []any{messageID, acmeTenant, directID, kind, cardID}},
+ {`INSERT INTO agent_local_runs(run_id,context_key,status,started_at,status_room_id) VALUES($1,$2,'running',clock_timestamp(),$3)`,
+ []any{runID, key, directID}},
+ {`INSERT INTO agent_runtime_inputs(context_key,input_id,input_sequence,payload,payload_hash,source_kind,source_message_id,source_inbox_id,status,local_run_id)
+ VALUES($1,$2,1,jsonb_build_object('invocationMessageIds',jsonb_build_array($3::text)),decode(repeat('00',32),'hex'),'inbox',$3,'room:'||$4,'handled',$5)`,
+ []any{key, "input_" + runID, messageID, directID, runID}},
+ {`INSERT INTO agent_local_run_inputs(run_id,context_key,input_id,relation,ordinal) VALUES($1,$2,$3,'initial',0)`,
+ []any{runID, key, "input_" + runID}},
+ } {
+ if _, err := env.pool.Exec(t.Context(), statement.query, statement.args...); err != nil {
+ t.Fatalf("seed direct chat Run %s: %v", runID, err)
+ }
+ }
+}
+
+// postRoomHandoff calls the handoff route as the CLI of runID in the given
+// Room Context; an empty runID sends no Run header.
+func postRoomHandoff(t *testing.T, env *testEnv, token, contextID, runID string, input map[string]any) (int, map[string]any) {
+ t.Helper()
+ encoded, err := json.Marshal(input)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request, err := http.NewRequestWithContext(t.Context(), http.MethodPost, env.server.URL+"/api/agent/v1/room-handoffs", bytes.NewReader(encoded))
+ if err != nil {
+ t.Fatal(err)
+ }
+ request.Header.Set("Authorization", "Bearer "+token)
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("X-TeamHub-Context-Kind", "room")
+ request.Header.Set("X-TeamHub-Context-Id", contextID)
+ if runID != "" {
+ request.Header.Set("X-TeamHub-Run-Id", runID)
+ }
+ response, err := http.DefaultClient.Do(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer response.Body.Close()
+ var body map[string]any
+ _ = json.NewDecoder(response.Body).Decode(&body)
+ return response.StatusCode, body
+}
diff --git a/contracts/generated/go/teamhubagentapi/openapi.gen.go b/contracts/generated/go/teamhubagentapi/openapi.gen.go
index 83ad040e..9aed6790 100644
--- a/contracts/generated/go/teamhubagentapi/openapi.gen.go
+++ b/contracts/generated/go/teamhubagentapi/openapi.gen.go
@@ -2244,6 +2244,36 @@ type AgentRoomCreationEffectivePayload struct {
Name string `json:"name"`
}
+// 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 {
+ // Instruction Self-contained instruction for the AnotherMe in the target Room. Hidden from the Room's timeline; the receiving Context decides what to post there.
+ Instruction string `json:"instruction"`
+
+ // InvocationId Stable SHA-256 operation identity derived by the CLI from the Agent identity, command, and caller operation ID. Credential rotation and Runtime restarts do not change it.
+ InvocationId AgentInvocationId `json:"invocation_id"`
+
+ // RoomId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ RoomId Id `json:"room_id"`
+}
+
+// AgentRoomHandoffResponse The handoff posted in the target Room.
+type AgentRoomHandoffResponse struct {
+ // Accepted Whether TeamHub posted the handoff.
+ Accepted bool `json:"accepted"`
+
+ // DuplicateRequest True only when the server recovered a prior committed operation.
+ DuplicateRequest bool `json:"duplicate_request"`
+
+ // HandoffId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ HandoffId Id `json:"handoff_id"`
+
+ // InboxId Canonical public Inbox of the target Room.
+ InboxId string `json:"inbox_id"`
+
+ // Reason Optional public receipt explanation.
+ Reason *string `json:"reason,omitempty"`
+}
+
// AgentRoomMembersRequest defines model for AgentRoomMembersRequest.
type AgentRoomMembersRequest struct {
InboxId string `json:"inbox_id"`
@@ -3309,6 +3339,9 @@ type WriteAgentPersonalProfileJSONRequestBody = AgentPersonalProfileWriteRequest
// SendAgentPresentationSequenceJSONRequestBody defines body for SendAgentPresentationSequence for application/json ContentType.
type SendAgentPresentationSequenceJSONRequestBody = AgentSendPresentationSequenceRequest
+// HandOffAgentRoomWorkJSONRequestBody defines body for HandOffAgentRoomWork for application/json ContentType.
+type HandOffAgentRoomWorkJSONRequestBody = AgentRoomHandoffRequest
+
// AddAgentRoomMemberJSONRequestBody defines body for AddAgentRoomMember for application/json ContentType.
type AddAgentRoomMemberJSONRequestBody = AgentAddRoomMemberRequest
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 be862421..9a93288d 100644
--- a/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts
@@ -564,6 +564,26 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/agent/v1/room-handoffs": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Hand a Human's request from the direct chat to the calling AnotherMe in another Room
+ * @description Authorizes an AnotherMe Meta Context in its direct chat with its Human, in a Run that the Human's own message there started. TeamHub posts one hidden handoff message in the target Room, where the Human and the AnotherMe must both be members, and it wakes the AnotherMe's Context in that Room to carry out the instruction. The caller never writes in the target Room itself. The invocation_id makes a replay return the original handoff.
+ */
+ post: operations["handOffAgentRoomWork"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/agent/v1/routines": {
parameters: {
query?: never;
@@ -2340,6 +2360,28 @@ export interface components {
/** @description Whether this invocation created the sponsor Direct Room. */
room_created: boolean;
};
+ /** @description 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. */
+ AgentRoomHandoffRequest: {
+ invocation_id: components["schemas"]["AgentInvocationId"];
+ room_id: components["schemas"]["Id"];
+ /** @description Self-contained instruction for the AnotherMe in the target Room. Hidden from the Room's timeline; the receiving Context decides what to post there. */
+ instruction: string;
+ };
+ /** @description The handoff posted in the target Room. */
+ AgentRoomHandoffResponse: {
+ /** @description True only when the server recovered a prior committed operation. */
+ duplicate_request: boolean;
+ /** @description Optional public receipt explanation. */
+ reason?: string;
+ /**
+ * @description Whether TeamHub posted the handoff.
+ * @constant
+ */
+ accepted: true;
+ /** @description Canonical public Inbox of the target Room. */
+ inbox_id: string;
+ handoff_id: components["schemas"]["Id"];
+ };
/** @enum {string} */
AgentRoutineWeekday:
| "monday"
@@ -3819,6 +3861,36 @@ export interface operations {
default: components["responses"]["InternalError"];
};
};
+ handOffAgentRoomWork: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["AgentRoomHandoffRequest"];
+ };
+ };
+ responses: {
+ /** @description The handoff is in the target Room and wakes the AnotherMe there. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentRoomHandoffResponse"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["Forbidden"];
+ 409: components["responses"]["Conflict"];
+ 503: components["responses"]["ServiceUnavailable"];
+ default: components["responses"]["InternalError"];
+ };
+ };
createAgentRoutine: {
parameters: {
query?: never;
diff --git a/contracts/openapi/components/agent-collaboration.yaml b/contracts/openapi/components/agent-collaboration.yaml
index 31d093d6..ba3b8043 100644
--- a/contracts/openapi/components/agent-collaboration.yaml
+++ b/contracts/openapi/components/agent-collaboration.yaml
@@ -439,6 +439,58 @@ components:
description: One non-empty user-visible private message body.
minLength: 1
maxLength: 50000
+ AgentRoomHandoffRequest:
+ type: object
+ description: >-
+ 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.
+ additionalProperties: false
+ required:
+ - invocation_id
+ - room_id
+ - instruction
+ properties:
+ invocation_id:
+ $ref: "#/components/schemas/AgentInvocationId"
+ room_id:
+ $ref: "./common.yaml#/components/schemas/Id"
+ instruction:
+ type: string
+ description: >-
+ Self-contained instruction for the AnotherMe in the target Room. Hidden from
+ the Room's timeline; the receiving Context decides what to post there.
+ minLength: 1
+ maxLength: 8000
+ AgentRoomHandoffResponse:
+ type: object
+ description: The handoff posted in the target Room.
+ additionalProperties: false
+ required:
+ - duplicate_request
+ - accepted
+ - inbox_id
+ - handoff_id
+ properties:
+ duplicate_request:
+ type: boolean
+ description: True only when the server recovered a prior committed operation.
+ reason:
+ type: string
+ minLength: 1
+ description: Optional public receipt explanation.
+ accepted:
+ type: boolean
+ const: true
+ description: Whether TeamHub posted the handoff.
+ inbox_id:
+ type: string
+ description: Canonical public Inbox of the target Room.
+ minLength: 6
+ maxLength: 69
+ pattern: "^room:[A-Za-z0-9][A-Za-z0-9_-]*$"
+ handoff_id:
+ $ref: "./common.yaml#/components/schemas/Id"
AgentSendDirectMessageResponse:
type: object
description: >-
diff --git a/contracts/openapi/teamhub-agent-api/openapi.yaml b/contracts/openapi/teamhub-agent-api/openapi.yaml
index c1549a72..759f7c8c 100644
--- a/contracts/openapi/teamhub-agent-api/openapi.yaml
+++ b/contracts/openapi/teamhub-agent-api/openapi.yaml
@@ -554,6 +554,46 @@ paths:
$ref: "../components/agent-api-errors.yaml#/components/responses/ServiceUnavailable"
default:
$ref: "../components/agent-api-errors.yaml#/components/responses/InternalError"
+ /api/agent/v1/room-handoffs:
+ post:
+ tags: [Agent Business API]
+ operationId: handOffAgentRoomWork
+ summary: Hand a Human's request from the direct chat to the calling AnotherMe in another Room
+ description: >-
+ Authorizes an AnotherMe Meta Context in its direct chat with its Human, in a Run
+ that the Human's own message there started. TeamHub posts one hidden handoff
+ message in the target Room, where the Human and the AnotherMe must both be
+ members, and it wakes the AnotherMe's Context in that Room to carry out the
+ instruction. The caller never writes in the target Room itself. The invocation_id
+ makes a replay return the original handoff.
+ security:
+ - agentBearer: []
+ x-deadline-ms: 5000
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-collaboration.yaml#/components/schemas/AgentRoomHandoffRequest"
+ responses:
+ "200":
+ description: The handoff is in the target Room and wakes the AnotherMe there.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-collaboration.yaml#/components/schemas/AgentRoomHandoffResponse"
+ "400":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Unauthenticated"
+ "403":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Forbidden"
+ "409":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Conflict"
+ "503":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/ServiceUnavailable"
+ default:
+ $ref: "../components/agent-api-errors.yaml#/components/responses/InternalError"
/api/agent/v1/routines:
post:
tags: [Agent Business API]