# Agent collaboration: tool surface

Contract: [Agent collaboration](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collaboration.html). Eight implementations compared: [comparison](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collab-comparison.html).

## Four domains

| Domain | What it is | Tools |
| --- | --- | --- |
| Planning: task | A hand-kept plan: a named task and its steps. Editing runs nothing. | `task_start`, `task_step`, `task_list` |
| Execution: job | An admitted record with `execution_id`, state and result | `read_conversation(execution_id)`, `list_agents`, `close_agent`; `execution.cancel` is a command for the UI and API |
| Entities: agent | A running conversation branch. A saved `AgentSpec` is separate configuration chosen by `agent`. | `agent`, `list_agents`, `close_agent` |
| Communication: message | Continues a branch or reads its history | `send_message`, `read_conversation` |

The domains describe resources, not disjoint namespaces. Cancelling work neither archives the branch nor deletes its configuration.

Background dispatch returns `execution_id`. `details.job_id` and `attach.job_id` keep their names: pass the execution ID there. No `task_id` aliases.

## Four actions

| Action | Call | Effect | Returns |
| --- | --- | --- | --- |
| Create | `agent(prompt, description, …)` | New branch named by `description`; runs `prompt`; admits a Job | Foreground: waits, final result. `run_in_background=true`: `execution_id`. |
| Assign | `send_message(to="name", message=…)` | Existing branch, conversation or Agent; admits a Job; queues if busy | `execution_id` |
| Wait | `send_message(to="name", notify_when_idle=true)` | Delivers nothing; one notice when the target is idle | The latest reply now, or a watch |
| Query | `list_agents`, `read_conversation`, `task_list` | Read-only, starts nothing | Text |

Foreground creation goes through `run_agent_turn` and `runner.spawn_job(wait=True)`: waiting neither exempts it from admission and resource limits nor removes its execution identity.

## Messages and assignments

| Guarantee | `send_message` | `agent()` |
| --- | --- | --- |
| Who may initiate | An enabled sender, to a resolvable unarchived branch | An enabled caller; output ownership and control authority constrain the resulting `execution_id` |
| Execution ID | Always, queued or direct | Always; foreground returns the result instead |
| Result | Background work tells its sender automatically when it ends (below). An explicit `send_message` reply is optional. Terminal outcome: result, error or cancellation. | Background work tells its sender automatically when it ends (below). An explicit `send_message` reply is optional. Terminal outcome: result, error or cancellation. |
| Cancel | Cancelling cannot withdraw a recorded message; its admitted execution follows canonical authority. A receipt is not an execution ID. | `execution.cancel` with `execution_id` and `expected_version`: queued work is withdrawn, running work enters cancellation |
| Cascade | Follows the execution-parent relationship: stopping a task stops all it spawned | Follows the execution-parent relationship: stopping a task stops all it spawned |
| Someone else's task | A known execution ID grants no control | `read_conversation` and `close_agent` allow the target execution session, the caller session or a qualifying ancestor. Control separately checks owner, project, session, action and expected version. |
| Concurrent | A receipt acknowledges delivery or queueing, not completion | A busy target queues the task and is not interrupted |

**Automatic completion notice**

- Every path ending a job goes through `_update_attach_card`: patches the card, finalizes `archive_when_done`, then `notices.queue(job)`.
- A finished, failed or stopped background agent, or the reply to a `send_message`, starts a notice turn in the sending conversation, in one result shape. Nothing is said for an agent the sender closed with `close_agent`.
- A mid-turn conversation gets it when the foreground turn ends; everything finished meanwhile shares one notice. Pending notices live in `<caller-session-dir>/notices.json` and survive a restart.
- The notice lands at the delivery session's HEAD and advances it, so results form one serial chain. A spawn's report is in context through its attach pointer; a delivery to an existing branch carries the reply inline.
- `send_message(to=…, notify_when_idle=true)` with no message rides the same queue and reports the target's latest reply once it goes idle.

## Limits on a chain

| Setting, default 0 = no limit | Counts | When exceeded |
| --- | --- | --- |
| `agent.max_spawn_depth` | Generations of new branches, default 1. Only creation adds. 1: a worker cannot spawn; 2: one more generation. | The creation is refused with a reason ("complete it yourself"). Messages stay if the hop and message budgets remain. |
| `agent.max_messages` | Creation and `send_message` across the chain, including A and B exchanges | New delivery refused. `read_conversation` and `close_agent` are unaffected. |
| `agent.max_spawn_fanout` | Agents created per (session, turn). A spawn passes counters to the child and leaves the parent's, so chain counters cannot count siblings. | That call is refused and tools stay: the list is frozen at turn start. |

```
openprogram config set agent.max_spawn_depth 2
openprogram config set agent.max_messages 8
openprogram config set agent.max_spawn_fanout 8
```

Live, stored in the `agent` section of `~/.openprogram/config.json`, and in Settings → Agent.

