Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(agent): add durable local-agent standby
Rahman1aef99582652
diff --git a/.env.example b/.env.exampleindex 5d905719..993e5a02 100644--- a/.env.example+++ b/.env.example@@ -245,6 +245,7 @@ OS_SESSION_SECRET=# Native Local Agents use private defaults; overrides are normally unnecessary.# OS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.json # live receive leases/aliases (0600)# OS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json # durable explicit local messages/tasks (0600)+# OS_LOCAL_AGENT_STANDBY_STORE=~/.mso/private/local-agent-standby.json # durable workflow-bound standby/claim state (0600)# OS_ORGANIZATION_STORE=~/.mso/private/organization.json # owner-private org units/seats/reporting/agent bindings (0600)# OS_LOCAL_AGENT_LEASE_MS=60000 # receiver lease; CLI heartbeat is lighter than this expiry# OS_TOOL_FORGE_DIR=~/.mso/tool-forge # private inert Tool Forge candidate/evaluation recordsdiff --git a/app/api/v1/alfa/cockpit/route.test.ts b/app/api/v1/alfa/cockpit/route.test.tsindex e6df1e4c..e4894399 100644--- a/app/api/v1/alfa/cockpit/route.test.ts+++ b/app/api/v1/alfa/cockpit/route.test.ts@@ -30,7 +30,7 @@ beforeEach(() => {mocks.readConfig.mockResolvedValue({ provider: "openai", model: "gpt-test", tokenSaver: "ponytail" });mocks.listProjects.mockResolvedValue({ total: 1, hasMore: false, scan: { truncated: false }, projects: [{ id: "root/mso", name: "mso", path: "/srv/mso", packageName: "mso", git: { branch: "main", head: "abcdef" } }] });mocks.sessions.mockResolvedValue([{ id: "s1", name: "luna", source: "cli", title: "Debug updater", updatedAt: "2026-09-04T00:00:00Z", estimatedTokens: 1200, eventCount: 4 }]);- mocks.agents.mockResolvedValue([{ id: "s2", name: "milo", label: "[milo]", status: "idle", title: "Worker", lastSeenAt: "2026-09-04T00:00:00Z" }]);+ mocks.agents.mockResolvedValue([{ id: "s2", name: "milo", label: "[milo]", status: "offline", title: "Worker", consumerConnected: false, standbyArmed: true, standbyState: "waiting", standbyWorkflowId: "wf-1", actionable: true, queuedCount: 0, lastSeenAt: "2026-09-04T00:00:00Z" }]);mocks.memories.mockResolvedValue([{ id: "legacy1", text: "prefers concise output", createdAt: 1 }]);mocks.typed.mockResolvedValue({ records: [{ record: { id: "m1", document: "USER.md", key: "editor", value: "zed", kind: "semantic", confidence: 1, sensitivity: "normal", provenance: { authority: "explicit", observedAt: "2026-09-04T00:00:00Z" } }, conflicts: [] },@@ -54,7 +54,15 @@ describe("Alfa cockpit read model", () => {expect(body.model).toEqual({ provider: "openai", model: "gpt-test", tokenSaver: "ponytail" });expect(body.projects.rows[0]).toMatchObject({ id: "root/mso", name: "mso" });expect(body.sessions[0]).toMatchObject({ name: "luna", source: "cli" });- expect(body.localAgents[0]).toMatchObject({ label: "[milo]", status: "idle" });+ expect(body.localAgents[0]).toMatchObject({+ label: "[milo]",+ status: "offline",+ consumerConnected: false,+ standbyArmed: true,+ standbyState: "waiting",+ actionable: true,+ queuedCount: 0,+ });expect(body.typedMemory.records[0]).toMatchObject({ key: "editor", value: "zed" });expect(body.typedMemory.records[1]).toMatchObject({ key: "Private memory", value: "Private memory", sensitivity: "private" });expect(body.legacyMemoryCount).toBe(1);diff --git a/app/api/v1/alfa/cockpit/route.ts b/app/api/v1/alfa/cockpit/route.tsindex 229de1f9..36f864eb 100644--- a/app/api/v1/alfa/cockpit/route.ts+++ b/app/api/v1/alfa/cockpit/route.ts@@ -126,6 +126,12 @@ export async function GET(req: NextRequest) {label: agent.label,status: agent.status,title: agent.title,+ consumerConnected: agent.consumerConnected,+ standbyArmed: agent.standbyArmed,+ standbyState: agent.standbyState,+ standbyWorkflowId: agent.standbyWorkflowId,+ actionable: agent.actionable,+ queuedCount: agent.queuedCount,cwd: agent.cwd,lastSeenAt: agent.lastSeenAt,})),diff --git a/app/mcp/route.ts b/app/mcp/route.tsindex d44ff87e..2c878b3d 100644--- a/app/mcp/route.ts+++ b/app/mcp/route.ts@@ -11,6 +11,7 @@ import { MCP_SERVER_VERSION } from "@/lib/mcp/toolset";import { visibleToolsForProfile } from "@/lib/mcp/tool-contract";import { mcpSessionHeaders, resolveMcpSession } from "@/lib/mcp/session-context";import { msoCapabilityRuntime } from "@/lib/mcp/capability-runtime";+import { ensureLocalAgentStandbyRuntime } from "@/lib/agent/local-agent-standby";export const runtime = "nodejs";export const dynamic = "force-dynamic";@@ -99,6 +100,10 @@ export async function POST(req: Request) {...(token.toolArgumentConstraints ? { toolArgumentConstraints: token.toolArgumentConstraints } : {}),capabilities: msoCapabilityRuntime,};+ // Rehydrate durable standby listeners after process restart. This only reads+ // persisted control-plane state and schedules eligible work; it never keeps+ // the current MCP request open for model execution.+ await ensureLocalAgentStandbyRuntime(msoCapabilityRuntime).catch(() => undefined);const result = await dispatch(rpc, effectiveScope, actor, agentContext);return Response.json(wire.modern ? modernMcpResult(result, MCP_SERVER_VERSION) : result, { status: wire.modern && (result.error as { code?: number } | undefined)?.code === -32601 ? 404 : 200, headers });}diff --git a/docs/A2A.md b/docs/A2A.mdindex 35e84e3c..d36d9242 100644--- a/docs/A2A.md+++ b/docs/A2A.md@@ -90,7 +90,9 @@ The Settings → **A2A** panel exposes the same flow, shows the one-time token oMSO 1.9 separates live same-host session communication from this remote interoperability protocol. `/agents`, `/message`, local `/delegate`, local inbox delivery, and the `local_agent_*` MCP tools use a private **presence lease + durable mailbox + SSE/event-bus** layer. They require no Agent Card, URL, registration, credential, refresh, or restart when another session appears or is renamed.-See [Local Agents](./LOCAL-AGENTS.md) for lifecycle (`ready` / `idle` / `busy` / `offline` / `ended`), short `@name` handles, receiver-subscription observability, delivery statuses, storage, TUI commands, tools, and API.+See [Local Agents](./LOCAL-AGENTS.md) for lifecycle (`ready` / `idle` / `busy` / `offline` / `ended`), short `@name` handles, foreground receiver observability, durable standby, delivery statuses, storage, TUI commands, tools, and API.++Durable Local Agent standby does **not** create a second orchestration engine. Once a structured local request is safely claimed, MSO executes it through the same bounded durable-session/A2A task machinery already used by `local_agent_request`; only the host-local mailbox/listener/claim layer is new. Public A2A keeps its own standard authenticated task lifecycle and trust boundary, but both paths converge on the existing bounded agent execution semantics rather than duplicating a model runtime.The older `mso a2a local ...` and loopback virtual-card helpers remain as compatibility/protocol-testing surfaces for one-shot local delegation. They are not the native live-session transport. `OS_A2A_ALLOW_LOOPBACK=0` can disable those legacy A2A-over-loopback paths without disabling Local Agents.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex d955b71c..fdf8e827 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.## 2026-09-20+**Added**++- `agent` add durable local-agent standby+**Fixed**- `chatgpt` stage portable OpenAI plugin packagediff --git a/docs/CHATGPT-PLUGIN.md b/docs/CHATGPT-PLUGIN.mdindex 60f82f59..988f8c49 100644--- a/docs/CHATGPT-PLUGIN.md+++ b/docs/CHATGPT-PLUGIN.md@@ -133,10 +133,14 @@ The ChatGPT model profile includes:- `local_agent_inbox`- `local_agent_reply`- `local_agent_request_wait`+- `local_agent_standby`+- `local_agent_request``local_agent_inbox(wait_ms=1..20000)` keeps only the current foreground MCP request open, registers the existing in-process Local Agent receiver, and returns early when another same-principal session sends a message. Durable file-backed mailbox state remains authoritative and closes the read→subscribe race. There is no DB, webhook, broker, WebSocket or spawned worker in this path.-A completely idle ChatGPT conversation still cannot be awakened by a remote MCP server. Its durable mail is delivered on its next MCP call. `local_agent_request` and `agent_subagent_run` are part of the ChatGPT model profile; their existing scope, isolation, and server-side authorization rules remain authoritative.+`local_agent_standby(mode="listen", workflow_id=...)` adds a different contract: the exec-scoped call returns immediately and arms server-native durable standby for that exact ChatGPT-bound AgentSession/workflow. After the assistant turn ends, an authorized same-owner correlated request can be claimed by MSO, executed through the existing bounded durable-session/A2A task machinery, replied to, and returned to waiting without another user `[continue]`. `consumerConnected` remains false unless a real foreground inbox receiver is actually subscribed.++This capability wakes the **durable MSO worker**, not the ChatGPT browser tab. MSO does not claim that an inactive ChatGPT conversation UI will spontaneously render a new assistant bubble; host-side relay/rendering is separate. A write-only caller cannot authorize standby execution, notify-only mail never executes, workflow finish/cancel disarms standby, and restart reconciliation rereads the durable mailbox after reinstalling standby listeners.## Original-byte file transferdiff --git a/docs/LOCAL-AGENTS.md b/docs/LOCAL-AGENTS.mdindex 78f5de79..66fe0240 100644--- a/docs/LOCAL-AGENTS.md+++ b/docs/LOCAL-AGENTS.md@@ -74,8 +74,9 @@ MSO persists both the raw role `agent` row and, only for a valid user-relay corr|---|---|---|| Talk to another **currently active** Agent session | `@name …` / correlated mailbox request | Immediate acknowledgement, durable queue, target processes only on its own explicit turn, async reply relays by correlation. || Send passive information | `/message` / `local_agent_message_send` | Notify-only by default; no synthetic assistant reply. Explicit low-level callers may queue to known offline sessions. |-| Need a result now from another durable session context | `local_agent_request` | `exec`-gated fresh bounded worker using that saved session context. It does **not** wake/control the original terminal or ChatGPT conversation. |-| Observe one mailbox request without polling forever | `local_agent_request_wait` | Foreground bounded wait/status check (0–30s): `replied`, `target_offline`, `consumer_absent`, or `timeout`. Never resends or starts a background worker. |+| Need a result now from another durable session context | `local_agent_request` | One-shot `exec`-gated fresh bounded worker using that saved session context. |+| Keep this exact session server-actionable between ChatGPT/terminal turns | `local_agent_standby(mode="listen")` | `exec`-gated durable standby bound to the exact active workflow. The call returns immediately; authorized correlated requests are claimed, executed sequentially through the existing durable-session worker, replied to, then the session returns to waiting. |+| Observe one mailbox request without polling forever | `local_agent_request_wait` | Foreground bounded wait/status check (0–30s): `replied`, `target_offline`, `consumer_absent`, or `timeout`. Never resends the request. |## Request/reply correlation@@ -102,7 +103,11 @@ Local Agents uses a small private lease store rather than rewriting the potentiaInteractive CLI sessions maintain a lightweight lease heartbeat and one SSE receive stream. There is no message polling loop. **Presence and consumption are separate signals:** `idle` means the lease is current; it does not by itself prove that an SSE receiver is subscribed. Directory rows therefore also expose `consumerConnected` and `consumerCount`. `/new` and `/resume` release the old receiver and bind the same terminal to the new durable session automatically. `/restart` keeps the exact durable session alive across process replacement and the replacement process renews its lease.-MCP conversation sessions have no persistent terminal socket, so MSO refreshes their lease around bound MCP tool calls. Toolset `2026.09.02.10` adds a KISS foreground receive path: `local_agent_inbox(wait_ms=...)` may keep one MCP call open for 0–20 seconds. A positive wait registers the same in-process Local Agent subscriber used by terminal delivery, keeps that session receivable/idle for the duration of the call, and returns early when another same-principal session sends a message. The implementation performs a second durable-mailbox read after subscribing so a message cannot be lost in the read→subscribe race. The subscriber is always removed on message, timeout, or error. When no MCP call is active, messages remain durable and are read on a later call; MSO still does not claim it can wake an idle ChatGPT conversation.+MCP conversation sessions have no persistent terminal socket, so MSO refreshes their presence lease around bound MCP tool calls. `local_agent_inbox(wait_ms=...)` remains the legacy **foreground** receive path: it may keep one MCP call open for 0–20 seconds, registers the normal receiver subscriber, performs a second durable-mailbox read to close the read→subscribe race, and always unsubscribes on message, timeout, or error.++Durable standby is a separate server-side state. `local_agent_standby(mode="listen", workflow_id=...)` is `exec`-gated, conversation-bound, and returns immediately. MSO persists the standby record in an owner-private store, registers a **standby** event listener that is deliberately excluded from `consumerConnected`, and rehydrates armed records from the durable mailbox after process restart. Directory rows therefore distinguish `consumerConnected` from `standbyArmed`, `standbyState`, `standbyWorkflowId`, `actionable`, `queuedCount`, and the current message id.++An armed offline ChatGPT session can execute a fresh bounded durable worker without a manual `[continue]`. This does **not** mean the original ChatGPT tab/socket was awakened: the server executes from the saved AgentSession context and writes a correlated result back to MSO. Whether the original ChatGPT UI later renders a new assistant bubble is a host/platform relay concern and must not be claimed unless independently observed.Only `ready`, `idle`, and `busy` sessions appear in the normal lease-active target list. `@mention` is stricter: it resolves only those rows that also have `consumerConnected=true`. An explicit lower-level send to a known `offline`/`ended` target can still retain a durable queued message; the sender receives `target_offline` instead of a false delivered status.@@ -125,8 +130,9 @@ Sender-visible statuses:| Status | Meaning ||---|---|| `delivered` | Persisted and handed to a live local receiver stream. It remains replayable until acknowledged. |-| `accepted` | Persisted for a live non-busy lease, but no receive-stream listener was present at that instant. Inspect `consumerConnected=false`; the durable inbox is authoritative. |-| `queued` | Persisted while the target is `busy`; an idle transition flushes the queue. |+| `accepted` | Persisted, but no foreground receiver or authorized standby claim has taken ownership yet. The durable inbox is authoritative. |+| `accepted_for_standby` | Persisted executable request accepted by an armed standby worker. This is **not** the same as `delivered`; execution may still be queued/claimed/running. |+| `queued` | Persisted while the foreground target is busy/offline or awaiting a compatible receiver. || `target_offline` | Target is known but its receiver is offline/ended. The message remains queued for the next receiver. || `failed` | Reserved for a delivery/store failure; schema/target errors are returned as request errors instead of fake delivery. |@@ -146,7 +152,9 @@ A message contains only the explicit `message` string plus minimal routing metadPayloads are limited to **16 KiB**, known secret-shaped values are redacted before persistence, terminal control bytes are stripped, and both private stores use owner-only `0700/0600`, no-follow reads, bounded size, security-store locking, and atomic replacement.-Receiving a local message grants no capability. The next model turn still has exactly the session's normal tool catalog, deployment scope, and `ask` / `auto-write` / `yolo` approval behavior.+Receiving a local message grants no capability. Standby state is control-plane metadata, not authorization. A request is auto-executable only when its durable mailbox metadata was created by an `exec`-scoped caller; a `write` caller may enqueue the same structured request but cannot authorize execution. `notify` and `reply` never wake the model worker. The bounded durable-session worker still uses the target session's normal capability/scope enforcement and receives only the explicit objective plus saved safe session context.++Standby uses one active command per session. A durable message claim plus a session execution lease prevents event/restart races from creating overlapping workers. On crash, an expired claim can be recovered idempotently; MSO promises at-most-one **active** execution, not impossible-to-prove exactly-once external side effects after a process dies between an external mutation and its completion marker. `workflow_finish` and `workflow_cancel` disarm the matching standby record, and every dispatch revalidates the exact workflow before model execution.## MCP tools@@ -154,8 +162,9 @@ Local messaging has explicit tools so it cannot be confused with public A2A peer| Tool | Scope | Purpose ||---|---|---|-| `local_agents_list` | read | List same-principal sessions, including short public names plus lease status and `consumerConnected` / `consumerCount`; optionally include offline/ended targets. |-| `local_agent_message_send` | write | Backward-compatible explicit send. Default `intent=notify`; can create a durable request and may explicitly queue to known offline targets. |+| `local_agents_list` | read | List same-principal sessions with lease/foreground receiver state **and** separate durable standby/actionable state. |+| `local_agent_standby` | exec | `listen` arms this exact conversation/workflow and returns immediately; `stop` disarms it. It never fakes `consumerConnected`. |+| `local_agent_message_send` | write | Backward-compatible explicit send. Default `intent=notify`; an exec-scoped caller can authorize a structured request for an armed standby, while write-only callers remain mailbox-only. || `local_agent_reply` | write | Reply to one exact request message ID; target, correlation ID, and relay policy are inherited. || `local_agent_request_wait` | read | Bounded 0–30s foreground wait/status for one exact sent request; returns replied/offline/no-consumer/timeout without resend. || `local_agent_inbox` | read | Read this exact durable session's mailbox with explicit intent/correlation metadata; optional `wait_ms=0..20000` makes the current foreground MCP call a bounded live receiver and returns early on peer delivery. |@@ -187,6 +196,7 @@ Defaults:```textOS_LOCAL_AGENT_PRESENCE_STORE=~/.mso/private/local-agent-presence.jsonOS_LOCAL_AGENT_MESSAGE_STORE=~/.mso/private/local-agent-messages.json+OS_LOCAL_AGENT_STANDBY_STORE=~/.mso/private/local-agent-standby.jsonOS_LOCAL_AGENT_LEASE_MS=60000```diff --git a/docs/MCP.md b/docs/MCP.mdindex 626850a2..012c70e5 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -204,7 +204,9 @@ RASMIC adds three stable generic MCP tools without coupling MSO to another reposOrganization is a separate private operating-structure domain. `organization_chart` reads units, seats, reporting lines, execution bindings, and live target status; `organization_manage` applies revision-checked mutations. Seats only reference existing Project Agent, Local Agent, or A2A targets and never copy credentials or hidden session context. Workflow graphs may reference a seat by `orgSeatId`, but the Organization registry remains the SSOT. See [Organization](./ORGANIZATION.md).-Local same-owner session collaboration is intentionally separate from public A2A. `local_agents_list` reports each durable session's short public `name`, lease status, and live receiver observability (`consumerConnected` / `consumerCount`). `local_agent_message_send` + `local_agent_reply` provide durable correlated mailbox semantics. `local_agent_inbox(wait_ms=...)` can hold one foreground MCP call for at most 20 seconds and returns early when a peer message arrives; the implementation registers the same in-process receiver used by terminal Local Agents, closes the read/subscribe race with a second durable-mailbox read, and unsubscribes on return/timeout. The default `wait_ms=0` preserves immediate reads. `local_agent_request_wait` remains the bounded wait for one exact correlated outbound request, while `local_agent_request` remains an explicit exec-gated fresh worker from another durable session context and never claims to wake/control its original terminal/ChatGPT process. Human `@name` mentions resolve active public names only.+Local same-owner session collaboration is intentionally separate from public A2A. `local_agents_list` reports presence/foreground receiver state (`consumerConnected` / `consumerCount`) separately from durable standby state (`standbyArmed`, `standbyState`, exact workflow, queue/actionable metadata). `local_agent_message_send` + `local_agent_reply` provide durable correlated mailbox semantics. `local_agent_inbox(wait_ms=...)` remains the bounded 0–20s **foreground** receiver and does not become a daemon.++`local_agent_standby` is the exec-scoped server-native path. `listen` validates the conversation-bound session plus exact active workflow, persists the armed record, subscribes a standby listener that does not increment `consumerConnected`, closes the subscribe/read race against the durable mailbox, and returns immediately. Executable requests carry structured authorization metadata; write-only requests, `notify`, and `reply` cannot wake a model worker. A durable claim + session lease enforces one active command per standby session, later requests remain queued, workflow finish/cancel disarms the record, and process restart reconciliation reinstalls listeners then drains eligible durable mail. Execution reuses the existing bounded durable-session/A2A task engine rather than introducing a second agent runtime.### Agent-to-Agent (A2A) peersdiff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 51c95d07..af166ff9 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,13 @@+## 2026-09-20 — Add durable server-native Local Agent standby++ChatGPT/MCP local-agent collaboration previously had two useful but incomplete modes: a foreground `local_agent_inbox(wait_ms)` receiver that ended with the current request, and one-shot `local_agent_request` execution from a saved durable session. A coordinator therefore could not safely leave a session waiting, send it work later, receive the result, and keep the worker available without another manual user turn.++This release adds `local_agent_standby` as an explicit exec-scoped control-plane primitive bound to the exact conversation session and active workflow. `listen` persists an owner-private standby record and returns immediately. A separate standby event channel rehydrates after process restart, rereads the durable mailbox to close subscribe/read races, atomically claims one authorized request, executes it through the existing durable-session/A2A task engine, emits the correlated reply, and returns the worker to `waiting`. Additional requests remain queued and drain sequentially. `stop`, `workflow_finish`, and `workflow_cancel` disarm the matching record; dispatch revalidates the workflow again immediately before model/tool execution.++Authorization and observability remain fail-closed. `consumerConnected` still means a real foreground receiver and standby listeners never increment it. Directory/UI state exposes `standbyArmed`, standby state/workflow, actionable state, queue count, and current message separately. Only structured correlated requests persisted by an exec-scoped caller are executable; write-only callers may enqueue but cannot grant execution, while notify/reply mail never starts a worker. Standby workers reuse the original workflow actor internally and cannot start/finish/cancel a replacement workflow. Durable message claims plus a per-session execution lease prevent overlapping event/restart workers; after a crash MSO can recover an expired claim, but intentionally does not claim exactly-once external side effects across an abrupt process death.++The implementation keeps the existing foreground inbox path, local one-shot request path, remote A2A protocol, and timed Workflow Graph wait node unchanged. Local Agent storage/dispatcher modules were split to stay inside the architecture line-count ratchet instead of raising policy limits. Targeted release regression covers immediate arm, disconnected-but-actionable presence, correlated execute/reply/waiting, duplicate event dedupe, sequential queueing, restart reconciliation, lifecycle disarm, stale workflow blocking, notify/write-scope non-execution, same-owner isolation, foreground inbox regression, local A2A worker reuse, fixed workflow propagation, MCP route/catalog/audit authorization, and Cockpit status projection.+## 2026-09-20 — Stage MSO as a portable OpenAI Agent PluginNative MCP App acceptance still returned structured data when the current ChatGPT conversation reached MSO through the generic orchestration wrapper. Server descriptors/resources were already correct, but the owner-private plugin package was legacy-only and staged rather than installed. Private staging now emits the current portable Agent Plugins layout: root `plugin.json` with `extensions.com.openai.apps`, the reviewed `claude-skills/` tree projected to root `skills/`, private redacted `.app.json`, and a rewritten `.codex-plugin/plugin.json` compatibility fallback. The doctor validates both manifests, the projected skill set, owner-only modes and registered-app binding without printing the App ID, and recognizes both portable and legacy cached installs. Repository `.app.json` remains empty and no MCP credential or maintainer-specific App ID is committed. This fixes the MSO-owned packaging gap; ChatGPT installation/refresh/selection remains host-owned and must be accepted from a new app-selected conversation.diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 1764f1b4..1cfecf25 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,18 +4,18 @@## Full MSO catalog-<!-- mcp-toolset: server=1.15.1 version=2026.09.19.5 tools=112 read=55 write=35 exec=22 -->+<!-- mcp-toolset: server=1.15.1 version=2026.09.20.1 tools=113 read=55 write=35 exec=23 -->| Fact | Current source value ||---|---:|| MCP server | `1.15.1` |-| Toolset | `2026.09.19.5` |-| Toolset changed at | `2026-09-19T22:42:49+07:00` |-| Transport tools | **114** |-| Model/operator tools | **112** |+| Toolset | `2026.09.20.1` |+| Toolset changed at | `2026-09-20T11:37:43+07:00` |+| Transport tools | **115** |+| Model/operator tools | **113** || Read | **55** || Write | **35** |-| Exec | **22** |+| Exec | **23** || App-only bridges | **2** |### Read (55)@@ -114,7 +114,7 @@- `workflow_finish`- `workflow_start`-### Exec (22)+### Exec (23)- `a2a_handoff`- `a2a_message_send`@@ -127,6 +127,7 @@- `flow_run`- `integration_execute`- `local_agent_request`+- `local_agent_standby`- `project_agent_run`- `project_database_call`- `project_database_query`@@ -146,17 +147,17 @@## ChatGPT model profile-<!-- mcp-chatgpt-profile: server=1.15.1 version=2026.09.19.5 tools=112 read=55 write=35 exec=22 app-only=2 total=114 -->+<!-- mcp-chatgpt-profile: server=1.15.1 version=2026.09.20.1 tools=113 read=55 write=35 exec=23 app-only=2 total=115 -->The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.| Fact | Current source value ||---|---:|-| ChatGPT transport tools | **114** |-| ChatGPT model/operator tools | **112** |+| ChatGPT transport tools | **115** |+| ChatGPT model/operator tools | **113** || Read | **55** || Write | **35** |-| Exec | **22** |+| Exec | **23** || App-only bridges | **2** |### ChatGPT read (55)@@ -255,7 +256,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `workflow_finish`- `workflow_start`-### ChatGPT exec (22)+### ChatGPT exec (23)- `a2a_handoff`- `a2a_message_send`@@ -268,6 +269,7 @@ The ChatGPT profile automatically projects the complete MSO-owned generic model/- `flow_run`- `integration_execute`- `local_agent_request`+- `local_agent_standby`- `project_agent_run`- `project_database_call`- `project_database_query`diff --git a/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx b/frontend/slices/assistant/components/alfa-cockpit-dialog.tsxindex 23adc87e..e3381b4b 100644--- a/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx+++ b/frontend/slices/assistant/components/alfa-cockpit-dialog.tsx@@ -97,7 +97,7 @@ export function AlfaCockpitDialog({<Section title="Native Sessions & Agents" icon={Bot}>{(data?.sessions ?? []).slice(0, 4).map((session) => <div key={session.id} className="flex gap-2 text-[11px]"><span className="min-w-0 flex-1 truncate">@{session.name} · {session.title}</span><Badge variant="outline" className="text-[9px]">{session.source}</Badge></div>)}- {(data?.localAgents ?? []).length ? <div className="flex flex-wrap gap-1.5 pt-1">{data!.localAgents.slice(0, 8).map((agent) => <Badge key={agent.id} variant="secondary">{agent.label} · {agent.status}</Badge>)}</div> : <p className="text-[10px] text-muted-foreground">No active same-owner local agents.</p>}+ {(data?.localAgents ?? []).length ? <div className="flex flex-wrap gap-1.5 pt-1">{data!.localAgents.slice(0, 8).map((agent) => <Badge key={agent.id} variant="secondary">{agent.label} · {agent.standbyArmed ? `standby ${agent.standbyState ?? "waiting"}${agent.queuedCount ? ` · ${agent.queuedCount} queued` : ""}` : agent.consumerConnected ? `${agent.status} · receiver` : agent.status}</Badge>)}</div> : <p className="text-[10px] text-muted-foreground">No actionable same-owner local agents.</p>}<p className="text-[10px] text-muted-foreground">These are durable MSO Agent sessions, separate from Alfa's browser chat history.</p></Section></ResponsiveDialog.Body>diff --git a/frontend/slices/assistant/lib/cockpit-types.ts b/frontend/slices/assistant/lib/cockpit-types.tsindex 0fbef533..c737d6cd 100644--- a/frontend/slices/assistant/lib/cockpit-types.ts+++ b/frontend/slices/assistant/lib/cockpit-types.ts@@ -56,6 +56,12 @@ export type AlfaCockpitData = {label: string;status: string;title: string;+ consumerConnected: boolean;+ standbyArmed: boolean;+ standbyState?: string;+ standbyWorkflowId?: string;+ actionable: boolean;+ queuedCount: number;cwd?: string;lastSeenAt: string;}>;diff --git a/frontend/slices/os-settings/components/mcp-session-guide.tsx b/frontend/slices/os-settings/components/mcp-session-guide.tsxindex a9711dc2..2d2fcb89 100644--- a/frontend/slices/os-settings/components/mcp-session-guide.tsx+++ b/frontend/slices/os-settings/components/mcp-session-guide.tsx@@ -32,6 +32,13 @@ export function McpSessionGuide({ sessionRef, onBack }: { sessionRef?: string; o<McpCopyField label="Wait for the reply" value={JSON.stringify({ request_message_id: "localmsg_REQUEST_ID", timeout_ms: 5000 }, null, 2)} multiline /><p className="text-xs text-muted-foreground">Tool: local_agent_request_wait · read scope. Queued or delivered does not mean completed. On timeout, check status; do not resend the same task blindly.</p></SettingsBlock>+ <SettingsBlock className="space-y-3">+ <h4 className="text-sm font-semibold">Optional: keep this session on durable standby</h4>+ <p className="text-sm">With an active workflow and exec scope, call <code>local_agent_standby</code> using <code>mode: "listen"</code>. The call returns immediately. Later authorized correlated requests can run through the saved durable session without keeping this ChatGPT tab or an MCP request open.</p>+ <McpCopyField label="Arm standby" value={JSON.stringify({ mode: "listen", workflow_id: "WORKFLOW_ID" }, null, 2)} multiline />+ <p className="text-xs text-muted-foreground"><code>consumerConnected</code> still means a real foreground receiver. Check <code>standbyArmed</code>, <code>standbyState</code>, workflow, and queued count separately. Finishing/cancelling the workflow disarms standby automatically.</p>+ <p className="text-xs text-muted-foreground">MSO can wake the durable worker; it does not promise that an inactive ChatGPT tab will spontaneously render a new assistant bubble.</p>+ </SettingsBlock><SettingsBlock className="space-y-3"><h4 className="text-sm font-semibold">Continue in the terminal</h4><McpCopyField label="CLI resume command" value={`mso agent --resume ${sessionRef || "agent-context-session"}`} />diff --git a/lib/a2a/inbound-agent.test.ts b/lib/a2a/inbound-agent.test.tsindex d30c1867..8a52a18f 100644--- a/lib/a2a/inbound-agent.test.ts+++ b/lib/a2a/inbound-agent.test.ts@@ -60,4 +60,48 @@ describe("inbound A2A model boundary", () => {sessionId: "task-123",});});++ it("locks standby delegation to the supplied workflow context and hides lifecycle controls", async () => {+ const fixedCapabilities = {+ list: vi.fn(() => [+ { name: "project_get", description: "project read", scope: "read" as const, inputSchema: { type: "object" as const, properties: { workflow_id: { type: "string" } } } },+ { name: "workflow_start", description: "start", scope: "write" as const, inputSchema: { type: "object" as const, properties: {} } },+ { name: "workflow_finish", description: "finish", scope: "write" as const, inputSchema: { type: "object" as const, properties: { workflow_id: { type: "string" } } } },+ { name: "local_agent_standby", description: "standby", scope: "exec" as const, inputSchema: { type: "object" as const, properties: { workflow_id: { type: "string" } } } },+ ]),+ invoke: vi.fn(async () => ({ content: [{ type: "text" as const, text: "ok" }] })),+ };+ let turn = 0;+ mocks.stream.mockImplementation(async ({ tools, emit }) => {+ expect(tools.map((tool: { name: string }) => tool.name)).toEqual(["project_get"]);+ if (turn++ === 0)+ emit("tool_use", { id: "call-fixed", name: "project_get", input: {} });+ else emit("delta", "fixed done");+ });+ const executionContext = {+ workflowId: "33333333-3333-4333-8333-333333333333",+ workflowActor: "mcp:standby-owner",+ fixedWorkflow: true,+ };+ const result = await runInboundA2AAgent({+ prompt: "continue",+ scope: "exec",+ principal: "a2a:local:session",+ taskId: "task-fixed",+ signal: new AbortController().signal,+ capabilities: fixedCapabilities,+ executionContext,+ });+ expect(result.text).toBe("fixed done");+ expect(fixedCapabilities.invoke).toHaveBeenCalledWith({+ name: "project_get",+ args: {},+ scope: "exec",+ actor: "a2a:local:session",+ principal: "a2a:local:session",+ sessionId: "task-fixed",+ workflowId: executionContext.workflowId,+ workflowActor: executionContext.workflowActor,+ });+ });});diff --git a/lib/a2a/inbound-agent.ts b/lib/a2a/inbound-agent.tsindex c9e09234..570efbe3 100644--- a/lib/a2a/inbound-agent.ts+++ b/lib/a2a/inbound-agent.ts@@ -7,11 +7,10 @@ import {import type { OaMsg, OaTool, OaToolUse } from "@/lib/ai/openai-stream";import type { AgentSession } from "@/lib/agent/session-types";import { buildMemoryContext } from "@/lib/agent/memory-context.mjs";-const MAX_ROUNDS = 10;const MAX_RESULT_BYTES = 64 * 1024;const MAX_OUTPUT_BYTES = 64 * 1024;-+const FIXED_WORKFLOW_DENY = new Set(["workflow_start", "workflow_finish", "workflow_cancel", "local_agent_standby"]);const EXTERNAL_TOOL_DENY = new Set(["agent_session_current","agent_sessions_list",@@ -23,7 +22,6 @@ const EXTERNAL_TOOL_DENY = new Set(["agent_memory_remember","agent_memory_forget",]);-function inboundSystem(scope: Scope, session?: AgentSession, prompt = ""): string {if (session) {const memoryContext = buildMemoryContext(session.memorySnapshot || {}, prompt, {@@ -93,9 +91,10 @@ function sessionHistory(session?: AgentSession): OaMsg[] {return out;}-function modelTools(runtime: CapabilityRuntime, scope: Scope): OaTool[] {+function modelTools(runtime: CapabilityRuntime, scope: Scope, fixedWorkflow = false): OaTool[] {return runtime.list(scope).filter(- (tool) => allows(scope, tool.scope) && !EXTERNAL_TOOL_DENY.has(tool.name),+ (tool) => allows(scope, tool.scope) && !EXTERNAL_TOOL_DENY.has(tool.name) &&+ !(fixedWorkflow && FIXED_WORKFLOW_DENY.has(tool.name)),).map((tool) => ({name: tool.name,description: tool.description,@@ -134,13 +133,14 @@ export async function runInboundA2AAgent(input: {signal: AbortSignal;onDelta?: (text: string) => void | Promise<void>;capabilities: CapabilityRuntime;+ executionContext?: { workflowId?: string; workflowActor?: string; fixedWorkflow?: boolean };}): Promise<{text: string;rounds: number;toolCalls: Array<{ name: string; ok: boolean }>;}> {const prepared = await prepareSelectedModel();- const tools = modelTools(input.capabilities, input.scope);+ const tools = modelTools(input.capabilities, input.scope, input.executionContext?.fixedWorkflow === true);const messages: OaMsg[] = [...sessionHistory(input.session),{ role: "user", text: input.prompt },@@ -193,6 +193,8 @@ export async function runInboundA2AAgent(input: {actor: input.principal,principal: input.principal,sessionId: input.taskId,+ ...(input.executionContext?.workflowId ? { workflowId: input.executionContext.workflowId } : {}),+ ...(input.executionContext?.workflowActor ? { workflowActor: input.executionContext.workflowActor } : {}),});const result = toolResultText(invoked);results.push({diff --git a/lib/a2a/local-session.test.ts b/lib/a2a/local-session.test.tsindex 1b11ad99..ececc912 100644--- a/lib/a2a/local-session.test.ts+++ b/lib/a2a/local-session.test.ts@@ -92,6 +92,30 @@ describe("same-host A2A durable-session agents", () => {await expect(handoffOwnerLocalSession("cli:owner", session.id, "answer this", capabilities, session.id)).rejects.toThrow(/same session/);});+ it("carries an optional fixed workflow execution context through the existing local A2A worker", async () => {+ const session = await bece();+ const executionContext = {+ workflowId: "22222222-2222-4222-8222-222222222222",+ workflowActor: "mcp:original-session",+ fixedWorkflow: true,+ };+ runner.mockImplementationOnce(async ({ session: target, executionContext: received }) => {+ expect(target.id).toBe(session.id);+ expect(received).toEqual(executionContext);+ return { text: "fixed workflow result", rounds: 1, toolCalls: [] };+ });+ const result = await handoffOwnerLocalSession(+ "cli:owner",+ session.id,+ "continue exact workflow",+ capabilities,+ undefined,+ executionContext,+ );+ expect(result.task.status.state).toBe("TASK_STATE_COMPLETED");+ expect(result.task.artifacts[0].parts[0].text).toBe("fixed workflow result");+ });+it("spawns a durable child agent that inherits context/cwd but has its own id", async () => {const source = await bece();runner.mockImplementationOnce(async ({ session: child, principal }) => {diff --git a/lib/a2a/local-session.ts b/lib/a2a/local-session.tsindex 908c5dd5..fb11da65 100644--- a/lib/a2a/local-session.ts+++ b/lib/a2a/local-session.ts@@ -11,7 +11,7 @@ import {import type { AgentSession } from "@/lib/agent/session-types";import type { CapabilityRuntime } from "@/lib/capabilities/runtime";import { a2aLoopbackOrigin } from "./network";-import { executeInboundA2ATask } from "./server-execution";+import { executeInboundA2ATask, type A2AExecutionContext } from "./server-execution";import { createA2ATask, taskPublicView } from "./tasks";import type { A2AAuthenticatedProfile } from "./server-protocol";@@ -43,7 +43,12 @@ export async function resolveA2ALocalSession(return resolveAgentSessionOwnerRef(ref);}-async function runLocalSessionTask(session: AgentSession, objective: string, capabilities: CapabilityRuntime) {+async function runLocalSessionTask(+ session: AgentSession,+ objective: string,+ capabilities: CapabilityRuntime,+ executionContext?: A2AExecutionContext,+) {const prompt = String(objective || "").trim();if (!prompt) throw new Error("A2A local objective is required");const principal = `a2a:local:${session.id}`;@@ -63,6 +68,7 @@ async function runLocalSessionTask(session: AgentSession, objective: string, capprompt,session,capabilities,+ executionContext,);return taskPublicView(completed);}@@ -77,12 +83,19 @@ export async function handoffA2ALocalSession(ref: string, objective: string, cap/** Execute against a same-owner durable session without requiring its terminal* process to be present. This is a fresh bounded agent run, never a TTY wake. */-export async function handoffOwnerLocalSession(principal: string, ref: string, objective: string, capabilities: CapabilityRuntime, currentSessionId?: string) {+export async function handoffOwnerLocalSession(+ principal: string,+ ref: string,+ objective: string,+ capabilities: CapabilityRuntime,+ currentSessionId?: string,+ executionContext?: A2AExecutionContext,+) {const session = await resolveAgentSessionRef(principal, ref);if (session.id === currentSessionId) throw new Error("cannot run a local agent request against the same session");return {session: agentSessionSummary(session),- task: await runLocalSessionTask(session, objective, capabilities),+ task: await runLocalSessionTask(session, objective, capabilities, executionContext),};}diff --git a/lib/a2a/server-execution.ts b/lib/a2a/server-execution.tsindex 0afbebad..d7f9248d 100644--- a/lib/a2a/server-execution.ts+++ b/lib/a2a/server-execution.ts@@ -19,12 +19,19 @@ import {} from "./server-events";import { a2aRpcOk, type A2ARpcId } from "./server-protocol";+export interface A2AExecutionContext {+ workflowId?: string;+ workflowActor?: string;+ fixedWorkflow?: boolean;+}+export async function executeInboundA2ATask(task: A2ATaskRecord,profile: A2AAuthenticatedProfile,prompt: string,session: AgentSession | undefined,capabilities: CapabilityRuntime,+ executionContext?: A2AExecutionContext,): Promise<A2ATaskRecord> {const principal = task.principal;const controller = new AbortController();@@ -51,6 +58,7 @@ export async function executeInboundA2ATask(session,signal: controller.signal,capabilities,+ executionContext,onDelta(chunk) {if (pendingDelta) {publishA2AEvent(diff --git a/lib/agent/local-agent-directory.ts b/lib/agent/local-agent-directory.tsindex b24f9d2e..a05c6d05 100644--- a/lib/agent/local-agent-directory.ts+++ b/lib/agent/local-agent-directory.ts@@ -1,9 +1,11 @@import path from "node:path";import { listAgentSessions } from "./session-store";+import { countLocalAgentExecutableMessages } from "./local-agent-mailbox";import { listLocalAgentPresence, localAgentStatus } from "./local-agent-presence";import { localAgentSubscriberCount } from "./local-agent-events";+import { listLocalAgentStandbyRecords } from "./local-agent-standby-store";import type { AgentSessionSummary } from "./session-types";-import type { LocalAgentPresenceRecord, LocalAgentTarget } from "./local-agent-types";+import type { LocalAgentPresenceRecord, LocalAgentStandbyRecord, LocalAgentTarget } from "./local-agent-types";function normalizeRef(value: string): string {const clean = String(value || "").trim();@@ -19,33 +21,47 @@ function cleanDisplayName(value: string): string {.slice(0, 80);}-function buildRows(+async function buildRows(+ principal: string,sessions: AgentSessionSummary[],presence: LocalAgentPresenceRecord[],+ standby: LocalAgentStandbyRecord[],now: number,-): LocalAgentTarget[] {- const byId = new Map(sessions.map((row) => [row.id, row]));- return presence.flatMap((entry) => {- const session = byId.get(entry.sessionId);- if (!session) return [];+): Promise<LocalAgentTarget[]> {+ const presenceById = new Map(presence.map((row) => [row.sessionId, row]));+ const standbyById = new Map(standby.map((row) => [row.sessionId, row]));+ const relevant = sessions.filter((session) => presenceById.has(session.id) || standbyById.has(session.id));+ return Promise.all(relevant.flatMap((session) => {+ const entry = presenceById.get(session.id);+ const armed = standbyById.get(session.id);const name = cleanDisplayName(session.name).toLocaleLowerCase();if (!name) return [];- const consumerCount = localAgentSubscriberCount(session.id);- return [{- id: session.id,- name,- alias: entry.alias,- label: `[${name}]`,- source: session.source,- title: session.title,- titleSource: session.titleSource,- status: localAgentStatus(entry, now),- consumerConnected: consumerCount > 0,- consumerCount,- ...(session.cwd ? { cwd: session.cwd } : {}),- lastSeenAt: entry.lastSeenAt,- }];- });+ return [Promise.resolve(countLocalAgentExecutableMessages(principal, session.id)).catch(() => 0).then((queuedCount) => {+ const consumerCount = localAgentSubscriberCount(session.id);+ const status = entry ? localAgentStatus(entry, now) : "offline";+ const standbyArmed = armed?.armed === true;+ const actionable = consumerCount > 0 || standbyArmed;+ return {+ id: session.id,+ name,+ alias: entry?.alias ?? session.id,+ label: `[${name}]`,+ source: session.source,+ title: session.title,+ titleSource: session.titleSource,+ status,+ consumerConnected: consumerCount > 0,+ consumerCount,+ standbyArmed,+ ...(armed ? { standbyState: armed.state, standbyWorkflowId: armed.workflowId, standbySince: armed.armedAt } : {}),+ actionable,+ queuedCount,+ ...(armed?.currentMessageId ? { currentCommand: armed.currentMessageId } : {}),+ ...(session.cwd ? { cwd: session.cwd } : {}),+ lastSeenAt: entry?.lastSeenAt ?? armed?.updatedAt ?? session.updatedAt,+ } satisfies LocalAgentTarget;+ })];+ }));}export async function listLocalAgents(@@ -53,12 +69,13 @@ export async function listLocalAgents(options: { currentSessionId?: string; includeOffline?: boolean; now?: number } = {},): Promise<LocalAgentTarget[]> {const now = options.now ?? Date.now();- const [sessions, presence] = await Promise.all([+ const [sessions, presence, standby] = await Promise.all([listAgentSessions(principal, 500),listLocalAgentPresence(principal),+ listLocalAgentStandbyRecords(principal),]);- return buildRows(sessions, presence, now)- .filter((row) => options.includeOffline || !["offline", "ended"].includes(row.status))+ return (await buildRows(principal, sessions, presence, standby, now))+ .filter((row) => options.includeOffline || row.actionable || !["offline", "ended"].includes(row.status)).filter((row) => !options.currentSessionId || row.id !== options.currentSessionId).sort((a, b) => a.name.localeCompare(b.name));}@@ -82,7 +99,7 @@ export async function resolveLocalAgent(const rows = await listLocalAgents(principal, { includeOffline: true });const matched = rows.filter((row) => matches(row, wanted));if (!matched.length) throw new Error("local agent target not found");- const active = matched.filter((row) => !["offline", "ended"].includes(row.status));+ const active = matched.filter((row) => row.actionable || !["offline", "ended"].includes(row.status));if (active.length > 1 || (!active.length && matched.length > 1)) {const choices = (active.length ? active : matched).map((row) => row.alias).join(" or ");throw new Error(`local agent target is ambiguous; use ${choices}`);diff --git a/lib/agent/local-agent-events.ts b/lib/agent/local-agent-events.tsindex e275789f..c3838490 100644--- a/lib/agent/local-agent-events.ts+++ b/lib/agent/local-agent-events.ts@@ -2,20 +2,21 @@ import type { LocalAgentMessageView } from "./local-agent-types";type Listener = (message: LocalAgentMessageView) => void;const listeners = new Map<string, Set<Listener>>();+const standbyListeners = new Map<string, Set<Listener>>();-export function subscribeLocalAgentMessages(sessionId: string, listener: Listener): () => void {- const set = listeners.get(sessionId) ?? new Set<Listener>();+function subscribe(registry: Map<string, Set<Listener>>, sessionId: string, listener: Listener): () => void {+ const set = registry.get(sessionId) ?? new Set<Listener>();set.add(listener);- listeners.set(sessionId, set);+ registry.set(sessionId, set);return () => {set.delete(listener);- if (!set.size) listeners.delete(sessionId);+ if (!set.size) registry.delete(sessionId);};}-export function publishLocalAgentMessage(sessionId: string, message: LocalAgentMessageView): number {+function publish(registry: Map<string, Set<Listener>>, sessionId: string, message: LocalAgentMessageView): number {let delivered = 0;- for (const listener of listeners.get(sessionId) ?? []) {+ for (const listener of registry.get(sessionId) ?? []) {try {listener(message);delivered += 1;@@ -26,10 +27,32 @@ export function publishLocalAgentMessage(sessionId: string, message: LocalAgentMreturn delivered;}+/** Foreground receiver subscription. This is the ONLY registry counted by consumerConnected. */+export function subscribeLocalAgentMessages(sessionId: string, listener: Listener): () => void {+ return subscribe(listeners, sessionId, listener);+}++/** Server-native standby subscription. Intentionally excluded from consumerConnected. */+export function subscribeLocalAgentStandbyMessages(sessionId: string, listener: Listener): () => void {+ return subscribe(standbyListeners, sessionId, listener);+}++export function publishLocalAgentMessage(sessionId: string, message: LocalAgentMessageView): number {+ return publish(listeners, sessionId, message);+}++export function publishLocalAgentStandbyMessage(sessionId: string, message: LocalAgentMessageView): number {+ return publish(standbyListeners, sessionId, message);+}+export function localAgentSubscriberCount(sessionId: string): number {return listeners.get(sessionId)?.size ?? 0;}+export function localAgentStandbySubscriberCount(sessionId: string): number {+ return standbyListeners.get(sessionId)?.size ?? 0;+}+export function localAgentConsumerConnected(sessionId: string): boolean {return localAgentSubscriberCount(sessionId) > 0;}diff --git a/lib/agent/local-agent-mailbox-storage.ts b/lib/agent/local-agent-mailbox-storage.tsnew file mode 100644index 00000000..8e1666dd--- /dev/null+++ b/lib/agent/local-agent-mailbox-storage.ts@@ -0,0 +1,101 @@+import { expandOwnerStorePath } from "@/lib/owner-store-path.js";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import os from "node:os";+import path from "node:path";+import { SESSION_ID } from "./session-files";+import { readLocalAgentStore, writeLocalAgentStore } from "./local-agent-private-store";+import type {+ LocalAgentMessageExecution,+ LocalAgentMessageView,+ LocalAgentStoredMessage,+} from "./local-agent-types";++export type LocalAgentMailboxStore = { version: 1; messages: LocalAgentStoredMessage[] };+const MAX_STORE_BYTES = 4 * 1024 * 1024;+const MAX_MESSAGES = 2000;+const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;+const STORE_PATH = expandOwnerStorePath(+ process.env.OS_LOCAL_AGENT_MESSAGE_STORE ??+ path.join(os.homedir(), ".mso", "private", "local-agent-messages.json"),+);+const EMPTY: LocalAgentMailboxStore = { version: 1, messages: [] };++function validExecution(value: unknown): value is LocalAgentMessageExecution {+ if (!value || typeof value !== "object") return false;+ const row = value as LocalAgentMessageExecution;+ return row.requested === true &&+ typeof row.authorized === "boolean" &&+ ["pending", "claimed", "completed", "failed"].includes(String(row.state)) &&+ (row.attempts === undefined || (Number.isInteger(row.attempts) && row.attempts >= 0 && row.attempts <= 1000)) &&+ (!row.claimedBy || (typeof row.claimedBy === "string" && row.claimedBy.length <= 160)) &&+ (!row.claimLeaseUntil || Number.isFinite(Date.parse(row.claimLeaseUntil))) &&+ (!row.taskId || /^task_[0-9a-f-]{36}$/.test(row.taskId)) &&+ (!row.completedAt || Number.isFinite(Date.parse(row.completedAt))) &&+ (!row.error || (typeof row.error === "string" && row.error.length <= 500));+}++function validMessage(value: unknown): value is LocalAgentStoredMessage {+ if (!value || typeof value !== "object") return false;+ const row = value as LocalAgentStoredMessage;+ return /^localmsg_[0-9a-f-]{36}$/.test(String(row.id || "")) &&+ /^[a-f0-9]{64}$/.test(String(row.principalHash || "")) &&+ SESSION_ID.test(String(row.senderSessionId || "")) &&+ SESSION_ID.test(String(row.targetSessionId || "")) &&+ typeof row.senderLabel === "string" && row.senderLabel.length <= 200 &&+ typeof row.targetLabel === "string" && row.targetLabel.length <= 200 &&+ ["message", "task"].includes(String(row.kind)) &&+ (!row.intent || ["request", "reply", "notify"].includes(String(row.intent))) &&+ (!row.correlationId || /^localcorr_[0-9a-f-]{36}$/.test(row.correlationId)) &&+ (!row.replyToMessageId || /^localmsg_[0-9a-f-]{36}$/.test(row.replyToMessageId)) &&+ (row.requiresUserRelay === undefined || typeof row.requiresUserRelay === "boolean") &&+ typeof row.text === "string" && Buffer.byteLength(row.text, "utf8") <= 16 * 1024 &&+ ["accepted", "queued", "delivered", "read"].includes(String(row.state)) &&+ (!row.execution || ((row.intent ?? "notify") === "request" && validExecution(row.execution))) &&+ Number.isFinite(Date.parse(String(row.createdAt || ""))) &&+ (!row.deliveredAt || Number.isFinite(Date.parse(row.deliveredAt))) &&+ (!row.readAt || Number.isFinite(Date.parse(row.readAt)));+}++function validStore(value: unknown): value is LocalAgentMailboxStore {+ if (!value || typeof value !== "object") return false;+ const row = value as LocalAgentMailboxStore;+ return row.version === 1 && Array.isArray(row.messages) &&+ row.messages.length <= MAX_MESSAGES && row.messages.every(validMessage);+}++export async function readLocalAgentMailboxStore(): Promise<LocalAgentMailboxStore> {+ return readLocalAgentStore(STORE_PATH, MAX_STORE_BYTES, EMPTY, validStore);+}++export function localAgentMessageView(row: LocalAgentStoredMessage): LocalAgentMessageView {+ const { principalHash: _principalHash, ...safe } = row;+ return {+ ...safe,+ intent: row.intent ?? "notify",+ requiresUserRelay: row.requiresUserRelay === true,+ ...(row.execution ? { execution: { ...row.execution } } : {}),+ };+}++function prune(messages: LocalAgentStoredMessage[], now = Date.now()): LocalAgentStoredMessage[] {+ return messages+ .filter((row) => {+ const created = Date.parse(row.createdAt);+ return Number.isFinite(created) && now - created <= RETENTION_MS;+ })+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))+ .slice(-MAX_MESSAGES);+}++export async function mutateLocalAgentMailboxStore<T>(+ mutate: (store: LocalAgentMailboxStore) => Promise<T> | T,+ options: { prune?: boolean } = {},+): Promise<T> {+ return withSecurityStoreLock(STORE_PATH, async () => {+ const store = await readLocalAgentMailboxStore();+ const result = await mutate(store);+ if (options.prune) store.messages = prune(store.messages);+ await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);+ return result;+ });+}diff --git a/lib/agent/local-agent-mailbox.ts b/lib/agent/local-agent-mailbox.tsindex 0c242282..68ed9e03 100644--- a/lib/agent/local-agent-mailbox.ts+++ b/lib/agent/local-agent-mailbox.ts@@ -1,87 +1,53 @@-import { expandOwnerStorePath } from "@/lib/owner-store-path.js";import { randomUUID } from "node:crypto";-import os from "node:os";-import path from "node:path";-import { withSecurityStoreLock } from "@/lib/security-store-lock";import { getAgentSession } from "./session-store";-import { principalHash, SESSION_ID } from "./session-files";-import { readLocalAgentStore, writeLocalAgentStore } from "./local-agent-private-store";-import type { LocalAgentMessageView, LocalAgentStoredMessage, LocalAgentStoredMessageState } from "./local-agent-types";+import { principalHash } from "./session-files";+import {+ localAgentMessageView,+ mutateLocalAgentMailboxStore,+ readLocalAgentMailboxStore,+} from "./local-agent-mailbox-storage";+import type {+ LocalAgentMessageView,+ LocalAgentStoredMessage,+ LocalAgentStoredMessageState,+} from "./local-agent-types";-type MailboxStore = { version: 1; messages: LocalAgentStoredMessage[] };-const MAX_STORE_BYTES = 4 * 1024 * 1024;-const MAX_MESSAGES = 2000;-const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;-const STORE_PATH = expandOwnerStorePath(process.env.OS_LOCAL_AGENT_MESSAGE_STORE ?? path.join(os.homedir(), ".mso", "private", "local-agent-messages.json"));-const EMPTY: MailboxStore = { version: 1, messages: [] };+const DEFAULT_CLAIM_LEASE_MS = 15 * 60_000;+const MESSAGE_ID = /^localmsg_[0-9a-f-]{36}$/;-function validMessage(value: unknown): value is LocalAgentStoredMessage {- if (!value || typeof value !== "object") return false;- const row = value as LocalAgentStoredMessage;- return /^localmsg_[0-9a-f-]{36}$/.test(String(row.id || "")) && /^[a-f0-9]{64}$/.test(String(row.principalHash || "")) &&- SESSION_ID.test(String(row.senderSessionId || "")) && SESSION_ID.test(String(row.targetSessionId || "")) &&- typeof row.senderLabel === "string" && row.senderLabel.length <= 200 && typeof row.targetLabel === "string" && row.targetLabel.length <= 200 &&- ["message", "task"].includes(String(row.kind)) && (!row.intent || ["request", "reply", "notify"].includes(String(row.intent))) &&- (!row.correlationId || /^localcorr_[0-9a-f-]{36}$/.test(row.correlationId)) && (!row.replyToMessageId || /^localmsg_[0-9a-f-]{36}$/.test(row.replyToMessageId)) &&- (row.requiresUserRelay === undefined || typeof row.requiresUserRelay === "boolean") && typeof row.text === "string" && Buffer.byteLength(row.text, "utf8") <= 16 * 1024 &&- ["accepted", "queued", "delivered", "read"].includes(String(row.state)) && Number.isFinite(Date.parse(String(row.createdAt || ""))) &&- (!row.deliveredAt || Number.isFinite(Date.parse(row.deliveredAt))) && (!row.readAt || Number.isFinite(Date.parse(row.readAt)));+async function requireSession(principal: string, sessionId: string, label = "target"): Promise<void> {+ if (!await getAgentSession(principal, sessionId))+ throw new Error(`local agent ${label} not found for this client`);}-function validStore(value: unknown): value is MailboxStore {- if (!value || typeof value !== "object") return false;- const row = value as MailboxStore;- return row.version === 1 && Array.isArray(row.messages) && row.messages.length <= MAX_MESSAGES && row.messages.every(validMessage);-}--async function readStore(): Promise<MailboxStore> {- return readLocalAgentStore(STORE_PATH, MAX_STORE_BYTES, EMPTY, validStore);-}--function view(row: LocalAgentStoredMessage): LocalAgentMessageView {- const { principalHash: _principalHash, ...safe } = row;- return { ...safe, intent: row.intent ?? "notify", requiresUserRelay: row.requiresUserRelay === true };-}--function prune(messages: LocalAgentStoredMessage[], now = Date.now()): LocalAgentStoredMessage[] {- return messages- .filter((row) => {- const created = Date.parse(row.createdAt);- return Number.isFinite(created) && now - created <= RETENTION_MS;- })- .sort((a, b) => a.createdAt.localeCompare(b.createdAt))- .slice(-MAX_MESSAGES);-}--export async function enqueueLocalAgentMessage(input: Omit<LocalAgentStoredMessage, "id" | "createdAt">): Promise<LocalAgentMessageView> {- const now = new Date().toISOString();+export async function enqueueLocalAgentMessage(+ input: Omit<LocalAgentStoredMessage, "id" | "createdAt">,+): Promise<LocalAgentMessageView> {const row: LocalAgentStoredMessage = {...input,id: `localmsg_${randomUUID()}`,- createdAt: now,+ createdAt: new Date().toISOString(),};- return withSecurityStoreLock(STORE_PATH, async () => {- const store = await readStore();- store.messages = prune([...store.messages, row]);- await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);- return view(row);- });+ return mutateLocalAgentMailboxStore((store) => {+ store.messages.push(row);+ return localAgentMessageView(row);+ }, { prune: true });}-export async function getLocalAgentInboxMessage(principal: string,targetSessionId: string,messageId: string,): Promise<LocalAgentMessageView | null> {- const session = await getAgentSession(principal, targetSessionId);- if (!session) throw new Error("local agent target not found for this client");- if (!/^localmsg_[0-9a-f-]{36}$/.test(messageId)) throw new Error("invalid local agent message id");+ await requireSession(principal, targetSessionId);+ if (!MESSAGE_ID.test(messageId)) throw new Error("invalid local agent message id");const owner = principalHash(principal);- const row = (await readStore()).messages.find((message) =>- message.principalHash === owner && message.targetSessionId === targetSessionId && message.id === messageId,+ const row = (await readLocalAgentMailboxStore()).messages.find((message) =>+ message.principalHash === owner &&+ message.targetSessionId === targetSessionId &&+ message.id === messageId,);- return row ? view(row) : null;+ return row ? localAgentMessageView(row) : null;}export async function updateLocalAgentMessageState(@@ -90,41 +56,40 @@ export async function updateLocalAgentMessageState(messageIds: string[],state: LocalAgentStoredMessageState,): Promise<LocalAgentMessageView[]> {- const session = await getAgentSession(principal, targetSessionId);- if (!session) throw new Error("local agent target not found for this client");+ await requireSession(principal, targetSessionId);const owner = principalHash(principal);- const wanted = new Set(messageIds.filter((id) => /^localmsg_[0-9a-f-]{36}$/.test(id)).slice(0, 200));+ const wanted = new Set(messageIds.filter((id) => MESSAGE_ID.test(id)).slice(0, 200));if (!wanted.size) return [];- return withSecurityStoreLock(STORE_PATH, async () => {- const store = await readStore();+ return mutateLocalAgentMailboxStore((store) => {const now = new Date().toISOString();const changed: LocalAgentMessageView[] = [];for (const row of store.messages) {- if (row.principalHash !== owner || row.targetSessionId !== targetSessionId || !wanted.has(row.id)) continue;+ if (row.principalHash !== owner ||+ row.targetSessionId !== targetSessionId ||+ !wanted.has(row.id)) continue;row.state = state;if ((state === "delivered" || state === "read") && !row.deliveredAt) row.deliveredAt = now;if (state === "read") row.readAt = now;- changed.push(view(row));+ changed.push(localAgentMessageView(row));}- await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);return changed;});}-export async function getLocalAgentSentMessage(principal: string,senderSessionId: string,messageId: string,): Promise<LocalAgentMessageView | null> {- const session = await getAgentSession(principal, senderSessionId);- if (!session) throw new Error("local agent sender not found for this client");- if (!/^localmsg_[0-9a-f-]{36}$/.test(messageId)) throw new Error("invalid local agent message id");+ await requireSession(principal, senderSessionId, "sender");+ if (!MESSAGE_ID.test(messageId)) throw new Error("invalid local agent message id");const owner = principalHash(principal);- const row = (await readStore()).messages.find((message) =>- message.principalHash === owner && message.senderSessionId === senderSessionId && message.id === messageId,+ const row = (await readLocalAgentMailboxStore()).messages.find((message) =>+ message.principalHash === owner &&+ message.senderSessionId === senderSessionId &&+ message.id === messageId,);- return row ? view(row) : null;+ return row ? localAgentMessageView(row) : null;}export async function findLocalAgentReply(@@ -132,15 +97,16 @@ export async function findLocalAgentReply(targetSessionId: string,replyToMessageId: string,): Promise<LocalAgentMessageView | null> {- const session = await getAgentSession(principal, targetSessionId);- if (!session) throw new Error("local agent target not found for this client");- if (!/^localmsg_[0-9a-f-]{36}$/.test(replyToMessageId)) throw new Error("invalid local agent message id");+ await requireSession(principal, targetSessionId);+ if (!MESSAGE_ID.test(replyToMessageId)) throw new Error("invalid local agent message id");const owner = principalHash(principal);- const row = (await readStore()).messages- .filter((message) => message.principalHash === owner && message.targetSessionId === targetSessionId &&- message.intent === "reply" && message.replyToMessageId === replyToMessageId)+ const row = (await readLocalAgentMailboxStore()).messages+ .filter((message) => message.principalHash === owner &&+ message.targetSessionId === targetSessionId &&+ message.intent === "reply" &&+ message.replyToMessageId === replyToMessageId).sort((a, b) => a.createdAt.localeCompare(b.createdAt))[0];- return row ? view(row) : null;+ return row ? localAgentMessageView(row) : null;}export async function listLocalAgentInbox(@@ -148,14 +114,101 @@ export async function listLocalAgentInbox(targetSessionId: string,options: { includeRead?: boolean; limit?: number } = {},): Promise<LocalAgentMessageView[]> {- const session = await getAgentSession(principal, targetSessionId);- if (!session) throw new Error("local agent target not found for this client");+ await requireSession(principal, targetSessionId);const owner = principalHash(principal);const limit = Math.max(1, Math.min(200, Math.trunc(options.limit || 100)));- return (await readStore()).messages+ return (await readLocalAgentMailboxStore()).messages.filter((row) => row.principalHash === owner && row.targetSessionId === targetSessionId).filter((row) => options.includeRead || row.state !== "read").sort((a, b) => a.createdAt.localeCompare(b.createdAt)).slice(-limit)- .map(view);+ .map(localAgentMessageView);+}++function executionClaimable(row: LocalAgentStoredMessage, now = Date.now()): boolean {+ const execution = row.execution;+ if (!execution?.requested || !execution.authorized) return false;+ if (execution.state === "completed" || execution.state === "failed") return false;+ if (execution.state === "pending") return true;+ return execution.state === "claimed" &&+ Boolean(execution.claimLeaseUntil) &&+ Date.parse(execution.claimLeaseUntil!) <= now;+}++export async function listLocalAgentExecutableInbox(+ principal: string,+ targetSessionId: string,+ limit = 200,+ now = Date.now(),+): Promise<LocalAgentMessageView[]> {+ await requireSession(principal, targetSessionId);+ const owner = principalHash(principal);+ return (await readLocalAgentMailboxStore()).messages+ .filter((row) => row.principalHash === owner && row.targetSessionId === targetSessionId)+ .filter((row) => (row.intent ?? "notify") === "request" && executionClaimable(row, now))+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))+ .slice(0, Math.max(1, Math.min(200, Math.trunc(limit) || 200)))+ .map(localAgentMessageView);+}++export async function countLocalAgentExecutableMessages(+ principal: string,+ targetSessionId: string,+): Promise<number> {+ return (await listLocalAgentExecutableInbox(principal, targetSessionId, 200)).length;+}++export async function claimLocalAgentMessageExecution(input: {+ principal: string;+ targetSessionId: string;+ messageId: string;+ claimedBy: string;+ now?: number;+}): Promise<LocalAgentMessageView | null> {+ await requireSession(input.principal, input.targetSessionId);+ const owner = principalHash(input.principal);+ const now = input.now ?? Date.now();+ return mutateLocalAgentMailboxStore((store) => {+ const row = store.messages.find((message) =>+ message.principalHash === owner &&+ message.targetSessionId === input.targetSessionId &&+ message.id === input.messageId,+ );+ if (!row || !executionClaimable(row, now) || !row.execution) return null;+ row.execution.state = "claimed";+ row.execution.claimedBy = input.claimedBy.slice(0, 160);+ row.execution.claimLeaseUntil = new Date(now + DEFAULT_CLAIM_LEASE_MS).toISOString();+ row.execution.attempts = (row.execution.attempts ?? 0) + 1;+ return localAgentMessageView(row);+ });+}++export async function finishLocalAgentMessageExecution(input: {+ principal: string;+ targetSessionId: string;+ messageId: string;+ claimedBy: string;+ state: "completed" | "failed";+ taskId?: string;+ error?: string;+}): Promise<LocalAgentMessageView | null> {+ await requireSession(input.principal, input.targetSessionId);+ const owner = principalHash(input.principal);+ return mutateLocalAgentMailboxStore((store) => {+ const row = store.messages.find((message) =>+ message.principalHash === owner &&+ message.targetSessionId === input.targetSessionId &&+ message.id === input.messageId,+ );+ if (!row?.execution ||+ row.execution.state !== "claimed" ||+ row.execution.claimedBy !== input.claimedBy) return null;+ row.execution.state = input.state;+ row.execution.completedAt = new Date().toISOString();+ if (input.taskId) row.execution.taskId = input.taskId;+ if (input.error) row.execution.error = input.error.slice(0, 500);+ else delete row.execution.error;+ delete row.execution.claimLeaseUntil;+ return localAgentMessageView(row);+ });}diff --git a/lib/agent/local-agent-messaging-wait.ts b/lib/agent/local-agent-messaging-wait.tsnew file mode 100644index 00000000..1e8d2232--- /dev/null+++ b/lib/agent/local-agent-messaging-wait.ts@@ -0,0 +1,79 @@+import { listLocalAgents } from "./local-agent-directory";+import {+ findLocalAgentReply,+ getLocalAgentSentMessage,+ listLocalAgentInbox,+} from "./local-agent-mailbox";+import { subscribeLocalAgentMessages } from "./local-agent-events";+import type { LocalAgentMessageView } from "./local-agent-types";++export const MAX_LOCAL_AGENT_INBOX_WAIT_MS = 20_000;++export async function waitForLocalAgentInbox(input: {+ principal: string;+ sessionId: string;+ includeRead?: boolean;+ limit?: number;+ waitMs?: number;+}): Promise<LocalAgentMessageView[]> {+ const limit = Math.max(1, Math.min(200, Math.trunc(input.limit ?? 100)));+ const waitMs = Number.isFinite(input.waitMs)+ ? Math.max(0, Math.min(MAX_LOCAL_AGENT_INBOX_WAIT_MS, Math.trunc(input.waitMs ?? 0)))+ : 0;+ const read = () => listLocalAgentInbox(input.principal, input.sessionId, {+ includeRead: input.includeRead === true,+ limit,+ });+ const initial = await read();+ if (initial.length || waitMs === 0) return initial;++ let wake = () => {};+ const signalled = new Promise<void>((resolve) => { wake = resolve; });+ const unsubscribe = subscribeLocalAgentMessages(input.sessionId, () => wake());+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ // Close the read→subscribe race; durable mailbox remains authoritative.+ const afterSubscribe = await read();+ if (afterSubscribe.length) return afterSubscribe;+ const timedOut = new Promise<void>((resolve) => { timer = setTimeout(resolve, waitMs); });+ await Promise.race([signalled, timedOut]);+ return read();+ } finally {+ if (timer) clearTimeout(timer);+ unsubscribe();+ }+}++export async function waitForLocalAgentReply(input: {+ principal: string;+ senderSessionId: string;+ requestMessageId: string;+ timeoutMs?: number;+}) {+ const request = await getLocalAgentSentMessage(+ input.principal,+ input.senderSessionId,+ input.requestMessageId,+ );+ if (!request || request.intent !== "request" || !request.correlationId)+ throw new Error("correlated local agent request not found for this session");+ const timeoutMs = Math.max(0, Math.min(30_000, Math.trunc(input.timeoutMs ?? 5_000)));+ const startedAt = Date.now();+ while (true) {+ const reply = await findLocalAgentReply(input.principal, input.senderSessionId, request.id);+ const target = (await listLocalAgents(input.principal, { includeOffline: true }))+ .find((row) => row.id === request.targetSessionId) ?? null;+ const elapsedMs = Date.now() - startedAt;+ if (reply) return { state: "replied" as const, elapsedMs, request, reply, target };+ if (target && !target.actionable && ["offline", "ended"].includes(target.status))+ return { state: "target_offline" as const, elapsedMs, request, reply: null, target };+ if (elapsedMs >= timeoutMs) {+ const state = target?.actionable === false+ ? "consumer_absent" as const+ : "timeout" as const;+ return { state, elapsedMs, request, reply: null, target };+ }+ await new Promise((resolve) =>+ setTimeout(resolve, Math.min(100, Math.max(1, timeoutMs - elapsedMs))));+ }+}diff --git a/lib/agent/local-agent-messaging.test.ts b/lib/agent/local-agent-messaging.test.tsindex 9df53e60..72064442 100644--- a/lib/agent/local-agent-messaging.test.ts+++ b/lib/agent/local-agent-messaging.test.ts@@ -7,6 +7,7 @@ const root = mkdtempSync(path.join(os.tmpdir(), "mso-local-agent-messaging-"));process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");process.env.OS_LOCAL_AGENT_PRESENCE_STORE = path.join(root, "presence.json");process.env.OS_LOCAL_AGENT_MESSAGE_STORE = path.join(root, "messages.json");+process.env.OS_LOCAL_AGENT_STANDBY_STORE = path.join(root, "standby.json");process.env.OS_LOCAL_AGENT_LEASE_MS = "15000";process.env.NEXT_PUBLIC_OS_DEMO = "0";diff --git a/lib/agent/local-agent-messaging.ts b/lib/agent/local-agent-messaging.tsindex ccbf4972..400b65cb 100644--- a/lib/agent/local-agent-messaging.ts+++ b/lib/agent/local-agent-messaging.ts@@ -3,12 +3,26 @@ import { redactText } from "@/lib/security/redact-text";import { getAgentSession } from "./session-store";import { principalHash } from "./session-files";import { listLocalAgents, resolveLocalAgent } from "./local-agent-directory";-import { enqueueLocalAgentMessage, findLocalAgentReply, getLocalAgentInboxMessage, getLocalAgentSentMessage, listLocalAgentInbox, updateLocalAgentMessageState } from "./local-agent-mailbox";-import { publishLocalAgentMessage, subscribeLocalAgentMessages } from "./local-agent-events";-import type { LocalAgentDeliveryStatus, LocalAgentMessageIntent, LocalAgentMessageKind, LocalAgentMessageView, LocalAgentTarget } from "./local-agent-types";+import {+ enqueueLocalAgentMessage,+ getLocalAgentInboxMessage,+ listLocalAgentInbox,+ updateLocalAgentMessageState,+} from "./local-agent-mailbox";+import {+ publishLocalAgentMessage,+ publishLocalAgentStandbyMessage,+} from "./local-agent-events";+import type {+ LocalAgentDeliveryStatus,+ LocalAgentMessageIntent,+ LocalAgentMessageKind,+ LocalAgentMessageView,+ LocalAgentTarget,+} from "./local-agent-types";export const MAX_LOCAL_AGENT_MESSAGE_BYTES = 16 * 1024;-export const MAX_LOCAL_AGENT_INBOX_WAIT_MS = 20_000;+export { MAX_LOCAL_AGENT_INBOX_WAIT_MS, waitForLocalAgentInbox, waitForLocalAgentReply } from "./local-agent-messaging-wait";function safePayload(value: string): string {const raw = String(value || "").trim();@@ -57,6 +71,7 @@ export async function sendLocalAgentMessage(input: {replyToMessageId?: string;requiresUserRelay?: boolean;requireActiveTarget?: boolean;+ executionAuthorized?: boolean;}): Promise<{status: LocalAgentDeliveryStatus;targetStatus: LocalAgentTarget["status"];@@ -75,9 +90,15 @@ export async function sendLocalAgentMessage(input: {const correlationId = correlation(input.correlationId) ?? (intent === "request" ? `localcorr_${randomUUID()}` : undefined);const owner = principalHash(input.principal);const targetOffline = target.status === "offline" || target.status === "ended";- if (input.requireActiveTarget && (targetOffline || !target.consumerConnected))- throw new Error(`local agent @${target.name} is not currently active with a receiver; no message was sent`);- const busy = target.status === "busy";+ if (input.requireActiveTarget && !target.actionable)+ throw new Error(`local agent @${target.name} is not currently active with a receiver or armed standby; no message was sent`);++ // Auto execution is encoded explicitly at persistence time. A write-scope+ // caller can enqueue a request but can never turn standby into an exec grant.+ const executionRequested = intent === "request";+ const executionAuthorized = executionRequested && input.executionAuthorized === true;+ const standbyAccepted = executionAuthorized && target.standbyArmed && target.standbyState !== "blocked";+ const busy = target.status === "busy" || target.standbyState === "working";let message = await enqueueLocalAgentMessage({principalHash: owner,senderSessionId: sender.id,@@ -90,11 +111,32 @@ export async function sendLocalAgentMessage(input: {...(input.replyToMessageId ? { replyToMessageId: input.replyToMessageId } : {}),requiresUserRelay: input.requiresUserRelay === true,text,- state: busy || targetOffline ? "queued" : "accepted",+ ...(executionRequested ? {+ execution: {+ requested: true,+ authorized: executionAuthorized,+ state: "pending",+ attempts: 0,+ },+ } : {}),+ state: standbyAccepted ? "accepted" : busy || targetOffline ? "queued" : "accepted",});- let status: LocalAgentDeliveryStatus = targetOffline ? "target_offline" : busy ? "queued" : "accepted";- if (!targetOffline && !busy && publishLocalAgentMessage(target.id, message) > 0) {+ // Standby listeners are deliberately separate from foreground receivers and+ // therefore never alter consumerConnected. The durable mailbox remains SSOT.+ publishLocalAgentStandbyMessage(target.id, message);++ let status: LocalAgentDeliveryStatus = standbyAccepted+ ? "accepted_for_standby"+ : targetOffline+ ? "target_offline"+ : busy+ ? "queued"+ : "accepted";++ // When standby owns an executable request, do not also actively dispatch it+ // to a foreground receiver; that would create two independent handlers.+ if (!standbyAccepted && !targetOffline && !busy && publishLocalAgentMessage(target.id, message) > 0) {const [updated] = await updateLocalAgentMessageState(input.principal, target.id, [message.id], "delivered");if (updated) message = updated;status = "delivered";@@ -130,7 +172,8 @@ export async function replyLocalAgentMessage(input: {export async function flushLocalAgentQueue(principal: string, targetSessionId: string): Promise<number> {const pending = (await listLocalAgentInbox(principal, targetSessionId, { limit: 200 }))- .filter((row) => row.state === "queued" || row.state === "accepted");+ .filter((row) => row.state === "queued" || row.state === "accepted")+ .filter((row) => !row.execution?.authorized);let delivered = 0;for (const message of pending) {if (publishLocalAgentMessage(targetSessionId, message) <= 0) continue;@@ -139,64 +182,3 @@ export async function flushLocalAgentQueue(principal: string, targetSessionId: s}return delivered;}---export async function waitForLocalAgentInbox(input: {- principal: string;- sessionId: string;- includeRead?: boolean;- limit?: number;- waitMs?: number;-}): Promise<LocalAgentMessageView[]> {- const limit = Math.max(1, Math.min(200, Math.trunc(input.limit ?? 100)));- const waitMs = Number.isFinite(input.waitMs)- ? Math.max(0, Math.min(MAX_LOCAL_AGENT_INBOX_WAIT_MS, Math.trunc(input.waitMs ?? 0)))- : 0;- const read = () => listLocalAgentInbox(input.principal, input.sessionId, { includeRead: input.includeRead === true, limit });- const initial = await read();- if (initial.length || waitMs === 0) return initial;-- let wake = () => {};- const signalled = new Promise<void>((resolve) => { wake = resolve; });- const unsubscribe = subscribeLocalAgentMessages(input.sessionId, () => wake());- let timer: ReturnType<typeof setTimeout> | undefined;- try {- // Close the read→subscribe race: a sender may persist mail after the first- // read but before this receiver registers. The mailbox remains authoritative.- const afterSubscribe = await read();- if (afterSubscribe.length) return afterSubscribe;- const timedOut = new Promise<void>((resolve) => { timer = setTimeout(resolve, waitMs); });- await Promise.race([signalled, timedOut]);- return read();- } finally {- if (timer) clearTimeout(timer);- unsubscribe();- }-}--export async function waitForLocalAgentReply(input: {- principal: string;- senderSessionId: string;- requestMessageId: string;- timeoutMs?: number;-}) {- const request = await getLocalAgentSentMessage(input.principal, input.senderSessionId, input.requestMessageId);- if (!request || request.intent !== "request" || !request.correlationId)- throw new Error("correlated local agent request not found for this session");- const timeoutMs = Math.max(0, Math.min(30_000, Math.trunc(input.timeoutMs ?? 5_000)));- const startedAt = Date.now();- while (true) {- const reply = await findLocalAgentReply(input.principal, input.senderSessionId, request.id);- const target = (await listLocalAgents(input.principal, { includeOffline: true }))- .find((row) => row.id === request.targetSessionId) ?? null;- const elapsedMs = Date.now() - startedAt;- if (reply) return { state: "replied" as const, elapsedMs, request, reply, target };- if (target && ["offline", "ended"].includes(target.status))- return { state: "target_offline" as const, elapsedMs, request, reply: null, target };- if (elapsedMs >= timeoutMs) {- const state = target?.consumerConnected === false ? "consumer_absent" as const : "timeout" as const;- return { state, elapsedMs, request, reply: null, target };- }- await new Promise((resolve) => setTimeout(resolve, Math.min(100, Math.max(1, timeoutMs - elapsedMs))));- }-}diff --git a/lib/agent/local-agent-standby-execution.ts b/lib/agent/local-agent-standby-execution.tsnew file mode 100644index 00000000..8211f0a1--- /dev/null+++ b/lib/agent/local-agent-standby-execution.ts@@ -0,0 +1,194 @@+import { randomUUID } from "node:crypto";+import { handoffOwnerLocalSession } from "@/lib/a2a/local-session";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";+import { activeWorkflowForActor } from "@/lib/workflow";+import {+ claimLocalAgentMessageExecution,+ finishLocalAgentMessageExecution,+} from "./local-agent-mailbox";+import { replyLocalAgentMessage } from "./local-agent-messaging";+import {+ acquireLocalAgentStandbyExecution,+ getLocalAgentStandbyRecord,+ releaseLocalAgentStandbyExecution,+ updateLocalAgentStandbyTask,+} from "./local-agent-standby-store";+import type { LocalAgentMessageView, LocalAgentStandbyRecord } from "./local-agent-types";++function taskResultText(value: unknown, fallback: string): string {+ if (!value || typeof value !== "object") return fallback;+ const task = value as {+ status?: { state?: string; message?: { parts?: Array<{ text?: string }> } };+ artifacts?: Array<{ parts?: Array<{ text?: string }> }>;+ };+ const artifactText = task.artifacts?.flatMap((artifact) => artifact.parts ?? [])+ .map((part) => typeof part.text === "string" ? part.text : "")+ .filter(Boolean)+ .join("\n")+ .trim();+ const statusText = task.status?.message?.parts+ ?.map((part) => typeof part.text === "string" ? part.text : "")+ .filter(Boolean)+ .join("\n")+ .trim();+ return (artifactText || statusText || fallback).slice(0, 16 * 1024);+}++function taskId(value: unknown): string | undefined {+ if (!value || typeof value !== "object") return undefined;+ const id = (value as { id?: unknown }).id;+ return typeof id === "string" && /^task_[0-9a-f-]{36}$/.test(id) ? id : undefined;+}++function taskCompleted(value: unknown): boolean {+ return Boolean(value && typeof value === "object" &&+ (value as { status?: { state?: unknown } }).status?.state === "TASK_STATE_COMPLETED");+}++function fatalErrorMessage(message: string): boolean {+ return /workflow_id was not found|session not found|target not found|not authorized|forbidden|revoked/i.test(message);+}++async function safeReply(+ principal: string,+ sessionId: string,+ request: LocalAgentMessageView,+ text: string,+): Promise<void> {+ if (request.intent !== "request" || !request.correlationId) return;+ await replyLocalAgentMessage({+ principal,+ senderSessionId: sessionId,+ replyToMessageId: request.id,+ text: text.slice(0, 16 * 1024),+ kind: request.kind,+ }).catch(() => undefined);+}++async function finishExecution(input: {+ record: LocalAgentStandbyRecord;+ claimed: LocalAgentMessageView;+ claimant: string;+ state: "completed" | "failed";+ taskId?: string;+ error?: string;+ fatal?: boolean;+}): Promise<void> {+ await finishLocalAgentMessageExecution({+ principal: input.record.principal,+ targetSessionId: input.record.sessionId,+ messageId: input.claimed.id,+ claimedBy: input.claimant,+ state: input.state,+ ...(input.taskId ? { taskId: input.taskId } : {}),+ ...(input.error ? { error: input.error } : {}),+ }).catch(() => undefined);+ const prefix = input.state === "completed" ? "" : "Standby command failed: ";+ await safeReply(+ input.record.principal,+ input.record.sessionId,+ input.claimed,+ input.state === "completed"+ ? input.error || "Standby command completed."+ : `${prefix}${input.error || "worker failed"}`,+ );+ await releaseLocalAgentStandbyExecution({+ principal: input.record.principal,+ sessionId: input.record.sessionId,+ messageId: input.claimed.id,+ claimedBy: input.claimant,+ ...(input.state === "failed" && input.error ? { error: input.error } : {}),+ ...(input.fatal ? { fatal: true } : {}),+ }).catch(() => undefined);+}++export async function executeLocalAgentStandbyMessage(input: {+ record: LocalAgentStandbyRecord;+ message: LocalAgentMessageView;+ capabilities: CapabilityRuntime;+ runtimeId: string;+}): Promise<{ advanced: boolean; fatal: boolean }> {+ const { record, message, capabilities } = input;+ const claimant = `${input.runtimeId}:${randomUUID()}`;+ const slot = await acquireLocalAgentStandbyExecution({+ principal: record.principal,+ sessionId: record.sessionId,+ messageId: message.id,+ claimedBy: claimant,+ });+ if (!slot) return { advanced: false, fatal: false };++ const claimed = await claimLocalAgentMessageExecution({+ principal: record.principal,+ targetSessionId: record.sessionId,+ messageId: message.id,+ claimedBy: claimant,+ });+ if (!claimed) {+ await releaseLocalAgentStandbyExecution({+ principal: record.principal,+ sessionId: record.sessionId,+ messageId: message.id,+ claimedBy: claimant,+ completed: false,+ });+ return { advanced: false, fatal: false };+ }++ try {+ const fresh = await getLocalAgentStandbyRecord(record.principal, record.sessionId);+ if (!fresh?.armed || fresh.workflowId !== record.workflowId)+ throw new Error("standby workflow is no longer active");+ if (!await activeWorkflowForActor(fresh.workflowActor, fresh.workflowId))+ throw new Error("workflow_id was not found for this MSO session");++ const result = await handoffOwnerLocalSession(+ record.principal,+ record.sessionId,+ claimed.text,+ capabilities,+ undefined,+ {+ workflowId: fresh.workflowId,+ workflowActor: fresh.workflowActor,+ fixedWorkflow: true,+ },+ );+ const id = taskId(result.task);+ if (id)+ await updateLocalAgentStandbyTask(record.principal, record.sessionId, claimed.id, claimant, id);+ if (taskCompleted(result.task)) {+ await finishExecution({+ record,+ claimed,+ claimant,+ state: "completed",+ ...(id ? { taskId: id } : {}),+ error: taskResultText(result.task, "Standby command completed."),+ });+ return { advanced: true, fatal: false };+ }+ const failure = taskResultText(result.task, "Standby worker failed to complete the command.");+ await finishExecution({+ record,+ claimed,+ claimant,+ state: "failed",+ ...(id ? { taskId: id } : {}),+ error: failure,+ });+ return { advanced: true, fatal: false };+ } catch (error) {+ const messageText = (error instanceof Error ? error.message : String(error)).slice(0, 500);+ const fatal = fatalErrorMessage(messageText);+ await finishExecution({+ record,+ claimed,+ claimant,+ state: "failed",+ error: messageText,+ fatal,+ });+ return { advanced: true, fatal };+ }+}diff --git a/lib/agent/local-agent-standby-recovery.test.ts b/lib/agent/local-agent-standby-recovery.test.tsnew file mode 100644index 00000000..0642e09a--- /dev/null+++ b/lib/agent/local-agent-standby-recovery.test.ts@@ -0,0 +1,124 @@+import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ arm,+ capabilities,+ cleanupStandbyFixture,+ events,+ eventually,+ mailbox,+ messaging,+ mocks,+ other,+ owner,+ pair,+ resetStandbyMocks,+ resetStandbyRuntime,+ standby,+ standbyStore,+ workflowActor,+ workflowId,+} from "./local-agent-standby-test-fixture";++beforeEach(resetStandbyMocks);+afterEach(resetStandbyRuntime);+afterAll(cleanupStandbyFixture);++describe("durable local-agent standby recovery and security", () => {+ it("reconciles an armed worker and pending mailbox request after runtime restart", async () => {+ const { coordinator, worker } = await pair();+ await arm(worker.id);+ standby.resetLocalAgentStandbyRuntimeForTest();+ expect(events.localAgentStandbySubscriberCount(worker.id)).toBe(0);++ const sent = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "survive restart",+ intent: "request",+ executionAuthorized: true,+ });+ expect(sent.status).toBe("accepted_for_standby");+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(mocks.handoff).not.toHaveBeenCalled();++ await standby.ensureLocalAgentStandbyRuntime(capabilities);+ await eventually(() =>+ mailbox.findLocalAgentReply(owner, coordinator.id, sent.message.id));+ expect(mocks.handoff).toHaveBeenCalledTimes(1);+ expect(events.localAgentStandbySubscriberCount(worker.id)).toBe(1);+ });++ it("never wakes for notify-only or a request not authorized by exec scope", async () => {+ const { coordinator, worker } = await pair();+ await arm(worker.id);+ const notify = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "FYI only",+ intent: "notify",+ executionAuthorized: true,+ });+ const writeOnly = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "write token request",+ intent: "request",+ executionAuthorized: false,+ });+ await new Promise((resolve) => setTimeout(resolve, 80));+ expect(mocks.handoff).not.toHaveBeenCalled();+ expect(notify.message.execution).toBeUndefined();+ expect(writeOnly.message.execution).toMatchObject({+ requested: true,+ authorized: false,+ state: "pending",+ });+ });++ it("disarms explicitly and refuses execution under a stale workflow", async () => {+ const { coordinator, worker } = await pair();+ await arm(worker.id);+ const stopped = await standby.stopLocalAgentStandby({+ principal: owner,+ sessionId: worker.id,+ workflowId,+ });+ expect(stopped).toMatchObject({ standbyArmed: false, changed: true });+ const afterStop = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "do not auto execute",+ intent: "request",+ executionAuthorized: true,+ });+ await new Promise((resolve) => setTimeout(resolve, 50));+ expect(afterStop.status).not.toBe("accepted_for_standby");+ expect(mocks.handoff).not.toHaveBeenCalled();++ await arm(worker.id);+ await new Promise((resolve) => setTimeout(resolve, 30));+ mocks.active = false;+ await standby.drainStandbySession(owner, worker.id);+ const blocked = await eventually(async () => {+ const current = await standbyStore.getLocalAgentStandbyRecord(owner, worker.id);+ return current?.state === "blocked" ? current : null;+ });+ expect(blocked).toMatchObject({ armed: false, state: "blocked" });+ });++ it("enforces same-owner standby state", async () => {+ const { worker } = await pair();+ await arm(worker.id);+ expect(await standbyStore.getLocalAgentStandbyRecord(other, worker.id)).toBeNull();+ await expect(standbyStore.armLocalAgentStandbyRecord({+ principal: other,+ sessionId: worker.id,+ workflowActor,+ workflowId,+ })).rejects.toThrow(/session not found/i);+ });+});diff --git a/lib/agent/local-agent-standby-storage.ts b/lib/agent/local-agent-standby-storage.tsnew file mode 100644index 00000000..efd32795--- /dev/null+++ b/lib/agent/local-agent-standby-storage.ts@@ -0,0 +1,89 @@+import { expandOwnerStorePath } from "@/lib/owner-store-path.js";+import { withSecurityStoreLock } from "@/lib/security-store-lock";+import os from "node:os";+import path from "node:path";+import { SESSION_ID } from "./session-files";+import { readLocalAgentStore, writeLocalAgentStore } from "./local-agent-private-store";+import type { LocalAgentStandbyRecord, LocalAgentStandbyState } from "./local-agent-types";++export type LocalAgentStandbyStore = { version: 1; entries: LocalAgentStandbyRecord[] };+const MAX_STORE_BYTES = 1024 * 1024;+const MAX_ENTRIES = 1000;+const RETENTION_MS = 30 * 24 * 60 * 60 * 1000;+const STORE_PATH = expandOwnerStorePath(+ process.env.OS_LOCAL_AGENT_STANDBY_STORE ??+ path.join(os.homedir(), ".mso", "private", "local-agent-standby.json"),+);+const EMPTY: LocalAgentStandbyStore = { version: 1, entries: [] };++function validRecord(value: unknown): value is LocalAgentStandbyRecord {+ if (!value || typeof value !== "object") return false;+ const row = value as LocalAgentStandbyRecord;+ return SESSION_ID.test(String(row.sessionId || "")) &&+ /^[a-f0-9]{64}$/.test(String(row.principalHash || "")) &&+ typeof row.principal === "string" && row.principal.length > 0 && row.principal.length <= 512 &&+ typeof row.workflowActor === "string" && row.workflowActor.length > 0 && row.workflowActor.length <= 512 &&+ /^[a-f0-9-]{36}$/.test(String(row.workflowId || "")) &&+ typeof row.armed === "boolean" &&+ ["waiting", "working", "blocked"].includes(String(row.state)) &&+ Number.isFinite(Date.parse(String(row.armedAt || ""))) &&+ Number.isFinite(Date.parse(String(row.updatedAt || ""))) &&+ (!row.executionLeaseUntil || Number.isFinite(Date.parse(row.executionLeaseUntil))) &&+ (!row.lastRunAt || Number.isFinite(Date.parse(row.lastRunAt))) &&+ (!row.currentMessageId || /^localmsg_[0-9a-f-]{36}$/.test(row.currentMessageId)) &&+ (!row.lastMessageId || /^localmsg_[0-9a-f-]{36}$/.test(row.lastMessageId)) &&+ (!row.currentTaskId || /^task_[0-9a-f-]{36}$/.test(row.currentTaskId)) &&+ (!row.claimedBy || row.claimedBy.length <= 160) &&+ (!row.lastError || row.lastError.length <= 500);+}++function validStore(value: unknown): value is LocalAgentStandbyStore {+ if (!value || typeof value !== "object") return false;+ const row = value as LocalAgentStandbyStore;+ return row.version === 1 && Array.isArray(row.entries) &&+ row.entries.length <= MAX_ENTRIES + 1 && row.entries.every(validRecord);+}++export async function readLocalAgentStandbyStore(): Promise<LocalAgentStandbyStore> {+ return readLocalAgentStore(STORE_PATH, MAX_STORE_BYTES, EMPTY, validStore);+}++function effectiveState(row: LocalAgentStandbyRecord, now = Date.now()): LocalAgentStandbyState {+ if (row.state === "working" && row.executionLeaseUntil &&+ Date.parse(row.executionLeaseUntil) <= now) return "waiting";+ return row.state;+}++export function standbyRecordView(+ row: LocalAgentStandbyRecord,+ now = Date.now(),+): LocalAgentStandbyRecord {+ return { ...row, state: effectiveState(row, now) };+}++function prune(entries: LocalAgentStandbyRecord[], now = Date.now()): LocalAgentStandbyRecord[] {+ return entries+ .filter((row) => row.armed || now - Date.parse(row.updatedAt) <= RETENTION_MS)+ .sort((a, b) => a.updatedAt.localeCompare(b.updatedAt))+ .slice(-MAX_ENTRIES);+}++export async function mutateLocalAgentStandbyStore<T>(+ mutate: (store: LocalAgentStandbyStore) => Promise<T> | T,+ options: { prune?: boolean; now?: number } = {},+): Promise<T> {+ return withSecurityStoreLock(STORE_PATH, async () => {+ const store = await readLocalAgentStandbyStore();+ const result = await mutate(store);+ if (options.prune) store.entries = prune(store.entries, options.now);+ await writeLocalAgentStore(STORE_PATH, store, MAX_STORE_BYTES);+ return result;+ });+}++export function clearStandbyExecution(row: LocalAgentStandbyRecord): void {+ delete row.currentMessageId;+ delete row.currentTaskId;+ delete row.executionLeaseUntil;+ delete row.claimedBy;+}diff --git a/lib/agent/local-agent-standby-store.ts b/lib/agent/local-agent-standby-store.tsnew file mode 100644index 00000000..00a9db74--- /dev/null+++ b/lib/agent/local-agent-standby-store.ts@@ -0,0 +1,215 @@+import { getAgentSession } from "./session-store";+import { principalHash } from "./session-files";+import {+ clearStandbyExecution,+ mutateLocalAgentStandbyStore,+ readLocalAgentStandbyStore,+ standbyRecordView,+} from "./local-agent-standby-storage";+import type { LocalAgentStandbyRecord } from "./local-agent-types";++const DEFAULT_EXECUTION_LEASE_MS = 15 * 60_000;++export { standbyRecordView } from "./local-agent-standby-storage";++export async function listLocalAgentStandbyRecords(+ principal: string,+): Promise<LocalAgentStandbyRecord[]> {+ const owner = principalHash(principal);+ return (await readLocalAgentStandbyStore()).entries+ .filter((row) => row.principalHash === owner)+ .map((row) => standbyRecordView(row));+}++export async function listAllArmedLocalAgentStandbyRecords(): Promise<LocalAgentStandbyRecord[]> {+ return (await readLocalAgentStandbyStore()).entries+ .filter((row) => row.armed)+ .map((row) => standbyRecordView(row));+}++export async function getLocalAgentStandbyRecord(+ principal: string,+ sessionId: string,+): Promise<LocalAgentStandbyRecord | null> {+ const owner = principalHash(principal);+ const row = (await readLocalAgentStandbyStore()).entries+ .find((entry) => entry.principalHash === owner && entry.sessionId === sessionId);+ return row ? standbyRecordView(row) : null;+}++export async function armLocalAgentStandbyRecord(input: {+ principal: string;+ sessionId: string;+ workflowActor: string;+ workflowId: string;+ now?: number;+}): Promise<LocalAgentStandbyRecord> {+ if (!await getAgentSession(input.principal, input.sessionId))+ throw new Error("local agent session not found for this client");+ const owner = principalHash(input.principal);+ const now = input.now ?? Date.now();+ const at = new Date(now).toISOString();+ return mutateLocalAgentStandbyStore((store) => {+ const current = store.entries+ .find((row) => row.principalHash === owner && row.sessionId === input.sessionId);+ if (current?.armed && current.workflowId !== input.workflowId)+ throw new Error("local agent session is already armed for another workflow");+ const next: LocalAgentStandbyRecord = {+ principalHash: owner,+ principal: input.principal,+ sessionId: input.sessionId,+ workflowActor: input.workflowActor,+ workflowId: input.workflowId,+ armed: true,+ state: "waiting",+ armedAt: current?.armedAt ?? at,+ updatedAt: at,+ ...(current?.lastMessageId ? { lastMessageId: current.lastMessageId } : {}),+ ...(current?.lastRunAt ? { lastRunAt: current.lastRunAt } : {}),+ };+ store.entries = [+ ...store.entries.filter((row) =>+ !(row.principalHash === owner && row.sessionId === input.sessionId)),+ next,+ ];+ return next;+ }, { prune: true, now });+}++export async function disarmLocalAgentStandbyRecord(+ principal: string,+ sessionId: string,+ workflowId?: string,+ reason?: string,+): Promise<LocalAgentStandbyRecord | null> {+ const owner = principalHash(principal);+ return mutateLocalAgentStandbyStore((store) => {+ const row = store.entries+ .find((entry) => entry.principalHash === owner && entry.sessionId === sessionId);+ if (!row || (workflowId && row.workflowId !== workflowId)) return null;+ row.armed = false;+ row.state = "waiting";+ row.updatedAt = new Date().toISOString();+ clearStandbyExecution(row);+ if (reason) row.lastError = reason.slice(0, 500);+ return standbyRecordView(row);+ }, { prune: true });+}++export async function disarmLocalAgentStandbyForWorkflow(+ workflowActor: string,+ workflowId: string,+ reason?: string,+): Promise<LocalAgentStandbyRecord[]> {+ return mutateLocalAgentStandbyStore((store) => {+ const changed: LocalAgentStandbyRecord[] = [];+ const at = new Date().toISOString();+ for (const row of store.entries) {+ if (!row.armed ||+ row.workflowActor !== workflowActor ||+ row.workflowId !== workflowId) continue;+ row.armed = false;+ row.state = "waiting";+ row.updatedAt = at;+ clearStandbyExecution(row);+ if (reason) row.lastError = reason.slice(0, 500);+ changed.push(standbyRecordView(row));+ }+ return changed;+ }, { prune: true });+}++export async function acquireLocalAgentStandbyExecution(input: {+ principal: string;+ sessionId: string;+ messageId: string;+ claimedBy: string;+ taskId?: string;+ now?: number;+}): Promise<LocalAgentStandbyRecord | null> {+ const owner = principalHash(input.principal);+ const now = input.now ?? Date.now();+ return mutateLocalAgentStandbyStore((store) => {+ const row = store.entries+ .find((entry) => entry.principalHash === owner && entry.sessionId === input.sessionId);+ if (!row?.armed || row.state === "blocked") return null;+ const activeLease = row.state === "working" &&+ row.executionLeaseUntil &&+ Date.parse(row.executionLeaseUntil) > now;+ if (activeLease) return null;+ row.state = "working";+ row.currentMessageId = input.messageId;+ row.claimedBy = input.claimedBy.slice(0, 160);+ row.executionLeaseUntil = new Date(now + DEFAULT_EXECUTION_LEASE_MS).toISOString();+ row.updatedAt = new Date(now).toISOString();+ if (input.taskId) row.currentTaskId = input.taskId;+ return standbyRecordView(row, now);+ });+}++export async function updateLocalAgentStandbyTask(+ principal: string,+ sessionId: string,+ messageId: string,+ claimedBy: string,+ taskId: string,+): Promise<void> {+ const owner = principalHash(principal);+ await mutateLocalAgentStandbyStore((store) => {+ const row = store.entries+ .find((entry) => entry.principalHash === owner && entry.sessionId === sessionId);+ if (!row || row.currentMessageId !== messageId || row.claimedBy !== claimedBy) return;+ row.currentTaskId = taskId;+ row.updatedAt = new Date().toISOString();+ });+}++export async function releaseLocalAgentStandbyExecution(input: {+ principal: string;+ sessionId: string;+ messageId: string;+ claimedBy: string;+ error?: string;+ fatal?: boolean;+ completed?: boolean;+}): Promise<LocalAgentStandbyRecord | null> {+ const owner = principalHash(input.principal);+ return mutateLocalAgentStandbyStore((store) => {+ const row = store.entries+ .find((entry) => entry.principalHash === owner && entry.sessionId === input.sessionId);+ if (!row ||+ row.currentMessageId !== input.messageId ||+ row.claimedBy !== input.claimedBy) return null;+ const now = new Date().toISOString();+ if (input.completed !== false) {+ row.lastMessageId = input.messageId;+ row.lastRunAt = now;+ }+ row.updatedAt = now;+ row.state = input.fatal ? "blocked" : "waiting";+ if (input.fatal) row.armed = false;+ if (input.error) row.lastError = input.error.slice(0, 500);+ else delete row.lastError;+ clearStandbyExecution(row);+ return standbyRecordView(row);+ });+}++export async function blockLocalAgentStandby(+ principal: string,+ sessionId: string,+ reason: string,+): Promise<LocalAgentStandbyRecord | null> {+ const owner = principalHash(principal);+ return mutateLocalAgentStandbyStore((store) => {+ const row = store.entries+ .find((entry) => entry.principalHash === owner && entry.sessionId === sessionId);+ if (!row) return null;+ row.armed = false;+ row.state = "blocked";+ row.lastError = reason.slice(0, 500);+ row.updatedAt = new Date().toISOString();+ clearStandbyExecution(row);+ return standbyRecordView(row);+ });+}diff --git a/lib/agent/local-agent-standby-test-fixture.ts b/lib/agent/local-agent-standby-test-fixture.tsnew file mode 100644index 00000000..733b8ede--- /dev/null+++ b/lib/agent/local-agent-standby-test-fixture.ts@@ -0,0 +1,111 @@+import { mkdtempSync, rmSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { vi } from "vitest";++export const root = mkdtempSync(path.join(os.tmpdir(), "mso-local-agent-standby-"));+process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");+process.env.OS_LOCAL_AGENT_PRESENCE_STORE = path.join(root, "presence.json");+process.env.OS_LOCAL_AGENT_MESSAGE_STORE = path.join(root, "messages.json");+process.env.OS_LOCAL_AGENT_STANDBY_STORE = path.join(root, "standby.json");+process.env.OS_A2A_TASK_STORE = path.join(root, "tasks.json");+process.env.OS_LOCAL_AGENT_LEASE_MS = "15000";+process.env.NEXT_PUBLIC_OS_DEMO = "0";++const hoistedMocks = vi.hoisted(() => ({+ active: true,+ handoff: vi.fn(),+}));+export const mocks = hoistedMocks;+vi.mock("@/lib/workflow", () => ({+ activeWorkflowForActor: vi.fn(async (_actor: string, id: string) =>+ mocks.active ? { id, steps: [] } : null),+}));+vi.mock("@/lib/a2a/local-session", () => ({+ handoffOwnerLocalSession: mocks.handoff,+}));++export const store = await import("./session-store");+export const presence = await import("./local-agent-presence");+export const directory = await import("./local-agent-directory");+export const mailbox = await import("./local-agent-mailbox");+export const messaging = await import("./local-agent-messaging");+export const events = await import("./local-agent-events");+export const standbyStore = await import("./local-agent-standby-store");+export const standby = await import("./local-agent-standby");++export const owner = "mcp-client:standby-owner";+export const other = "mcp-client:foreign";+export const workflowActor = "mcp:standby-owner";+export const workflowId = "11111111-1111-4111-8111-111111111111";+export const capabilities = {+ list: () => [],+ invoke: vi.fn(async () => ({ content: [] })),+};++export function completedTask(text = "standby result") {+ return {+ session: { id: "target" },+ task: {+ id: `task_${crypto.randomUUID()}`,+ status: { state: "TASK_STATE_COMPLETED", timestamp: new Date().toISOString() },+ artifacts: [{+ artifactId: "artifact",+ name: "result",+ parts: [{ text, mediaType: "text/plain" }],+ }],+ history: [],+ metadata: { "mso.scope": "exec" },+ },+ };+}++export async function pair() {+ const coordinator = await store.createAgentSession(owner, "mcp");+ const worker = await store.createAgentSession(owner, "mcp");+ await presence.touchLocalAgentPresence(+ owner,+ coordinator.id,+ "idle",+ `test:${coordinator.id}`,+ );+ await presence.touchLocalAgentPresence(owner, worker.id, "idle", `test:${worker.id}`);+ return { coordinator, worker };+}++export async function arm(workerId: string) {+ return standby.armLocalAgentStandby({+ principal: owner,+ sessionId: workerId,+ workflowActor,+ workflowId,+ capabilities,+ });+}++export async function eventually<T>(+ read: () => Promise<T | null | undefined | false>,+ timeoutMs = 2500,+): Promise<T> {+ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ const value = await read();+ if (value) return value as T;+ await new Promise((resolve) => setTimeout(resolve, 10));+ }+ throw new Error("timed out waiting for standby test condition");+}++export function resetStandbyMocks(): void {+ mocks.active = true;+ mocks.handoff.mockReset();+ mocks.handoff.mockResolvedValue(completedTask());+}++export function resetStandbyRuntime(): void {+ standby.resetLocalAgentStandbyRuntimeForTest();+}++export function cleanupStandbyFixture(): void {+ rmSync(root, { recursive: true, force: true });+}diff --git a/lib/agent/local-agent-standby.test.ts b/lib/agent/local-agent-standby.test.tsnew file mode 100644index 00000000..b17fa95c--- /dev/null+++ b/lib/agent/local-agent-standby.test.ts@@ -0,0 +1,174 @@+import { afterAll, afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ arm,+ capabilities,+ cleanupStandbyFixture,+ completedTask,+ directory,+ events,+ eventually,+ mailbox,+ messaging,+ mocks,+ owner,+ pair,+ resetStandbyMocks,+ resetStandbyRuntime,+ standbyStore,+ workflowActor,+ workflowId,+} from "./local-agent-standby-test-fixture";++beforeEach(resetStandbyMocks);+afterEach(resetStandbyRuntime);+afterAll(cleanupStandbyFixture);++describe("server-native durable local-agent standby execution", () => {+ it("arms immediately without a foreground receiver and remains explicitly actionable", async () => {+ const { worker } = await pair();+ const started = Date.now();+ const result = await arm(worker.id);+ expect(Date.now() - started).toBeLessThan(500);+ expect(result).toMatchObject({+ mode: "listen",+ status: "waiting",+ standbyArmed: true,+ workflowId,+ });+ const row = (await directory.listLocalAgents(owner, { includeOffline: true }))+ .find((item) => item.id === worker.id);+ expect(row).toMatchObject({+ consumerConnected: false,+ consumerCount: 0,+ standbyArmed: true,+ standbyState: "waiting",+ standbyWorkflowId: workflowId,+ actionable: true,+ });+ expect(events.localAgentSubscriberCount(worker.id)).toBe(0);+ expect(events.localAgentStandbySubscriberCount(worker.id)).toBe(1);+ });++ it("executes a correlated request, replies once, and returns to waiting", async () => {+ const { coordinator, worker } = await pair();+ await arm(worker.id);+ const sent = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "perform one bounded task",+ kind: "task",+ intent: "request",+ requiresUserRelay: true,+ executionAuthorized: true,+ });+ expect(sent.status).toBe("accepted_for_standby");+ const reply = await eventually(() =>+ mailbox.findLocalAgentReply(owner, coordinator.id, sent.message.id));+ expect(reply.text).toBe("standby result");+ expect(mocks.handoff).toHaveBeenCalledTimes(1);+ expect(mocks.handoff).toHaveBeenCalledWith(+ owner,+ worker.id,+ "perform one bounded task",+ capabilities,+ undefined,+ { workflowId, workflowActor, fixedWorkflow: true },+ );+ const record = await eventually(async () => {+ const current = await standbyStore.getLocalAgentStandbyRecord(owner, worker.id);+ return current?.state === "waiting" &&+ current.lastMessageId === sent.message.id+ ? current+ : null;+ });+ expect(record).toMatchObject({+ armed: true,+ state: "waiting",+ lastMessageId: sent.message.id,+ });+ const executed = await mailbox.getLocalAgentInboxMessage(+ owner,+ worker.id,+ sent.message.id,+ );+ expect(executed?.execution).toMatchObject({+ authorized: true,+ state: "completed",+ attempts: 1,+ });+ });++ it("does not execute the same durable message twice when duplicate events arrive", async () => {+ const { coordinator, worker } = await pair();+ await arm(worker.id);+ const sent = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "deduplicate me",+ intent: "request",+ executionAuthorized: true,+ });+ events.publishLocalAgentStandbyMessage(worker.id, sent.message);+ events.publishLocalAgentStandbyMessage(worker.id, sent.message);+ await eventually(() =>+ mailbox.findLocalAgentReply(owner, coordinator.id, sent.message.id));+ await new Promise((resolve) => setTimeout(resolve, 30));+ expect(mocks.handoff).toHaveBeenCalledTimes(1);+ });++ it("queues a second request while working and drains sequentially with no overlap", async () => {+ const { coordinator, worker } = await pair();+ await arm(worker.id);+ let releaseFirst!: () => void;+ let active = 0;+ let peak = 0;+ mocks.handoff.mockImplementationOnce(async () => {+ active += 1;+ peak = Math.max(peak, active);+ await new Promise<void>((resolve) => { releaseFirst = resolve; });+ active -= 1;+ return completedTask("first done");+ });+ mocks.handoff.mockImplementationOnce(async () => {+ active += 1;+ peak = Math.max(peak, active);+ active -= 1;+ return completedTask("second done");+ });++ const first = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "first",+ intent: "request",+ executionAuthorized: true,+ });+ await eventually(async () => mocks.handoff.mock.calls.length === 1 ? true : null);+ const second = await messaging.sendLocalAgentMessage({+ principal: owner,+ senderSessionId: coordinator.id,+ target: worker.id,+ text: "second",+ intent: "request",+ executionAuthorized: true,+ });+ await new Promise((resolve) => setTimeout(resolve, 30));+ expect(mocks.handoff).toHaveBeenCalledTimes(1);+ const row = (await directory.listLocalAgents(owner, { includeOffline: true }))+ .find((item) => item.id === worker.id);+ expect(row?.queuedCount).toBeGreaterThanOrEqual(1);+ releaseFirst();+ await eventually(() =>+ mailbox.findLocalAgentReply(owner, coordinator.id, second.message.id));+ expect(await mailbox.findLocalAgentReply(+ owner,+ coordinator.id,+ first.message.id,+ )).toBeTruthy();+ expect(mocks.handoff).toHaveBeenCalledTimes(2);+ expect(peak).toBe(1);+ });+});diff --git a/lib/agent/local-agent-standby.ts b/lib/agent/local-agent-standby.tsnew file mode 100644index 00000000..b46a6021--- /dev/null+++ b/lib/agent/local-agent-standby.ts@@ -0,0 +1,183 @@+import { randomUUID } from "node:crypto";+import type { CapabilityRuntime } from "@/lib/capabilities/runtime";+import { activeWorkflowForActor } from "@/lib/workflow";+import { getAgentSession } from "./session-store";+import { listLocalAgentExecutableInbox } from "./local-agent-mailbox";+import {+ localAgentConsumerConnected,+ subscribeLocalAgentStandbyMessages,+} from "./local-agent-events";+import { executeLocalAgentStandbyMessage } from "./local-agent-standby-execution";+import {+ armLocalAgentStandbyRecord,+ blockLocalAgentStandby,+ disarmLocalAgentStandbyForWorkflow,+ disarmLocalAgentStandbyRecord,+ getLocalAgentStandbyRecord,+ listAllArmedLocalAgentStandbyRecords,+} from "./local-agent-standby-store";+import type { LocalAgentStandbyRecord } from "./local-agent-types";++const runtimeId = `standby:${process.pid}:${randomUUID()}`;+const subscriptions = new Map<string, () => void>();+const inFlightSessions = new Set<string>();+let runtimeCapabilities: CapabilityRuntime | null = null;+let reconcilePromise: Promise<void> | null = null;++function executionKey(+ record: Pick<LocalAgentStandbyRecord, "principalHash" | "sessionId">,+): string {+ return `${record.principalHash}:${record.sessionId}`;+}++function removeSubscription(sessionId: string): void {+ const unsubscribe = subscriptions.get(sessionId);+ if (!unsubscribe) return;+ subscriptions.delete(sessionId);+ unsubscribe();+}++function installSubscription(record: LocalAgentStandbyRecord): void {+ if (!record.armed || subscriptions.has(record.sessionId)) return;+ const unsubscribe = subscribeLocalAgentStandbyMessages(record.sessionId, (message) => {+ if (!message.execution?.requested ||+ !message.execution.authorized ||+ message.intent !== "request") return;+ void drainStandbySession(record.principal, record.sessionId).catch(() => undefined);+ });+ subscriptions.set(record.sessionId, unsubscribe);+}++async function validateRecord(+ record: LocalAgentStandbyRecord,+): Promise<{ valid: true } | { valid: false; reason: string }> {+ const session = await getAgentSession(record.principal, record.sessionId).catch(() => null);+ if (!session) return { valid: false, reason: "standby session no longer exists" };+ const workflow = await activeWorkflowForActor(record.workflowActor, record.workflowId)+ .catch(() => null);+ if (!workflow) return { valid: false, reason: "standby workflow is no longer active" };+ return { valid: true };+}++export async function drainStandbySession(+ principal: string,+ sessionId: string,+): Promise<void> {+ if (!runtimeCapabilities) return;+ const initial = await getLocalAgentStandbyRecord(principal, sessionId).catch(() => null);+ if (!initial?.armed) return;+ const key = executionKey(initial);+ if (inFlightSessions.has(key)) return;+ inFlightSessions.add(key);+ try {+ for (let processed = 0; processed < 100; processed += 1) {+ const record = await getLocalAgentStandbyRecord(principal, sessionId);+ if (!record?.armed) break;+ const validation = await validateRecord(record);+ if (!validation.valid) {+ await blockLocalAgentStandby(principal, sessionId, validation.reason);+ removeSubscription(sessionId);+ break;+ }+ const [next] = await listLocalAgentExecutableInbox(principal, sessionId, 1);+ if (!next) break;+ const result = await executeLocalAgentStandbyMessage({+ record,+ message: next,+ capabilities: runtimeCapabilities,+ runtimeId,+ });+ if (result.fatal) {+ removeSubscription(sessionId);+ break;+ }+ if (!result.advanced) break;+ }+ } finally {+ inFlightSessions.delete(key);+ }+}++export async function ensureLocalAgentStandbyRuntime(+ capabilities: CapabilityRuntime,+): Promise<void> {+ runtimeCapabilities = capabilities;+ if (reconcilePromise) return reconcilePromise;+ reconcilePromise = (async () => {+ const records = await listAllArmedLocalAgentStandbyRecords();+ for (const record of records) {+ installSubscription(record);+ // Subscribe first, then reread durable mail to close the event/read race.+ void drainStandbySession(record.principal, record.sessionId).catch(() => undefined);+ }+ })().finally(() => {+ reconcilePromise = null;+ });+ return reconcilePromise;+}++export async function armLocalAgentStandby(input: {+ principal: string;+ sessionId: string;+ workflowActor: string;+ workflowId: string;+ capabilities: CapabilityRuntime;+}) {+ if (!await activeWorkflowForActor(input.workflowActor, input.workflowId))+ throw new Error("workflow_id was not found for this MSO session");+ runtimeCapabilities = input.capabilities;+ const record = await armLocalAgentStandbyRecord(input);+ installSubscription(record);+ // Server takes over reconciliation; the current MCP/HTTP call returns now.+ void drainStandbySession(input.principal, input.sessionId).catch(() => undefined);+ return {+ mode: "listen" as const,+ status: "waiting" as const,+ standbyArmed: true,+ actionable: true,+ consumerConnected: localAgentConsumerConnected(record.sessionId),+ sessionId: record.sessionId,+ workflowId: record.workflowId,+ armedAt: record.armedAt,+ };+}++export async function stopLocalAgentStandby(input: {+ principal: string;+ sessionId: string;+ workflowId: string;+}) {+ const record = await disarmLocalAgentStandbyRecord(+ input.principal,+ input.sessionId,+ input.workflowId,+ "standby explicitly stopped",+ );+ removeSubscription(input.sessionId);+ return {+ mode: "stop" as const,+ standbyArmed: false,+ sessionId: input.sessionId,+ workflowId: input.workflowId,+ changed: Boolean(record),+ };+}++export async function disarmLocalAgentStandbyWorkflow(+ workflowActor: string,+ workflowId: string,+ reason: string,+): Promise<number> {+ const changed = await disarmLocalAgentStandbyForWorkflow(workflowActor, workflowId, reason);+ for (const row of changed) removeSubscription(row.sessionId);+ return changed.length;+}++/** Test-only process-restart simulation: subscriptions are ephemeral by design. */+export function resetLocalAgentStandbyRuntimeForTest(): void {+ for (const unsubscribe of subscriptions.values()) unsubscribe();+ subscriptions.clear();+ inFlightSessions.clear();+ runtimeCapabilities = null;+ reconcilePromise = null;+}diff --git a/lib/agent/local-agent-types.ts b/lib/agent/local-agent-types.tsindex 735de411..20103600 100644--- a/lib/agent/local-agent-types.ts+++ b/lib/agent/local-agent-types.ts@@ -6,11 +6,45 @@ export type LocalAgentMessageKind = "message" | "task";export type LocalAgentMessageIntent = "request" | "reply" | "notify";export type LocalAgentDeliveryStatus =| "accepted"+ | "accepted_for_standby"| "delivered"| "queued"| "target_offline"| "failed";export type LocalAgentStoredMessageState = "accepted" | "queued" | "delivered" | "read";+export type LocalAgentStandbyState = "waiting" | "working" | "blocked";+export type LocalAgentMessageExecutionState = "pending" | "claimed" | "completed" | "failed";++export interface LocalAgentMessageExecution {+ requested: true;+ authorized: boolean;+ state: LocalAgentMessageExecutionState;+ attempts?: number;+ claimedBy?: string;+ claimLeaseUntil?: string;+ taskId?: string;+ completedAt?: string;+ error?: string;+}++export interface LocalAgentStandbyRecord {+ principalHash: string;+ principal: string;+ sessionId: string;+ workflowActor: string;+ workflowId: string;+ armed: boolean;+ state: LocalAgentStandbyState;+ armedAt: string;+ updatedAt: string;+ executionLeaseUntil?: string;+ claimedBy?: string;+ currentMessageId?: string;+ currentTaskId?: string;+ lastMessageId?: string;+ lastRunAt?: string;+ lastError?: string;+}export interface LocalAgentPresenceRecord {sessionId: string;@@ -34,6 +68,13 @@ export interface LocalAgentTarget {status: LocalAgentStatus;consumerConnected: boolean;consumerCount: number;+ standbyArmed: boolean;+ standbyState?: LocalAgentStandbyState;+ standbyWorkflowId?: string;+ standbySince?: string;+ actionable: boolean;+ queuedCount: number;+ currentCommand?: string;cwd?: string;lastSeenAt: string;}@@ -52,6 +93,7 @@ export interface LocalAgentStoredMessage {requiresUserRelay?: boolean;text: string;state: LocalAgentStoredMessageState;+ execution?: LocalAgentMessageExecution;createdAt: string;deliveredAt?: string;readAt?: string;@@ -70,6 +112,7 @@ export interface LocalAgentMessageView {requiresUserRelay: boolean;text: string;state: LocalAgentStoredMessageState;+ execution?: LocalAgentMessageExecution;createdAt: string;deliveredAt?: string;readAt?: string;diff --git a/lib/capabilities/actors.ts b/lib/capabilities/actors.tsindex 95d71a06..8c1cef93 100644--- a/lib/capabilities/actors.ts+++ b/lib/capabilities/actors.ts@@ -1,7 +1,8 @@import type { CapabilityToolProfile } from "./tool";-export interface CapabilityAgentContext { principal?: string; sessionId?: string; toolProfile?: CapabilityToolProfile; trustedOpenAiFileParams?: boolean; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }+export interface CapabilityAgentContext { principal?: string; sessionId?: string; workflowActorOverride?: string; toolProfile?: CapabilityToolProfile; trustedOpenAiFileParams?: boolean; allowedTools?: readonly string[]; toolArgumentConstraints?: Readonly<Record<string, Readonly<Record<string, readonly string[]>>>>; }export function workflowActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {+ if (context?.workflowActorOverride) return context.workflowActorOverride;return context?.principal && context.sessionId ? `${context.principal}#session:${context.sessionId}` : actor;}export function recipeActor(actor: string | undefined, context?: CapabilityAgentContext): string | undefined {diff --git a/lib/capabilities/runtime.ts b/lib/capabilities/runtime.tsindex 5e204f41..b897ca34 100644--- a/lib/capabilities/runtime.ts+++ b/lib/capabilities/runtime.ts@@ -17,6 +17,9 @@ export interface CapabilityInvocation {actor?: string;principal?: string;sessionId?: string;+ /** Optional fixed workflow context used by durable delegated workers. */+ workflowId?: string;+ workflowActor?: string;}export interface CapabilityInvocationResult {diff --git a/lib/mcp/capability-runtime.ts b/lib/mcp/capability-runtime.tsindex 7060c442..3e9af712 100644--- a/lib/mcp/capability-runtime.ts+++ b/lib/mcp/capability-runtime.ts@@ -25,14 +25,17 @@ export const msoCapabilityRuntime: CapabilityRuntime = {async invoke(input) {const tool = TOOLS_BY_NAME.get(input.name);if (!tool) return { content: [{ type: "text", text: `error: unknown tool: ${input.name}` }], isError: true };+ const args = { ...(input.args ?? {}) };+ if (input.workflowId) args.workflow_id = input.workflowId;const outcome = await executeCapabilityCall({tool,- args: input.args ?? {},+ args,scope: input.scope,actor: input.actor,context: {principal: input.principal,sessionId: input.sessionId,+ ...(input.workflowActor ? { workflowActorOverride: input.workflowActor } : {}),capabilities: msoCapabilityRuntime,},});diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex ff59bec0..47fc08a7 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -92,6 +92,7 @@ const MCP_ONLY: Record<string, string> = {"local.agent.reply": "correlated replies belong to the durable Local Agents session mailbox; Alfa browser threads do not share that session identity or inbox","local.agent.request.wait": "bounded request observation is tied to the durable Local Agents mailbox/correlation ledger; Alfa browser threads do not own that AgentSession sender identity","local.agent.request": "fresh-worker execution from another durable AgentSession context belongs to the terminal/MCP orchestration runtime; Alfa browser threads neither share that isolated session store nor its exec delegation boundary",+ "local.agent.standby": "durable standby is bound to an external/CLI AgentSession plus exact active workflow; Alfa browser threads do not share that durable session/workflow identity, while Cockpit only observes its safe projected status","tool.forge.candidates": "Tool Forge is the external/terminal cognitive-runtime promotion pipeline; Alfa has a separate in-app lifecycle and must not implicitly expose generated project capabilities","tool.forge.propose": "same Forge boundary; creating an inert candidate depends on learned external workflow recipes rather than Alfa owner recall","tool.forge.evaluate": "Forge evaluation may execute project-owned fixtures only inside the dedicated sandbox and therefore stays on the scoped external/terminal automation surface",@@ -214,6 +215,7 @@ describe("MCP rate limits mirror the routes", () => {"local-agent.send": 60,"local-agent.wait": 30,"local-agent.request": 12,+ "local-agent.standby": 30,"tool.forge.propose": 20,"tool.forge.evaluate": 10,"tool.forge.promote": 6,diff --git a/lib/mcp/session-workflow-isolation.test.ts b/lib/mcp/session-workflow-isolation.test.tsindex a77c8f8d..a6dd54ae 100644--- a/lib/mcp/session-workflow-isolation.test.ts+++ b/lib/mcp/session-workflow-isolation.test.ts@@ -32,6 +32,11 @@ describe("conversation-scoped workflow ownership", () => {const intent = "verify the repeated session-scoped deployment recipe";expect(aOwner).not.toBe(bOwner);+ expect(workflowActor("a2a:delegate", {+ principal: "a2a:local:worker",+ sessionId: "task_delegate",+ workflowActorOverride: aOwner,+ })).toBe(aOwner);expect(learnedOwnerA).toBe(principal);expect(learnedOwnerB).toBe(principal);diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.tsindex 1708d514..aec4a16c 100644--- a/lib/mcp/tool-contract.ts+++ b/lib/mcp/tool-contract.ts@@ -47,7 +47,7 @@ const TITLES: Record<string, string> = {read_pipeline: "Run Read Pipeline", fs_list: "List Files", fs_read: "Read File", fs_search: "Search Directories", fs_write: "Write File",exec_run: "Run Command", exec_job_start: "Start Command Job", exec_job_status: "Command Job Status", exec_job_cancel: "Cancel Command Job",agent_session_current: "Current Agent Session", agent_session_flow: "Read Session Flow", agent_session_action_resolve: "Resolve Session Action", agent_session_rename: "Rename Agent Session",- local_agents_list: "List Local Agents", local_agent_inbox: "Receive Local Agent Messages",+ local_agents_list: "List Local Agents", local_agent_inbox: "Receive Local Agent Messages", local_agent_standby: "Local Agent Standby",organization_chart: "Organization Chart", organization_manage: "Manage Organization",local_agent_message_send: "Send Local Agent Message", local_agent_reply: "Reply to Local Agent", local_agent_request_wait: "Wait for Local Agent Reply",a2a_agent_discover: "Discover A2A Agent", a2a_agents_list: "List A2A Agents", a2a_message_send: "Send A2A Message",diff --git a/lib/mcp/tools-local-agents.test.ts b/lib/mcp/tools-local-agents.test.tsindex 2c17a509..12b6c389 100644--- a/lib/mcp/tools-local-agents.test.ts+++ b/lib/mcp/tools-local-agents.test.ts@@ -15,6 +15,7 @@ describe("native local session agent MCP tools", () => {expect(local.get("local_agent_message_send")?.scope).toBe("write");expect(local.get("local_agent_reply")?.scope).toBe("write");expect(local.get("local_agent_request")?.scope).toBe("exec");+ expect(local.get("local_agent_standby")?.scope).toBe("exec");});it("describes local collaboration without Agent Card registration", () => {@@ -26,6 +27,8 @@ describe("native local session agent MCP tools", () => {expect(local.get("local_agent_request_wait")?.description).toMatch(/bounded foreground/i);expect(local.get("local_agent_request")?.description).toMatch(/fresh bounded worker/i);expect(local.get("local_agent_inbox")?.description).toMatch(/bounded interval/i);+ expect(local.get("local_agent_standby")?.description).toMatch(/returns immediately/i);+ expect(local.get("local_agent_standby")?.description).toMatch(/consumerConnected/i);const inboxSchema = JSON.stringify(local.get("local_agent_inbox")?.inputSchema ?? {});expect(inboxSchema).toContain('"wait_ms"');expect(inboxSchema).toContain('"maximum":20000');diff --git a/lib/mcp/tools-local-agents.ts b/lib/mcp/tools-local-agents.tsindex e4af9e48..2d53a858 100644--- a/lib/mcp/tools-local-agents.ts+++ b/lib/mcp/tools-local-agents.ts@@ -1,6 +1,11 @@import { listLocalAgents } from "@/lib/agent/local-agent-directory";import { updateLocalAgentMessageState } from "@/lib/agent/local-agent-mailbox";import { replyLocalAgentMessage, sendLocalAgentMessage, waitForLocalAgentInbox, waitForLocalAgentReply } from "@/lib/agent/local-agent-messaging";+import {+ armLocalAgentStandby,+ ensureLocalAgentStandbyRuntime,+ stopLocalAgentStandby,+} from "@/lib/agent/local-agent-standby";import { handoffOwnerLocalSession } from "@/lib/a2a/local-session";import { type McpRunContext, type McpTool, S, str } from "./tool-kit";@@ -13,31 +18,77 @@ function sessionContext(context: McpRunContext): { principal: string; sessionId:export const LOCAL_AGENT_TOOLS: McpTool[] = [{name: "local_agents_list",- description: "List same-owner MSO session agents on this host. Every session has a short public name such as milo or luna for @mention UX. status reflects the presence lease; consumerConnected/consumerCount separately report whether this MSO runtime currently has an inbound receiver subscribed. No Agent Card, URL, registration, refresh, or restart is required.",+ description: "List same-owner MSO session agents on this host. status reflects the presence lease; consumerConnected/consumerCount report only foreground inbound receivers. standbyArmed/standbyState/actionable separately report durable server-native standby, so an offline ChatGPT tab is never mislabeled connected.",scope: "read",annotations: { readOnlyHint: true, idempotentHint: true },limit: { key: "local-agent.read", max: 60, windowMs: 60_000 },- inputSchema: S({ include_offline: { type: "boolean", description: "Also include known sessions whose receive lease expired or explicitly ended. Default false." } }),+ inputSchema: S({ include_offline: { type: "boolean", description: "Also include known sessions whose receive lease expired or explicitly ended. Armed standby agents are included regardless because they remain actionable." } }),run: async (a, context) => {const current = sessionContext(context);+ if (context.capabilities) await ensureLocalAgentStandbyRuntime(context.capabilities).catch(() => undefined);return listLocalAgents(current.principal, { currentSessionId: current.sessionId, includeOffline: a.include_offline === true });},},+ {+ name: "local_agent_standby",+ description: "Arm or stop durable server-native standby for this exact conversation-bound session and workflow. listen returns immediately; MSO keeps the saved session actionable after this tool call ends, executes only explicitly authorized correlated requests sequentially, replies, and returns to waiting. This does not keep an HTTP call open and does not make consumerConnected true.",+ chatgptDescription: "Arm/stop durable local-agent standby.",+ scope: "exec",+ annotations: { idempotentHint: true, destructiveHint: false, openWorldHint: false },+ audit: { action: "agent.session" as const },+ actionContract: {+ phase: "execute",+ target: "local-agent-standby",+ sourceOfTruth: "live",+ validators: ["workflow-ownership", "session-ownership", "exec-scope"],+ verify: ["local_agents_list"],+ confirmation: "none",+ concurrency: "contextual",+ presentation: "structured",+ },+ limit: { key: "local-agent.standby", max: 30, windowMs: 60_000 },+ inputSchema: S({+ mode: { type: "string", enum: ["listen", "stop"], description: "listen arms durable standby; stop disarms it." },+ }, ["mode"]),+ run: async (a, context) => {+ const current = sessionContext(context);+ if (!context.capabilities) throw new Error("capability runtime unavailable for local-agent standby");+ if (!context.workflowId || !context.workflowActor)+ throw new Error("local_agent_standby requires this conversation's exact active workflow_id");+ const mode = str(a, "mode");+ if (mode === "stop") {+ return stopLocalAgentStandby({+ principal: current.principal,+ sessionId: current.sessionId,+ workflowId: context.workflowId,+ });+ }+ if (mode !== "listen") throw new Error("local_agent_standby mode must be listen or stop");+ return armLocalAgentStandby({+ principal: current.principal,+ sessionId: current.sessionId,+ workflowActor: context.workflowActor,+ workflowId: context.workflowId,+ capabilities: context.capabilities,+ });+ },+ },{name: "local_agent_message_send",- description: "Send one explicit text message/task to another same-owner MSO session agent. Defaults to notify-only semantics, so it never causes a user-facing relay by itself. For a request that expects a later answer, set intent=request and requires_user_relay=true; the receiver should answer that exact request with local_agent_reply. No hidden transcript, memory, credentials, tool arguments, or extra permissions are copied.",+ description: "Send one explicit text message/task to another same-owner MSO session agent. Defaults to notify-only semantics. intent=request creates correlation metadata; when the target has durable standby armed, only an exec-scoped caller authorizes automatic execution. A write-scoped caller can enqueue the same request but cannot grant execution. No hidden transcript, memory, credentials, tool arguments, or extra permissions are copied.",scope: "write",limit: { key: "local-agent.send", max: 60, windowMs: 60_000 },audit: { action: "agent.message", targetArg: "target" },inputSchema: S({- target: { type: "string", description: "Local public name such as milo, [milo], legacy internal alias such as agent-b, or exact durable session id." },+ target: { type: "string", description: "Local public name, legacy internal alias, or exact durable session id." },message: { type: "string", description: "Explicit payload, maximum 16 KiB." },kind: { type: "string", enum: ["message", "task"], description: "message (default) or task." },intent: { type: "string", enum: ["notify", "request"], description: "notify (default) or request. Replies must use local_agent_reply." },- requires_user_relay: { type: "boolean", description: "For request intent only: relay a correlated reply directly to the originating user-facing conversation." },+ requires_user_relay: { type: "boolean", description: "For request intent only: relay a correlated reply directly to the originating user-facing conversation when the surface supports it." },}, ["target", "message"]),run: async (a, context) => {const current = sessionContext(context);+ if (context.capabilities) await ensureLocalAgentStandbyRuntime(context.capabilities).catch(() => undefined);return sendLocalAgentMessage({principal: current.principal,senderSessionId: current.sessionId,@@ -46,12 +97,13 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [kind: typeof a.kind === "string" ? a.kind : undefined,intent: typeof a.intent === "string" ? a.intent : undefined,requiresUserRelay: a.requires_user_relay === true,+ executionAuthorized: context.scope === "exec",});},},{name: "local_agent_request",- description: "Run an explicit objective against another same-owner durable MSO session and return its result. Unlike mailbox delivery, it works when that session's terminal receiver is offline: MSO starts a fresh bounded worker using the target session's saved context. It never wakes or controls a ChatGPT/terminal process, and it copies no hidden live transcript.",+ description: "Run an explicit objective against another same-owner durable MSO session and return its result. Unlike mailbox delivery, it works when that session's terminal receiver is offline: MSO starts a fresh bounded worker using the target session's saved context. It is the on-demand primitive also reused by durable standby; it never wakes or controls a ChatGPT/terminal process and copies no hidden live transcript.",scope: "exec",limit: { key: "local-agent.request", max: 12, windowMs: 60_000 },audit: { action: "agent.message", targetArg: "target" },@@ -69,7 +121,7 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [},{name: "local_agent_request_wait",- description: "Wait a bounded foreground interval for the correlated reply to one exact request previously sent by this session. Returns replied, target_offline, consumer_absent, or timeout with current receiver observability. This never starts a background loop and never resends the request.",+ description: "Wait a bounded foreground interval for the correlated reply to one exact request previously sent by this session. Returns replied, target_offline, consumer_absent, or timeout with current receiver/standby observability. This never starts a background loop and never resends the request.",scope: "read",annotations: { readOnlyHint: true, idempotentHint: true },limit: { key: "local-agent.wait", max: 30, windowMs: 60_000 },@@ -111,7 +163,7 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [},{name: "local_agent_inbox",- description: "Read durable local-agent messages for this exact session. With wait_ms > 0, keep this foreground MCP call open for a bounded interval and return as soon as a peer message arrives; this uses the existing in-process receiver plus the durable mailbox, never a background loop. Each item carries explicit intent/correlation metadata. If intent=request, answer it with local_agent_reply(reply_to_message_id=<item.id>, ...); do not invent correlation by parsing text. By default only unread items are returned.",+ description: "Read durable local-agent messages for this exact session. With wait_ms > 0, keep this foreground MCP call open for a bounded interval and return as soon as a peer message arrives; this legacy receiver remains separate from server-native standby. Each item carries explicit intent/correlation metadata. If intent=request, answer it with local_agent_reply. By default only unread items are returned.",scope: "read",annotations: { readOnlyHint: true, idempotentHint: true },limit: { key: "local-agent.read", max: 120, windowMs: 60_000 },@@ -119,7 +171,7 @@ export const LOCAL_AGENT_TOOLS: McpTool[] = [include_read: { type: "boolean" },limit: { type: "number", description: "1-200, default 100." },acknowledge: { type: "boolean", description: "When true, mark returned messages read after retrieval." },- wait_ms: { type: "number", minimum: 0, maximum: 20000, description: "Optional foreground receive wait in milliseconds. Default 0 preserves immediate inbox reads; max 20000. Returns early when a peer message arrives." },+ wait_ms: { type: "number", minimum: 0, maximum: 20000, description: "Optional foreground receive wait in milliseconds. Default 0 preserves immediate inbox reads; max 20000." },}),run: async (a, context) => {const current = sessionContext(context);diff --git a/lib/mcp/tools-workflow-lifecycle.ts b/lib/mcp/tools-workflow-lifecycle.tsindex 512b9dcb..377e3c1c 100644--- a/lib/mcp/tools-workflow-lifecycle.ts+++ b/lib/mcp/tools-workflow-lifecycle.ts@@ -2,6 +2,7 @@ import { inspectProject, resolveProjectHint } from "@/lib/host/projects-api";import { activeWorkflowForActor, cancelWorkflow, finishWorkflow, workflowStepProvenance } from "@/lib/workflow";import { getAgentSession } from "@/lib/agent/session-store";import { agentSessionLabel } from "@/lib/agent/session-name";+import { disarmLocalAgentStandbyWorkflow } from "@/lib/agent/local-agent-standby";import { assessAutomationPromotion, buildAutomationScriptManifest, workflowCleanupGuidance } from "@/lib/orchestration/automation";import { classifyTask } from "@/lib/orchestration/classifier";import { buildEvidenceReceipt, validateEvidenceReceipt } from "@/lib/orchestration/evidence";@@ -48,11 +49,14 @@ export const WORKFLOW_LIFECYCLE_TOOLS: McpTool[] = [reason: { type: "string", description: "Optional reason; no secrets." },}, ["workflow_id"]),run: async (a, context) => {+ const workflowActor = context.workflowActor ?? context.actor;const cancelled = await cancelWorkflow({- actor: context.workflowActor ?? context.actor,+ actor: workflowActor,workflowId: str(a, "workflow_id"),reason: opt(a, "reason"),});+ if (workflowActor)+ await disarmLocalAgentStandbyWorkflow(workflowActor, cancelled.workflow.id, "workflow cancelled");return { ...cancelled, cleanup: workflowCleanupGuidance(cancelled.workflow.orchestration) };},},@@ -106,6 +110,7 @@ export const WORKFLOW_LIFECYCLE_TOOLS: McpTool[] = [const finished = await finishWorkflow({actor, recipeActor: context.recipeActor ?? context.actor, workflowId, summary, success, stepProvenance,});+ if (actor) await disarmLocalAgentStandbyWorkflow(actor, workflowId, "workflow finished");const automation = assessAutomationPromotion(finished.recipe);const persistenceWarnings: string[] = [];let evidencePath: string | undefined;diff --git a/lib/mcp/tools-workflow-standby-lifecycle.test.ts b/lib/mcp/tools-workflow-standby-lifecycle.test.tsnew file mode 100644index 00000000..854c3076--- /dev/null+++ b/lib/mcp/tools-workflow-standby-lifecycle.test.ts@@ -0,0 +1,66 @@+import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdtempSync, rmSync } from "node:fs";+import os from "node:os";+import path from "node:path";++vi.mock("server-only", () => ({}));++const root = mkdtempSync(path.join(os.tmpdir(), "mso-standby-workflow-lifecycle-"));+process.env.OS_AGENT_SESSIONS_DIR = path.join(root, "sessions");+process.env.OS_LOCAL_AGENT_STANDBY_STORE = path.join(root, "standby.json");+process.env.OS_SKILL_MEMORY_STORE = path.join(root, "workflow.json");+process.env.NEXT_PUBLIC_OS_DEMO = "0";++const workflow = await import("@/lib/workflow");+const sessions = await import("@/lib/agent/session-store");+const standbyStore = await import("@/lib/agent/local-agent-standby-store");+const { WORKFLOW_LIFECYCLE_TOOLS } = await import("./tools-workflow-lifecycle");++const actor = "mcp:standby-lifecycle";+const principal = "mcp-client:standby-lifecycle";+const tools = new Map(WORKFLOW_LIFECYCLE_TOOLS.map((tool) => [tool.name, tool]));++async function armedWorkflow(intent: string) {+ const started = await workflow.startWorkflow({ actor, scope: "write", intent });+ const session = await sessions.createAgentSession(principal, "mcp");+ await standbyStore.armLocalAgentStandbyRecord({+ principal,+ sessionId: session.id,+ workflowActor: actor,+ workflowId: started.workflow.id,+ });+ return { session, workflow: started.workflow };+}++beforeEach(() => {+ workflow.resetWorkflowStoreCache();+});++afterAll(() => {+ workflow.resetWorkflowStoreCache();+ rmSync(root, { recursive: true, force: true });+});++describe("workflow lifecycle disarms durable local-agent standby", () => {+ it("workflow_cancel disarms the exact matching standby record", async () => {+ const started = await armedWorkflow("cancel standby integration");+ await tools.get("workflow_cancel")!.run(+ { workflow_id: started.workflow.id, reason: "test cancel" },+ { actor, workflowActor: actor, scope: "write" },+ );+ const record = await standbyStore.getLocalAgentStandbyRecord(principal, started.session.id);+ expect(record).toMatchObject({ workflowId: started.workflow.id, armed: false });+ expect(await workflow.activeWorkflowForActor(actor, started.workflow.id)).toBeNull();+ });++ it("workflow_finish disarms the exact matching standby record", async () => {+ const started = await armedWorkflow("finish standby integration");+ await tools.get("workflow_finish")!.run(+ { workflow_id: started.workflow.id, summary: "verified", success: true },+ { actor, workflowActor: actor, scope: "write" },+ );+ const record = await standbyStore.getLocalAgentStandbyRecord(principal, started.session.id);+ expect(record).toMatchObject({ workflowId: started.workflow.id, armed: false });+ expect(await workflow.activeWorkflowForActor(actor, started.workflow.id)).toBeNull();+ });+});diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex 63fa801c..ec8fa63d 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -4,8 +4,8 @@ import type { McpTool } from "./tool-kit";import { toolDescriptor, type McpToolProfile } from "./tool-contract";export const MCP_SERVER_VERSION = "1.15.1";-export const MCP_TOOLSET_VERSION = "2026.09.19.5";-export const MCP_TOOLSET_CHANGED_AT = "2026-09-19T22:42:49+07:00";+export const MCP_TOOLSET_VERSION = "2026.09.20.1";+export const MCP_TOOLSET_CHANGED_AT = "2026-09-20T11:37:43+07:00";export type McpToolsetInfo = {serverVersion: string;diff --git a/lib/orchestration/capability-catalog.mjs b/lib/orchestration/capability-catalog.mjsindex 887d5332..313a818b 100644--- a/lib/orchestration/capability-catalog.mjs+++ b/lib/orchestration/capability-catalog.mjs@@ -35,7 +35,7 @@ const ROUTES = [{ id: "cloudflare-dns", priority: 100, patterns: [/\bcloudflare\b.*\b(dns|zone|record)\b/i], tools: ["cloudflare_zones_list", "cloudflare_dns_upsert"], budget: 10_000 },{ id: "hostinger-dns", priority: 100, patterns: [/\bhostinger\b.*\b(dns|domain|record)\b/i], tools: ["hostinger_dns_upsert"], budget: 10_000 },{ id: "dokploy", priority: 95, patterns: [/\bdokploy\b/i], tools: ["dokploy_projects_list", "dokploy_project_ensure"], budget: 10_000 },- { id: "local-agent", priority: 100, patterns: [/\b(local|same[- ]host|session)\b.*\b(agent|delegate|message|inbox|request|reply)\b/i, /\blocal_agent_/i], tools: ["local_agents_list", "local_agent_inbox", "local_agent_message_send", "local_agent_reply", "local_agent_request_wait", "local_agent_request"], budget: 12_000 },+ { id: "local-agent", priority: 100, patterns: [/\b(local|same[- ]host|session)\b.*\b(agent|delegate|message|inbox|request|reply)\b/i, /\blocal_agent_/i], tools: ["local_agents_list", "local_agent_inbox", "local_agent_standby", "local_agent_message_send", "local_agent_reply", "local_agent_request_wait", "local_agent_request"], budget: 12_000 },{ id: "subagent", priority: 100, patterns: [/\b(subagent|spawn .*reviewer|spawn .*worker|independent reviewer|isolated worker)\b/i], tools: ["agent_subagent_run"], budget: 12_000 },{ id: "a2a", priority: 100, patterns: [/\b(a2a|agent card|remote agent|peer agent|handoff)\b/i], tools: ["a2a_agents_list", "a2a_agent_discover", "a2a_message_send", "a2a_handoff", "a2a_task_get"], budget: 12_000 },{ id: "forge", priority: 100, patterns: [/\b(tool forge|forge candidate|promote .*tool|self[- ]improv|generate tool)\b/i], tools: ["tool_forge_candidates", "tool_forge_propose", "tool_forge_evaluate", "tool_forge_promote"], budget: 12_000 },diff --git a/scripts/mso-gateway-recovery.test.ts b/scripts/mso-gateway-recovery.test.tsindex c5a48c74..bb404ff2 100644--- a/scripts/mso-gateway-recovery.test.ts+++ b/scripts/mso-gateway-recovery.test.ts@@ -70,7 +70,7 @@ exec node -e 'require(process.argv[1] + ".cjs")' "$0" "$@"run(["stop"], f.env);for (let i = 0; i < 50 && spawned.some(alive); i++) await new Promise((r) => setTimeout(r, 20));expect(spawned.filter(alive)).toEqual([]);- }, 10_000);+ }, 20_000);it("preserves owned runtime identity when only the old tunnel died", async () => {const f = fixture();