You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by xx...@apache.org on 2026/10/19 06:48:43 UTC
(maka) 01/01: feat(assistant): execute tools across connected Maka hosts
This is an automated email from the ASF dual-hosted git repository.
xxhZs pushed a commit to branch feat/assistant-remote-host-tools
in repository https://gitbox.apache.org/repos/asf/maka.git
commit 591c08bc2bc365f85320eab3b7133486ae2448cb
Author: xxhZs <84...@users.noreply.github.com>
AuthorDate: Mon Oct 19 14:48:09 2026 +0800
feat(assistant): execute tools across connected Maka hosts
---
.../src/main/__tests__/remote-host-tools.test.ts | 196 +++++++++
apps/desktop/src/main/remote-host-tools.ts | 243 +++++++++++
apps/desktop/src/main/runtime-host-boot.ts | 9 +
docs/remote-agent-tools.md | 93 +++++
.../__tests__/assistant-memory-feedback.test.ts | 9 +-
.../src/__tests__/authenticated-websocket.test.ts | 266 ++++++++++++
.../src/__tests__/execution-composition.test.ts | 455 +++++++++++++++++++++
.../__tests__/execution-model-composition.test.ts | 52 +++
.../src/__tests__/remote-tools.test.ts | 423 +++++++++++++++++++
packages/runtime-host/src/assistant/bot/bridge.ts | 2 +
.../src/assistant/index-initiative/host.ts | 119 +++++-
packages/runtime-host/src/assistant/service.ts | 17 +-
packages/runtime-host/src/protocol/index.ts | 5 +-
packages/runtime-host/src/protocol/operations.ts | 8 +-
packages/runtime-host/src/protocol/remote-tools.ts | 89 ++++
.../src/server/execution-composition.ts | 123 ++++++
.../src/server/interactive-run-composer.ts | 20 +-
packages/runtime-host/src/server/remote-tools.ts | 369 +++++++++++++++++
18 files changed, 2484 insertions(+), 14 deletions(-)
diff --git a/apps/desktop/src/main/__tests__/remote-host-tools.test.ts b/apps/desktop/src/main/__tests__/remote-host-tools.test.ts
new file mode 100644
index 0000000000..dc14234ae5
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/remote-host-tools.test.ts
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { RemoteHostToolsBridge } from '../remote-host-tools.js';
+function setup() {
+ const calls: { host: string; input: any }[] = [];
+ let online = true,
+ accepted = true,
+ ackFails = false;
+ const pending = [{ id: 'event-1', sessionId: 'owner', content: { text: 'done' } }];
+ const targets = ['main', 'remote'].map((host) => ({
+ hostId: host,
+ epoch: host,
+ readiness: 'ready',
+ target: { profile: { name: host } },
+ candidate: {
+ client: {
+ request: async (_op: string, input: any) => {
+ calls.push({ host, input });
+ if (input.action === 'origin') return { value: { sessionId: 'owner' } };
+ if (input.action === 'events') return { value: host === 'remote' ? [...pending] : [] };
+ if (input.action === 'deliver') return { value: { accepted } };
+ if (input.action === 'ack') {
+ if (ackFails) throw Error('disconnect');
+ pending.splice(0);
+ }
+ return { value: { ok: true } };
+ },
+ },
+ },
+ }));
+ const bridge = new RemoteHostToolsBridge(
+ () =>
+ ({
+ entries: () => (online ? targets : [targets[0]]),
+ ownsScope: (s: any) => s.hostId === 'main' && s.targetEpoch === 'main',
+ }) as any,
+ );
+ return {
+ bridge,
+ calls,
+ pending,
+ tools: bridge.tools({ hostId: 'main', targetEpoch: 'main' }),
+ offline: () => {
+ online = false;
+ },
+ accept: (v: boolean) => {
+ accepted = v;
+ },
+ failAck: (v: boolean) => {
+ ackFails = v;
+ },
+ };
+}
+test('remote tools bind the origin and stable target, never default Host', async () => {
+ const f = setup();
+ try {
+ const open = f.tools.find((t) => t.name === 'RemoteHostOpen')!;
+ await open.impl({ hostId: 'remote', templateSession: 'template' }, {
+ sessionId: 'bot-worker',
+ } as any);
+ assert.equal(f.calls[1].host, 'remote');
+ assert.equal(f.calls[1].input.originSession, 'owner');
+ await assert.rejects(
+ async () =>
+ open.impl({ hostId: 'main', templateSession: 'template' }, {
+ sessionId: 'bot-worker',
+ } as any),
+ /local tools/,
+ );
+ await f.tools
+ .find((t) => t.name === 'RemoteToolSearch')!
+ .impl({ hostId: 'remote', contextId: 'context', query: '' }, {
+ sessionId: 'bot-worker',
+ } as any);
+ assert.deepEqual(f.calls.at(-1)!.input.origin, { hostId: 'main', sessionId: 'owner' });
+ f.offline();
+ await assert.rejects(
+ async () =>
+ open.impl({ hostId: 'remote', templateSession: 'template' }, {
+ sessionId: 'bot-worker',
+ } as any),
+ /offline/,
+ );
+ } finally {
+ f.bridge.close();
+ }
+});
+test('feedback is acknowledged only after durable Inbox acceptance; lost acknowledgement retries same identity', async () => {
+ const f = setup();
+ try {
+ f.accept(false);
+ await f.bridge.poll();
+ assert.equal(f.pending.length, 1);
+ f.accept(true);
+ f.failAck(true);
+ await f.bridge.poll();
+ assert.equal(f.pending.length, 1);
+ f.failAck(false);
+ await f.bridge.poll();
+ assert.equal(f.pending.length, 0);
+ const delivered = f.calls.filter((c) => c.input.action === 'deliver');
+ assert.equal(new Set(delivered.map((c) => c.input.id)).size, 1);
+ assert.equal(delivered[0].input.content.hostId, 'remote');
+ } finally {
+ f.bridge.close();
+ }
+});
+test('stale origin scope cannot start remote work', async () => {
+ const f = setup();
+ try {
+ const tools = f.bridge.tools({ hostId: 'main', targetEpoch: 'expired' });
+ await assert.rejects(
+ async () => tools.find((t) => t.name === 'HostList')!.impl({}, {} as any),
+ /unavailable/,
+ );
+ assert.equal(f.calls.length, 0);
+ } finally {
+ f.bridge.close();
+ }
+});
+
+test('a stalled Host cannot block another Host feedback; every request has a transport deadline', async () => {
+ const delivered: string[] = [];
+ const timeouts: number[] = [];
+ let slowFinished = false;
+ const targets = ['main', 'slow', 'healthy'].map((hostId) => ({
+ hostId, readiness: 'ready', target: { profile: { name: hostId } }, candidate: { client: {
+ request: async (_op: string, input: any, timeoutMs: number) => {
+ timeouts.push(timeoutMs);
+ if (hostId === 'slow') {
+ await new Promise((resolve) => setTimeout(resolve, timeoutMs));
+ slowFinished = true;
+ throw Error('request_timeout');
+ }
+ if (input.action === 'events') return { value: hostId === 'healthy' && input.originHost === 'main' ? [{ id: 'ok', sessionId: 'bot', content: { text: 'ready' } }] : [] };
+ if (input.action === 'deliver') {
+ assert.equal(slowFinished, false, 'healthy feedback must not wait for the stalled Host');
+ delivered.push(input.id);
+ return { value: { accepted: true } };
+ }
+ return { value: {} };
+ },
+ } },
+ }));
+ const bridge = new RemoteHostToolsBridge(() => ({ entries: () => targets }) as any, 50);
+ try {
+ await bridge.poll();
+ assert.deepEqual(delivered, ['remote:healthy:ok']);
+ assert.ok(timeouts.length > 0 && timeouts.every((ms) => ms === 50));
+ } finally { bridge.close(); }
+});
+
+test('a rejected event does not hide later feedback and failed calls retain retry identity', async () => {
+ const delivered: string[] = [];
+ const targets = ['main', 'remote'].map((hostId) => ({ hostId, readiness: 'ready', candidate: { client: {
+ request: async (_op: string, input: any) => {
+ if (input.action === 'origin') return { value: { sessionId: 'bot' } };
+ if (input.action === 'call') throw Error('connection lost after dispatch');
+ if (input.action === 'events') return { value: hostId === 'remote' ? [
+ { id: 'bad', sessionId: 'old', content: {} }, { id: 'good', sessionId: 'bot', content: {} },
+ ] : [] };
+ if (input.action === 'deliver') {
+ if (input.sessionId === 'old') throw Error('conversation unavailable');
+ delivered.push(input.id);
+ return { value: { accepted: true } };
+ }
+ return { value: {} };
+ },
+ } } }));
+ const bridge = new RemoteHostToolsBridge(() => ({ entries: () => targets, ownsScope: () => true }) as any);
+ try {
+ await bridge.poll();
+ assert.deepEqual(delivered, ['remote:remote:good']);
+ const call = bridge.tools({ hostId: 'main', targetEpoch: 'e' }).find((t) => t.name === 'RemoteToolCall')!;
+ await assert.rejects(async () => call.impl({ hostId: 'remote', contextId: 'ctx', callId: 'stable-id', tool: 'Write', arguments: {} }, { sessionId: 'bot' } as any), /callId=stable-id.*RemoteToolResult.*SAME/);
+ } finally { bridge.close(); }
+});
diff --git a/apps/desktop/src/main/remote-host-tools.ts b/apps/desktop/src/main/remote-host-tools.ts
new file mode 100644
index 0000000000..4c9fa67699
--- /dev/null
+++ b/apps/desktop/src/main/remote-host-tools.ts
@@ -0,0 +1,243 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { z } from 'zod';
+import type { MakaTool } from '@maka/runtime/tool-runtime';
+import type { RemoteToolsRequest } from '@maka/runtime-host/protocol';
+import type { RuntimeHostDesktopManager } from './runtime-host-desktop-manager.js';
+
+type ScopedRequest<T = RemoteToolsRequest> = T extends { contextId: string; origin: unknown }
+ ? Omit<T, 'origin'>
+ : never;
+
+const id = z.string().min(1).max(256);
+/** Desktop-owned transport only. Execution, receipts and mailboxes live on Hosts. */
+export class RemoteHostToolsBridge {
+ private polling = false;
+ private readonly feedbackErrors = new Map<string, string>();
+ private stopped = false;
+ private readonly timer: ReturnType<typeof setInterval>;
+ constructor(
+ private readonly manager: () => RuntimeHostDesktopManager | undefined,
+ private readonly requestTimeoutMs = 15_000,
+ ) {
+ this.timer = setInterval(() => {
+ void this.poll();
+ }, 5000);
+ this.timer.unref();
+ }
+ private targets() {
+ return this.manager()?.entries() ?? [];
+ }
+ private target(hostId: string) {
+ const candidates = this.targets().filter((t) => t.hostId === hostId && t.readiness === 'ready');
+ if (candidates.length !== 1 || !('candidate' in candidates[0]!))
+ throw Error('Target Host is offline or ambiguous');
+ return candidates[0]!.candidate.client;
+ }
+ private async request(hostId: string, input: RemoteToolsRequest) {
+ try {
+ return (await this.target(hostId).request('remote.tools', input, this.requestTimeoutMs)).value;
+ } catch (error) {
+ if (input.action === 'call')
+ throw new Error(`Remote response unavailable for callId=${input.callId}, contextId=${input.contextId}, hostId=${hostId}. Execution may still be running. Use RemoteToolResult or retry the SAME callId and arguments; do not create a new call to repeat the effect. ${String(error)}`, { cause: error });
+ throw error;
+ }
+ }
+ tools(scope?: { hostId: string; targetEpoch: string }): readonly MakaTool[] {
+ const invoke = async (hostId: string, input: RemoteToolsRequest) => {
+ if (this.stopped || !scope || !this.manager()?.ownsScope(scope))
+ throw Error('Origin Host connection is no longer active');
+ if (hostId === scope.hostId) throw Error('Use local tools for the current Host');
+ return { hostId, value: await this.request(hostId, input) };
+ };
+ const scopedInvoke = async (hostId: string, request: ScopedRequest, sessionId: string) => {
+ if (!scope || !this.manager()?.ownsScope(scope))
+ throw Error('Origin connection is unavailable');
+ const origin = (await this.request(scope.hostId, { action: 'origin', sessionId })) as {
+ sessionId: string;
+ };
+ return invoke(hostId, {
+ ...request,
+ origin: { hostId: scope.hostId, sessionId: origin.sessionId },
+ } as RemoteToolsRequest);
+ };
+ const tool = (
+ name: string,
+ description: string,
+ parameters: MakaTool['parameters'],
+ impl: MakaTool['impl'],
+ ): MakaTool => ({
+ name,
+ description,
+ parameters,
+ impl,
+ categoryHint: 'custom_tool',
+ recoveryMode: 'never_auto_retry',
+ executionSemantics: 'exclusive_step',
+ ...(name === 'HostList' ? { discovery: 'direct' as const } : {}),
+ });
+ return [
+ tool(
+ 'HostList',
+ 'List connected Maka Hosts. Optional hostId lists that Host’s existing Sessions to choose a workspace/permission template for RemoteHostOpen. Offline is not empty. No model is started.',
+ z.object({ hostId: id.optional() }).strict(),
+ async (input) => {
+ if (!scope || !this.manager()?.ownsScope(scope))
+ throw Error('Origin connection is unavailable');
+ if (input.hostId) return invoke(input.hostId, { action: 'contexts' });
+ return this.targets()
+ .filter((t) => t.hostId !== scope.hostId)
+ .map((t) => ({
+ hostId: t.hostId,
+ name: t.target.profile.name,
+ status: t.readiness,
+ feedbackError: [...this.feedbackErrors].filter(([pair]) => pair.startsWith(`${t.hostId}:`)).map(([, error]) => error).join("; ") || null,
+ }));
+ },
+ ),
+ tool(
+ 'RemoteHostOpen',
+ 'Open or recover a dedicated tool execution context on a target Host, using an existing Session as the workspace, model and permission template. Does not start a model or modify the template. Keep the returned context id for subsequent calls.',
+ z.object({ hostId: id, templateSession: id }).strict(),
+ async (input, ctx) => {
+ if (!scope || !this.manager()?.ownsScope(scope))
+ throw Error('Origin connection is unavailable');
+ const origin = (await this.request(scope.hostId, {
+ action: 'origin',
+ sessionId: ctx.sessionId,
+ })) as { sessionId: string };
+ return invoke(input.hostId, {
+ action: 'open',
+ originHost: scope.hostId,
+ originSession: origin.sessionId,
+ templateSession: input.templateSession,
+ });
+ },
+ ),
+ tool(
+ 'RemoteToolSearch',
+ 'Discover exported tools and their exact argument schemas on a target Host. Remote references, cursors and task ids must be used on the same Host/context.',
+ z.object({ hostId: id, contextId: id, query: z.string().max(300).default('') }).strict(),
+ (input, ctx) =>
+ scopedInvoke(
+ input.hostId,
+ {
+ action: 'search',
+ contextId: input.contextId,
+ query: input.query,
+ },
+ ctx.sessionId,
+ ),
+ ),
+ tool(
+ 'RemoteToolCall',
+ 'Execute one discovered tool on the target Host without another model call. Supply a stable callId; retries with the same content reuse its receipt. running means accepted, not complete: use RemoteToolResult. completed means settled: inspect the result for tool errors. outcome_unknown must be investigated, never replayed with a fresh id. MatterDelegate starts a remote continuous task; its updates return to the initiating assistant. Do not call local Matter tools with remote task IDs.',
+ z
+ .object({ hostId: id, contextId: id, callId: id, tool: id, arguments: z.unknown() })
+ .strict(),
+ (input, ctx) =>
+ scopedInvoke(
+ input.hostId,
+ {
+ action: 'call',
+ contextId: input.contextId,
+ callId: input.callId,
+ tool: input.tool,
+ arguments: input.arguments,
+ },
+ ctx.sessionId,
+ ),
+ ),
+ tool(
+ 'RemoteToolCancel',
+ 'Request cancellation of a running remote tool call on user request. Cancellation is not rollback; inspect its final receipt. Use remote MatterTaskControl to cancel a delegated task.',
+ z.object({ hostId: id, contextId: id, callId: id }).strict(),
+ (input, ctx) =>
+ scopedInvoke(
+ input.hostId,
+ {
+ action: 'cancel',
+ contextId: input.contextId,
+ callId: input.callId,
+ },
+ ctx.sessionId,
+ ),
+ ),
+ tool(
+ 'RemoteToolResult',
+ 'Read the durable receipt of a previously submitted remote call. Does not re-execute it. Task creation success is not task completion; query MatterTasks on the same Host/context.',
+ z.object({ hostId: id, contextId: id, callId: id }).strict(),
+ (input, ctx) =>
+ scopedInvoke(
+ input.hostId,
+ {
+ action: 'result',
+ contextId: input.contextId,
+ callId: input.callId,
+ },
+ ctx.sessionId,
+ ),
+ ),
+ ];
+ }
+ async poll() {
+ if (this.polling || this.stopped) return;
+ this.polling = true;
+ try {
+ const ready = this.targets().filter((t) => t.readiness === 'ready');
+ // Independent Host pairs must not wait for an unresponsive peer.
+ await Promise.all(ready.flatMap((target) => ready
+ .filter((origin) => origin.hostId !== target.hostId)
+ .map(async (origin) => {
+ const pair = `${target.hostId}:${origin.hostId}`;
+ try {
+ const events = (await this.request(target.hostId, {
+ action: 'events', originHost: origin.hostId,
+ })) as { id: string; sessionId: string; content: unknown }[];
+ this.feedbackErrors.delete(pair);
+ for (const event of events) {
+ if (this.stopped) break;
+ try {
+ const receipt = (await this.request(origin.hostId, {
+ action: 'deliver', sessionId: event.sessionId,
+ id: `remote:${target.hostId}:${event.id}`, source: target.hostId,
+ content: { hostId: target.hostId, ...(event.content as object) },
+ })) as { accepted: boolean; manualOnly?: boolean };
+ if (receipt.accepted || receipt.manualOnly)
+ await this.request(target.hostId, { action: 'ack', ids: [event.id] });
+ } catch (error) {
+ // One rejected event must not prevent delivery of subsequent events.
+ this.feedbackErrors.set(pair, String(error));
+ }
+ }
+ } catch (error) {
+ this.feedbackErrors.set(pair, String(error));
+ }
+ })));
+
+ } finally {
+ this.polling = false;
+ }
+ }
+ close() {
+ this.stopped = true;
+ clearInterval(this.timer);
+ }
+}
diff --git a/apps/desktop/src/main/runtime-host-boot.ts b/apps/desktop/src/main/runtime-host-boot.ts
index cb09c7b1be..58a8843218 100644
--- a/apps/desktop/src/main/runtime-host-boot.ts
+++ b/apps/desktop/src/main/runtime-host-boot.ts
@@ -17,6 +17,7 @@
* under the License.
*/
+import { RemoteHostToolsBridge } from './remote-host-tools.js';
import { createAssistantWebBackend } from './assistant-web-backend.js';
import { startAssistantWebServer } from './assistant-web-server.js';
import { resolveDesktopWslHostHandoff } from './runtime-host-wsl-handoff.js';
@@ -344,6 +345,8 @@ const [runtimeHostClientInstanceId, runtimeHostStartup] = await Promise.all([
}),
]);
let runtimeHostManager: RuntimeHostDesktopManager | undefined;
+const remoteHostTools = new RemoteHostToolsBridge(() => runtimeHostManager);
+app.once('before-quit', () => remoteHostTools.close());
function activeRuntimeHostRef(): DesktopTargetScope | undefined {
const current = runtimeHostManager?.current();
return current?.hostId
@@ -1079,6 +1082,12 @@ const createLocalRuntimeHostManager = () => createRuntimeHostDesktopManager(
}
return [
workHubControl.group(scope),
+ {
+ offerId: 'desktop_remote_hosts',
+ label: 'Remote Maka Hosts',
+ description: 'Discover and use other connected Owner Hosts. Effects run under target Host permissions; task feedback returns through the bridge.',
+ tools: remoteHostTools.tools(scope),
+ },
{
offerId: 'desktop_artifact_preview',
label: 'HTML Artifact preview',
diff --git a/docs/remote-agent-tools.md b/docs/remote-agent-tools.md
new file mode 100644
index 0000000000..a197106f68
--- /dev/null
+++ b/docs/remote-agent-tools.md
@@ -0,0 +1,93 @@
+# One assistant, multiple Maka Hosts
+
+The Desktop publishes a `desktop_remote_hosts` Client Capability offer. A bound
+Agent can discover other connected Owner Hosts, open a dedicated execution
+context and call exported tools. Calls use the existing authenticated Host
+connection; SSH, TLS and Peer transports need no separate tool transport.
+
+## Agent flow
+
+1. `HostList` lists hosts and availability. `HostList({hostId})` lists existing
+ sessions that can serve as workspace/model/permission templates.
+2. `RemoteHostOpen({hostId, templateSession})` creates or recovers a dedicated
+ context for the origin conversation. It copies the selected template's cwd,
+ model and execution boundary (native Maka Sessions only); it does not start a model or alter that session.
+3. `RemoteToolSearch({hostId, contextId, query})` returns exported tool schemas.
+4. `RemoteToolCall({hostId, contextId, callId, tool, arguments})` executes through
+ the target ToolRuntime. Reusing a callId with identical input returns the
+ durable receipt; changed input is rejected. A short call returns inline.
+5. `running` is admission, not completion. Use `RemoteToolResult` for a pending
+ receipt. The target also retains deferred results for the origin Bot Inbox.
+ Ordinary sessions use result queries without an automatic model wake.
+
+All paths, cursors, index IDs and task IDs belong to the returned host/context.
+Keep that route when following an original reference or updating a task. Remote
+cursors do not become local memory cursors. Memory reads retain the target's
+source authorization and refresh/checkpoint semantics.
+
+## Continuous work and feedback
+
+Call the exported `MatterDelegate` on the chosen target. Task creation returns
+an identity, not a completed outcome. `MatterTasks`, `MatterTaskMessage`,
+`MatterReply`, `MatterTaskControl`, `MatterDelegationRecover` and
+`MatterFeedbackRetry` operate in the same remote context.
+The target runs its existing Matter scheduler and review loop.
+
+Task progress/questions, index job feedback and discovery reports go into a durable target outbox instead of starting an extra
+conversation Agent on the target. Desktop forwards it to the origin Bot Inbox,
+then acknowledges it. A lost acknowledgement repeats the same Inbox identity.
+The origin is normalized to the owner conversation so replacing the Bot worker
+does not change the feedback destination. Disabled/offline assistants retain
+undelivered feedback; ordinary sessions retain results for manual queries.
+
+Network requests have a 15-second response deadline; it does not cancel target
+execution. An uncertain call retains its call/context/Host identity for result
+queries or retries with the same identity. Independent Host pairs relay in
+parallel; a failed event does not block later events.
+
+There is no whole-call ten-minute deadline. The one-second inline wait only
+selects inline versus deferred delivery; it does not stop execution. Individual
+tools retain their own native limits. `RemoteToolCancel` requests cancellation of
+a pending call; it does not roll back effects or cancel a delegated Matter. A Host restart marks interrupted calls
+`outcome_unknown` and does not replay effects. Known completed receipts survive
+restart. The context permits one in-flight call at a time.
+
+## Permissions and compatibility
+
+Both ends need compatibility epoch 225. Existing credentials with explicit
+operation lists need the new `remote.tools` grant (reissue/pair through normal
+Host administration); no code silently expands an existing credential.
+Guest and capability-provider credentials cannot invoke this operation.
+The Desktop capability offer uses normal capability admission and the origin
+session's existing boundary requirements. The destination ToolRuntime enforces
+its execution context's boundary. A network connection is not permission to use
+an arbitrary UI provider.
+
+Exports include filesystem/shell and every Bot business tool (the shared
+`BOT_DELEGATION_TOOLS` list): memory reads, index creation/grouping/maintenance,
+Matter management/recovery and proactive-discovery configuration. Remote index
+jobs use the target's ordinary scheduler; creation and checkpoints are unchanged.
+Each remote context has its own durable discovery schedule and worker, without a
+second Bot or changes to the target's existing local assistant schedule. Discovery
+configuration is recovered after restart. Parameter defaults are applied before
+executing the native tool. Loop-control tools (`SendUser`, `Sleep`, `MatterSettle`), arbitrary
+plugins and recursive remote calls are not exported. Browser/Computer Use
+provider selection is not implemented by this transport. Required approvals
+that this standalone context cannot present fail through the normal runtime
+boundary instead of silently granting access.
+
+## Operation and current limits
+
+The bridge needs Desktop running and both Owner connections available. Existing
+remote tasks continue under their Host scheduler while the bridge is offline.
+The bridge checks feedback every five seconds without model calls. HostList
+reports observed bridge errors. Source data and indexes stay on their owner
+Host, and index maintenance stays with that Host's existing shared scheduler.
+There is no database replication, cross-host index builder, automatic primary
+Bot election, worker migration, or native cross-host attachment rendering.
+This adds other Hosts as tools to the current assistant; it does not merge
+separately configured assistant conversations on different Hosts.
+
+Persistent state is `<Host control directory>/remote-tools/remote-tools.sqlite`
+(0600): context identities, call receipts, tool event traces and feedback outbox.
+The bridge does not copy model connection credentials into its catalog or context metadata. Exported tools still have their normal ability to read files allowed by the target boundary.
diff --git a/packages/runtime-host/src/__tests__/assistant-memory-feedback.test.ts b/packages/runtime-host/src/__tests__/assistant-memory-feedback.test.ts
index e0b52d61a9..987f6a2bb1 100644
--- a/packages/runtime-host/src/__tests__/assistant-memory-feedback.test.ts
+++ b/packages/runtime-host/src/__tests__/assistant-memory-feedback.test.ts
@@ -24,6 +24,7 @@ import { MemoryController } from '../assistant/memory-network/controller.js';
function setup() {
const db = new DatabaseSync(':memory:');
+ db.exec('CREATE TABLE memory_meta(key TEXT PRIMARY KEY,value TEXT NOT NULL)');
const workers = new Map(
['a', 'b'].map((id) => [
id,
@@ -123,7 +124,11 @@ test('stopping a shared index job cancels once, waits, and disables all members'
await Promise.resolve();
await f.controller.control('b', 'stop');
assert.equal(cancellations, 1);
- assert.ok([...f.workers.values()].every((w) => w.nextCheckAt === null && w.lastError === null));
+ assert.ok(
+ [...f.workers].every(
+ ([id, w]) => f.controller.nextCheck(id) === null && w.lastError === null,
+ ),
+ );
assert.equal(f.controller.runs.size, 0);
assert.ok(
[...f.workers.values()].every((w) => w.maintenanceEnabled === false && w.continuationStopped),
@@ -138,7 +143,7 @@ test('stop from a paused member finds the running scheduled sibling', async () =
try {
let cancelled = false;
f.controller.enabled = (id: string) => id === 'b';
- f.controller.run = async (_: string, signal: AbortSignal) => {
+ f.controller.runGroup = async (_: string[], signal: AbortSignal) => {
await new Promise<void>((resolve) =>
signal.addEventListener(
'abort',
diff --git a/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts b/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts
index 1b343b035b..dd17f16ea0 100644
--- a/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts
+++ b/packages/runtime-host/src/__tests__/authenticated-websocket.test.ts
@@ -18,6 +18,7 @@
*/
import assert from 'node:assert/strict';
+import net from 'node:net';
import { createHash } from 'node:crypto';
import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
@@ -1621,3 +1622,268 @@ async function waitForCondition(condition: () => Promise<boolean>): Promise<void
message: 'condition did not become true',
});
}
+
+test('remote tools cross an authenticated socket and reuse receipts after target restart', {
+ timeout: 120000,
+}, async () => {
+ const base = await mkdtemp(join(tmpdir(), 'maka-remote-tools-wire-'));
+ const root = join(base, 'target');
+ const capability = await resolveStorageRoot({ path: root, kind: 'interactive' });
+ let host = await startExecutionRuntimeHostService({
+ rootPath: root,
+ websocket: { host: '127.0.0.1', port: 0 },
+ });
+ let local: RuntimeHostConnection | undefined, remote: RuntimeHostConnection | undefined;
+ try {
+ local = requireConnection(await connectRuntimeHost({ rootPath: root, protocol: PROTOCOL }));
+ await configureTestModel(local);
+ const template = await local.request('session.create', {
+ sessionId: 'remote-template',
+ workspace: { kind: 'host_path', path: root },
+ modelTarget: { kind: 'default' },
+ permissionMode: 'bypass',
+ });
+ assert.ok(!('kind' in template));
+ const issued = await local.request('access.credential.issue', {
+ principalKind: 'remote_owner',
+ principalId: 'remote-tools-test',
+ operationGrants: ['remote.tools'],
+ canPublishClientCapabilities: false,
+ canUseHostPaths: false,
+ });
+ const credential = await consumeAccessCredentialDelivery(
+ root,
+ issued.deliveryId,
+ issued.credentialId,
+ );
+ const connect = async () => {
+ const result = await connectRemoteRuntimeHost({
+ url: host.websocketEndpoints[0]!,
+ credential,
+ expectedRootId: capability.rootId,
+ compositionId: INTERACTIVE_RUNTIME_HOST_COMPOSITION_ID,
+ protocol: PROTOCOL,
+ });
+ assert.equal(result.kind, 'connected');
+ if (result.kind !== 'connected') throw Error('Not connected');
+ return result.connection;
+ };
+ remote = await connect();
+ const opened = (
+ await remote.request('remote.tools', {
+ action: 'open',
+ originHost: 'origin-host',
+ originSession: 'origin-bot',
+ templateSession: 'remote-template',
+ })
+ ).value as { id: string };
+ const configureDiscovery = {
+ action: 'call' as const,
+ contextId: opened.id,
+ origin: { hostId: 'origin-host', sessionId: 'origin-bot' },
+ callId: 'configure-discovery',
+ tool: 'InitiativeConfigure',
+ arguments: { intervalMinutes: 77 },
+ };
+ const configReceipt = (await remote.request('remote.tools', configureDiscovery)).value as any;
+ assert.equal(configReceipt.result.result.intervalMs, 77 * 60000);
+ await writeFile(join(root, 'evidence.txt'), 'REMOTE WIRE EVIDENCE');
+ const call = {
+ action: 'call' as const,
+ contextId: opened.id,
+ origin: { hostId: 'origin-host', sessionId: 'origin-bot' },
+ callId: 'wire-read',
+ tool: 'Read',
+ arguments: { path: 'evidence.txt' },
+ };
+ let receipt = (await remote.request('remote.tools', call)).value as any;
+ await waitFor(async () => {
+ receipt = (
+ await remote!.request('remote.tools', {
+ action: 'result',
+ contextId: opened.id,
+ origin: { hostId: 'origin-host', sessionId: 'origin-bot' },
+ callId: 'wire-read',
+ })
+ ).value;
+ return receipt.status === 'completed';
+ });
+ assert.match(JSON.stringify(receipt), /REMOTE WIRE EVIDENCE/);
+ await remote.close();
+ remote = undefined;
+ await local.close();
+ local = undefined;
+ await host.close();
+ host = await startExecutionRuntimeHostService({
+ rootPath: root,
+ websocket: { host: '127.0.0.1', port: 0 },
+ });
+ remote = await connect();
+ const recoveredDiscovery = (
+ await remote.request('remote.tools', {
+ ...configureDiscovery,
+ callId: 'discovery-status',
+ tool: 'InitiativeStatus',
+ arguments: {},
+ })
+ ).value as any;
+ assert.equal(recoveredDiscovery.result.result.intervalMs, 77 * 60000);
+ assert.equal(recoveredDiscovery.result.result.enabled, false);
+ await writeFile(join(root, 'evidence.txt'), 'CHANGED AFTER RESTART');
+ assert.deepEqual((await remote.request('remote.tools', call)).value, receipt);
+ assert.match(
+ JSON.stringify(
+ (await remote.request('remote.tools', { ...call, callId: 'fresh-read' })).value,
+ ),
+ /CHANGED AFTER RESTART/,
+ );
+ } finally {
+ await remote?.close();
+ await local?.close();
+ await host.close();
+ await rm(base, { recursive: true, force: true });
+ }
+});
+
+test('remote response loss on a real TCP socket preserves effects and receipts without replay', {
+ timeout: 30000,
+}, async () => {
+ const base = await mkdtemp(join(tmpdir(), 'maka-remote-loss-'));
+ const root = join(base, 'target');
+ const capability = await resolveStorageRoot({ path: root, kind: 'interactive' });
+ const host = await startExecutionRuntimeHostService({
+ rootPath: root,
+ websocket: { host: '127.0.0.1', port: 0 },
+ });
+ let local: RuntimeHostConnection | undefined, remote: RuntimeHostConnection | undefined;
+ let blackhole = false;
+ const sockets = new Set<net.Socket>();
+ const targetUrl = new URL(host.websocketEndpoints[0]!);
+ const proxy = net.createServer((client) => {
+ const upstream = net.connect(Number(targetUrl.port), '127.0.0.1');
+ sockets.add(client);
+ sockets.add(upstream);
+ client.pipe(upstream);
+ upstream.on('data', (chunk) => {
+ if (!blackhole) client.write(chunk);
+ });
+ client.on('close', () => {
+ sockets.delete(client);
+ upstream.destroy();
+ });
+ upstream.on('close', () => {
+ sockets.delete(upstream);
+ client.destroy();
+ });
+ client.on('error', () => upstream.destroy());
+ upstream.on('error', () => client.destroy());
+ });
+ await new Promise<void>((resolve) => proxy.listen(0, '127.0.0.1', resolve));
+ const proxyUrl = new URL(targetUrl);
+ proxyUrl.port = String((proxy.address() as net.AddressInfo).port);
+ try {
+ local = requireConnection(await connectRuntimeHost({ rootPath: root, protocol: PROTOCOL }));
+ await configureTestModel(local);
+ await local.request('session.create', {
+ sessionId: 'template',
+ workspace: { kind: 'host_path', path: root },
+ modelTarget: { kind: 'default' },
+ permissionMode: 'bypass',
+ });
+ const issued = await local.request('access.credential.issue', {
+ principalKind: 'remote_owner',
+ principalId: 'loss-test',
+ operationGrants: ['remote.tools'],
+ canPublishClientCapabilities: false,
+ canUseHostPaths: false,
+ });
+ const credential = await consumeAccessCredentialDelivery(
+ root,
+ issued.deliveryId,
+ issued.credentialId,
+ );
+ const connect = async (url: string) => {
+ const result = await connectRemoteRuntimeHost({
+ url,
+ credential,
+ expectedRootId: capability.rootId,
+ compositionId: INTERACTIVE_RUNTIME_HOST_COMPOSITION_ID,
+ protocol: PROTOCOL,
+ });
+ if (result.kind !== 'connected') throw Error(JSON.stringify(result));
+ return result.connection;
+ };
+ remote = await connect(proxyUrl.toString());
+ const opened = (
+ await remote.request('remote.tools', {
+ action: 'open',
+ originHost: 'origin',
+ originSession: 'bot',
+ templateSession: 'template',
+ })
+ ).value as any;
+ const call = {
+ action: 'call' as const,
+ contextId: opened.id,
+ origin: { hostId: 'origin', sessionId: 'bot' },
+ callId: 'lost-response',
+ tool: 'Bash',
+ arguments: { command: 'echo once >> effect.txt; sleep 0.5; echo completed' },
+ };
+ const response = remote.request('remote.tools', call, 250);
+ const rejected = assert.rejects(response, (error: any) => {
+ assert.match(String(error.cause), /timed out/i);
+ assert.match(error.message, /outcome is unknown/);
+ return true;
+ });
+ await waitFor(
+ async () => {
+ try {
+ return (await readFile(join(root, 'effect.txt'), 'utf8')).includes('once');
+ } catch {
+ return false;
+ }
+ },
+ { timeoutMs: 3000 },
+ );
+ // The effect is confirmed before discarding the server's final response bytes.
+ blackhole = true;
+ await rejected;
+ await remote.close();
+ remote = await connect(targetUrl.toString());
+ let receipt: any;
+ await waitFor(
+ async () => {
+ receipt = (
+ await remote!.request('remote.tools', {
+ action: 'result',
+ contextId: opened.id,
+ origin: call.origin,
+ callId: call.callId,
+ })
+ ).value;
+ return receipt.status === 'completed';
+ },
+ { timeoutMs: 5000 },
+ );
+ assert.deepEqual((await remote.request('remote.tools', call)).value, receipt);
+ assert.equal(await readFile(join(root, 'effect.txt'), 'utf8'), 'once\n');
+ // A later healthy request still succeeds after the failed connection.
+ const next = (
+ await remote.request('remote.tools', {
+ ...call,
+ callId: 'next',
+ tool: 'Read',
+ arguments: { path: 'effect.txt' },
+ })
+ ).value;
+ assert.match(JSON.stringify(next), /once/);
+ } finally {
+ for (const socket of sockets) socket.destroy();
+ await new Promise<void>((resolve) => proxy.close(() => resolve()));
+ await remote?.close();
+ await local?.close();
+ await host.close();
+ await rm(base, { recursive: true, force: true });
+ }
+});
diff --git a/packages/runtime-host/src/__tests__/execution-composition.test.ts b/packages/runtime-host/src/__tests__/execution-composition.test.ts
index b68ae6b24b..7a9cce3174 100644
--- a/packages/runtime-host/src/__tests__/execution-composition.test.ts
+++ b/packages/runtime-host/src/__tests__/execution-composition.test.ts
@@ -5442,3 +5442,458 @@ test('disabling during Bot publication fences the uncommitted message and permit
}
});
});
+
+test('remote tools use a dedicated context and real target filesystem without model execution', async () => {
+ await withCompositionRoot(async ({ root, owner }) => {
+ let modelCalls = 0;
+ const { composition, manager } = await createCapturedExecutionComposition(owner, {
+ primaryBackendFactory: (ctx) => {
+ modelCalls++;
+ return new FakeBackend(ctx);
+ },
+ });
+ const caller: ConnectionContext = {
+ hostEpoch: 'execution-composition-test',
+ connectionId: 'remote-client',
+ principal: 'remote-owner',
+ principalKind: 'remote_owner',
+ acquireResidency: () => new HostResidencyRegistry().acquire('remote-test'),
+ };
+ const request = async (input: any) => {
+ const result = await composition.handlers['remote.tools'](
+ 'contextId' in input
+ ? { ...input, origin: { hostId: 'other-host', sessionId: 'main-bot' } }
+ : input,
+ caller,
+ );
+ assert.equal(result.ok, true, JSON.stringify(result));
+ return (result as any).result.value;
+ };
+ try {
+ const template = await manager.createSession({
+ cwd: root,
+ llmConnectionId: FAKE_CONNECTION_ID,
+ llmConnectionSlug: 'fake',
+ model: 'fake-model',
+ permissionMode: 'bypass',
+ });
+ await writeFile(join(root, 'remote-evidence.txt'), 'ONLY THIS HOST');
+ const opened = await request({
+ action: 'open',
+ originHost: 'other-host',
+ originSession: 'main-bot',
+ templateSession: template.id,
+ });
+ assert.notEqual(opened.sessionId, template.id);
+ const found = await request({ action: 'search', contextId: opened.id, query: 'Read' });
+ assert.ok(found.tools.some((t: any) => t.name === 'Read'));
+ const call = {
+ action: 'call',
+ contextId: opened.id,
+ callId: 'read-evidence',
+ tool: 'Read',
+ arguments: { path: join(root, 'remote-evidence.txt') },
+ };
+ let value = await request(call);
+ await pollFor(async () => {
+ value = await request({ action: 'result', contextId: opened.id, callId: 'read-evidence' });
+ return value.status === 'completed';
+ });
+ assert.match(JSON.stringify(value), /ONLY THIS HOST/);
+ assert.deepEqual(await request(call), value);
+ const memory = await request({
+ action: 'call',
+ contextId: opened.id,
+ callId: 'memory',
+ tool: 'MemoryIndexList',
+ arguments: {},
+ });
+ assert.equal(memory.status, 'completed');
+ assert.doesNotMatch(JSON.stringify(memory), /requires an active|providerError/);
+ assert.equal(modelCalls, 0);
+ const written = await request({
+ action: 'call',
+ contextId: opened.id,
+ callId: 'write',
+ tool: 'Write',
+ arguments: { path: join(root, 'remote-written.txt'), content: 'REMOTE WRITE' },
+ });
+ assert.doesNotMatch(JSON.stringify(written), /providerError/);
+ const shell = await request({
+ action: 'call',
+ contextId: opened.id,
+ callId: 'shell',
+ tool: 'Bash',
+ arguments: { command: 'pwd' },
+ });
+ let shellResult = shell;
+ await pollFor(async () => {
+ shellResult = await request({ action: 'result', contextId: opened.id, callId: 'shell' });
+ return shellResult.status === 'completed';
+ });
+ assert.doesNotMatch(JSON.stringify(shellResult), /providerError/);
+ assert.match(JSON.stringify(shellResult), new RegExp(root));
+ const task = await request({
+ action: 'call',
+ contextId: opened.id,
+ callId: 'delegate',
+ tool: 'MatterDelegate',
+ arguments: {
+ taskKey: 'remote-task',
+ title: 'Remote follow-up',
+ request: 'Wait for the delivery confirmation and report it.',
+ },
+ });
+ assert.doesNotMatch(JSON.stringify(task), /providerError/);
+ const tasks = await request({
+ action: 'call',
+ contextId: opened.id,
+ callId: 'tasks',
+ tool: 'MatterTasks',
+ arguments: {},
+ });
+ assert.match(JSON.stringify(tasks), /Remote follow-up/);
+ const matterId = task.result.result.id;
+ assert.ok(matterId, JSON.stringify(task));
+ const paused = await request({
+ action: 'call',
+ contextId: opened.id,
+ callId: 'pause-task',
+ tool: 'MatterTaskControl',
+ arguments: { id: matterId, action: 'pause' },
+ });
+ assert.doesNotMatch(JSON.stringify(paused), /providerError/);
+ let feedback: any[] = [];
+ await pollFor(
+ async () => {
+ feedback = await request({ action: 'events', originHost: 'other-host' });
+ return feedback.some((e) => e.content.type === 'task_update');
+ },
+ { timeoutMs: 5000, pollMs: 20 },
+ );
+ assert.match(JSON.stringify(feedback), /Remote follow-up/);
+ assert.equal(feedback.find((e) => e.content.type === 'task_update').sessionId, 'main-bot');
+ const readonlyTemplate = await manager.createSession({
+ cwd: root,
+ llmConnectionId: FAKE_CONNECTION_ID,
+ llmConnectionSlug: 'fake',
+ model: 'fake-model',
+ permissionMode: 'explore',
+ });
+ const readonlyContext = await request({
+ action: 'open',
+ originHost: 'other-host',
+ originSession: 'main-bot',
+ templateSession: readonlyTemplate.id,
+ });
+ const rejected = await request({
+ action: 'call',
+ contextId: readonlyContext.id,
+ callId: 'forbidden-write',
+ tool: 'Write',
+ arguments: { path: join(root, 'forbidden.txt'), content: 'MUST NOT EXIST' },
+ });
+ assert.match(JSON.stringify(rejected), /error|denied|permission/i);
+ await assert.rejects(stat(join(root, 'forbidden.txt')), { code: 'ENOENT' });
+ const denied = await composition.handlers['remote.tools'](
+ { action: 'contexts' },
+ { ...caller, principalKind: 'session_guest' },
+ );
+ assert.equal(denied.ok, false);
+ } finally {
+ await composition.close();
+ }
+ });
+});
+
+test('every Bot business tool executes remotely with native storage, workers and feedback routing', {
+ timeout: 60000,
+}, async (t) => {
+ let assistant!: PersonalAssistantService;
+ const recover = PersonalAssistantService.prototype.recover;
+ t.mock.method(
+ PersonalAssistantService.prototype,
+ 'recover',
+ function (this: PersonalAssistantService, ...args: Parameters<typeof recover>) {
+ assistant = this;
+ return recover.apply(this, args);
+ },
+ );
+ await withCompositionRoot(async ({ root, owner }) => {
+ const workerErrors: unknown[] = [];
+ const invokeWorker = async (sessionId: string, turnId: string, name: string, args: any) => {
+ const tool = assistant.tools.find((x) => x.name === name)!;
+ return tool.impl((tool.parameters as any).parse(args), {
+ sessionId,
+ turnId,
+ toolCallId: randomUUID(),
+ cwd: root,
+ abortSignal: new AbortController().signal,
+ } as any);
+ };
+ const { composition, manager } = await createCapturedExecutionComposition(owner, {
+ primaryBackendFactory: (context) =>
+ new (class extends FakeBackend {
+ override async *send(input: BackendSendInput): AsyncIterable<SessionEvent> {
+ try {
+ const invoke = (name: string, args: any) =>
+ invokeWorker(context.sessionId, input.turnId, name, args);
+ if (input.text.startsWith('Organize')) {
+ const ids = [
+ ...new Set([
+ ...[...input.text.matchAll(/"indexId":"([^"]+)"/g)].map((x) => x[1]),
+ ...[...input.text.matchAll(/Organize index ([^. ]+)/g)].map((x) => x[1]),
+ ]),
+ ];
+ assert.ok(ids.length);
+ for (const indexId of ids) {
+ const index: any = await invoke('MemoryIndexRead', { indexId });
+ const page: any = await invoke('MemoryHistory', {
+ to: index.range.to,
+ mode: 'messages',
+ types: ['user'],
+ });
+ const saved: any = await invoke('MemoryIndexWrite', {
+ indexId,
+ key: 'event',
+ expectedRevision: index.index.revision,
+ text:
+ 'Remote event evidence\n' + page.items.map((m: any) => m.citation).join('\n'),
+ });
+ await invoke('MemoryIndexCheckpoint', {
+ indexId,
+ rangeId: index.range.rangeId,
+ expectedRevision: saved.revision,
+ notes: 'Controlled worker completed native checkpoint',
+ complete: true,
+ });
+ }
+ } else if (input.text.includes('Heartbeat ID:')) {
+ await invoke('DiscoveryContext', {});
+ await invoke('DiscoveryReport', { text: 'Remote discovery evidence report' });
+ } else if (input.text.startsWith('Runtime wake notification')) {
+ const workspace = JSON.parse(
+ input.text.split('Matter workspace (paths and host metadata):\n')[1]!,
+ );
+ await invoke('MatterRead', { activationId: workspace.activationId });
+ await invoke('MatterAskBot', {
+ requestKey: 'approval',
+ question: 'Which delivery location?',
+ evidence: 'The user has not selected a delivery location.',
+ });
+ yield* super.send({ ...input, text: FAKE_HOLD_OPEN_PROMPT });
+ return;
+ }
+ } catch (error) {
+ workerErrors.push(error);
+ }
+ yield* super.send({ ...input, text: 'Controlled worker finished' });
+ }
+ })(context),
+ });
+ const caller: ConnectionContext = {
+ hostEpoch: 'execution-composition-test',
+ connectionId: 'remote-full',
+ principal: 'remote-owner',
+ principalKind: 'remote_owner',
+ acquireResidency: () => new HostResidencyRegistry().acquire('remote-full'),
+ };
+ const req = async (input: any) => {
+ const r = await composition.handlers['remote.tools'](input, caller);
+ assert.equal(r.ok, true, JSON.stringify(r));
+ return (r as any).result.value;
+ };
+ const used = new Set<string>();
+ let contextId: string;
+ const origin = { hostId: 'origin', sessionId: 'bot' };
+ const call = async (tool: string, args: any = {}) => {
+ used.add(tool);
+ const callId = randomUUID();
+ let r = await req({ action: 'call', contextId, origin, callId, tool, arguments: args });
+ await pollFor(
+ async () => {
+ if (r.status !== 'running') return true;
+ r = await req({ action: 'result', contextId, origin, callId });
+ return r.status !== 'running';
+ },
+ { timeoutMs: 10000 },
+ );
+ assert.equal(r.status, 'completed', JSON.stringify(r));
+ assert.doesNotMatch(JSON.stringify(r), /providerError/, tool + ': ' + JSON.stringify(r));
+ assert.ok(r.result?.result !== undefined, tool + ': ' + JSON.stringify(r));
+ return r.result.result;
+ };
+ const events = () => req({ action: 'events', originHost: 'origin' });
+ try {
+ const template = await manager.createSession({
+ cwd: root,
+ llmConnectionId: FAKE_CONNECTION_ID,
+ llmConnectionSlug: 'fake',
+ model: 'fake-model',
+ permissionMode: 'bypass',
+ });
+ const opened = await req({
+ action: 'open',
+ originHost: 'origin',
+ originSession: 'bot',
+ templateSession: template.id,
+ });
+ contextId = opened.id;
+ const localChat = await manager.createSession({
+ cwd: root,
+ llmConnectionId: FAKE_CONNECTION_ID,
+ llmConnectionSlug: 'fake',
+ model: 'fake-model',
+ permissionMode: 'bypass',
+ });
+ await assistant.call('assistant.bind', { sessionId: localChat.id });
+ const localBinding = await assistant.call('assistant.binding', {});
+ // Seed history through real Host turn admission, not a replacement memory adapter.
+ const seeded = await composition.handlers['turn.start'](
+ {
+ sessionId: template.id,
+ turnId: randomUUID(),
+ content: { text: 'Lab camera must be returned on Friday.' },
+ },
+ { ...caller, principalKind: 'local_owner' },
+ );
+ assert.equal(seeded.ok, true, JSON.stringify(seeded));
+ await pollFor(() => manager.runningTurnIds(template.id).length === 0, { timeoutMs: 5000 });
+ const sources = await call('MemorySources');
+ assert.ok(sources.some((s: any) => s.id === 'maka'));
+ const range = await call('MemoryRange', { sources: ['maka'] });
+ const page = await call('MemoryHistory', { to: range.to, mode: 'messages', types: ['user'] });
+ assert.ok(page.items.length);
+ const original = await call('MemoryOriginal', { ref: page.items[0].ref });
+ assert.match(JSON.stringify(original), /Lab camera/);
+ const created = await call('MemoryIndexCreate', {
+ name: 'Remote events',
+ instructions: 'Summarize events with original citations',
+ cursor: range.to,
+ background: true,
+ });
+ const indexId = created.index.id;
+ let index: any;
+ await pollFor(
+ async () => {
+ index = await call('MemoryIndexRead', { indexId });
+ return index.range?.completed && !index.maintenance.running;
+ },
+ { timeoutMs: 15000 },
+ );
+ assert.ok((await call('MemoryIndexList')).some((i: any) => i.id === indexId));
+ assert.match(
+ JSON.stringify(await call('MemoryIndexContent', { indexId, view: 'full' })),
+ /Remote event evidence/,
+ );
+ assert.ok((await call('MemoryIndexLinks', { indexId, key: 'event' })).originalCount > 0);
+ await call('MemoryIndexAddSources', { indexIds: [indexId], sources: ['maka'] });
+ for (const action of ['pause', 'resume', 'configure'])
+ await call('MemoryIndexControl', {
+ indexId,
+ action,
+ ...(action === 'configure' ? { intervalMs: 43200000 } : {}),
+ });
+ const coveredBefore = (await call('MemoryIndexRead', { indexId })).coverage.cursor;
+ const update = await composition.handlers['turn.start'](
+ {
+ sessionId: template.id,
+ turnId: randomUUID(),
+ content: { text: 'Update: the lab camera has now been returned.' },
+ },
+ { ...caller, principalKind: 'local_owner' },
+ );
+ assert.equal(update.ok, true);
+ await pollFor(() => manager.runningTurnIds(template.id).length === 0, { timeoutMs: 5000 });
+ const stale = await call('MemoryIndexRead', { indexId });
+ assert.equal(stale.coverage.cursor, coveredBefore);
+ assert.notEqual(stale.freshness.observedCursor, coveredBefore);
+ const delta = await call('MemoryHistory', {
+ from: coveredBefore,
+ to: stale.freshness.observedCursor,
+ mode: 'messages',
+ });
+ assert.match(JSON.stringify(delta), /now been returned/);
+ await call('MemoryIndexMaintain', { indexId, background: false });
+ assert.notEqual((await call('MemoryIndexRead', { indexId })).coverage.cursor, coveredBefore);
+ const group = await call('MemoryIndexCreateGroup', {
+ cursor: range.to,
+ indexes: [
+ { number: 1, name: 'Followups', instructions: 'Open tasks' },
+ { number: 2, name: 'Preferences', instructions: 'Preferences only' },
+ ],
+ background: false,
+ });
+ assert.equal(group.members.length, 2);
+ const g1 = await call('MemoryIndexRead', { indexId: group.members[0].indexId });
+ const g2 = await call('MemoryIndexRead', { indexId: group.members[1].indexId });
+ assert.equal(g1.maintenance.group.sessionId, g2.maintenance.group.sessionId);
+ assert.equal(g1.range.completed, true);
+ assert.equal(g2.range.completed, true);
+ assert.ok((await events()).some((e: any) => e.content.source === 'memory-network'));
+ await call('InitiativeStatus');
+ await call('InitiativeConfigure', { intervalMinutes: 61 });
+ const enabled = await call('InitiativeEnable');
+ assert.equal(enabled.intervalMs, 61 * 60000);
+ for (const action of ['pause', 'resume', 'check'])
+ await call('InitiativeControl', { action });
+ await pollFor(async () => (await events()).some((e: any) => e.content.type === 'discovery'), {
+ timeoutMs: 10000,
+ });
+ await call('InitiativeControl', { action: 'pause' });
+ assert.equal((await call('InitiativeStatus')).enabled, false);
+ // Remote discovery must not bind/start the target Host's local Bot.
+ assert.deepEqual(
+ ((await assistant.call('assistant.binding', {})) as any).state,
+ (localBinding as any).state,
+ );
+ const task = await call('MatterDelegate', {
+ taskKey: 'full-task',
+ title: 'Remote delivery',
+ request: 'Clarify the delivery location before proceeding.',
+ });
+ assert.ok(task.id);
+ assert.equal((await call('MatterDelegationRecover', { taskKey: 'full-task' })).id, task.id);
+ let question: any;
+ await pollFor(
+ async () => {
+ question = (await events()).find(
+ (e: any) => e.content.content?.kind === 'clarification_request',
+ );
+ return !!question;
+ },
+ { timeoutMs: 10000 },
+ );
+ await call('MatterReply', {
+ requestId: question.content.content.requestId,
+ answer: 'Use the laboratory reception desk.',
+ });
+ await call('MatterTaskMessage', { id: task.id, text: 'Also include the receipt number.' });
+ assert.equal((await call('MatterTasks', { id: task.id })).id, task.id);
+ await call('MatterTaskControl', { id: task.id, action: 'pause' });
+ let feedback: any;
+ await pollFor(
+ async () => {
+ feedback = (await events()).find(
+ (e: any) =>
+ e.content.type === 'task_update' &&
+ e.content.content?.kind !== 'clarification_request',
+ );
+ return !!feedback;
+ },
+ { timeoutMs: 5000 },
+ );
+ await call('MatterFeedbackRetry', { notificationId: feedback.content.id });
+ await call('MatterTaskControl', { id: task.id, action: 'cancel' });
+ const { BOT_DELEGATION_TOOLS } = await import('../assistant/bot/capabilities.js');
+ assert.deepEqual(
+ [...BOT_DELEGATION_TOOLS].filter((name) => !used.has(name)),
+ [],
+ );
+ assert.deepEqual(workerErrors.map(String), []);
+ assert.ok((await events()).every((e: any) => e.sessionId === 'bot'));
+ } finally {
+ await composition.close();
+ }
+ });
+});
diff --git a/packages/runtime-host/src/__tests__/execution-model-composition.test.ts b/packages/runtime-host/src/__tests__/execution-model-composition.test.ts
index d829aac87a..2b00815710 100644
--- a/packages/runtime-host/src/__tests__/execution-model-composition.test.ts
+++ b/packages/runtime-host/src/__tests__/execution-model-composition.test.ts
@@ -7165,3 +7165,55 @@ test('prompt suggestions ask Kimi K3 for its lowest effort instead of its defaul
await rm(base, { recursive: true, force: true });
}
});
+
+test('assistant tool ceiling admits bound remote Host tools without unrelated client tools', async () => {
+ const fixture = backendCreationFixture({
+ abortSignal: new AbortController().signal,
+ resolveExecutionConnection: async () => readyExecutionConnection(),
+ readPricing: async () => ({ revision: 0, overrides: [] }),
+ });
+ const tool = (name: string): MakaTool => ({
+ name,
+ description: name,
+ parameters: z.object({}),
+ impl: async () => ({}),
+ });
+ const factory = createInteractiveRunComposerFactory({
+ skills: {
+ readCanonicalModelInventory: async () => ({ inventory: [] }),
+ } as unknown as HostSkillCatalogCoordinator,
+ memory: { readPromptProjection: async () => ({}) } as unknown as HostMemoryCoordinator,
+ sessionTodo: {} as SessionTodoToolStore,
+ clientCapabilities: {
+ snapshotForSession: () => ({
+ tools: [
+ tool('mcp__desktop_remote_hosts__HostList'),
+ tool('mcp__desktop_remote_hosts__RemoteToolCall'),
+ tool('mcp__unrelated__dangerous'),
+ ],
+ }),
+ } as unknown as HostClientCapabilityCoordinator,
+ resolveTavilyWebSearchReadiness: async () => false,
+ resolveToolCeiling: () => [tool('SendUser'), tool('Sleep')],
+ });
+ const composer = await factory({
+ backendContext: fixture.context,
+ connection: readyExecutionConnection().connection as any,
+ modelId: MODEL_ID,
+ runtimePolicy: { revision: 0, policy: createDefaultRuntimePolicy() },
+ contextWindow: null,
+ });
+ assert.equal(
+ composer.tools.find((t) => t.name === 'mcp__desktop_remote_hosts__HostList')?.discovery,
+ 'direct',
+ );
+ assert.deepEqual(
+ composer.tools.map((t) => t.name),
+ [
+ 'SendUser',
+ 'Sleep',
+ 'mcp__desktop_remote_hosts__HostList',
+ 'mcp__desktop_remote_hosts__RemoteToolCall',
+ ],
+ );
+});
diff --git a/packages/runtime-host/src/__tests__/remote-tools.test.ts b/packages/runtime-host/src/__tests__/remote-tools.test.ts
new file mode 100644
index 0000000000..44d9dd5184
--- /dev/null
+++ b/packages/runtime-host/src/__tests__/remote-tools.test.ts
@@ -0,0 +1,423 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { DatabaseSync } from 'node:sqlite';
+import { z } from 'zod';
+import { RemoteToolsHost } from '../server/remote-tools.js';
+import { remoteToolsRequest } from '../protocol/remote-tools.js';
+import { operationAllowsRemoteOwner } from '../protocol/operations.js';
+async function fixture() {
+ const dir = await mkdtemp(join(tmpdir(), 'maka-remote-'));
+ let count = 0,
+ created = 0;
+ const delivered: unknown[] = [];
+ const deps: ConstructorParameters<typeof RemoteToolsHost>[1] = {
+ list: async () => [{ sessionId: 'template' }],
+ create: async () => {
+ created++;
+ return 'remote-session';
+ },
+ tools: async () => [
+ {
+ name: 'Read',
+ description: 'Read file',
+ parameters: z.object({ path: z.string() }).passthrough(),
+ impl: async () => 'unused',
+ },
+ {
+ name: 'SendUser',
+ description: 'Forbidden',
+ parameters: z.object({}),
+ impl: async () => '',
+ },
+ ],
+ execute: async (_session: string, _id: string, _tool: unknown, args: unknown) => {
+ count++;
+ return args;
+ },
+ deliver: (_session: string, input: unknown) => {
+ delivered.push(input);
+ return true;
+ },
+ };
+ let host = new RemoteToolsHost(dir, deps);
+ const c = (await host.request(
+ { action: 'open', originHost: 'main', originSession: 'bot', templateSession: 'template' },
+ 'owner',
+ )) as { id: string };
+ return {
+ dir,
+ deps,
+ c,
+ get host() {
+ return host;
+ },
+ get count() {
+ return count;
+ },
+ get created() {
+ return created;
+ },
+ delivered,
+ async restart() {
+ await host.close();
+ host = new RemoteToolsHost(dir, deps);
+ },
+ async close() {
+ await host.close();
+ await rm(dir, { recursive: true, force: true });
+ },
+ };
+}
+test('remote context and call receipts persist, retry never repeats an effect', async () => {
+ const f = await fixture();
+ try {
+ const call = {
+ action: 'call' as const,
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'call',
+ tool: 'Read',
+ arguments: { path: 'a' },
+ };
+ assert.equal(((await f.host.request(call, 'owner')) as any).status, 'completed');
+ await f.host.request(call, 'owner');
+ assert.equal(f.count, 1);
+ await f.restart();
+ await f.host.request(call, 'owner');
+ assert.equal(f.count, 1);
+ const c = (await f.host.request(
+ { action: 'open', originHost: 'main', originSession: 'bot', templateSession: 'template' },
+ 'owner',
+ )) as any;
+ assert.equal(c.id, f.c.id);
+ assert.equal(f.created, 1);
+ await assert.rejects(
+ f.host.request({ ...call, arguments: { path: 'b' } }, 'owner'),
+ /different arguments/,
+ );
+ } finally {
+ await f.close();
+ }
+});
+test('context isolation, explicit tool exports and original schema', async () => {
+ const f = await fixture();
+ try {
+ await assert.rejects(
+ f.host.request(
+ {
+ action: 'search',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ query: '',
+ },
+ 'other',
+ ),
+ /another principal/,
+ );
+ await assert.rejects(
+ f.host.request(
+ {
+ action: 'search',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'other-bot' },
+ query: '',
+ },
+ 'owner',
+ ),
+ /another origin conversation/,
+ );
+ const found = (await f.host.request(
+ {
+ action: 'search',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ query: '',
+ },
+ 'owner',
+ )) as any;
+ assert.deepEqual(
+ found.tools.map((t: any) => t.name),
+ ['Read'],
+ );
+ assert.ok(found.tools[0].parameters.properties.path);
+ const keywords = (await f.host.request(
+ {
+ action: 'search',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ query: 'read write files shell',
+ },
+ 'owner',
+ )) as any;
+ assert.deepEqual(
+ keywords.tools.map((t: any) => t.name),
+ ['Read'],
+ );
+ await assert.rejects(
+ f.host.request(
+ {
+ action: 'call',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'bad',
+ tool: 'SendUser',
+ arguments: {},
+ },
+ 'owner',
+ ),
+ /not exported/,
+ );
+ } finally {
+ await f.close();
+ }
+});
+test('feedback is durable, scoped and acknowledged only explicitly', async () => {
+ const f = await fixture();
+ try {
+ assert.equal(
+ f.host.feedback('remote-session', {
+ id: 'progress',
+ type: 'task_update',
+ source: 'matter',
+ content: { text: 'done' },
+ }),
+ true,
+ );
+ const event = { action: 'events' as const, originHost: 'main' };
+ const a = (await f.host.request(event, 'owner')) as any[];
+ assert.equal(a.length, 1);
+ assert.deepEqual(await f.host.request(event, 'other'), []);
+ await f.restart();
+ assert.deepEqual(await f.host.request(event, 'owner'), a);
+ await f.host.request({ action: 'ack', ids: [a[0].id] }, 'other');
+ assert.equal(((await f.host.request(event, 'owner')) as any[]).length, 1);
+ await f.host.request({ action: 'ack', ids: [a[0].id] }, 'owner');
+ assert.deepEqual(await f.host.request(event, 'owner'), []);
+ } finally {
+ await f.close();
+ }
+});
+test('tool failure settles and later calls still run; inline reads do not wake the Bot', async () => {
+ const f = await fixture();
+ try {
+ f.deps.execute = async () => {
+ throw Error('network failed');
+ };
+ const call = {
+ action: 'call' as const,
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'failure',
+ tool: 'Read',
+ arguments: { path: 'a' },
+ };
+ const result = (await f.host.request(call, 'owner')) as any;
+ assert.match(result.result.error, /network failed/);
+ f.deps.execute = async () => ({ ok: true });
+ assert.equal(
+ ((await f.host.request({ ...call, callId: 'next' }, 'owner')) as any).result.ok,
+ true,
+ );
+ assert.deepEqual(await f.host.request({ action: 'events', originHost: 'main' }, 'owner'), []);
+ } finally {
+ await f.close();
+ }
+});
+test('interrupted execution is outcome_unknown after restart, never automatically replayed', async () => {
+ const f = await fixture();
+ try {
+ const db = new DatabaseSync(join(f.dir, 'remote-tools.sqlite'));
+ db.prepare('INSERT INTO calls(id,context,fingerprint,status,result) VALUES(?,?,?,?,NULL)').run(
+ 'interrupted',
+ f.c.id,
+ 'fingerprint',
+ 'running',
+ );
+ db.close();
+ await f.restart();
+ const db2 = new DatabaseSync(join(f.dir, 'remote-tools.sqlite'));
+ assert.equal(
+ db2.prepare('SELECT status FROM calls WHERE id=?').get('interrupted')!.status,
+ 'outcome_unknown',
+ );
+ db2.close();
+ assert.equal(f.count, 0);
+ } finally {
+ await f.close();
+ }
+});
+test('protocol rejects extra routing fields and grants only explicit owner operation', () => {
+ assert.equal(remoteToolsRequest.safeParse({ action: 'contexts', command: 'rm' }).success, false);
+ assert.equal(operationAllowsRemoteOwner('remote.tools'), true);
+});
+
+test('deferred calls keep running, reject overlapping work, and support explicit cancellation', async () => {
+ const f = await fixture();
+ try {
+ f.deps.execute = async (_s, _id, _tool, _args, _event, signal) =>
+ new Promise((_resolve, reject) =>
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true }),
+ );
+ const call = {
+ action: 'call' as const,
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'long',
+ tool: 'Read',
+ arguments: { path: 'a' },
+ };
+ assert.equal(((await f.host.request(call, 'owner')) as any).status, 'running');
+ await assert.rejects(
+ f.host.request({ ...call, callId: 'overlap' }, 'owner'),
+ /active tool call/,
+ );
+ await assert.rejects(
+ f.host.request(
+ {
+ action: 'cancel',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'long',
+ },
+ 'other',
+ ),
+ /another principal/,
+ );
+ await f.host.request(
+ {
+ action: 'cancel',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'long',
+ },
+ 'owner',
+ );
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ const result = (await f.host.request(
+ {
+ action: 'result',
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'long',
+ },
+ 'owner',
+ )) as any;
+ assert.equal(result.status, 'outcome_unknown');
+ assert.match(result.result.error, /cancelled/);
+ const events = (await f.host.request(
+ { action: 'events', originHost: 'main' },
+ 'owner',
+ )) as any[];
+ assert.equal(events.length, 1);
+ assert.equal(events[0].content.callId, 'long');
+ } finally {
+ await f.close();
+ }
+});
+
+test('all Bot business capabilities are exported; its chat loop remains local', async () => {
+ const { BOT_TOOLS, BOT_DELEGATION_TOOLS } = await import('../assistant/bot/capabilities.js');
+ const { REMOTE_TOOL_NAMES } = await import('../server/remote-tools.js');
+ for (const name of BOT_DELEGATION_TOOLS) assert.ok(REMOTE_TOOL_NAMES.has(name), name);
+ for (const name of BOT_TOOLS)
+ if (!BOT_DELEGATION_TOOLS.has(name)) assert.equal(REMOTE_TOOL_NAMES.has(name), false, name);
+});
+test('retry argument object order is irrelevant; discovery feedback retains its type', async () => {
+ const f = await fixture();
+ try {
+ const call = {
+ action: 'call' as const,
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'order',
+ tool: 'Read',
+ arguments: { path: 'a', options: { first: 1, second: 2 } },
+ };
+ await f.host.request(call, 'owner');
+ await f.host.request(
+ { ...call, arguments: { options: { second: 2, first: 1 }, path: 'a' } },
+ 'owner',
+ );
+ assert.equal(f.count, 1);
+ await f.host.request(
+ {
+ action: 'deliver',
+ sessionId: 'bot',
+ id: 'd',
+ source: 'remote',
+ content: { type: 'discovery', content: 'finding' },
+ },
+ 'owner',
+ );
+ assert.equal((f.delivered[0] as any).type, 'discovery');
+ } finally {
+ await f.close();
+ }
+});
+
+test('large results and batched feedback remain transportable without repeating work', async () => {
+ const f = await fixture();
+ try {
+ let effects = 0;
+ f.deps.execute = async () => {
+ effects++;
+ return { text: 'x'.repeat(3 * 1024 * 1024) };
+ };
+ const call = {
+ action: 'call' as const,
+ contextId: f.c.id,
+ origin: { hostId: 'main', sessionId: 'bot' },
+ callId: 'large',
+ tool: 'Read',
+ arguments: { path: 'large' },
+ };
+ const receipt = (await f.host.request(call, 'owner')) as any;
+ assert.equal(receipt.status, 'completed');
+ assert.equal(receipt.resultUnavailable.code, 'result_too_large');
+ await f.host.request(call, 'owner');
+ assert.equal(effects, 1);
+ for (let i = 0; i < 5; i++)
+ f.host.feedback('remote-session', {
+ id: `big-${i}`,
+ type: 'system_event',
+ source: 'test',
+ content: 'x'.repeat(800_000),
+ });
+ let count = 0;
+ for (;;) {
+ const events = (await f.host.request(
+ { action: 'events', originHost: 'main' },
+ 'owner',
+ )) as any[];
+ if (!events.length) break;
+ assert.ok(Buffer.byteLength(JSON.stringify({ value: events })) < 2 * 1024 * 1024);
+ count += events.length;
+ await f.host.request({ action: 'ack', ids: events.map((e) => e.id) }, 'owner');
+ }
+ assert.equal(count, 5);
+ } finally {
+ await f.close();
+ }
+});
diff --git a/packages/runtime-host/src/assistant/bot/bridge.ts b/packages/runtime-host/src/assistant/bot/bridge.ts
index 4ed810f12a..e1c7a44147 100644
--- a/packages/runtime-host/src/assistant/bot/bridge.ts
+++ b/packages/runtime-host/src/assistant/bot/bridge.ts
@@ -36,6 +36,7 @@ export interface BotEndpoint {
/** In-process routing only; durable mailbox and wake state belong to the Bot. */
export class AssistantBotBridge {
private endpoint?: BotEndpoint;
+ constructor(private readonly remotePost?: (owner: string, input: InboxInput) => boolean) {}
register(endpoint: BotEndpoint) {
this.endpoint = endpoint;
}
@@ -65,6 +66,7 @@ export class AssistantBotBridge {
return true;
}
post(owner: string, input: InboxInput) {
+ if (this.remotePost?.(owner, input)) return true;
if (!this.isConversation(owner)) return false;
this.endpoint!.post(input);
return true;
diff --git a/packages/runtime-host/src/assistant/index-initiative/host.ts b/packages/runtime-host/src/assistant/index-initiative/host.ts
index 257ea7c03e..599d062952 100644
--- a/packages/runtime-host/src/assistant/index-initiative/host.ts
+++ b/packages/runtime-host/src/assistant/index-initiative/host.ts
@@ -18,7 +18,10 @@
*/
import type { AssistantModuleServices } from '../service.js';
-import { randomUUID } from 'node:crypto';
+import { randomUUID, createHash } from 'node:crypto';
+import { readdir, mkdir } from 'node:fs/promises';
+import { join } from 'node:path';
+import type { MakaTool } from '@maka/runtime/tool-runtime';
import { z } from 'zod';
import { InitiativeStore } from './store.js';
import { InitiativeController } from './controller.js';
@@ -29,6 +32,99 @@ export async function initializeInitiative(
directory: string,
config: any = {},
) {
+ // Remote contexts have their own discovery schedule, but no second chat Bot.
+ // Keep their workers and reports attached to the originating conversation.
+ const scopes = new Map<string, { tools: Map<string, MakaTool>; store: InitiativeStore }>();
+ const pending = new Map<string, Promise<any>>();
+ const starters: (() => () => void | Promise<void>)[] = [];
+ const stops: (() => void | Promise<void>)[] = [];
+ let started = false;
+ const root = join(directory, 'remote-discovery');
+ const create = async (key: string, binding?: { sessionId: string; cwd: string }) => {
+ const tools = new Map<string, MakaTool>();
+ const store = await installInitiative(
+ {
+ ...ctx,
+ tools: {
+ ...ctx.tools,
+ register: (tool) => {
+ tools.set(tool.name, tool);
+ },
+ },
+ onStart: (start) => {
+ starters.push(start);
+ if (started) stops.push(start());
+ },
+ },
+ join(root, key),
+ config,
+ binding ?? 'recover',
+ );
+ const scope = { tools, store };
+ scopes.set(key, scope);
+ return scope;
+ };
+ await mkdir(root, { recursive: true, mode: 0o700 });
+ for (const entry of await readdir(root, { withFileTypes: true }))
+ if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name)) await create(entry.name);
+ const route = async (sessionId: string, cwd: string) => {
+ for (const scope of scopes.values()) {
+ const state = scope.store.get();
+ if (state?.sessionId === sessionId || state?.discoverySession === sessionId) return scope;
+ }
+ if (!ctx.isRemoteContext?.(sessionId)) return undefined;
+ const key = createHash('sha256').update(sessionId).digest('hex');
+ let opening = pending.get(key);
+ if (!opening) {
+ opening = create(key, { sessionId, cwd });
+ pending.set(key, opening);
+ void opening.finally(() => pending.delete(key)).catch(() => {});
+ }
+ return opening;
+ };
+ await installInitiative(
+ {
+ ...ctx,
+ tools: {
+ ...ctx.tools,
+ register: (tool) =>
+ ctx.tools.register({
+ ...tool,
+ impl: (input, call) => {
+ const scope = [...scopes.values()].find((entry) => {
+ const state = entry.store.get();
+ return (
+ state?.sessionId === call.sessionId || state?.discoverySession === call.sessionId
+ );
+ });
+ if (scope) return (scope.tools.get(tool.name) ?? tool).impl(input, call);
+ if (!ctx.isRemoteContext?.(call.sessionId)) return tool.impl(input, call);
+ return route(call.sessionId, call.cwd!).then((remote) =>
+ (remote?.tools.get(tool.name) ?? tool).impl(input, call),
+ );
+ },
+ }),
+ },
+ },
+ directory,
+ config,
+ );
+ ctx.onStart(() => {
+ started = true;
+ for (const start of starters) stops.push(start());
+ return async () => {
+ started = false;
+ await Promise.all(stops.map((stop) => stop()));
+ };
+ });
+}
+
+async function installInitiative(
+ ctx: AssistantModuleServices,
+ directory: string,
+ config: any,
+ remote?: { sessionId: string; cwd: string } | 'recover',
+): Promise<InitiativeStore> {
const limits = { tickMs: config.tickMs ?? 5000 };
for (const [name, value] of Object.entries(limits))
if (!Number.isSafeInteger(value) || value < 10 || value > 3600000)
@@ -41,9 +137,18 @@ export async function initializeInitiative(
controller.start();
return () => controller.close();
};
+ if (remote) {
+ if (remote !== 'recover') {
+ if (!store.lease()) throw Error('Remote discovery is owned by another process');
+ store.bind(remote);
+ }
+ if (!store.get()) throw Error('Remote discovery binding is missing');
+ }
ctx.onStart(activate);
- initializeBot(ctx, directory, store);
- registerAssistant(ctx, store, controller);
+ if (!remote) {
+ initializeBot(ctx, directory, store);
+ registerAssistant(ctx, store, controller);
+ }
ctx.backgroundSessions.register(() =>
store.get()?.discoverySession ? [store.get().discoverySession] : [],
);
@@ -60,12 +165,13 @@ export async function initializeInitiative(
if (!state?.active || state.discoverySession !== call.sessionId)
throw Error('Not the active exploration worker');
const id = `discovery:${state.active.id}:${call.toolCallId}`;
- const reported = ctx.bot.post(state.sessionId, {
+ const report = {
id,
- type: 'discovery',
+ type: 'discovery' as const,
source: call.sessionId,
content: input.text,
- });
+ };
+ const reported = ctx.bot.post(state.sessionId, report);
if (!reported) throw Error('Bot did not accept the discovery report');
return { reported, sentToUser: false };
},
@@ -178,4 +284,5 @@ export async function initializeInitiative(
? '你是独立的主动探索 Agent。通过可用工具调查。值得交流的发现用 DiscoveryReport 交给个人助手 Bot,由它和用户交流;没有合适内容可以直接结束。这里不是用户聊天框,不要委派执行任务。'
: undefined,
});
+ return store;
}
diff --git a/packages/runtime-host/src/assistant/service.ts b/packages/runtime-host/src/assistant/service.ts
index 14a46c411c..1a3a41ae29 100644
--- a/packages/runtime-host/src/assistant/service.ts
+++ b/packages/runtime-host/src/assistant/service.ts
@@ -53,6 +53,8 @@ type Dispose = () => void | Promise<void>;
/** Shared Host capabilities retain invocation identity and source permissions. No plugin Fiber owns this service. */
export interface AssistantDependencies {
+ isRemoteContext?(sessionId: string): boolean;
+ remoteFeedback?(owner: string, input: import('./bot/store.js').InboxInput): boolean;
agents: PluginAgentService;
llm: PluginLlmService;
sessionQuery: PluginSessionQueryService;
@@ -88,7 +90,7 @@ export interface AssistantModuleServices
class AssistantRuntime {
readonly tools: MakaTool[] = [];
- readonly bot = new AssistantBotBridge();
+ readonly bot: AssistantBotBridge;
private readonly sections: PluginSystemPromptSection[] = [];
private readonly contexts: PluginSystemPromptSection[] = [];
private readonly checks: TurnFinishCheck[] = [];
@@ -106,7 +108,9 @@ class AssistantRuntime {
constructor(
readonly directory: string,
readonly dependencies: AssistantDependencies,
- ) {}
+ ) {
+ this.bot = new AssistantBotBridge(dependencies.remoteFeedback);
+ }
async recover(legacy: HostPluginDataRuntime, entries: readonly MakaCompositionEntryInspection[]) {
if (this.initialized) throw Error('Personal assistant already initialized');
@@ -471,6 +475,15 @@ export class PersonalAssistantService {
? this.runtime!.tools.filter((tool) => BOT_TOOLS.has(tool.name))
: undefined;
}
+ remoteOrigin(sessionId: string) {
+ return this.runtime?.bot.ownerFor(sessionId) ?? sessionId;
+ }
+ receiveRemote(sessionId: string, input: import('./bot/store.js').InboxInput) {
+ if (!this.enabled || this.draining) return false;
+ const owner = this.runtime!.bot.ownerFor(sessionId) ?? sessionId;
+ if (!this.runtime!.bot.isConversation(owner)) return 'manual_only' as const;
+ return this.runtime!.bot.post(owner, input);
+ }
async receiveUser(
sessionId: string,
id: string,
diff --git a/packages/runtime-host/src/protocol/index.ts b/packages/runtime-host/src/protocol/index.ts
index 402c767787..3d36b28110 100644
--- a/packages/runtime-host/src/protocol/index.ts
+++ b/packages/runtime-host/src/protocol/index.ts
@@ -113,7 +113,8 @@ export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
// Also adds assistant.avatar/assistant.avatar-image and the bot block on assistant.binding.
// 223 is used by the distinct protocol changes in open PRs #6115 and #6091;
// re-check against main at merge time (the protocol epoch gate remains authoritative).
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 224 as const;
+// 225: Owner-scoped remote tool contexts, receipts and task feedback operations.
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 225 as const;
// 222: Built-in personal assistant operations and the Host-owned default-off
// master switch require matching Client and Host support.
// 221: Epoch-220 peers do not support `artifact.image.resolve` or its image
@@ -914,3 +915,5 @@ function requireReplacement(value: unknown): HostIncompatible['replacement'] {
if (value === 'blocked_by_residency' || value === 'wait_for_idle_exit') return value;
throw invalidProtocolFrame('Invalid replacement disposition');
}
+
+export * from './remote-tools.js';
diff --git a/packages/runtime-host/src/protocol/operations.ts b/packages/runtime-host/src/protocol/operations.ts
index 3192a38ccf..8c139729b3 100644
--- a/packages/runtime-host/src/protocol/operations.ts
+++ b/packages/runtime-host/src/protocol/operations.ts
@@ -35,6 +35,7 @@ import { HOSTED_EXECUTION_OPERATION_SPECS } from './hosted-execution.js';
import { GOAL_OPERATION_SPECS } from './goal.js';
import { INTERACTION_OPERATION_SPECS } from './interaction.js';
import { MESSAGE_OPERATION_SPECS } from './message.js';
+import { REMOTE_TOOLS_OPERATION_SPECS } from './remote-tools.js';
import { PERSONAL_ASSISTANT_OPERATION_SPECS } from './personal-assistant.js';
import { MEMORY_OPERATION_SPECS } from './memory.js';
import { NETWORK_PROXY_OPERATION_SPECS } from './network-proxy.js';
@@ -238,7 +239,11 @@ export const HOST_OPERATION_SPECS = composeOperationSpecMaps(
USAGE_PRICING_OPERATION_SPECS,
STORAGE_USAGE_OPERATION_SPECS,
STORAGE_RETENTION_OPERATION_SPECS,
- composeOperationSpecMaps(MEMORY_OPERATION_SPECS, PERSONAL_ASSISTANT_OPERATION_SPECS),
+ composeOperationSpecMaps(
+ MEMORY_OPERATION_SPECS,
+ PERSONAL_ASSISTANT_OPERATION_SPECS,
+ REMOTE_TOOLS_OPERATION_SPECS,
+ ),
OAUTH_OPERATION_SPECS,
EXTERNAL_AGENT_SETUP_OPERATION_SPECS,
CLIENT_CAPABILITY_OPERATION_SPECS,
@@ -318,6 +323,7 @@ export const REMOTE_OWNER_OPERATION_GRANTS = Object.freeze([
'plugin.client.query',
'plugin.client.remote.call',
'personal-assistant.call',
+ 'remote.tools',
'plugin.client.remote.stream.close',
'plugin.client.remote.stream.next',
'plugin.client.remote.stream.open',
diff --git a/packages/runtime-host/src/protocol/remote-tools.ts b/packages/runtime-host/src/protocol/remote-tools.ts
new file mode 100644
index 0000000000..e6d9db9601
--- /dev/null
+++ b/packages/runtime-host/src/protocol/remote-tools.ts
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { z } from 'zod';
+import { defineOperation } from './operation-spec.js';
+import { requireEncodedByteLimit } from './codec.js';
+export const REMOTE_TOOLS_RESULT_BYTES = 2 * 1024 * 1024;
+const id = z.string().min(1).max(256);
+const origin = z.object({ hostId: id, sessionId: id }).strict();
+export const remoteToolsRequest = z.discriminatedUnion('action', [
+ z.object({ action: z.literal('origin'), sessionId: id }).strict(),
+ z.object({ action: z.literal('contexts') }).strict(),
+ z
+ .object({ action: z.literal('open'), originHost: id, originSession: id, templateSession: id })
+ .strict(),
+ z
+ .object({
+ action: z.literal('search'),
+ contextId: id,
+ origin,
+ query: z.string().max(300).default(''),
+ })
+ .strict(),
+ z
+ .object({
+ action: z.literal('call'),
+ contextId: id,
+ origin,
+ callId: id,
+ tool: id,
+ arguments: z.unknown(),
+ })
+ .strict(),
+ z.object({ action: z.literal('cancel'), contextId: id, origin, callId: id }).strict(),
+ z.object({ action: z.literal('result'), contextId: id, origin, callId: id }).strict(),
+ z.object({ action: z.literal('events'), originHost: id }).strict(),
+ z.object({ action: z.literal('ack'), ids: z.array(id).max(100) }).strict(),
+ z
+ .object({ action: z.literal('deliver'), sessionId: id, id, source: id, content: z.unknown() })
+ .strict(),
+]);
+export type RemoteToolsRequest = z.infer<typeof remoteToolsRequest>;
+export const REMOTE_TOOLS_OPERATION_SPECS = {
+ 'remote.tools': defineOperation<
+ RemoteToolsRequest,
+ { value: unknown },
+ | 'invalid_request'
+ | 'unauthorized'
+ | 'host_not_ready'
+ | 'host_draining'
+ | 'operation_unavailable'
+ | 'internal_failure'
+ >({
+ mode: 'command',
+ availability: 'ready',
+ errors: [
+ 'invalid_request',
+ 'unauthorized',
+ 'host_not_ready',
+ 'host_draining',
+ 'operation_unavailable',
+ 'internal_failure',
+ ],
+ decodeInput(value) {
+ requireEncodedByteLimit(value, 'Remote tool request', 128 * 1024);
+ return remoteToolsRequest.parse(value);
+ },
+ decodeOutput(value) {
+ requireEncodedByteLimit(value, 'Remote tool result', REMOTE_TOOLS_RESULT_BYTES);
+ return z.object({ value: z.unknown() }).strict().parse(value);
+ },
+ }),
+};
diff --git a/packages/runtime-host/src/server/execution-composition.ts b/packages/runtime-host/src/server/execution-composition.ts
index 5db8e7a045..3db735db72 100644
--- a/packages/runtime-host/src/server/execution-composition.ts
+++ b/packages/runtime-host/src/server/execution-composition.ts
@@ -25,6 +25,8 @@ import { ChatImageDeliveryService } from './chat-image-delivery.js';
import { downloadChatImage, ImageSourceError } from './chat-image-source.js';
import { readAvatarImageSource } from './avatar-image-source.js';
import { createWorkHubResultRuntime } from './workhub-result-runtime.js';
+import { RemoteToolsHost } from './remote-tools.js';
+import { ToolRuntime } from '@maka/runtime/tool-runtime';
import { createWorkHubInspectionTool } from './workhub-inspection-tool.js';
import { copyWorkHubAttachmentsToTarget } from './workhub-message-attachments.js';
import { createHash, randomUUID } from 'node:crypto';
@@ -449,9 +451,12 @@ export async function createExecutionRuntimeHostComposition(
},
);
+ let remoteTools: RemoteToolsHost | undefined;
const personalAssistant = (assistant = new PersonalAssistantService(
join(context.owner.controlDirectory, 'personal-assistant'),
{
+ remoteFeedback: (owner, input) => remoteTools?.feedback(owner, input) ?? false,
+ isRemoteContext: (sessionId) => remoteTools?.ownsSession(sessionId) ?? false,
stopSessions: async () => {
if (!rootCoordinator) return;
const failures: unknown[] = [];
@@ -949,6 +954,91 @@ export async function createExecutionRuntimeHostComposition(
...runtimePolicy.modelTools,
];
const hostTools = [...childHostTools, ...recallTools];
+ remoteTools = new RemoteToolsHost(join(context.owner.controlDirectory, 'remote-tools'), {
+ origin: (sessionId) => personalAssistant.remoteOrigin(sessionId),
+ list: async () =>
+ (await stores.sessionStore.listHeaders())
+ .filter(
+ (h) => !h.parentSessionId && !h.labels?.some((l) => l.startsWith('remote-context:')),
+ )
+ .map((h) => ({
+ sessionId: h.id,
+ name: h.name,
+ cwd: h.cwd,
+ permissionMode: h.permissionMode,
+ })),
+ create: async (template, label) => {
+ const existing = (await stores.sessionStore.listHeaders()).find((h) =>
+ h.labels?.includes(label),
+ );
+ if (existing) return existing.id;
+ const parent = await stores.sessionStore.readHeaderSnapshot(template);
+ if (parent.executorId) throw Error('Remote tools require a native Maka Session template');
+ const boundary = await stores.sessionStore.readExecutionBoundary(template);
+ const created = await requireSessionManager(manager).createSession(
+ {
+ cwd: parent.cwd,
+ name: 'Remote tools',
+ labels: [label, 'remote-tool-context'],
+ llmConnectionSlug: parent.llmConnectionSlug,
+ ...(parent.llmConnectionId ? { llmConnectionId: parent.llmConnectionId } : {}),
+ ...(parent.model ? { model: parent.model } : {}),
+ ...(parent.thinkingLevel ? { thinkingLevel: parent.thinkingLevel } : {}),
+ permissionMode: parent.permissionMode,
+ },
+ { initialBoundary: boundary },
+ );
+ hostChanges.publishSessionCatalog(created.id);
+ return created.id;
+ },
+ tools: async () => {
+ const policy = await runtimePolicyStores.runtimePolicy.getSnapshot();
+ return [
+ ...buildBuiltinTools({
+ ...builtinTools,
+ shell: resolveTurnShellPlan(policy.policy.shell),
+ }),
+ ...personalAssistant.tools,
+ ];
+ },
+ execute: async (sessionId, callId, tool, args, event, signal) => {
+ const header = await stores.sessionStore.readHeaderSnapshot(sessionId);
+ if (requireSessionManager(manager).runningTurnIds(sessionId).length)
+ throw Error('Remote execution context is busy');
+ const runtime = new ToolRuntime({
+ sessionId,
+ header,
+ turnId: callId,
+ runId: callId,
+ invocationId: callId,
+ // No provider request is made; this runtime settles tools only.
+ connection: { slug: 'remote-tools', providerType: 'custom', defaultModel: 'tools-only' },
+ modelId: 'tools-only',
+ readExecutionBoundary: () => stores.sessionStore.readExecutionBoundary(sessionId),
+ readPermissionMode: async () =>
+ (await stores.sessionStore.readHeaderSnapshot(sessionId)).permissionMode,
+ newId: randomUUID,
+ now: Date.now,
+ getPermissionPauseTarget: () => null,
+ });
+ return runtime.settleToolCall({
+ tool,
+ turnId: callId,
+ stepId: callId,
+ toolCallId: callId,
+ input: args,
+ abortSignal: signal,
+ eventSink: {
+ push: event,
+ pushAndWaitUntilConsumed: async (value) => {
+ event(value);
+ },
+ },
+ });
+ },
+ deliver: (sessionId, input) => personalAssistant.receiveRemote(sessionId, input),
+ });
+
const childAgentTools = createHostChildAgentToolComposition({
builtinTools,
hostTools: childHostTools,
@@ -3257,6 +3347,39 @@ export async function createExecutionRuntimeHostComposition(
(connectionId) => pluginPlatformCoordinator.releaseConnection(connectionId),
],
}),
+ createRuntimeHostDomainModule({
+ id: 'remote-tools',
+ handlers: [
+ {
+ 'remote.tools': async (input, caller) => {
+ if (caller.principalKind !== 'local_owner' && caller.principalKind !== 'remote_owner')
+ return {
+ ok: false,
+ error: {
+ code: 'unauthorized',
+ message: 'Remote tools require an Owner credential',
+ },
+ };
+ try {
+ return {
+ ok: true,
+ result: { value: await remoteTools!.request(input, caller.principal) },
+ };
+ } catch (error) {
+ return {
+ ok: false,
+ error: {
+ code: 'invalid_request',
+ message: error instanceof Error ? error.message : String(error),
+ },
+ };
+ }
+ },
+ },
+ ],
+ drain: [() => remoteTools!.beginDrain()],
+ close: [() => remoteTools!.close()],
+ }),
createRuntimeHostDomainModule({
id: 'personal-assistant',
handlers: [
diff --git a/packages/runtime-host/src/server/interactive-run-composer.ts b/packages/runtime-host/src/server/interactive-run-composer.ts
index 17e3b43e83..91b5dfc11d 100644
--- a/packages/runtime-host/src/server/interactive-run-composer.ts
+++ b/packages/runtime-host/src/server/interactive-run-composer.ts
@@ -174,7 +174,11 @@ export function createInteractiveRunComposer(input: InteractiveRunComposerInput)
input.boundTools !== undefined ||
(input.toolProfile !== undefined && input.toolProfile !== 'workhub-coordination-v2')
? []
- : (input.clientCapabilities?.tools ?? []);
+ : (input.clientCapabilities?.tools ?? []).map((tool) =>
+ tool.name === 'mcp__desktop_remote_hosts__HostList'
+ ? { ...tool, discovery: 'direct' as const }
+ : tool,
+ );
const returnMissingInformation = () =>
typeof input.returnMissingInformation === 'function'
? input.returnMissingInformation()
@@ -479,7 +483,19 @@ export function createInteractiveRunComposerFactory(
backendContext.abortSignal,
)
: false;
- const nativeCeiling = input.resolveToolCeiling?.(backendContext.sessionId);
+ const baseNativeCeiling = input.resolveToolCeiling?.(backendContext.sessionId);
+ const nativeCeiling = baseNativeCeiling
+ ? [
+ ...baseNativeCeiling,
+ ...(clientCapabilities?.tools ?? [])
+ .filter((t) => t.name.startsWith('mcp__desktop_remote_hosts__'))
+ .map((t) =>
+ t.name === 'mcp__desktop_remote_hosts__HostList'
+ ? { ...t, discovery: 'direct' as const }
+ : t,
+ ),
+ ]
+ : undefined;
const candidateHostTools = [...(input.hostTools ?? []), ...rootTools];
const toolSurface = routeInteractiveRunToolSurface({
runtimePolicy,
diff --git a/packages/runtime-host/src/server/remote-tools.ts b/packages/runtime-host/src/server/remote-tools.ts
new file mode 100644
index 0000000000..dba7e68ce3
--- /dev/null
+++ b/packages/runtime-host/src/server/remote-tools.ts
@@ -0,0 +1,369 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { createHash, randomUUID } from 'node:crypto';
+import { mkdirSync, chmodSync } from 'node:fs';
+import { join } from 'node:path';
+import { DatabaseSync } from 'node:sqlite';
+import { z } from 'zod';
+import type { MakaTool } from '@maka/runtime/tool-runtime';
+import { REMOTE_TOOLS_RESULT_BYTES, type RemoteToolsRequest } from '../protocol/remote-tools.js';
+import type { InboxInput } from '../assistant/bot/store.js';
+import { canonicalToolArgsHash } from '@maka/core/tool-args-identity';
+import { BOT_DELEGATION_TOOLS } from '../assistant/bot/capabilities.js';
+
+// The single origin Bot owns communication/lifecycle; all its business tools run on targets.
+export const REMOTE_TOOL_NAMES = new Set([
+ ...BOT_DELEGATION_TOOLS,
+ 'Read',
+ 'Glob',
+ 'Grep',
+ 'Write',
+ 'Edit',
+ 'Bash',
+ 'WriteStdin',
+ 'StopBackgroundTask',
+ 'MemorySourceQuery',
+ 'MemoryStatus',
+]);
+interface RemoteContext {
+ id: string;
+ principal: string;
+ originHost: string;
+ originSession: string;
+ templateSession: string;
+ sessionId: string;
+}
+interface Dependencies {
+ origin?(sessionId: string): string;
+ list(): Promise<unknown>;
+ create(template: string, label: string): Promise<string>;
+ tools(sessionId: string): Promise<readonly MakaTool[]>;
+ execute(
+ sessionId: string,
+ callId: string,
+ tool: MakaTool,
+ args: unknown,
+ event: (value: unknown) => void,
+ signal: AbortSignal,
+ ): Promise<unknown>;
+ deliver(sessionId: string, input: InboxInput): boolean | 'manual_only';
+}
+const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
+export class RemoteToolsHost {
+ private readonly db: DatabaseSync;
+ private readonly active = new Map<string, Promise<void>>();
+ private readonly abort = new AbortController();
+ private readonly cancellations = new Map<string, AbortController>();
+ private opening: Promise<unknown> = Promise.resolve();
+ constructor(
+ directory: string,
+ private readonly deps: Dependencies,
+ ) {
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
+ const path = join(directory, 'remote-tools.sqlite');
+ this.db = new DatabaseSync(path);
+ chmodSync(path, 0o600);
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;
+ CREATE TABLE IF NOT EXISTS contexts(id TEXT PRIMARY KEY,payload TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS calls(id TEXT PRIMARY KEY,context TEXT NOT NULL,fingerprint TEXT NOT NULL,status TEXT NOT NULL,result TEXT);
+ CREATE TABLE IF NOT EXISTS trace(seq INTEGER PRIMARY KEY AUTOINCREMENT,call_id TEXT NOT NULL,payload TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS outbox(id TEXT PRIMARY KEY,principal TEXT NOT NULL,origin_host TEXT NOT NULL,origin_session TEXT NOT NULL,payload TEXT NOT NULL,acked INTEGER NOT NULL DEFAULT 0);`);
+ if (
+ !this.db
+ .prepare('PRAGMA table_info(calls)')
+ .all()
+ .some((c) => c.name === 'call_id')
+ )
+ this.db.exec('ALTER TABLE calls ADD COLUMN call_id TEXT');
+ // No re-execution after a process dies between an effect and its receipt.
+ const interrupted = this.db
+ .prepare("SELECT id,context,call_id FROM calls WHERE status='running'")
+ .all();
+ this.db.exec("UPDATE calls SET status='outcome_unknown' WHERE status='running'");
+ for (const row of interrupted) {
+ const c = this.context(String(row.context));
+ this.emit(c, String(row.id), {
+ contextId: c.id,
+ callId: row.call_id ?? null,
+ status: 'outcome_unknown',
+ message:
+ 'Host restarted before this tool call had a durable outcome. Inspect target state before retrying.',
+ });
+ }
+ }
+ private context(id: string, principal?: string): RemoteContext {
+ const row = this.db.prepare('SELECT payload FROM contexts WHERE id=?').get(id);
+ if (!row) throw Error('Remote execution context not found');
+ const context = JSON.parse(String(row.payload)) as RemoteContext;
+ if (principal && context.principal !== principal)
+ throw Error('Remote context belongs to another principal');
+ return context;
+ }
+ private receipt(context: RemoteContext, callId: string) {
+ const row = this.db
+ .prepare('SELECT status,result FROM calls WHERE id=? AND context=?')
+ .get(digest([context.id, callId]), context.id);
+ if (!row) return { callId, contextId: context.id, status: 'not_found' };
+ const bytes = row.result ? Buffer.byteLength(String(row.result)) : 0;
+ return {
+ callId,
+ contextId: context.id,
+ status: row.status,
+ ...(bytes > REMOTE_TOOLS_RESULT_BYTES - 8192
+ ? {
+ resultUnavailable: {
+ code: 'result_too_large',
+ bytes,
+ message:
+ 'Full result retained on target. Execution is settled; do not repeat a mutation. For reads, issue a smaller paginated query with a new callId.',
+ },
+ }
+ : row.result
+ ? { result: JSON.parse(String(row.result)) }
+ : {}),
+ };
+ }
+ private emit(context: RemoteContext, id: string, payload: unknown) {
+ const existing = this.db.prepare('SELECT payload FROM outbox WHERE id=?').get(id);
+ if (existing && existing.payload !== JSON.stringify(payload))
+ throw Error('Remote feedback identity conflict');
+ this.db
+ .prepare(
+ 'INSERT OR IGNORE INTO outbox(id,principal,origin_host,origin_session,payload) VALUES(?,?,?,?,?)',
+ )
+ .run(
+ id,
+ context.principal,
+ context.originHost,
+ context.originSession,
+ JSON.stringify(payload),
+ );
+ }
+ ownsSession(sessionId: string): boolean {
+ return this.db
+ .prepare('SELECT payload FROM contexts')
+ .all()
+ .some((row) => JSON.parse(String(row.payload)).sessionId === sessionId);
+ }
+ feedback(owner: string, input: InboxInput): boolean {
+ for (const row of this.db.prepare('SELECT payload FROM contexts').all()) {
+ const c = JSON.parse(String(row.payload)) as RemoteContext;
+ if (c.sessionId !== owner) continue;
+ this.emit(c, digest([c.id, input.id]), { contextId: c.id, ...input });
+ return true;
+ }
+ return false;
+ }
+ async request(raw: RemoteToolsRequest, principal: string): Promise<unknown> {
+ this.abort.signal.throwIfAborted();
+ if (raw.action === 'origin')
+ return { sessionId: this.deps.origin?.(raw.sessionId) ?? raw.sessionId };
+ if (raw.action === 'contexts') return this.deps.list();
+ if (raw.action === 'open') {
+ const next = this.opening.then(async () => {
+ const id = digest([principal, raw.originHost, raw.originSession, raw.templateSession]);
+ const existing = this.db.prepare('SELECT payload FROM contexts WHERE id=?').get(id);
+ if (existing) return JSON.parse(String(existing.payload));
+ const sessionId = await this.deps.create(raw.templateSession, `remote-context:${id}`);
+ const context: RemoteContext = {
+ id,
+ principal,
+ originHost: raw.originHost,
+ originSession: raw.originSession,
+ templateSession: raw.templateSession,
+ sessionId,
+ };
+ this.db.prepare('INSERT INTO contexts VALUES(?,?)').run(id, JSON.stringify(context));
+ return context;
+ });
+ this.opening = next.catch(() => {});
+ return next;
+ }
+ if (raw.action === 'events') {
+ const events: { id: unknown; sessionId: unknown; content: unknown }[] = [];
+ let bytes = 0;
+ for (const row of this.db
+ .prepare(
+ 'SELECT id,origin_session,payload FROM outbox WHERE principal=? AND origin_host=? AND acked=0 ORDER BY rowid LIMIT 100',
+ )
+ .all(principal, raw.originHost)) {
+ let content = JSON.parse(String(row.payload));
+ if (Buffer.byteLength(String(row.payload)) > REMOTE_TOOLS_RESULT_BYTES - 8192)
+ content = {
+ contextId: content.contextId,
+ callId: content.callId,
+ status: content.status,
+ error:
+ 'Feedback exceeds transport budget; full content retained on target. Query the task/index or a smaller page. Do not repeat completed work.',
+ };
+ const event = { id: row.id, sessionId: row.origin_session, content };
+ const size = Buffer.byteLength(JSON.stringify(event));
+ if (events.length && bytes + size > REMOTE_TOOLS_RESULT_BYTES - 4096) break;
+ events.push(event);
+ bytes += size + 1;
+ }
+ return events;
+ }
+ if (raw.action === 'ack') {
+ for (const id of raw.ids)
+ this.db.prepare('UPDATE outbox SET acked=1 WHERE id=? AND principal=?').run(id, principal);
+ return { acknowledged: true };
+ }
+ if (raw.action === 'deliver') {
+ const content = raw.content as { type?: string; taskId?: string } | null;
+ const result = this.deps.deliver(raw.sessionId, {
+ id: raw.id,
+ type:
+ content?.type === 'task_update'
+ ? 'task_update'
+ : content?.type === 'discovery'
+ ? 'discovery'
+ : 'system_event',
+ source: raw.source,
+ content: raw.content,
+ });
+ return { accepted: result === true, manualOnly: result === 'manual_only' };
+ }
+ const context = this.context(raw.contextId, principal);
+ if (raw.origin.hostId !== context.originHost || raw.origin.sessionId !== context.originSession)
+ throw Error('Remote context belongs to another origin conversation');
+ if (raw.action === 'cancel') {
+ this.cancellations
+ .get(digest([context.id, raw.callId]))
+ ?.abort(Error('Remote call cancelled by user'));
+ return { cancellationRequested: true, ...this.receipt(context, raw.callId) };
+ }
+ if (raw.action === 'result') return this.receipt(context, raw.callId);
+ const tools = (await this.deps.tools(context.sessionId)).filter((t) =>
+ REMOTE_TOOL_NAMES.has(t.name),
+ );
+ if (raw.action === 'search')
+ return {
+ contextId: context.id,
+ sessionId: context.sessionId,
+ tools: tools
+ .filter((t) => {
+ const terms = raw.query.toLowerCase().trim().split(/\s+/).filter(Boolean);
+ const text = `${t.name} ${t.description}`.toLowerCase();
+ return terms.length === 0 || terms.some((term) => text.includes(term));
+ })
+ .map((t) => ({
+ name: t.name,
+ description: t.description,
+ parameters:
+ t.parameters instanceof z.ZodType
+ ? z.toJSONSchema(t.parameters, { unrepresentable: 'any', io: 'input' })
+ : t.parameters,
+ executionSemantics: t.executionSemantics,
+ recoveryMode: t.recoveryMode,
+ })),
+ notice:
+ 'References, paths, task IDs and cursors belong to this target Host and context. Follow-up operations must use the same context. No model is started for a tool call.',
+ };
+ const key = digest([context.id, raw.callId]);
+ const fingerprint = canonicalToolArgsHash(raw.tool, raw.arguments);
+ const prior = this.db.prepare('SELECT fingerprint FROM calls WHERE id=?').get(key);
+ if (prior) {
+ if (
+ prior.fingerprint !== fingerprint &&
+ prior.fingerprint !== digest([raw.tool, raw.arguments])
+ )
+ throw Error('callId already identifies different arguments');
+ return this.receipt(context, raw.callId);
+ }
+ const tool = tools.find((t) => t.name === raw.tool);
+ if (!tool) throw Error('Tool is not exported by this Host; discover available tools first');
+ const args =
+ tool.parameters instanceof z.ZodType ? tool.parameters.parse(raw.arguments) : raw.arguments;
+ if (this.db.prepare("SELECT 1 FROM calls WHERE context=? AND status='running'").get(context.id))
+ throw Error(
+ 'Remote context has an active tool call; read its result before starting another',
+ );
+ this.db
+ .prepare(
+ 'INSERT INTO calls(id,context,fingerprint,status,result,call_id) VALUES(?,?,?,?,NULL,?)',
+ )
+ .run(key, context.id, fingerprint, 'running', raw.callId);
+ const cancellation = new AbortController();
+ this.cancellations.set(key, cancellation);
+ let deferred = false;
+ const work = Promise.resolve().then(async () => {
+ let result: unknown;
+ let status = 'completed';
+ try {
+ result = await this.deps.execute(
+ context.sessionId,
+ key,
+ tool,
+ args,
+ (event) => {
+ this.db
+ .prepare('INSERT INTO trace(call_id,payload) VALUES(?,?)')
+ .run(key, JSON.stringify(event));
+ },
+ AbortSignal.any([this.abort.signal, cancellation.signal]),
+ );
+ } catch (error) {
+ status = 'outcome_unknown';
+ result = { error: error instanceof Error ? error.message : String(error) };
+ }
+ const serialized = JSON.stringify(result ?? null);
+ this.db.exec('BEGIN IMMEDIATE');
+ try {
+ this.db
+ .prepare('UPDATE calls SET status=?,result=? WHERE id=?')
+ .run(status, serialized, key);
+ if (deferred)
+ this.emit(context, key, { tool: raw.tool, ...this.receipt(context, raw.callId) });
+ this.db.exec('COMMIT');
+ } catch (error) {
+ this.db.exec('ROLLBACK');
+ throw error;
+ }
+ });
+ this.active.set(key, work);
+ void work
+ .finally(() => {
+ this.active.delete(key);
+ this.cancellations.delete(key);
+ })
+ .catch(() => {});
+ // Short operations return inline. Longer operations remain owned by this Host.
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ await Promise.race([
+ work,
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, 1000);
+ }),
+ ]);
+ if (timer) clearTimeout(timer);
+ deferred = true;
+ return this.receipt(context, raw.callId);
+ }
+ beginDrain() {
+ this.abort.abort(Error('Remote tools Host is draining'));
+ }
+ async close() {
+ this.abort.abort(Error('Remote tools Host is closing'));
+ await this.opening;
+ await Promise.allSettled(this.active.values());
+ this.db.close();
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org