- A completion notice re-binds the finished job's message count without adding one. Generation depth returns to the dispatcher's value: reading results is not creating, so a coordinator can start the next batch.
- Admission is independent: `max_jobs_per_session`, `max_queued_per_session`, `max_live_per_session`; see [resource governance](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/reliability/agent-resource-governance.html).
- Self-messaging is always refused: `to=` addressing the initiator's current branch is a direct cycle.

## Archiving

Branches stay in the session DAG. Archiving writes `archived: true` into the branch's shared metadata, seen by every sender. Set by `archive_agent(to="name")` or by `agent(archive_when_done=true)` on completion.

| Call on an archived branch | Result |
| --- | --- |
| `send_message(to=…)` | Refused by the shared address resolver, once the address resolves to the tip |
| `list_agents` default view | Left out |
| `list_agents(scope="archived")` | Listed |
| `read_conversation(…)` | Full transcript |
| `agent(start_from="SID:MSG_ID")` | Forks a new branch. This is the only way on; there is no unarchive. |

## Scenarios

**Dispatch a batch of tasks**

1. `task_start(title=…, steps=[…])`, one step per piece of work, in the order they depend on each other.
2. One background `agent(prompt, description, run_in_background=true)` call per task; each hands back its `execution_id` immediately.
3. `list_agents()` for running work; `read_conversation(execution_id)` for output; `close_agent` or the UI to stop.
4. Completion notices arrive in the caller.
5. `task_step(next=true)` as each returns; a sub-agent can tick its own step with `task_step(step=N)`.

**Reuse an existing agent**

1. `list_agents(scope="all")`: grouped by session, with name, usable `to="SID:HEAD"`, turn count, approximate word count and tail preview.
2. `send_message(to="name", message=…)` to ask, notify, or give it work; its reply comes back as a notice.
3. A busy target queues the work, without interruption or loss, until the current turn finishes.

**Inspect an old conversation**

1. `list_agents(scope="all")` for the address and size.
2. `read_conversation(session_id="SID:HEAD", start_turn=-10)`: negatives count from the end.
3. `include_function_calls=false` for text only; the default includes tools, arguments and results.
4. `max_chars=60000` drops later turns past the limit. Archived branches stay readable.

## Interface

| Interface | Contract |
| --- | --- |
| `agent` | Create and run a branch, or dispatch with `to`. Saved AgentSpec creation is a different operation. |
| `read_conversation(execution_id)` | Status, and the reply once terminal, without waiting |
| `close_agent(target)` | Stops an owned execution with its descendants and archives its branch |
| `execution.cancel` | The Web UI submits execution ID, expected status version and command ID through the control endpoint |
| `list_agents` | Conversation branches and running work, not the AgentSpec registry |

The [comparison](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/collaboration/agent-collab-comparison.html) is design context; external tool names are not aliases.

## Attach cards

A call at message A in source session S creating a branch in T persists an attach node in S with `predecessor=A`, `extra.attach.session_id=T`, `extra.attach.head_id=H`. Stream `data.session_id=S` picks the conversation; `card_id` is stable. There is no `attach.caller_session_id`.

| Operation | Session | Locator |
| --- | --- | --- |
| Load or update the card | S, from a transcript read or `transcript_update` | Attach node ID |
| Place at the call site | S | `predecessor`; live `tool_call_id`, legacy ordered fallback |
| Inspect the branch | T = `attach.session_id` | `attach.head_id`; absent while a background branch runs |
| Status or cancel | Execution authority, independent of placement | `job_id`; canonical `execution_id` and `status_version` |

The mapper attaches cards to caller messages in S; AssistantBubble separates same-session and external cards. A cross-session target is not a DAG node in S: resolve H in T, never search S for H or move the card.

## Implementation status

| State | Items |
| --- | --- |
| Verified | Tool inventory, identifier compatibility, Job admission, message delivery and receipts, attach fields, manual and `archive_when_done` archive, automatic completion notice, output reads after message-budget exhaustion |
| Open | Archiving an address with `close_agent` has no creator check: any local session with the tool may archive another branch. `read_conversation` has no target-level owner or project ACL. The full AttachCard's cross-session Open navigates to T without selecting H, while the execution strip checks out T and H; both should open the same branch and show an unavailable target without moving the card. |

**Code**

- [Registered model tools](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/programs/tools/agents/agent/__init__.py), [job_output](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/programs/tools/agents/agent/job_output/job_output.py)
- [Attach nodes](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/conversation/peer_agents/sub_agent_run.py), [AttachCard](https://github.com/Fzkuji/OpenProgram/blob/main/apps/web/components/chat/messages/cards/attach-card.tsx), [row projection](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/interfaces/server/transcript/rows.py)
- [Job completion](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/jobs/runner/progress.py), [notices](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/jobs/notices.py), [dispatch](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/jobs/runner/dispatch.py), [borrowed claims](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/runtime/jobs/runner/borrowed.py)
- [Message delivery](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/programs/tools/agents/send_message/send_message/send_message.py), [history reading](https://github.com/Fzkuji/OpenProgram/blob/main/openprogram/programs/tools/knowledge/read_conversation.py)
