Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent-runtime): park on a long-running shell command instead of polling it (#22979)

Arvin Xue0724291bf29
diff --git a/apps/cli/src/commands/connect/completionWatch.ts b/apps/cli/src/commands/connect/completionWatch.ts
new file mode 100644
index 00000000000..f3c8625f74d
--- /dev/null
+++ b/apps/cli/src/commands/connect/completionWatch.ts
@@ -0,0 +1,71 @@
+import {
+ type CompletionReporter,
+ resolveWatchableShell,
+ type ToolCallRequestMessage,
+ type ToolCallResponseMessage,
+ watchToolCallCompletion,
+ withCompletionWatch,
+} from '@lobechat/device-gateway-client';
+
+import { executeToolCall } from '../../tools';
+
+type WireResult = ToolCallResponseMessage['result'];
+
+/** The longest single local wait for a watched command (the shell's own cap). */
+const COMPLETION_OBSERVATION_TIMEOUT_MS = 600_000;
+
+export interface CompletionReplyOptions {
+ getReporter: () => CompletionReporter | null | undefined;
+ getToolAuth: () => Parameters<typeof executeToolCall>[3];
+ logger: {
+ error: (...args: any[]) => void;
+ info: (...args: any[]) => void;
+ warn: (...args: any[]) => void;
+ };
+}
+
+/**
+ * The reply for a finished tool call. When the server asked for a late result
+ * and the command is still running, the reply says this device keeps watching
+ * (`state.completionWatch`) and the final `getCommandOutput` answer is reported
+ * once the process exits β€” the server parks the run instead of the model
+ * polling.
+ *
+ * The watch runs outside `maintenance.run` on purpose: a command can run for
+ * hours, and a CLI restart must not wait on it. A restart loses the watch; the
+ * server's own deadline then closes the call.
+ */
+export const prepareCompletionReply = (
+ request: ToolCallRequestMessage,
+ result: WireResult,
+ { getReporter, getToolAuth, logger }: CompletionReplyOptions,
+): WireResult => {
+ const shellId = resolveWatchableShell(request, result);
+ if (!shellId || !request.operationId || !request.completion) return result;
+
+ void watchToolCallCompletion({
+ getReporter,
+ logger,
+ observe: async () => {
+ const output = await executeToolCall(
+ 'getCommandOutput',
+ JSON.stringify({ shell_id: shellId, timeout: COMPLETION_OBSERVATION_TIMEOUT_MS }),
+ COMPLETION_OBSERVATION_TIMEOUT_MS,
+ getToolAuth(),
+ );
+ const running = (output.state as { running?: unknown } | undefined)?.running === true;
+ const final: WireResult = { content: output.content, success: output.success };
+ if (output.error !== undefined) final.error = output.error;
+ if (output.state !== undefined) final.state = output.state;
+ return { done: output.success === false || !running, result: final };
+ },
+ operationId: request.operationId,
+ toolCallId: request.completion.toolCallId,
+ }).catch((err) => {
+ logger.error(
+ `Completion watch for ${shellId} failed: ${err instanceof Error ? err.message : err}`,
+ );
+ });
+
+ return withCompletionWatch(result);
+};
diff --git a/apps/cli/src/commands/connect/handlers.test.ts b/apps/cli/src/commands/connect/handlers.test.ts
index 4758be8f6b0..c2eb0cf3907 100644
--- a/apps/cli/src/commands/connect/handlers.test.ts
+++ b/apps/cli/src/commands/connect/handlers.test.ts
@@ -118,3 +118,98 @@ describe('bindGatewayClientHandlers tool_call_request routing', () => {
});
});
});
+
+describe('bindGatewayClientHandlers tool_call_request completion', () => {
+ const stillRunning = {
+ content: 'Command is still running after the wait window.\nshell_id: sh-1',
+ state: { commandId: 'sh-1', isBackground: false, running: true, success: true },
+ success: true,
+ };
+ const finished = {
+ content: 'Exit code: 0\nASYNC_DONE',
+ state: { exitCode: 0, running: false, stdout: 'ASYNC_DONE', success: true },
+ success: true,
+ };
+ const runCommand = (completion?: { toolCallId: string }): ToolCallRequestMessage => ({
+ completion,
+ operationId: 'op-1',
+ requestId: 'req-1',
+ toolCall: {
+ apiName: 'runCommand',
+ arguments: '{"command":"sleep 120"}',
+ identifier: 'lobe-local-system',
+ },
+ type: 'tool_call_request',
+ });
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+ let client: ReturnType<typeof createClient>['client'] & {
+ off: ReturnType<typeof vi.fn>;
+ reportToolCallCompletion: ReturnType<typeof vi.fn>;
+ };
+ let handlers: ReturnType<typeof createClient>['handlers'];
+
+ beforeEach(() => {
+ vi.mocked(executeToolCall).mockReset();
+ const created = createClient();
+ handlers = created.handlers;
+ client = Object.assign(created.client, {
+ off: vi.fn(),
+ reportToolCallCompletion: vi
+ .fn()
+ .mockResolvedValue({ operationId: 'op-1', status: 'delivered', toolCallId: 'call-1' }),
+ });
+ bindGatewayClientHandlers(client as unknown as GatewayClient, createContext());
+ });
+
+ it('keeps watching a still-running command and reports its final output', async () => {
+ vi.mocked(executeToolCall).mockResolvedValueOnce(stillRunning).mockResolvedValueOnce(finished);
+
+ await handlers.tool_call_request(runCommand({ toolCallId: 'call-1' }));
+ await flush();
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-1',
+ result: expect.objectContaining({
+ state: expect.objectContaining({ commandId: 'sh-1', completionWatch: true }),
+ }),
+ });
+ expect(executeToolCall).toHaveBeenLastCalledWith(
+ 'getCommandOutput',
+ JSON.stringify({ shell_id: 'sh-1', timeout: 600_000 }),
+ 600_000,
+ expect.anything(),
+ );
+ expect(client.reportToolCallCompletion).toHaveBeenCalledWith({
+ operationId: 'op-1',
+ result: { content: finished.content, state: finished.state, success: true },
+ toolCallId: 'call-1',
+ });
+ });
+
+ it('answers as before when the server did not ask for a late result', async () => {
+ vi.mocked(executeToolCall).mockResolvedValueOnce(stillRunning);
+
+ await handlers.tool_call_request(runCommand());
+ await flush();
+
+ expect(client.sendToolCallResponse.mock.calls[0][0].result.state).not.toHaveProperty(
+ 'completionWatch',
+ );
+ expect(executeToolCall).toHaveBeenCalledTimes(1);
+ expect(client.reportToolCallCompletion).not.toHaveBeenCalled();
+ });
+
+ it('does not watch a command that already finished', async () => {
+ vi.mocked(executeToolCall).mockResolvedValueOnce(finished);
+
+ await handlers.tool_call_request(runCommand({ toolCallId: 'call-1' }));
+ await flush();
+
+ expect(client.sendToolCallResponse.mock.calls[0][0].result.state).not.toHaveProperty(
+ 'completionWatch',
+ );
+ expect(executeToolCall).toHaveBeenCalledTimes(1);
+ expect(client.reportToolCallCompletion).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/cli/src/commands/connect/handlers.ts b/apps/cli/src/commands/connect/handlers.ts
index fa4bae96cdb..872074c2e8b 100644
--- a/apps/cli/src/commands/connect/handlers.ts
+++ b/apps/cli/src/commands/connect/handlers.ts
@@ -22,6 +22,7 @@ import { executeToolCall } from '../../tools';
import { executeBrowserCall, type resolveBrowserDevice } from '../../tools/browser';
import { executeComputerUseCall, type resolveComputerUseDevice } from '../../tools/computerUse';
import { log } from '../../utils/logger';
+import { prepareCompletionReply } from './completionWatch';
/** Everything a gateway connection's request handlers need from the host process. */
export interface GatewayHandlerContext {
@@ -150,16 +151,27 @@ export function bindGatewayClientHandlers(
log.toolResult(requestId, result.success, result.content, operationId);
}
- client.sendToolCallResponse({
- requestId,
- result: {
+ const reply = prepareCompletionReply(
+ request,
+ {
content: result.content,
error: result.error,
executionTimeMs,
state: result.state,
success: result.success,
},
- });
+ {
+ getReporter: () => client,
+ getToolAuth,
+ logger: {
+ error: (...args) => error(args.join(' ')),
+ info: (...args) =>
+ isDaemonChild ? appendLog(`[COMPLETION] ${args.join(' ')}`) : info(args.join(' ')),
+ warn: (...args) => error(args.join(' ')),
+ },
+ },
+ );
+ client.sendToolCallResponse({ requestId, result: reply });
});
// Handle generic server-internal device RPCs (git / workspace / file ops).
diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.completion.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.completion.test.ts
new file mode 100644
index 00000000000..e9470c817f7
--- /dev/null
+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.completion.test.ts
@@ -0,0 +1,144 @@
+import { EventEmitter } from 'node:events';
+
+import type { ToolCallRequestMessage } from '@lobechat/device-gateway-client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import GatewayConnectionService from '../gatewayConnectionSrv';
+
+vi.mock('electron', () => ({
+ app: {
+ getPath: vi.fn((name: string) => `/mock/path/${name}`),
+ getVersion: vi.fn(() => '0.0.0-test'),
+ },
+ powerSaveBlocker: { isStarted: vi.fn(() => false), start: vi.fn(() => 1), stop: vi.fn() },
+}));
+
+vi.mock('@lobechat/local-file-shell/shell', () => ({
+ executeDeviceOperation: (_meta: unknown, run: () => Promise<unknown>) => run(),
+}));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+}));
+
+const createClient = () =>
+ Object.assign(new EventEmitter(), {
+ reportToolCallCompletion: vi.fn().mockResolvedValue({
+ operationId: 'op-1',
+ status: 'delivered',
+ toolCallId: 'call-1',
+ }),
+ sendToolCallResponse: vi.fn(),
+ });
+
+const runCommandRequest = (
+ overrides: Partial<ToolCallRequestMessage> = {},
+): ToolCallRequestMessage => ({
+ operationId: 'op-1',
+ requestId: 'req-1',
+ toolCall: {
+ apiName: 'runCommand',
+ arguments: JSON.stringify({ command: 'sleep 120' }),
+ identifier: 'lobe-local-system',
+ },
+ type: 'tool_call_request',
+ ...overrides,
+});
+
+const stillRunning = {
+ content: 'Command is still running after the wait window.\nshell_id: sh-1',
+ state: { commandId: 'sh-1', isBackground: false, running: true, success: true },
+ success: true,
+};
+
+const finished = {
+ content: 'Exit code: 0\nASYNC_DONE',
+ state: { exitCode: 0, running: false, stdout: 'ASYNC_DONE', success: true },
+ success: true,
+};
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe('GatewayConnectionService tool call completion', () => {
+ let service: GatewayConnectionService;
+ let client: ReturnType<typeof createClient>;
+ let toolCallHandler: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ service = new GatewayConnectionService({} as App);
+ client = createClient();
+ (service as any).client = client;
+ toolCallHandler = vi.fn();
+ service.setToolCallHandler(toolCallHandler as any);
+ });
+
+ it('keeps watching a still-running command and reports its final output', async () => {
+ toolCallHandler.mockResolvedValueOnce(stillRunning).mockResolvedValueOnce(finished);
+
+ await (service as any).handleToolCallRequest(
+ runCommandRequest({ completion: { toolCallId: 'call-1' } }),
+ client,
+ );
+ await flush();
+
+ expect(client.sendToolCallResponse).toHaveBeenCalledWith({
+ requestId: 'req-1',
+ result: expect.objectContaining({
+ state: expect.objectContaining({ commandId: 'sh-1', completionWatch: true }),
+ }),
+ });
+ expect(toolCallHandler).toHaveBeenLastCalledWith('lobe-local-system', 'getCommandOutput', {
+ shell_id: 'sh-1',
+ timeout: 600_000,
+ });
+ expect(client.reportToolCallCompletion).toHaveBeenCalledWith({
+ operationId: 'op-1',
+ result: { content: finished.content, state: finished.state, success: true },
+ toolCallId: 'call-1',
+ });
+ });
+
+ it('answers as before when the server did not ask for a late result', async () => {
+ toolCallHandler.mockResolvedValueOnce(stillRunning);
+
+ await (service as any).handleToolCallRequest(runCommandRequest(), client);
+ await flush();
+
+ const reply = client.sendToolCallResponse.mock.calls[0][0];
+ expect(reply.result.state).not.toHaveProperty('completionWatch');
+ expect(toolCallHandler).toHaveBeenCalledTimes(1);
+ expect(client.reportToolCallCompletion).not.toHaveBeenCalled();
+ });
+
+ it('does not watch a command that already finished', async () => {
+ toolCallHandler.mockResolvedValueOnce(finished);
+
+ await (service as any).handleToolCallRequest(
+ runCommandRequest({ completion: { toolCallId: 'call-1' } }),
+ client,
+ );
+ await flush();
+
+ const reply = client.sendToolCallResponse.mock.calls[0][0];
+ expect(reply.result.state).not.toHaveProperty('completionWatch');
+ expect(toolCallHandler).toHaveBeenCalledTimes(1);
+ expect(client.reportToolCallCompletion).not.toHaveBeenCalled();
+ });
+
+ it('reports through the workspace connection the call arrived on', async () => {
+ const workspaceClient = createClient();
+ (service as any).workspaceClients.set('ws-1', workspaceClient);
+ toolCallHandler.mockResolvedValueOnce(stillRunning).mockResolvedValueOnce(finished);
+
+ await (service as any).handleToolCallRequest(
+ runCommandRequest({ completion: { toolCallId: 'call-1' } }),
+ workspaceClient,
+ );
+ await flush();
+
+ expect(workspaceClient.reportToolCallCompletion).toHaveBeenCalledTimes(1);
+ expect(client.reportToolCallCompletion).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index 6d62f783300..d272367ebd4 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -17,7 +17,6 @@ import type {
RpcRequestMessage,
SystemInfoRequestMessage,
ToolCallRequestMessage,
- ToolCallResponseMessage,
} from '@lobechat/device-gateway-client';
import {
type DeviceGatewayEndpoint,
@@ -46,6 +45,7 @@ import { safeGetPath } from '@/utils/user-path';
import { discoverDeviceGateway } from './gatewayDiscovery';
import { collectBundledCliAgentRuntimes, collectGatewaySystemInfo } from './gatewaySystemInfo';
+import { prepareToolCallReply, serializeWireError, toWireResult } from './gatewayToolCallReply';
import { ServiceModule } from './index';
const logger = createLogger('services:GatewayConnectionSrv');
@@ -98,20 +98,6 @@ interface McpCallHandler {
* object) into the string shape the wire protocol expects. Returns undefined
* when there's no error to transmit.
*/
-const serializeWireError = (err: unknown): string | undefined => {
- if (err === undefined || err === null) return undefined;
- if (typeof err === 'string') return err;
- if (err instanceof Error) return err.message;
- if (typeof err === 'object' && 'message' in err && typeof err.message === 'string') {
- return err.message;
- }
- try {
- return JSON.stringify(err);
- } catch {
- return String(err);
- }
-};
-
interface AgentRunHandler {
(request: AgentRunRequestMessage): Promise<{ reason?: string; status: 'accepted' | 'rejected' }>;
}
@@ -1308,6 +1294,14 @@ export default class GatewayConnectionService extends ServiceModule {
// ─── Tool Call Routing ───
+ /** The live connection on `client`'s principal, after any reconnect or re-enroll. */
+ private currentClientFor(client: GatewayClient): () => GatewayClient | null {
+ for (const [workspaceId, current] of this.workspaceClients) {
+ if (current === client) return () => this.workspaceClients.get(workspaceId) ?? null;
+ }
+ return () => this.client;
+ }
+
private handleToolCallRequest = async (
request: ToolCallRequestMessage,
client: GatewayClient,
@@ -1345,22 +1339,16 @@ export default class GatewayConnectionService extends ServiceModule {
}
});
- // Forward the typed envelope unchanged. Critically, do NOT stringify the
- // whole result into `content` β€” that would bury the structured payload
- // inside a JSON blob and lose `state`. The wire protocol carries each
- // field separately so downstream (`DeviceGateway` β†’ `RuntimeExecutors`)
- // can persist `state` to `pluginState`. Optional fields are only set
- // when present so payloads stay minimal.
- const wireResult: ToolCallResponseMessage['result'] = {
- content: result.content,
- executionTimeMs: Math.round(performance.now() - startedAt),
- success: result.success,
- };
- const wireError = serializeWireError(result.error);
- if (wireError !== undefined) wireResult.error = wireError;
- if (result.state !== undefined) wireResult.state = result.state;
-
- client.sendToolCallResponse({ requestId, result: wireResult });
+ const wireResult = toWireResult(result, Math.round(performance.now() - startedAt));
+ const reply = await prepareToolCallReply({
+ getReporter: this.currentClientFor(client),
+ logger,
+ request,
+ result: wireResult,
+ runTool: (id, name, args) => this.toolCallHandler!(id, name, args),
+ });
+
+ client.sendToolCallResponse({ requestId, result: reply });
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.error(`Tool call failed: apiName=${apiName}, error=${errorMsg}`);
diff --git a/apps/desktop/src/main/services/gatewayToolCallReply.ts b/apps/desktop/src/main/services/gatewayToolCallReply.ts
new file mode 100644
index 00000000000..ebdebda5089
--- /dev/null
+++ b/apps/desktop/src/main/services/gatewayToolCallReply.ts
@@ -0,0 +1,106 @@
+import type {
+ CompletionReporter,
+ ToolCallRequestMessage,
+ ToolCallResponseMessage,
+} from '@lobechat/device-gateway-client';
+
+type WireResult = ToolCallResponseMessage['result'];
+
+/** The longest single local wait for a watched command (the shell's own cap). */
+const COMPLETION_OBSERVATION_TIMEOUT_MS = 600_000;
+
+interface ToolOutput {
+ content: string;
+ error?: unknown;
+ state?: unknown;
+ success: boolean;
+}
+
+interface ReplyLogger {
+ error: (...args: any[]) => void;
+ info: (...args: any[]) => void;
+ warn: (...args: any[]) => void;
+}
+
+export const serializeWireError = (err: unknown): string | undefined => {
+ if (err === undefined || err === null) return undefined;
+ if (typeof err === 'string') return err;
+ if (err instanceof Error) return err.message;
+ if (typeof err === 'object' && 'message' in err && typeof err.message === 'string') {
+ return err.message;
+ }
+ try {
+ return JSON.stringify(err);
+ } catch {
+ return String(err);
+ }
+};
+
+/**
+ * Forward the typed envelope unchanged. Critically, do NOT stringify the whole
+ * result into `content` β€” that would bury the structured payload inside a JSON
+ * blob and lose `state`. The wire protocol carries each field separately so
+ * downstream (`DeviceGateway` β†’ `RuntimeExecutors`) can persist `state` to
+ * `pluginState`. Optional fields are only set when present so payloads stay
+ * minimal.
+ */
+export const toWireResult = (output: ToolOutput, executionTimeMs?: number): WireResult => {
+ const wire: WireResult = { content: output.content, success: output.success };
+ if (executionTimeMs !== undefined) wire.executionTimeMs = executionTimeMs;
+ const wireError = serializeWireError(output.error);
+ if (wireError !== undefined) wire.error = wireError;
+ if (output.state !== undefined) wire.state = output.state;
+ return wire;
+};
+
+export interface ToolCallReplyParams {
+ /** The client to report the late result through, re-read on every send. */
+ getReporter: () => CompletionReporter | null | undefined;
+ logger: ReplyLogger;
+ request: ToolCallRequestMessage;
+ result: WireResult;
+ /** The same tool dispatch the gateway call used, so the late answer reads like `getCommandOutput`. */
+ runTool: (identifier: string | undefined, apiName: string, args: unknown) => Promise<ToolOutput>;
+}
+
+/**
+ * The reply for a finished tool call. When the server asked for a late result
+ * and the command is still running, the reply says the device keeps watching
+ * (`state.completionWatch`) and the final `getCommandOutput` answer is reported
+ * once the process exits β€” so the server can park the run instead of the model
+ * polling.
+ */
+export const prepareToolCallReply = async ({
+ getReporter,
+ logger,
+ request,
+ result,
+ runTool,
+}: ToolCallReplyParams): Promise<WireResult> => {
+ if (!request.completion || !request.operationId) return result;
+
+ const { resolveWatchableShell, watchToolCallCompletion, withCompletionWatch } =
+ await import('@lobechat/device-gateway-client');
+ const shellId = resolveWatchableShell(request, result);
+ if (!shellId) return result;
+
+ const { identifier } = request.toolCall;
+ void watchToolCallCompletion({
+ getReporter,
+ logger,
+ observe: async () => {
+ const output = await runTool(identifier, 'getCommandOutput', {
+ shell_id: shellId,
+ timeout: COMPLETION_OBSERVATION_TIMEOUT_MS,
+ });
+ const running = (output.state as { running?: unknown } | undefined)?.running === true;
+ return { done: output.success === false || !running, result: toWireResult(output) };
+ },
+ operationId: request.operationId,
+ toolCallId: request.completion.toolCallId,
+ }).catch((error) => {
+ logger.error(`Completion watch for ${shellId} failed:`, serializeWireError(error));
+ });
+
+ return withCompletionWatch(result);
+};
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index 08e21b51c5e..77eb9c41d45 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -439,6 +439,39 @@ export class GatewayStreamNotifier implements IStreamEventManager {
await this.httpPostAwait('/api/operations/tool-execute', { data, operationId });
}
+ /**
+ * Tell the gateway that this operation is parked on a deferred tool, so its
+ * inactivity watchdog stops reading the silence as a dead function.
+ *
+ * Best-effort and version-tolerant: a gateway that predates the route answers
+ * 404, which resolves `false` β€” the caller then falls back to its own timeout
+ * (the 30-minute watchdog is a hard ceiling there). Never throws: failing to
+ * extend a watchdog must not fail the tool call that is parking.
+ */
+ async markOperationParked(
+ operationId: string,
+ params: { parkedUntil: number; reason?: string; stepIndex?: number },
+ ): Promise<boolean> {
+ try {
+ const res = await this.httpPostResponse('/api/operations/park', {
+ operationId,
+ parkedUntil: params.parkedUntil,
+ reason: params.reason ?? 'deferred_tool',
+ stepIndex: params.stepIndex,
+ });
+ if (res.ok) return true;
+ if (res.status === 404) {
+ log('markOperationParked: gateway has no /park route (op=%s)', operationId);
+ return false;
+ }
+ log('markOperationParked failed (op=%s): %d %s', operationId, res.status, res.body);
+ return false;
+ } catch (error) {
+ log('markOperationParked failed (op=%s): %O', operationId, error);
+ return false;
+ }
+ }
+
/**
* Hand one relayed LLM attempt to the user's device. The gateway delivers it
* to the client that started the run (when connected) and keeps it
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/asyncShellPark.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/asyncShellPark.test.ts
new file mode 100644
index 00000000000..f74d562fac0
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/__tests__/asyncShellPark.test.ts
@@ -0,0 +1,170 @@
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
+import { describe, expect, it, vi } from 'vitest';
+
+import { parkAsyncShell } from '../asyncShellPark';
+
+const buildCtx = () => {
+ const create = vi.fn(async () => ({ id: 'msg_placeholder' }));
+ const updatePluginState = vi.fn(async () => {});
+ const markOperationParked = vi.fn(async () => true);
+ const scheduleShellExpiry = vi.fn(async () => {});
+
+ return {
+ ctx: {
+ messageModel: { create, updatePluginState },
+ operationId: 'op_1',
+ scheduleShellExpiry,
+ stepIndex: 4,
+ streamManager: { markOperationParked },
+ topicId: 'topic_1',
+ } as any,
+ create,
+ markOperationParked,
+ scheduleShellExpiry,
+ updatePluginState,
+ };
+};
+
+const state = { origin: { agentId: 'agent_1', threadId: 'thread_1', topicId: 'topic_1' } } as any;
+const toolCall = {
+ apiName: 'runCommand',
+ arguments: '{}',
+ id: 'call_1',
+ identifier: LocalSystemIdentifier,
+} as any;
+
+const runningResult = (state: Record<string, unknown>) =>
+ ({ content: '', executionTime: 10, state, success: true }) as any;
+
+describe('parkAsyncShell', () => {
+ it('parks a command started in the background', async () => {
+ const { ctx, create, markOperationParked, scheduleShellExpiry } = buildCtx();
+
+ const execution = await parkAsyncShell(
+ ctx,
+ {
+ parentMessageId: 'msg_parent',
+ resultLimit: { canReadArchive: true, maxLength: 4000 },
+ state,
+ toolCall,
+ },
+ runningResult({
+ commandId: 'sh-1',
+ completionWatch: true,
+ isBackground: true,
+ success: true,
+ }),
+ );
+
+ expect(execution?.result).toMatchObject({
+ deferred: true,
+ state: { commandId: 'sh-1', toolMessageId: 'msg_placeholder' },
+ success: true,
+ });
+ // The placeholder exists BEFORE the pause chunk advertises it: without the
+ // row the client can never load it and the barrier can never clear.
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentId: 'msg_parent',
+ pluginState: expect.objectContaining({
+ asyncShell: expect.objectContaining({
+ // The late result has no step context: the limit travels with the row.
+ archive: expect.objectContaining({
+ agentId: 'agent_1',
+ canReadArchive: true,
+ maxLength: 4000,
+ topicId: 'topic_1',
+ }),
+ commandId: 'sh-1',
+ }),
+ status: 'pending',
+ }),
+ role: 'tool',
+ tool_call_id: 'call_1',
+ }),
+ );
+ // Scoped to the parking step, whose own closing events follow the park.
+ expect(markOperationParked).toHaveBeenCalledWith(
+ 'op_1',
+ expect.objectContaining({ reason: 'async_shell', stepIndex: 4 }),
+ );
+ // One deadline message, not a poll loop.
+ expect(scheduleShellExpiry).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationId: 'op_1',
+ toolCallId: 'call_1',
+ toolMessageId: 'msg_placeholder',
+ }),
+ );
+ });
+
+ it('parks a foreground command that outlived its wait window', async () => {
+ const { ctx } = buildCtx();
+
+ const execution = await parkAsyncShell(
+ ctx,
+ { parentMessageId: 'msg_parent', state, toolCall },
+ runningResult({ commandId: 'sh-2', completionWatch: true, running: true, success: true }),
+ );
+
+ expect(execution?.result.deferred).toBe(true);
+ });
+
+ it.each([
+ ['the command already exited', { commandId: 'sh-3', completionWatch: true, exitCode: 0 }],
+ ['the command failed to spawn', { commandId: 'sh-3', completionWatch: true, error: 'ENOENT' }],
+ ['it is not a shell result', { completionWatch: true, exitCode: 1 }],
+ // An older device (or a gateway that did not relay the registration) never
+ // reports back: parking would leave the run waiting for its timeout.
+ ['the device is not watching the command', { commandId: 'sh-3', running: true }],
+ ])('does not park when %s', async (_label, resultState) => {
+ const { ctx, create } = buildCtx();
+
+ const execution = await parkAsyncShell(
+ ctx,
+ { parentMessageId: 'msg_parent', state, toolCall },
+ runningResult(resultState),
+ );
+
+ expect(execution).toBeNull();
+ expect(create).not.toHaveBeenCalled();
+ });
+
+ it('reuses the tool row a resumed (approved) call already owns', async () => {
+ const { ctx, create, scheduleShellExpiry, updatePluginState } = buildCtx();
+
+ const execution = await parkAsyncShell(
+ ctx,
+ { existingToolMessageId: 'msg_existing', parentMessageId: 'msg_parent', state, toolCall },
+ runningResult({ commandId: 'sh-6', completionWatch: true, running: true }),
+ );
+
+ // A second row with the same tool_call_id would leave the approved one
+ // empty forever and make the completion lookup ambiguous.
+ expect(create).not.toHaveBeenCalled();
+ expect(updatePluginState).toHaveBeenCalledWith(
+ 'msg_existing',
+ expect.objectContaining({ asyncShell: expect.objectContaining({ commandId: 'sh-6' }) }),
+ );
+ expect(execution?.result.state).toMatchObject({ toolMessageId: 'msg_existing' });
+ expect(scheduleShellExpiry).toHaveBeenCalledWith(
+ expect.objectContaining({ toolMessageId: 'msg_existing' }),
+ );
+ });
+
+ it('does not park a non-shell tool', async () => {
+ const { ctx } = buildCtx();
+
+ const execution = await parkAsyncShell(
+ ctx,
+ {
+ parentMessageId: 'msg_parent',
+ state,
+ toolCall: { ...toolCall, apiName: 'getCommandOutput' },
+ },
+ runningResult({ commandId: 'sh-4', completionWatch: true, isBackground: true }),
+ );
+
+ expect(execution).toBeNull();
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.asyncShell.test.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.asyncShell.test.ts
new file mode 100644
index 00000000000..80e6d2eed59
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.asyncShell.test.ts
@@ -0,0 +1,175 @@
+import type { AgentRuntimeHost, AgentState } from '@lobechat/agent-runtime';
+import {
+ AgentRuntime,
+ createAgentRuntimeExecutors,
+ GeneralChatAgent,
+} from '@lobechat/agent-runtime';
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
+import type { ChatToolPayload } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { HookDispatcher } from '@/server/services/agentRuntime/hooks';
+
+import type { RuntimeExecutorContext } from '../context';
+import { ServerToolTransport } from './ServerToolTransport';
+
+const { dispatchClient, isInterrupted, parkAsyncShell } = vi.hoisted(() => ({
+ dispatchClient: vi.fn(),
+ isInterrupted: vi.fn(),
+ parkAsyncShell: vi.fn(),
+}));
+vi.mock('../dispatchClientTool', () => ({ dispatchClientTool: dispatchClient }));
+vi.mock('../asyncShellPark', () => ({ parkAsyncShell }));
+vi.mock('@/database/models/user', () => ({ UserModel: { getEmailsByIds: async () => [] } }));
+vi.mock('@/database/server', () => ({ getServerDB: async () => ({}) }));
+vi.mock('@/server/services/queue/impls', () => ({ isQueueAgentRuntimeEnabled: () => false }));
+vi.mock('@/libs/qstash', () => ({ OtelQstashClient: class {} }));
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: class {
+ getAgentVisibility = async () => 'private';
+ },
+}));
+vi.mock('../executorHelpers', () => ({
+ archiveRuntimeToolResult: async (result: unknown) => result,
+ buildServerAgentMemberRunner: () => undefined,
+ buildServerVirtualSubAgentRunner: () => undefined,
+ GEN_AI_FUNCTION_TOOL_TYPE: 'function',
+ isOperationInterrupted: isInterrupted,
+ log: () => {},
+ registerWorkFromIntent: vi.fn(),
+ TOOL_MAX_RETRIES: 2,
+ TOOL_PRICING: {},
+}));
+
+const runCommandCall: ChatToolPayload = {
+ apiName: 'runCommand',
+ arguments: '{"command":"sleep 600"}',
+ executor: 'server',
+ id: 'call-shell',
+ identifier: LocalSystemIdentifier,
+ type: 'builtin',
+};
+
+const stillRunning = {
+ content: 'Command is still running after the wait window.\nshell_id: sh-1',
+ state: { commandId: 'sh-1', completionWatch: true, running: true, success: true },
+ success: true,
+};
+
+function setup() {
+ const execute = vi.fn().mockResolvedValue(stillRunning);
+ const rows: Record<string, unknown>[] = [];
+ const state = {
+ cost: {
+ calculatedAt: '',
+ currency: 'USD',
+ llm: { byModel: [], currency: 'USD', total: 0 },
+ tools: { byTool: [], currency: 'USD', total: 0 },
+ total: 0,
+ },
+ createdAt: '',
+ lastModified: '',
+ messages: [],
+ operationId: 'op',
+ origin: { agentId: 'agent', topicId: 'topic' },
+ status: 'running',
+ stepCount: 0,
+ usage: {
+ humanInteraction: {
+ approvalRequests: 0,
+ promptRequests: 0,
+ selectRequests: 0,
+ totalWaitingTimeMs: 0,
+ },
+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },
+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },
+ },
+ userInterventionConfig: { approvalMode: 'auto-run' },
+ } as AgentState;
+ const transport = new ServerToolTransport({
+ hookDispatcher: new HookDispatcher(),
+ operationId: 'op',
+ serverDB: {},
+ stepIndex: 1,
+ streamManager: { sendToolExecute: vi.fn() },
+ toolExecutionService: { executeTool: execute },
+ userId: 'user',
+ } as unknown as RuntimeExecutorContext);
+ const host: AgentRuntimeHost = {
+ operation: { agentId: 'agent', operationId: 'op', stepIndex: 1 },
+ transports: {
+ messages: {
+ createToolMessage: vi.fn(async (row) => {
+ rows.push(row);
+ return { ...row, id: `row-${rows.length}` };
+ }),
+ findToolMessageIdByToolCallId: vi.fn(),
+ query: vi.fn(async () => rows),
+ update: vi.fn(),
+ updateToolIntervention: vi.fn(),
+ updateToolMessage: vi.fn(),
+ } as unknown as AgentRuntimeHost['transports']['messages'],
+ stream: { publishChunk: vi.fn(), publishEvent: vi.fn() },
+ tools: transport,
+ },
+ };
+ const runtime = new AgentRuntime(new GeneralChatAgent({ operationId: 'op' }), {
+ executors: createAgentRuntimeExecutors(host),
+ });
+ const step = () =>
+ runtime.step(state, {
+ payload: {
+ hasToolsCalling: true,
+ parentMessageId: 'assistant',
+ toolsCalling: [runCommandCall],
+ },
+ phase: 'llm_result',
+ });
+ return { execute, rows, step };
+}
+
+beforeEach(() => {
+ isInterrupted.mockReset().mockResolvedValue(false);
+ dispatchClient.mockReset();
+ parkAsyncShell.mockReset().mockResolvedValue(null);
+});
+
+describe('async shell on the device-gateway path', () => {
+ // Desktop and `lh connect` commands in a server run go through the
+ // local-system server runtime (device gateway), never the client dispatch.
+ // The park used to hang off the client branch only, so it never ran.
+ it('offers a server-runtime runCommand result to the park', async () => {
+ const fixture = setup();
+ parkAsyncShell.mockResolvedValue({
+ attempts: 1,
+ result: {
+ content: '',
+ deferred: true,
+ state: { commandId: 'sh-1', toolMessageId: 'placeholder' },
+ success: true,
+ },
+ });
+
+ const result = await fixture.step();
+
+ expect(dispatchClient).not.toHaveBeenCalled();
+ expect(parkAsyncShell).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ parentMessageId: 'assistant', toolCall: runCommandCall }),
+ expect.objectContaining({ state: expect.objectContaining({ completionWatch: true }) }),
+ );
+ expect(result.newState.status).toBe('waiting_for_async_tool');
+ // The parked call writes no tool row now: the completion fills the placeholder.
+ expect(fixture.rows).toHaveLength(0);
+ });
+
+ it('keeps the normal answer when the park declines', async () => {
+ const fixture = setup();
+
+ const result = await fixture.step();
+
+ expect(parkAsyncShell).toHaveBeenCalledTimes(1);
+ expect(result.newState.status).not.toBe('waiting_for_async_tool');
+ expect(JSON.stringify(fixture.rows)).toContain('shell_id: sh-1');
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
index cffe899feb4..7077e71f583 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts
@@ -34,6 +34,7 @@ import {
} from '@/server/services/aiAgent/deviceToolAudit';
import { resolveRunWorkAccessScope } from '@/server/services/workRegistration';
+import { parkAsyncShell } from '../asyncShellPark';
import type { RuntimeExecutorContext } from '../context';
import { dispatchClientTool } from '../dispatchClientTool';
import {
@@ -352,6 +353,27 @@ export class ServerToolTransport implements ToolTransport {
),
},
);
+
+ // A device command still running after its wait window, which the
+ // device promised to report on: park instead of returning the
+ // `shell_id`. A no-op for every other result.
+ execution =
+ (await parkAsyncShell(
+ this.ctx,
+ {
+ existingToolMessageId: context.reuseExistingMessage
+ ? context.toolMessageId
+ : undefined,
+ parentMessageId: context.parentMessageId,
+ resultLimit: {
+ canReadArchive: enabledToolIds.includes(AgentDocumentsIdentifier),
+ maxLength: context.toolResultMaxLength,
+ },
+ state: context.state,
+ toolCall: chatToolPayload,
+ },
+ execution.result,
+ )) ?? execution;
}
if (execution.result.deferred) {
diff --git a/apps/server/src/modules/AgentRuntime/asyncShellPark.ts b/apps/server/src/modules/AgentRuntime/asyncShellPark.ts
new file mode 100644
index 00000000000..c1631e01287
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/asyncShellPark.ts
@@ -0,0 +1,198 @@
+import type { AgentState, ToolRunExecution } from '@lobechat/agent-runtime';
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
+import type { ChatToolPayload } from '@lobechat/types';
+import debug from 'debug';
+
+import {
+ ASYNC_SHELL_PARK_WINDOW_MS,
+ ASYNC_SHELL_TIMEOUT_MS,
+} from '@/server/services/deviceGateway/toolCallCompletion';
+
+import type { RuntimeExecutorContext } from './context';
+
+const log = debug('lobe-server:agent-runtime:async-shell');
+
+/**
+ * A device shell command may outlive the tool call that started it. Rather
+ * than holding the step (800s function ceiling) or handing the model a
+ * `shell_id` to poll, the runtime parks the operation; the device reports the
+ * command's final result through the device gateway when it exits
+ * (`/api/agent/device-tool-completion`), and that resumes the run.
+ */
+
+interface CommandStateShape {
+ commandId?: unknown;
+ completionWatch?: unknown;
+ error?: unknown;
+ exitCode?: unknown;
+ isBackground?: unknown;
+ running?: unknown;
+ success?: unknown;
+}
+
+/**
+ * Whether this dispatch handed off a command that is still running AND that the
+ * device promised to report on.
+ *
+ * `run_in_background` returns before observing (no `running` flag), and a
+ * foreground call that outlived its wait window reports `running: true`. A
+ * command that failed to spawn is not a wait: it already has an answer.
+ * `completionWatch` is the device's promise that a late result will follow β€”
+ * without it (older device or gateway) nothing would ever resume the run, so
+ * the model keeps the `shell_id` and polls as before.
+ */
+const runningShellId = (state: unknown): string | undefined => {
+ if (!state || typeof state !== 'object') return undefined;
+ const shell = state as CommandStateShape;
+ if (shell.completionWatch !== true) return undefined;
+ if (typeof shell.commandId !== 'string' || shell.commandId.length === 0) return undefined;
+ if (shell.error) return undefined;
+ if (shell.exitCode !== undefined && shell.exitCode !== null) return undefined;
+ if (shell.success === false) return undefined;
+ if (shell.isBackground === true || shell.running === true) return shell.commandId;
+ return undefined;
+};
+
+/**
+ * How the step would have size-limited this call's result. The late result
+ * arrives with no step context, so the park records it for the completion.
+ */
+export interface AsyncShellResultLimit {
+ /** Whether the run can page an archived result (`lobe-agent-documents`). */
+ canReadArchive: boolean;
+ /** The run's `toolResultMaxLength`; unset β†’ the default limit. */
+ maxLength?: number;
+}
+
+export interface ParkAsyncShellParams {
+ /**
+ * The tool row this call already owns β€” set when the call resumes after an
+ * approval. The completion is written into it instead of a second row with
+ * the same `tool_call_id`.
+ */
+ existingToolMessageId?: string;
+ /** Which message owns this tool call β€” the placeholder hangs off it. */
+ parentMessageId: string;
+ resultLimit?: AsyncShellResultLimit;
+ state: AgentState;
+ toolCall: ChatToolPayload;
+}
+
+/**
+ * Park the operation on a still-running shell command.
+ *
+ * Returns the deferred execution for the runtime, or `null` when this call is
+ * not a long-running shell and should be handled normally.
+ */
+export const parkAsyncShell = async (
+ ctx: RuntimeExecutorContext,
+ { existingToolMessageId, parentMessageId, resultLimit, state, toolCall }: ParkAsyncShellParams,
+ /** Only the device's command state is read. */
+ result: { state?: unknown },
+): Promise<ToolRunExecution | null> => {
+ if (toolCall.identifier !== LocalSystemIdentifier) return null;
+ if (toolCall.apiName !== 'runCommand') return null;
+
+ const commandId = runningShellId(result.state);
+ if (!commandId) return null;
+
+ const agentId = state.origin?.agentId;
+ const topicId = ctx.topicId ?? state.origin?.topicId;
+ if (!agentId || !topicId) {
+ // Without an anchor the placeholder cannot be created, so the barrier could
+ // never clear. Fall through to the normal result instead of parking.
+ log('park skipped: missing agent/topic (op=%s)', ctx.operationId);
+ return null;
+ }
+
+ const startedAt = new Date().toISOString();
+ const pluginState = {
+ asyncShell: {
+ // Everything the completion needs to size-limit the result the way this
+ // step would have (see `archiveRuntimeToolResult` in the transport).
+ archive: {
+ agentId,
+ canReadArchive: resultLimit?.canReadArchive ?? false,
+ maxLength: resultLimit?.maxLength,
+ topicId,
+ workspaceId: state.origin?.workspaceId ?? ctx.workspaceId,
+ },
+ commandId,
+ startedAt,
+ timeoutMs: ASYNC_SHELL_TIMEOUT_MS,
+ },
+ status: 'pending',
+ };
+
+ // The row the completion will be written into. Created here β€” before the
+ // park β€” because the runtime's pause chunk has to advertise it (otherwise the
+ // client never loads the row) and the completion barrier looks it up by
+ // `tool_call_id`.
+ let placeholderId: string;
+ if (existingToolMessageId) {
+ await ctx.messageModel.updatePluginState(existingToolMessageId, pluginState);
+ placeholderId = existingToolMessageId;
+ } else {
+ const placeholder = await ctx.messageModel.create({
+ agentId,
+ content: '',
+ groupId: state.origin?.groupId ?? undefined,
+ parentId: parentMessageId,
+ plugin: toolCall as any,
+ pluginState,
+ role: 'tool',
+ threadId: state.origin?.threadId,
+ tool_call_id: toolCall.id,
+ topicId,
+ });
+ placeholderId = placeholder.id;
+ }
+
+ // Ask the gateway to stop treating this run's silence as a dead function
+ // until the command comes back. Best-effort: an older gateway answers 404 and
+ // the caller's own timeout still bounds the wait.
+ // `stepIndex` scopes the park to this step: the step's own closing events
+ // still follow, and must not end the park the way the resume does.
+ await ctx.streamManager.markOperationParked?.(ctx.operationId, {
+ parkedUntil: Date.now() + ASYNC_SHELL_PARK_WINDOW_MS,
+ reason: 'async_shell',
+ stepIndex: ctx.stepIndex,
+ });
+
+ // One deadline, not a poll: if the device never reports back the run would
+ // otherwise sit parked until the gateway's own (longer) watchdog kills it with
+ // an opaque inactivity error. This writes a real tool error instead, so the
+ // model can adapt.
+ await ctx.scheduleShellExpiry?.({
+ delayMs: ASYNC_SHELL_TIMEOUT_MS,
+ operationId: ctx.operationId,
+ toolCallId: toolCall.id,
+ toolMessageId: placeholderId,
+ });
+
+ log(
+ 'parked op=%s on shell %s (toolCallId=%s, messageId=%s)',
+ ctx.operationId,
+ commandId,
+ toolCall.id,
+ placeholderId,
+ );
+
+ return {
+ attempts: 1,
+ result: {
+ content: '',
+ deferred: true,
+ // `deferredToolMessageId` lifts this onto the pause chunk so the client
+ // pulls the placeholder into its store while the run is parked.
+ state: {
+ commandId,
+ isBackground: true,
+ startedAt,
+ success: true,
+ toolMessageId: placeholderId,
+ },
+ success: true,
+ },
+ };
+};
diff --git a/apps/server/src/modules/AgentRuntime/context.ts b/apps/server/src/modules/AgentRuntime/context.ts
index 2ff93fb0114..cdb07f26500 100644
--- a/apps/server/src/modules/AgentRuntime/context.ts
+++ b/apps/server/src/modules/AgentRuntime/context.ts
@@ -90,6 +90,23 @@ export interface RuntimeExecutorContext {
>,
) => Promise<boolean>;
operationId: string;
+ /**
+ * Register the one-shot deadline for a parked shell command.
+ *
+ * The wait itself costs nothing β€” the device reports completion as a late
+ * tool result β€” so something has to fail the run when the device never comes
+ * back (closed app, killed process, lost session). One delayed message per
+ * command, fired once; never a polling loop.
+ *
+ * Absent on hosts without a queue: the caller then relies on the gateway's
+ * own watchdog deadline.
+ */
+ scheduleShellExpiry?: (params: {
+ delayMs: number;
+ operationId: string;
+ toolCallId: string;
+ toolMessageId: string;
+ }) => Promise<void>;
serverDB: LobeChatDatabase;
stepIndex: number;
stream?: boolean;
diff --git a/apps/server/src/modules/AgentRuntime/types.ts b/apps/server/src/modules/AgentRuntime/types.ts
index 508c24cbc33..a2dc5de168d 100644
--- a/apps/server/src/modules/AgentRuntime/types.ts
+++ b/apps/server/src/modules/AgentRuntime/types.ts
@@ -239,6 +239,29 @@ export interface IStreamEventManager {
limit?: number,
) => Promise<StreamHistoryPage>;
+ /**
+ * Optional: tell the gateway that this operation is deliberately silent
+ * because it is waiting on a deferred tool result.
+ *
+ * The gateway's inactivity watchdog treats silence as a dead agent-runtime
+ * function. A parked operation emits nothing until its result arrives β€” for a
+ * shell command that can be tens of minutes β€” so without this it is rewritten
+ * as `Operation abandoned: inactivity_watchdog` mid-wait. The deadline
+ * replaces the watchdog window until the first real event clears it.
+ *
+ * Absent on managers without a gateway (local/desktop runs have no watchdog
+ * to satisfy). Resolves to `false` when the gateway does not implement the
+ * route, so callers can fall back to their own timeout.
+ */
+ markOperationParked?: (
+ operationId: string,
+ /**
+ * `stepIndex` is the parking step: its own later events must not end the
+ * park, only a later step (the resume) or the run ending does.
+ */
+ params: { parkedUntil: number; reason?: string; stepIndex?: number },
+ ) => Promise<boolean>;
+
/**
* Optional: open a one-shot relay channel on the gateway, owned by `userId`.
* Present only with a gateway, like {@link sendLlmExecute}.
diff --git a/apps/server/src/router-hono/agent/handlers/__tests__/deviceToolCompletion.test.ts b/apps/server/src/router-hono/agent/handlers/__tests__/deviceToolCompletion.test.ts
new file mode 100644
index 00000000000..8508844d1cb
--- /dev/null
+++ b/apps/server/src/router-hono/agent/handlers/__tests__/deviceToolCompletion.test.ts
@@ -0,0 +1,156 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { deviceToolCompletion } from '../deviceToolCompletion';
+
+const mockCompleteDeferredShell = vi.fn(async () => ({ handled: true, resumed: true }) as any);
+const mockResolveOwner = vi.fn(async () => ({ userId: 'user_1' }) as any);
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: async () => ({}) as any,
+}));
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: class {
+ completeDeferredShell = mockCompleteDeferredShell;
+ },
+}));
+
+vi.mock('../resolveOperationOwner', () => ({
+ resolveOperationOwner: () => mockResolveOwner(),
+}));
+
+function buildContext(body: unknown) {
+ return {
+ json: (b: any, status = 200) => Response.json(b, { status }),
+ req: { json: async () => body },
+ } as any;
+}
+
+const completion = {
+ deviceId: 'device_1',
+ operationId: 'op_1',
+ result: {
+ content: 'Command completed successfully.',
+ state: { exitCode: 0, running: false },
+ success: true,
+ },
+ toolCallId: 'call_1',
+ userId: 'user_1',
+};
+
+describe('deviceToolCompletion', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('resumes the parked operation with the device result', async () => {
+ const res = await deviceToolCompletion(buildContext(completion));
+
+ expect(res.status).toBe(200);
+ await expect(res.json()).resolves.toEqual({ handled: true, resumed: true });
+ expect(mockCompleteDeferredShell).toHaveBeenCalledWith({
+ operationId: 'op_1',
+ result: expect.objectContaining({
+ content: 'Command completed successfully.',
+ state: { exitCode: 0, running: false },
+ success: true,
+ toolCallId: 'call_1',
+ }),
+ });
+ });
+
+ it('normalizes a device error string into a tool error', async () => {
+ await deviceToolCompletion(
+ buildContext({
+ ...completion,
+ result: { content: 'shell_id not found', error: 'NOT_FOUND', success: false },
+ }),
+ );
+
+ expect(mockCompleteDeferredShell).toHaveBeenCalledWith(
+ expect.objectContaining({
+ result: expect.objectContaining({
+ error: { message: 'NOT_FOUND', type: 'device_error' },
+ success: false,
+ }),
+ }),
+ );
+ });
+
+ it('refuses a completion from another account', async () => {
+ const res = await deviceToolCompletion(buildContext({ ...completion, userId: 'user_2' }));
+
+ // 4xx β†’ the gateway answers `rejected` and the device stops resending.
+ expect(res.status).toBe(403);
+ expect(mockCompleteDeferredShell).not.toHaveBeenCalled();
+ });
+
+ it('matches a workspace device against the run workspace', async () => {
+ mockResolveOwner.mockResolvedValueOnce({ userId: 'user_9', workspaceId: 'ws_1' });
+
+ const res = await deviceToolCompletion(
+ buildContext({ ...completion, userId: undefined, workspaceId: 'ws_1' }),
+ );
+
+ expect(res.status).toBe(200);
+ expect(mockCompleteDeferredShell).toHaveBeenCalled();
+ });
+
+ it('refuses a workspace device for a run in another workspace', async () => {
+ mockResolveOwner.mockResolvedValueOnce({ userId: 'user_1', workspaceId: 'ws_other' });
+
+ const res = await deviceToolCompletion(
+ buildContext({ ...completion, userId: undefined, workspaceId: 'ws_1' }),
+ );
+
+ expect(res.status).toBe(403);
+ expect(mockCompleteDeferredShell).not.toHaveBeenCalled();
+ });
+
+ it('asks for a resend while the placeholder is not written yet', async () => {
+ mockCompleteDeferredShell.mockResolvedValueOnce({
+ handled: false,
+ reason: 'placeholder_missing',
+ });
+
+ const res = await deviceToolCompletion(buildContext(completion));
+
+ // 5xx β†’ the gateway answers `retry`; acknowledging would drop the only copy.
+ expect(res.status).toBe(503);
+ });
+
+ it('acknowledges a completion for a call that was never parked', async () => {
+ mockCompleteDeferredShell.mockResolvedValueOnce({
+ handled: false,
+ reason: 'not_deferred_shell',
+ });
+
+ const res = await deviceToolCompletion(buildContext(completion));
+
+ expect(res.status).toBe(200);
+ });
+
+ it('answers 404 for an unknown operation', async () => {
+ mockResolveOwner.mockResolvedValueOnce(undefined);
+
+ const res = await deviceToolCompletion(buildContext(completion));
+
+ expect(res.status).toBe(404);
+ });
+
+ it('rejects a malformed body', async () => {
+ const res = await deviceToolCompletion(buildContext({ operationId: 'op_1' }));
+
+ expect(res.status).toBe(400);
+ });
+
+ it('lets the device retry when delivery throws', async () => {
+ mockCompleteDeferredShell.mockRejectedValueOnce(new Error('db down'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const res = await deviceToolCompletion(buildContext(completion));
+
+ expect(res.status).toBe(500);
+ });
+});
diff --git a/apps/server/src/router-hono/agent/handlers/deviceToolCompletion.ts b/apps/server/src/router-hono/agent/handlers/deviceToolCompletion.ts
new file mode 100644
index 00000000000..e24060ea753
--- /dev/null
+++ b/apps/server/src/router-hono/agent/handlers/deviceToolCompletion.ts
@@ -0,0 +1,112 @@
+import debug from 'debug';
+import type { Context } from 'hono';
+import { z } from 'zod';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { resolveOperationOwner } from './resolveOperationOwner';
+
+const log = debug('lobe-server:agent:device-tool-completion');
+
+const DeviceToolCompletionBodySchema = z.object({
+ deviceId: z.string().min(1),
+ operationId: z.string().min(1),
+ result: z.object({
+ content: z.string().nullable().optional(),
+ error: z.unknown().optional(),
+ executionTimeMs: z.number().nonnegative().optional(),
+ state: z.record(z.string(), z.any()).optional(),
+ success: z.boolean(),
+ }),
+ toolCallId: z.string().min(1),
+ /** The principal the gateway dispatched the call under: one of the two. */
+ userId: z.string().optional(),
+ workspaceId: z.string().optional(),
+});
+
+const toErrorPayload = (error: unknown) => {
+ if (error === undefined || error === null) return undefined;
+ if (typeof error === 'string') return { message: error, type: 'device_error' };
+ if (typeof error === 'object' && typeof (error as { message?: unknown }).message === 'string')
+ return error as { message: string; type?: string };
+ return { message: String(error), type: 'device_error' };
+};
+
+/**
+ * Receive the late, final result of a device tool call β€” a shell command the
+ * device kept watching after its `runCommand` reply β€” relayed by the device
+ * gateway, and resume the operation parked on it.
+ *
+ * Auth: `deviceGatewayServiceAuth` on the route. The gateway only forwards a
+ * completion for a call the server registered, and reports the principal it
+ * dispatched under; that principal must own the operation, so one account's
+ * device cannot complete another account's run.
+ *
+ * Responses map to the gateway's ack: 2xx β†’ `delivered`, 4xx β†’ `rejected`,
+ * 5xx β†’ `retry` (the device resends). Delivery is idempotent: the backfill is
+ * `onlyIfEmpty` and the resume is CAS-guarded.
+ */
+export async function deviceToolCompletion(c: Context): Promise<Response> {
+ let parsed;
+ try {
+ parsed = DeviceToolCompletionBodySchema.safeParse(await c.req.json());
+ } catch {
+ return c.json({ error: 'Invalid JSON body' }, 400);
+ }
+ if (!parsed.success) {
+ return c.json({ error: 'Invalid body', issues: parsed.error.issues }, 400);
+ }
+
+ const { operationId, result, toolCallId, userId, workspaceId } = parsed.data;
+
+ try {
+ const serverDB = await getServerDB();
+ const owner = await resolveOperationOwner(serverDB, operationId);
+ if (!owner) {
+ log('No owner for operation %s', operationId);
+ return c.json({ error: 'Unknown operation' }, 404);
+ }
+
+ const principalMatches = workspaceId
+ ? owner.workspaceId === workspaceId
+ : !!userId && owner.userId === userId;
+ if (!principalMatches) {
+ log('Principal mismatch for operation %s (tool=%s)', operationId, toolCallId);
+ return c.json({ error: 'Operation does not belong to this device principal' }, 403);
+ }
+
+ const aiAgentService = new AiAgentService(serverDB, owner.userId, {
+ includeShareVisitor: Boolean(owner.streamOwnerUserId),
+ workspaceId: owner.workspaceId,
+ });
+
+ const outcome = await aiAgentService.completeDeferredShell({
+ operationId,
+ result: {
+ content: result.content ?? null,
+ error: toErrorPayload(result.error),
+ executionTimeMs: result.executionTimeMs,
+ state: result.state,
+ success: result.success,
+ toolCallId,
+ },
+ });
+
+ log('op=%s tool=%s handled=%s', operationId, toolCallId, String(outcome.handled));
+
+ if (!outcome.handled && outcome.reason === 'placeholder_missing') {
+ // The park writes the placeholder right after the device's `runCommand`
+ // reply returns, so a command that ends at once can report first. Ask for
+ // a resend instead of acknowledging away the only copy of the answer.
+ return c.json({ error: 'Placeholder is not ready', retryable: true }, 503);
+ }
+
+ // `not_deferred_shell`: the call was never parked (the server answered it
+ // with the `shell_id` instead). Acknowledge so the device stops resending.
+ return c.json(outcome);
+ } catch (error) {
+ console.error('[agent/device-tool-completion] delivery failed:', error);
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/apps/server/src/router-hono/agent/handlers/resolveOperationOwner.ts b/apps/server/src/router-hono/agent/handlers/resolveOperationOwner.ts
new file mode 100644
index 00000000000..4302d23b840
--- /dev/null
+++ b/apps/server/src/router-hono/agent/handlers/resolveOperationOwner.ts
@@ -0,0 +1,43 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import { eq } from 'drizzle-orm';
+
+import { agentOperations } from '@/database/schemas/agentOperations';
+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
+
+export interface OperationOwner {
+ /** Set only for a shared-agent visitor run: the visitor owns the stream. */
+ streamOwnerUserId?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+/**
+ * Whose rows a background delivery should read and write.
+ *
+ * Same trust chain as `/subagent-callback`: the caller is service-token
+ * verified and the operation row is the authority. The Redis metadata is the
+ * fast path; it can be gone after a reap, and a 401 there would drop a result
+ * the device cannot resend β€” so fall back to the durable row.
+ */
+export async function resolveOperationOwner(
+ serverDB: LobeChatDatabase,
+ operationId: string,
+): Promise<OperationOwner | undefined> {
+ const metadata = await new AgentRuntimeCoordinator().getOperationMetadata(operationId);
+
+ if (metadata?.userId) {
+ return {
+ streamOwnerUserId: metadata.streamOwnerUserId,
+ userId: metadata.userId,
+ workspaceId: metadata.workspaceId,
+ };
+ }
+
+ const [row] = await serverDB
+ .select({ userId: agentOperations.userId, workspaceId: agentOperations.workspaceId })
+ .from(agentOperations)
+ .where(eq(agentOperations.id, operationId))
+ .limit(1);
+
+ return row ? { userId: row.userId, workspaceId: row.workspaceId ?? undefined } : undefined;
+}
diff --git a/apps/server/src/router-hono/agent/handlers/shellExpire.ts b/apps/server/src/router-hono/agent/handlers/shellExpire.ts
new file mode 100644
index 00000000000..610a090f636
--- /dev/null
+++ b/apps/server/src/router-hono/agent/handlers/shellExpire.ts
@@ -0,0 +1,92 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import debug from 'debug';
+import type { Context } from 'hono';
+
+import { getServerDB } from '@/database/core/db-adaptor';
+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { resolveOperationOwner } from './resolveOperationOwner';
+
+const log = debug('lobe-server:agent:shell-expire');
+
+interface ShellExpireBody {
+ operationId?: string;
+ /**
+ * QStash nests the scheduled fields under `payload` (see
+ * `QStashQueueServiceImpl.scheduleMessage`); the local queue spreads them at
+ * the top level instead. Declared so both shapes can be read.
+ */
+ payload?: {
+ toolCallId?: string;
+ toolMessageId?: string;
+ };
+ toolCallId?: string;
+ toolMessageId?: string;
+}
+
+/**
+ * Deadline for a parked shell command.
+ *
+ * Scheduled once when the operation parks, and delivered by QStash after the
+ * configured wait. It is the only cost the wait carries besides its two ends:
+ * the device normally reports completion long before this fires, and then this
+ * message finds the placeholder already filled and does nothing.
+ *
+ * Auth: `qstashAuth` on the route.
+ */
+export async function shellExpire(c: Context): Promise<Response> {
+ let body: ShellExpireBody;
+ try {
+ body = await c.req.json();
+ } catch {
+ return c.json({ error: 'Invalid JSON body' }, 400);
+ }
+
+ // QStash keeps `operationId` at the top level and carries the tool ids inside
+ // `body.payload`. Reading the top level alone made every queued delivery fail
+ // the guard below with 400, so a wait that should have been closed by its
+ // deadline stayed parked until the gateway's own watchdog killed it.
+ const { operationId, toolCallId } = { ...body, ...body.payload };
+ if (!operationId || !toolCallId) {
+ return c.json({ error: 'operationId and toolCallId are required' }, 400);
+ }
+
+ try {
+ const coordinator = new AgentRuntimeCoordinator();
+ const state: AgentState | null = await coordinator.loadAgentState(operationId);
+
+ // Already resumed (the device won the race), interrupted, or reaped: there
+ // is nothing left to fail. This is the common case, not an error.
+ if (!state || state.status !== 'waiting_for_async_tool') {
+ log('skip: op=%s is not parked (%s)', operationId, state?.status ?? 'no state');
+ return c.json({ skipped: true });
+ }
+
+ const serverDB = await getServerDB();
+ const owner = await resolveOperationOwner(serverDB, operationId);
+ if (!owner) {
+ log('skip: no owner for op=%s', operationId);
+ return c.json({ skipped: true });
+ }
+
+ const aiAgentService = new AiAgentService(serverDB, owner.userId, {
+ includeShareVisitor: Boolean(owner.streamOwnerUserId),
+ workspaceId: owner.workspaceId,
+ });
+
+ const outcome = await aiAgentService.completeDeferredShell({
+ operationId,
+ reason: 'timeout',
+ result: { content: null, success: false, toolCallId },
+ });
+
+ log('expired op=%s tool=%s handled=%s', operationId, toolCallId, String(outcome.handled));
+
+ return c.json(outcome);
+ } catch (error) {
+ console.error('[agent/shell-expire] failed:', error);
+ // Non-2xx β†’ QStash redelivers; the backfill is idempotent.
+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
+ }
+}
diff --git a/apps/server/src/router-hono/agent/index.ts b/apps/server/src/router-hono/agent/index.ts
index f35f65a12b4..15828d7c648 100644
--- a/apps/server/src/router-hono/agent/index.ts
+++ b/apps/server/src/router-hono/agent/index.ts
@@ -7,6 +7,7 @@ import { botCallback } from './handlers/botCallback';
import { botReplay } from './handlers/botReplay';
import { botWakeFlush } from './handlers/botWakeFlush';
import { channelAdvance, channelCallback } from './handlers/channel';
+import { deviceToolCompletion } from './handlers/deviceToolCompletion';
import {
documentAccess,
documentProjection,
@@ -27,9 +28,11 @@ import { messengerWebhook } from './handlers/messengerWebhook';
import { platformWebhook } from './handlers/platformWebhook';
import { reapOperations } from './handlers/reapOperations';
import { runStep, runStepHealth } from './handlers/runStep';
+import { shellExpire } from './handlers/shellExpire';
import { subAgentCallback } from './handlers/subAgentCallback';
import { toolResult } from './handlers/toolResult';
import { bearerSecretAuth } from './middlewares/bearerSecretAuth';
+import { deviceGatewayServiceAuth } from './middlewares/deviceGatewayServiceAuth';
import { qstashAuth } from './middlewares/qstashAuth';
import { qstashOrApiKeyAuth } from './middlewares/qstashOrApiKeyAuth';
import { serviceTokenAuth } from './middlewares/serviceTokenAuth';
@@ -61,6 +64,13 @@ app.post('/webhooks/inbox-report', qstashAuth(), agentInboxReport);
// POST /api/agent/tool-result β€” gateway-side tool result LPUSH'd to Redis
app.post('/tool-result', serviceTokenAuth(), toolResult);
+// POST /api/agent/device-tool-completion β€” device gateway relays the final
+// result of a device command that a parked operation is waiting on
+app.post('/device-tool-completion', deviceGatewayServiceAuth(), deviceToolCompletion);
+
+// POST /api/agent/shell-expire β€” deadline for a parked shell command (QStash)
+app.post('/shell-expire', qstashAuth(), shellExpire);
+
// LLM relay: the user's device runs one LLM attempt for a device-only model
// provider. Auth is the per-call lease token carried by `llm_execute`.
// GET /api/agent/llm-relay/:callId/payload β€” request body of the attempt
diff --git a/apps/server/src/router-hono/agent/middlewares/deviceGatewayServiceAuth.ts b/apps/server/src/router-hono/agent/middlewares/deviceGatewayServiceAuth.ts
new file mode 100644
index 00000000000..e49357e209c
--- /dev/null
+++ b/apps/server/src/router-hono/agent/middlewares/deviceGatewayServiceAuth.ts
@@ -0,0 +1,28 @@
+import debug from 'debug';
+import type { MiddlewareHandler } from 'hono';
+
+import { gatewayEnv } from '@/envs/gateway';
+
+const log = debug('lobe-server:agent:device-gateway-service-auth');
+
+/**
+ * Authenticates the device gateway calling back into the server, against
+ * `DEVICE_GATEWAY_SERVICE_TOKEN` via `Authorization: Bearer <token>` β€” the same
+ * token the server presents when it dispatches to the gateway.
+ *
+ * Distinct from {@link serviceTokenAuth} (agent gateway): the two gateways hold
+ * different secrets, and neither should be able to impersonate the other.
+ */
+export const deviceGatewayServiceAuth = (): MiddlewareHandler => async (c, next) => {
+ const serviceToken = gatewayEnv.DEVICE_GATEWAY_SERVICE_TOKEN;
+ if (!serviceToken) {
+ log('DEVICE_GATEWAY_SERVICE_TOKEN is not configured');
+ return c.json({ error: 'Service not configured' }, 503);
+ }
+
+ if (c.req.header('authorization') !== `Bearer ${serviceToken}`) {
+ return c.json({ error: 'Unauthorized' }, 401);
+ }
+
+ await next();
+};
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/asyncShellResult.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/asyncShellResult.test.ts
new file mode 100644
index 00000000000..58e7947006e
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/asyncShellResult.test.ts
@@ -0,0 +1,307 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { completeDeferredShell } from '../asyncShellResult';
+
+const POLL_PLUGIN = {
+ id: 'msg_placeholder',
+ state: {
+ asyncShell: { commandId: 'sh-1', startedAt: '2026-01-01T00:00:00.000Z', timeoutMs: 1_800_000 },
+ status: 'pending',
+ },
+ toolCallId: 'call_1',
+};
+
+const buildDeps = (plugin: unknown = POLL_PLUGIN, backfillSuccess = true) => {
+ const updateToolMessage = vi.fn(async (_id: string, _payload: any) => ({
+ success: backfillSuccess,
+ }));
+ const tryResumeParentFromAsyncTool = vi.fn(async () => true);
+ // Passthrough by default: no `afterToolCall` policy configured.
+ const controlCompletedToolResult = vi.fn(async (input: any) => ({
+ blocked: false,
+ cancelled: false,
+ result: input.result,
+ }));
+
+ return {
+ deps: {
+ controlCompletedToolResult,
+ messageModel: { findMessagePlugin: vi.fn(), updateToolMessage } as any,
+ serverDB: {
+ query: { messagePlugins: { findFirst: vi.fn(async () => plugin) } },
+ } as any,
+ tryResumeParentFromAsyncTool,
+ },
+ controlCompletedToolResult,
+ tryResumeParentFromAsyncTool,
+ updateToolMessage,
+ };
+};
+
+describe('completeDeferredShell', () => {
+ it('backfills the placeholder and resumes the parked operation', async () => {
+ const { deps, tryResumeParentFromAsyncTool, updateToolMessage } = buildDeps();
+
+ const outcome = await completeDeferredShell(deps, {
+ operationId: 'op_1',
+ result: {
+ content: 'Command completed successfully.\nstdout: 42 tests passed',
+ state: { exitCode: 0 },
+ success: true,
+ toolCallId: 'call_1',
+ },
+ });
+
+ expect(outcome).toEqual({ handled: true, resumed: true });
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'msg_placeholder',
+ expect.objectContaining({
+ content: 'Command completed successfully.\nstdout: 42 tests passed',
+ // Idempotent: a duplicate late result (or the expiry message racing it)
+ // must not overwrite the answer that landed first.
+ onlyIfEmpty: true,
+ pluginState: expect.objectContaining({ exitCode: 0, status: 'completed' }),
+ }),
+ );
+ // The barrier trusts this write instead of re-reading a lagging replica.
+ expect(tryResumeParentFromAsyncTool).toHaveBeenCalledWith(
+ { parentOperationId: 'op_1' },
+ expect.objectContaining({
+ knownFulfilledMessageId: 'msg_placeholder',
+ scheduleVerifyOnHold: true,
+ }),
+ );
+ });
+
+ it('keeps the device command state the tool card renders', async () => {
+ const { deps, updateToolMessage } = buildDeps();
+
+ // A device reports the late result in `getCommandOutput`'s shape: output
+ // and liveness, but no command id of its own.
+ await completeDeferredShell(deps, {
+ operationId: 'op_1',
+ result: {
+ content: 'Exit code: 0\n42 tests passed',
+ state: { exitCode: 0, running: false, status: 'done', stdout: '42 tests passed' },
+ success: true,
+ toolCallId: 'call_1',
+ },
+ });
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'msg_placeholder',
+ expect.objectContaining({
+ pluginState: expect.objectContaining({
+ asyncShell: expect.objectContaining({ commandId: 'sh-1' }),
+ commandId: 'sh-1',
+ exitCode: 0,
+ running: false,
+ // The park's outcome wins over a same-named device field.
+ status: 'completed',
+ stdout: '42 tests passed',
+ }),
+ }),
+ );
+ });
+
+ it('size-limits the answer the way the synchronous path does', async () => {
+ const archive = {
+ agentId: 'agent_1',
+ canReadArchive: true,
+ maxLength: 100,
+ topicId: 'topic_1',
+ };
+ const { deps, updateToolMessage } = buildDeps({
+ ...POLL_PLUGIN,
+ state: { ...POLL_PLUGIN.state, asyncShell: { ...POLL_PLUGIN.state.asyncShell, archive } },
+ });
+ const archiveResult = vi.fn(async () => 'first 100 chars… [archived]');
+ const noisy = 'x'.repeat(10_000);
+
+ await completeDeferredShell(
+ { ...deps, archiveResult },
+ {
+ operationId: 'op_1',
+ result: { content: noisy, state: { exitCode: 0 }, success: true, toolCallId: 'call_1' },
+ },
+ );
+
+ // The parked step recorded its limit; a noisy background command must not
+ // bypass it just because its answer arrived late.
+ expect(archiveResult).toHaveBeenCalledWith(
+ expect.objectContaining({ ...archive, content: noisy, toolCallId: 'call_1' }),
+ );
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'msg_placeholder',
+ expect.objectContaining({ content: 'first 100 chars… [archived]' }),
+ );
+ });
+
+ it('does not archive a result the policy withheld', async () => {
+ const { deps, controlCompletedToolResult } = buildDeps({
+ ...POLL_PLUGIN,
+ state: {
+ ...POLL_PLUGIN.state,
+ asyncShell: { ...POLL_PLUGIN.state.asyncShell, archive: { canReadArchive: true } },
+ },
+ });
+ controlCompletedToolResult.mockResolvedValueOnce({
+ blocked: true,
+ cancelled: false,
+ result: { content: 'Denied by policy.', success: false },
+ });
+ const archiveResult = vi.fn(async (input: { content: string }) => input.content);
+
+ await completeDeferredShell(
+ { ...deps, archiveResult },
+ {
+ operationId: 'op_1',
+ result: { content: 'secret output', success: true, toolCallId: 'call_1' },
+ },
+ );
+
+ expect(archiveResult).not.toHaveBeenCalled();
+ });
+
+ it('runs the result policy before the answer reaches history', async () => {
+ const { deps, controlCompletedToolResult, updateToolMessage } = buildDeps();
+ // A configured `afterToolCall` policy denies the command's output. This
+ // completion never travelled through `ServerToolTransport`, so the gate has
+ // to run here as well β€” otherwise the raw device text is what history and
+ // the model get.
+ controlCompletedToolResult.mockResolvedValueOnce({
+ blocked: true,
+ cancelled: false,
+ result: {
+ content: 'Denied by policy.',
+ error: 'hook_denied',
+ state: { phase: 'afterToolCall', type: 'blocked' },
+ success: false,
+ },
+ } as any);
+
+ await completeDeferredShell(deps, {
+ operationId: 'op_1',
+ result: { content: 'secret', state: { exitCode: 0 }, success: true, toolCallId: 'call_1' },
+ });
+
+ expect(controlCompletedToolResult).toHaveBeenCalledWith(
+ expect.objectContaining({ operationId: 'op_1', toolMessageId: 'msg_placeholder' }),
+ );
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'msg_placeholder',
+ expect.objectContaining({
+ content: 'Denied by policy.',
+ pluginError: 'hook_denied',
+ // A withheld result replaces the whole state, including the shell ids.
+ replacePluginState: true,
+ }),
+ );
+ });
+
+ it('marks a failed command and still resumes', async () => {
+ const { deps, tryResumeParentFromAsyncTool, updateToolMessage } = buildDeps();
+
+ await completeDeferredShell(deps, {
+ operationId: 'op_1',
+ result: { content: null, state: { exitCode: 2 }, success: true, toolCallId: 'call_1' },
+ });
+
+ expect(updateToolMessage).toHaveBeenCalledWith(
+ 'msg_placeholder',
+ expect.objectContaining({
+ content: 'Command failed with exit code 2.',
+ pluginState: expect.objectContaining({ status: 'error' }),
+ }),
+ );
+ expect(tryResumeParentFromAsyncTool).toHaveBeenCalled();
+ });
+
+ it('reports a timeout without claiming the command failed', async () => {
+ const { deps, updateToolMessage } = buildDeps();
+
+ await completeDeferredShell(deps, {
+ operationId: 'op_1',
+ reason: 'timeout',
+ result: { content: null, success: false, toolCallId: 'call_1' },
+ });
+
+ const [, payload] = updateToolMessage.mock.calls[0] as unknown as [string, any];
+ // The command may still be running on the device: say so and name the shell
+ // so the model can check on it instead of re-running the work.
+ expect(payload.content).toContain('may still be running');
+ expect(payload.content).toContain('sh-1');
+ expect(payload.pluginError).toMatchObject({ type: 'timeout' });
+ expect(payload.pluginState).toMatchObject({ status: 'error' });
+ });
+
+ it('keeps looking for a placeholder the park has not written yet', async () => {
+ const { deps, tryResumeParentFromAsyncTool, updateToolMessage } = buildDeps();
+ // A command that ends immediately can report before `parkAsyncShell` has
+ // inserted the row: miss once, then find it.
+ (deps.serverDB as any).query.messagePlugins.findFirst = vi
+ .fn()
+ .mockResolvedValueOnce(null)
+ .mockResolvedValue(POLL_PLUGIN);
+
+ const outcome = await completeDeferredShell(
+ { ...deps, placeholderWait: { attempts: 3, intervalMs: 0 } },
+ {
+ operationId: 'op_1',
+ result: { content: 'fast', success: true, toolCallId: 'call_1' },
+ },
+ );
+
+ expect(outcome).toEqual({ handled: true, resumed: true });
+ expect(updateToolMessage).toHaveBeenCalled();
+ expect(tryResumeParentFromAsyncTool).toHaveBeenCalled();
+ });
+
+ it('reports a missing placeholder instead of swallowing the completion', async () => {
+ const { deps, updateToolMessage } = buildDeps();
+ (deps.serverDB as any).query.messagePlugins.findFirst = vi.fn(async () => null);
+
+ const outcome = await completeDeferredShell(
+ { ...deps, placeholderWait: { attempts: 0, intervalMs: 0 } },
+ {
+ operationId: 'op_1',
+ result: { content: 'fast', success: true, toolCallId: 'call_1' },
+ },
+ );
+
+ // Distinct from `not_deferred_shell`: the caller has to keep this result,
+ // because the device will not send it again.
+ expect(outcome).toEqual({ handled: false, reason: 'placeholder_missing' });
+ expect(updateToolMessage).not.toHaveBeenCalled();
+ });
+
+ it('ignores a result for a tool that was never parked', async () => {
+ const { deps, updateToolMessage } = buildDeps({
+ id: 'msg_other',
+ state: null,
+ toolCallId: 'x',
+ });
+
+ const outcome = await completeDeferredShell(deps, {
+ operationId: 'op_1',
+ result: { content: 'ok', success: true, toolCallId: 'x' },
+ });
+
+ expect(outcome).toEqual({ handled: false, reason: 'not_deferred_shell' });
+ expect(updateToolMessage).not.toHaveBeenCalled();
+ });
+
+ it('throws when the placeholder cannot be written', async () => {
+ // Never resume on a failed backfill: the barrier would read the row as
+ // unfulfilled and the run would strand instead of being retried.
+ const { deps, tryResumeParentFromAsyncTool } = buildDeps(POLL_PLUGIN, false);
+
+ await expect(
+ completeDeferredShell(deps, {
+ operationId: 'op_1',
+ result: { content: 'ok', success: true, toolCallId: 'call_1' },
+ }),
+ ).rejects.toThrow(/failed to backfill/);
+ expect(tryResumeParentFromAsyncTool).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/asyncShellResult.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/asyncShellResult.ts
new file mode 100644
index 00000000000..0d17e2fed32
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/asyncShellResult.ts
@@ -0,0 +1,282 @@
+import type { ToolRunResult } from '@lobechat/agent-runtime';
+import type { LobeChatDatabase } from '@lobechat/database';
+import debug from 'debug';
+
+import type { MessageModel } from '@/database/models/message';
+
+const log = debug('lobe-server:agent-runtime:async-shell');
+
+export interface DeferredShellResult {
+ content: string | null;
+ error?: { message: string; type?: string };
+ executionTimeMs?: number;
+ state?: Record<string, unknown>;
+ success: boolean;
+ toolCallId: string;
+}
+
+/**
+ * The `afterToolCall` gate a deferred completion goes through. Typed by shape
+ * rather than by the runtime's own signature so this module keeps depending on
+ * nothing but the models it writes.
+ */
+export type DeferredShellResultControl = (input: {
+ operationId?: string;
+ preserveUsage?: boolean;
+ result: ToolRunResult;
+ toolMessageId: string;
+}) => Promise<{ blocked: boolean; cancelled: boolean; result: ToolRunResult }>;
+
+/**
+ * Size-limits a completed result the way the synchronous path does
+ * (`archiveToolResultIfNeeded`): over the limit, the full text is archived when
+ * the run can page it and the model gets a window plus a notice.
+ */
+export type DeferredShellResultArchive = (input: {
+ agentId?: string;
+ canReadArchive: boolean;
+ content: string;
+ maxLength?: number;
+ toolCallId: string;
+ topicId?: string;
+ workspaceId?: string;
+}) => Promise<string>;
+
+export interface AsyncShellResultDeps {
+ /** Unset in tests that do not exercise the size limit. */
+ archiveResult?: DeferredShellResultArchive;
+ /**
+ * A late device result never travels back through `ServerToolTransport`, so
+ * this path has to run the same controls before the answer reaches history.
+ */
+ controlCompletedToolResult: DeferredShellResultControl;
+ messageModel: Pick<MessageModel, 'findMessagePlugin' | 'updateToolMessage'>;
+ /**
+ * Override for {@link PLACEHOLDER_WAIT}, used by tests to keep the wait
+ * instant. Production callers leave it out.
+ */
+ placeholderWait?: { attempts: number; intervalMs: number };
+ serverDB: LobeChatDatabase;
+ /** Barrier + single-fire CAS + re-dispatch of the parked step. */
+ tryResumeParentFromAsyncTool: (
+ params: { parentOperationId: string },
+ options?: { knownFulfilledMessageId?: string; scheduleVerifyOnHold?: boolean },
+ ) => Promise<boolean>;
+}
+
+/** The placeholder state written by `parkAsyncShell`. */
+interface AsyncShellPluginState {
+ asyncShell?: {
+ archive?: {
+ agentId?: string;
+ canReadArchive?: boolean;
+ maxLength?: number;
+ topicId?: string;
+ workspaceId?: string;
+ };
+ commandId?: string;
+ startedAt?: string;
+ timeoutMs?: number;
+ };
+ status?: string;
+}
+
+export interface CompleteDeferredShellParams {
+ /** Operation the parked step belongs to (the gateway's operation id). */
+ operationId: string;
+ /**
+ * Why the placeholder is being closed. `timeout` comes from the scheduled
+ * deadline, not from the device: the command may still be running there, so
+ * the text has to say so instead of claiming a failure that did not happen.
+ */
+ reason?: 'device_result' | 'timeout';
+ result: DeferredShellResult;
+}
+
+export type CompleteDeferredShellOutcome =
+ | { handled: false; reason: 'not_deferred_shell' }
+ /**
+ * The completion itself is fine, but its placeholder never showed up. Only
+ * reachable when a device reports a command it already saw start, so the
+ * caller must keep the result instead of acknowledging it away.
+ */
+ | { handled: false; reason: 'placeholder_missing' }
+ | { handled: true; resumed: boolean };
+
+/**
+ * The command outlived its deadline. Say what is actually true: the run was
+ * parked and gave up waiting β€” not that the command failed. The shell id lets
+ * the model check on it (or kill it) instead of assuming the work was undone.
+ */
+const timeoutContent = (commandId?: string, timeoutMs?: number): string => {
+ const minutes = Math.round((timeoutMs ?? 0) / 60_000) || undefined;
+ const waited = minutes ? `${minutes} minutes` : 'the configured wait';
+ const shell = commandId ? ` (shell_id: ${commandId})` : '';
+ return (
+ `Command did not finish within ${waited}${shell}. ` +
+ 'It may still be running on the device β€” use getCommandOutput to check on it, or killCommand to stop it.'
+ );
+};
+
+/** What the model sees when the command produced no text of its own. */
+const synthesizeContent = (result: DeferredShellResult): string => {
+ if (result.content && result.content.trim().length > 0) return result.content;
+
+ const exitCode = (result.state as { exitCode?: unknown } | undefined)?.exitCode;
+ if (typeof exitCode === 'number' && exitCode !== 0) {
+ return `Command failed with exit code ${exitCode}.`;
+ }
+ return result.error ? `Command failed: ${result.error.message}` : 'Command completed.';
+};
+
+/**
+ * How long a completion keeps looking for its placeholder before it is taken to
+ * belong to something else.
+ *
+ * The device starts `watchDeferredShell` as soon as it has sent the running
+ * receipt, while the server writes the placeholder only after that receipt has
+ * come back through `dispatchClientTool`. A command that ends quickly can
+ * therefore report completion before the row exists β€” and that report is the
+ * only copy of its answer. Poll briefly for it rather than declaring the result
+ * foreign on the first miss.
+ */
+const PLACEHOLDER_WAIT = { attempts: 6, intervalMs: 250 };
+
+const findPlaceholder = async (deps: AsyncShellResultDeps, toolCallId: string) => {
+ const { attempts, intervalMs } = deps.placeholderWait ?? PLACEHOLDER_WAIT;
+
+ for (let attempt = 0; ; attempt++) {
+ const plugin = await deps.serverDB.query.messagePlugins.findFirst({
+ where: (mp, { eq: eqOp }) => eqOp(mp.toolCallId, toolCallId),
+ });
+ if (plugin || attempt >= attempts) return plugin;
+
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
+ }
+};
+
+/**
+ * Finish a shell command that outlived its tool call.
+ *
+ * The device reports the command's completion long after the dispatching step
+ * ended, so there is no BLPOP waiter: the operation is parked, and its
+ * placeholder tool message is waiting for this write. Backfilling it and then
+ * resuming the parked operation is exactly the path the sub-agent bridge uses,
+ * which is why the barrier, the single-fire CAS and the verify watchdog are all
+ * reused here rather than re-implemented.
+ *
+ * Returns `handled: false` for a result that is not ours (a normal synchronous
+ * tool result racing the queue path, `not_deferred_shell`) or for one whose
+ * placeholder has not been written yet (`placeholder_missing`). The two are not
+ * interchangeable: the first can be dropped, the second is the only copy of the
+ * command's answer and the caller has to keep it.
+ */
+export async function completeDeferredShell(
+ deps: AsyncShellResultDeps,
+ { operationId, reason = 'device_result', result }: CompleteDeferredShellParams,
+): Promise<CompleteDeferredShellOutcome> {
+ const plugin = await findPlaceholder(deps, result.toolCallId);
+ if (!plugin) return { handled: false, reason: 'placeholder_missing' };
+
+ const pluginState = plugin.state as AsyncShellPluginState | null;
+ if (!pluginState?.asyncShell) return { handled: false, reason: 'not_deferred_shell' };
+
+ const exitCode = (result.state as { exitCode?: unknown } | undefined)?.exitCode;
+ const timedOut = reason === 'timeout';
+ const failed =
+ timedOut ||
+ result.success === false ||
+ result.error !== undefined ||
+ (typeof exitCode === 'number' && exitCode !== 0);
+
+ const content = timedOut
+ ? timeoutContent(pluginState.asyncShell.commandId, pluginState.asyncShell.timeoutMs)
+ : synthesizeContent(result);
+
+ const completed: ToolRunResult = {
+ content,
+ error:
+ result.error ??
+ (timedOut
+ ? { message: 'Command did not finish within its wait window.', type: 'timeout' }
+ : undefined),
+ executionTime: result.executionTimeMs,
+ state: {
+ // The device's own command state (stdout/stderr/output files) is what the
+ // tool card renders; the park's bookkeeping and the outcome win over it.
+ ...result.state,
+ commandId: pluginState.asyncShell.commandId,
+ ...pluginState,
+ error: result.error,
+ exitCode,
+ finishedAt: new Date().toISOString(),
+ status: failed ? 'error' : 'completed',
+ },
+ success: !failed,
+ };
+
+ // Run the configured `afterToolCall` policy before the answer is persisted.
+ // This completion bypasses `ServerToolTransport`, so nothing has evaluated a
+ // result policy on it yet: without this the raw device output would land in
+ // history and be handed to the model even when that policy denies or replaces
+ // it. `subAgentBridge` runs the same gate for its deferred results.
+ const controlled = await deps.controlCompletedToolResult({
+ operationId,
+ preserveUsage: true,
+ result: completed,
+ // The policy inspects the parked call's arguments, not this completion.
+ toolMessageId: plugin.id,
+ });
+
+ // Same order as the synchronous path: controls first, then the size limit, so
+ // a policy sees the whole output and history never holds more than the limit.
+ const archive = pluginState.asyncShell.archive;
+ const persistedContent =
+ !controlled.blocked && deps.archiveResult && archive && controlled.result.content
+ ? await deps.archiveResult({
+ agentId: archive.agentId,
+ canReadArchive: archive.canReadArchive === true,
+ content: controlled.result.content,
+ maxLength: archive.maxLength,
+ toolCallId: result.toolCallId,
+ topicId: archive.topicId,
+ workspaceId: archive.workspaceId,
+ })
+ : controlled.result.content;
+
+ const backfill = await deps.messageModel.updateToolMessage(plugin.id, {
+ content: persistedContent,
+ pluginError: controlled.result.error ?? null,
+ pluginState: controlled.result.state,
+ onlyIfEmpty: true,
+ ...(controlled.blocked && { replacePluginState: true }),
+ });
+
+ if (!backfill.success) {
+ // Leave the operation parked: the verify watchdog and the caller's retry
+ // both need the placeholder unchanged, and a partial write would look
+ // fulfilled to the barrier.
+ throw new Error(
+ `async shell: failed to backfill tool message ${plugin.id} (op=${operationId}, tool=${result.toolCallId})`,
+ );
+ }
+
+ // `applied: false` means an earlier answer (the device result or the expiry)
+ // already filled the placeholder; this one changed nothing.
+ log(
+ 'shell %s: op=%s tool=%s message=%s exit=%s blocked=%s',
+ backfill.applied ? 'completed' : 'already answered, ignored',
+ operationId,
+ result.toolCallId,
+ plugin.id,
+ String(exitCode),
+ String(controlled.blocked),
+ );
+
+ const resumed = await deps.tryResumeParentFromAsyncTool(
+ { parentOperationId: operationId },
+ { knownFulfilledMessageId: plugin.id, scheduleVerifyOnHold: true },
+ );
+
+ return { handled: true, resumed };
+}
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.localShellExpiry.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.localShellExpiry.test.ts
new file mode 100644
index 00000000000..3a70e837f84
--- /dev/null
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.localShellExpiry.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
+
+import { completeDeferredShell } from './asyncShellResult';
+import { type RuntimeFactoryDeps, setupLocalExecutionCallback } from './runtimeFactory';
+
+vi.mock('./asyncShellResult', () => ({
+ completeDeferredShell: vi.fn().mockResolvedValue({ handled: true }),
+}));
+
+const mockedCompleteDeferredShell = vi.mocked(completeDeferredShell);
+
+const captureCallback = (deps: Record<string, unknown>) => {
+ const impl = new LocalQueueServiceImpl();
+ const setCallback = vi.spyOn(impl, 'setExecutionCallback');
+ setupLocalExecutionCallback({
+ queueService: { getImpl: () => impl },
+ ...deps,
+ } as unknown as RuntimeFactoryDeps);
+ return setCallback.mock.calls[0][0];
+};
+
+const baseDeps = () => ({
+ controlCompletedToolResult: vi.fn(),
+ coordinator: { loadAgentState: vi.fn().mockResolvedValue({ status: 'waiting_for_async_tool' }) },
+ executeStep: vi.fn(),
+ messageModel: { findMessagePlugin: vi.fn(), updateToolMessage: vi.fn() },
+ serverDB: {},
+ tryResumeParentFromAsyncTool: vi.fn(),
+});
+
+describe('local delivery of a parked shell expiry', () => {
+ it('closes the placeholder as a timeout instead of re-running the completed step 0', async () => {
+ const deps = baseDeps();
+ const callback = captureCallback(deps);
+
+ await callback('op-1', 0, undefined, {
+ expireShell: true,
+ toolCallId: 'call-1',
+ toolMessageId: 'msg-1',
+ });
+
+ expect(deps.executeStep).not.toHaveBeenCalled();
+ expect(deps.coordinator.loadAgentState).toHaveBeenCalledWith('op-1');
+ expect(mockedCompleteDeferredShell).toHaveBeenCalledTimes(1);
+ expect(mockedCompleteDeferredShell.mock.calls[0][1]).toEqual({
+ operationId: 'op-1',
+ reason: 'timeout',
+ result: { content: null, success: false, toolCallId: 'call-1' },
+ });
+ });
+
+ it('leaves an operation that is no longer parked alone', async () => {
+ const deps = baseDeps();
+ deps.coordinator.loadAgentState.mockResolvedValue({ status: 'running' });
+ const callback = captureCallback(deps);
+
+ await callback('op-2', 0, undefined, { expireShell: true, toolCallId: 'call-2' });
+
+ expect(mockedCompleteDeferredShell).not.toHaveBeenCalled();
+ expect(deps.executeStep).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
index d24bc039f84..d619cd2781e 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/runtimeFactory.ts
@@ -5,6 +5,7 @@ import {
createAgentAccountOutboundAudit,
} from '@lobechat/builtin-tool-agent-account';
import { DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
import { getModelPropertyWithFallback } from '@lobechat/model-runtime';
import { type UIChatMessage } from '@lobechat/types';
@@ -17,10 +18,12 @@ import {
type RuntimeExecutorContext,
} from '@/server/modules/AgentRuntime/RuntimeExecutors';
import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
+import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';
import { createWidgetDryRunAudit } from '@/server/services/widget/dryRunAudit';
import { stateHasEntityFileEdits } from '@/server/services/workRegistration';
import { hookDispatcher } from '../hooks';
+import { completeDeferredShell } from './asyncShellResult';
import { createEvalConnectorHook } from './evalConnectorHook';
import { createEvalToolGateHook } from './evalToolGateHook';
import { DurableStatusUnavailableError } from './executionErrors';
@@ -33,7 +36,9 @@ const log = debug('lobe-server:agent-runtime-service');
export type RuntimeFactoryDeps = Pick<
AgentRuntimeServiceContext,
| 'agentFactory'
+ | 'baseURL'
| 'completeGroupMemberBarrier'
+ | 'controlCompletedToolResult'
| 'coordinator'
| 'delegate'
| 'executeStep'
@@ -42,6 +47,7 @@ export type RuntimeFactoryDeps = Pick<
| 'serverDB'
| 'streamManager'
| 'toolExecutionService'
+ | 'tryResumeParentFromAsyncTool'
| 'userId'
| 'workspaceId'
>;
@@ -64,6 +70,15 @@ export function setupLocalExecutionCallback(deps: RuntimeFactoryDeps): void {
if (impl instanceof LocalQueueServiceImpl) {
log('Setting up local execution callback');
impl.setExecutionCallback(async (operationId, stepIndex, context, payload) => {
+ // A parked shell's deadline rides this same local callback, but it is not
+ // a step: it is delivered with `stepIndex: 0`, which the completed-step
+ // guard skips, so the placeholder would stay parked past its deadline.
+ // Close it the way the QStash `/shell-expire` endpoint does instead.
+ if (payload?.expireShell === true) {
+ await expireLocalDeferredShell(deps, operationId, payload.toolCallId);
+ return;
+ }
+
// Mirror the QStash path where payload fields (approvedToolCall,
// toolMessageId, resumeAsyncTool, …) ride the request body into
// executeStep. Without this spread, local/in-memory resumes silently
@@ -88,6 +103,55 @@ export function setupLocalExecutionCallback(deps: RuntimeFactoryDeps): void {
}
}
+/**
+ * Close a parked shell that outlived its wait window on the local queue.
+ *
+ * Mirrors `/api/agent/shell-expire`: the same `waiting_for_async_tool` guard
+ * (a device result that won the race leaves the operation alone) and the same
+ * `completeDeferredShell(..., { reason: 'timeout' })` call, which backfills the
+ * placeholder and re-dispatches the parked step. Only the delivery differs β€”
+ * the local queue has no HTTP hop to route through.
+ */
+async function expireLocalDeferredShell(
+ deps: RuntimeFactoryDeps,
+ operationId: string,
+ toolCallId?: string,
+): Promise<void> {
+ if (!toolCallId) {
+ log('[%s] shell expiry carried no toolCallId; nothing to close', operationId);
+ return;
+ }
+
+ const state = await deps.coordinator.loadAgentState(operationId);
+ if (!state || state.status !== 'waiting_for_async_tool') {
+ log('[%s] shell expiry skipped: operation is no longer parked', operationId);
+ return;
+ }
+
+ const outcome = await completeDeferredShell(
+ {
+ archiveResult: async ({ maxLength, ...input }) =>
+ (
+ await archiveToolResultIfNeeded({
+ ...input,
+ identifier: LocalSystemIdentifier,
+ limit: maxLength,
+ serverDB: deps.serverDB,
+ userId: deps.userId,
+ })
+ ).content,
+ controlCompletedToolResult: (input) => deps.controlCompletedToolResult(input),
+ messageModel: deps.messageModel,
+ serverDB: deps.serverDB,
+ tryResumeParentFromAsyncTool: (params, resumeOptions) =>
+ deps.tryResumeParentFromAsyncTool(params, resumeOptions),
+ },
+ { operationId, reason: 'timeout', result: { content: null, success: false, toolCallId } },
+ );
+
+ log('[%s] shell expiry handled the placeholder=%s', operationId, String(outcome.handled));
+}
+
/**
* The relay executor a new run carries: the one its client declared, else
* its parent's, so a child run (group member, `callSubAgent` / `callAgent`
@@ -298,6 +362,19 @@ export async function createAgentRuntime(
messageModel: deps.messageModel,
modelRuntimeConfig,
operationId,
+ scheduleShellExpiry: deps.queueService
+ ? async ({ delayMs, operationId: expiryOperationId, toolCallId, toolMessageId }) => {
+ await deps.queueService!.scheduleMessage({
+ context: undefined,
+ delay: delayMs,
+ endpoint: `${deps.baseURL}/shell-expire`,
+ operationId: expiryOperationId,
+ payload: { expireShell: true, toolCallId, toolMessageId },
+ priority: 'low',
+ stepIndex: 0,
+ });
+ }
+ : undefined,
serverDB: deps.serverDB,
stepIndex,
stream: plan?.stream,
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 3f98dbff69a..40a322322a6 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -1,6 +1,7 @@
import type { AgentState } from '@lobechat/agent-runtime';
import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
import type { SandboxStorageClaim } from '@lobechat/builtin-tool-cloud-sandbox';
+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';
import type { LobeChatDatabase } from '@lobechat/database';
import type {
AgentRunInitRequest,
@@ -50,6 +51,11 @@ import type {
SubAgentBridgeParams,
} from '@/server/services/agentRuntime';
import { AgentRuntimeService } from '@/server/services/agentRuntime';
+import {
+ completeDeferredShell,
+ type CompleteDeferredShellOutcome,
+ type CompleteDeferredShellParams,
+} from '@/server/services/agentRuntime/AgentRuntimeService/asyncShellResult';
import type {
ExecGroupMemberParams,
ExecGroupMemberResult,
@@ -59,6 +65,7 @@ import { ComposioService } from '@/server/services/composio';
import { DocumentService } from '@/server/services/document';
import { MarketService } from '@/server/services/market';
import type { SteerQueueScope } from '@/server/services/redis/steerQueue';
+import { archiveToolResultIfNeeded } from '@/server/services/toolExecution/archiveToolResult';
import {
type BackgroundSubAgentResult,
@@ -403,6 +410,42 @@ export class AiAgentService {
return this.agentRuntimeService.completeSubAgentBridge(params);
}
+ /**
+ * Finish a shell command that outlived its tool call.
+ *
+ * Driven by `/api/agent/tool-result` when the gateway forwards a device's
+ * late `deferred` result. Routed through the AiAgentService like the other
+ * bridges so the placeholder backfill and the resume barrier stay
+ * workspace-scoped.
+ */
+ completeDeferredShell(
+ params: CompleteDeferredShellParams,
+ ): Promise<CompleteDeferredShellOutcome> {
+ return completeDeferredShell(
+ {
+ archiveResult: async ({ maxLength, ...input }) =>
+ (
+ await archiveToolResultIfNeeded({
+ ...input,
+ identifier: LocalSystemIdentifier,
+ limit: maxLength,
+ serverDB: this.db,
+ userId: this.userId,
+ })
+ ).content,
+ // The parked step never returned through `ServerToolTransport`, so this
+ // is the only place an `afterToolCall` policy can see its answer.
+ controlCompletedToolResult: (input) =>
+ this.agentRuntimeService.controlCompletedToolResult(input),
+ messageModel: this.messageModel,
+ serverDB: this.db,
+ tryResumeParentFromAsyncTool: (resumeParams, options) =>
+ this.agentRuntimeService.tryResumeParentFromAsyncTool(resumeParams, options),
+ },
+ params,
+ );
+ }
+
/**
* Group-action member completion bridge entry point β€” driven by the QStash
* `group-member-callback` webhook (queue mode). Forwards to the workspace-scoped
diff --git a/apps/server/src/services/deviceGateway/agents.ts b/apps/server/src/services/deviceGateway/agents.ts
index aff6304247a..8349137bbe8 100644
--- a/apps/server/src/services/deviceGateway/agents.ts
+++ b/apps/server/src/services/deviceGateway/agents.ts
@@ -7,6 +7,7 @@ import {
type DeviceMessageApiResult,
type DeviceToolCallResult,
type GatewayMcpParams,
+ type GatewayToolCallCompletion,
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import type {
@@ -211,6 +212,8 @@ export async function executeToolCall(
getClient: DeviceClientGetter,
params: {
clientKinds?: DeviceClient[];
+ /** Lets the device report this call's final result later; see `buildShellCompletion`. */
+ completion?: GatewayToolCallCompletion;
deviceId: string;
operationId?: string;
userId: string;
diff --git a/apps/server/src/services/deviceGateway/authorizedToolCall.ts b/apps/server/src/services/deviceGateway/authorizedToolCall.ts
index 5e3fd0bec00..98ada3046f5 100644
--- a/apps/server/src/services/deviceGateway/authorizedToolCall.ts
+++ b/apps/server/src/services/deviceGateway/authorizedToolCall.ts
@@ -1,5 +1,8 @@
import type { LobeChatDatabase } from '@lobechat/database';
-import type { DeviceToolCallResult } from '@lobechat/device-gateway-client';
+import type {
+ DeviceToolCallResult,
+ GatewayToolCallCompletion,
+} from '@lobechat/device-gateway-client';
import type { DeviceClient } from '@lobechat/types';
import { resolveDeviceDispatchAuthorizationFailure } from './dispatchAuthorization';
@@ -22,6 +25,8 @@ export const executeAuthorizedDeviceToolCall = async (
params: {
/** Device clients that may serve the call; see `deviceGateway.executeToolCall`. */
clientKinds?: DeviceClient[];
+ /** Lets the device report this call's final result later; see `buildShellCompletion`. */
+ completion?: GatewayToolCallCompletion;
deviceId: string;
operationId?: string;
userId: string;
diff --git a/apps/server/src/services/deviceGateway/toolCallCompletion.ts b/apps/server/src/services/deviceGateway/toolCallCompletion.ts
new file mode 100644
index 00000000000..03ae9f13d8e
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/toolCallCompletion.ts
@@ -0,0 +1,47 @@
+import type { GatewayToolCallCompletion } from '@lobechat/device-gateway-client';
+import urlJoin from 'url-join';
+
+import { appEnv } from '@/envs/app';
+
+/**
+ * Async shell: a device `runCommand` that outlives its wait window parks the
+ * run, and the device reports the command's final result when it exits.
+ *
+ * Always on. It degrades on its own: a device or gateway that does not speak
+ * late completions never confirms `completionWatch`, so nothing parks and the
+ * model gets `shell_id` back to poll, as before.
+ */
+
+/** Server-side wait before a parked command is failed and the run resumed. */
+export const ASYNC_SHELL_TIMEOUT_MS = 30 * 60 * 1000;
+
+/**
+ * How long the agent gateway's inactivity watchdog is told to hold for.
+ * Longer than {@link ASYNC_SHELL_TIMEOUT_MS}: the server owns the real timeout
+ * (a clean tool error), this only stops the watchdog killing a healthy wait.
+ */
+export const ASYNC_SHELL_PARK_WINDOW_MS = 2 * 60 * 60 * 1000;
+
+/** The device gateway keeps a registration a little past the server's own deadline. */
+const COMPLETION_TTL_SLACK_MS = 10 * 60 * 1000;
+
+export const DEVICE_TOOL_COMPLETION_PATH = '/api/agent/device-tool-completion';
+
+/**
+ * The registration that lets the device report this `runCommand`'s final
+ * result later, or `undefined` when the call cannot be correlated. The device only watches when this is present, and the server
+ * only parks when the device says it is watching (`state.completionWatch`), so
+ * an older device or gateway leaves the old polling behaviour in place.
+ */
+export const buildShellCompletion = (
+ toolCallId: string | undefined,
+): GatewayToolCallCompletion | undefined => {
+ if (!toolCallId) return undefined;
+
+ const baseUrl = process.env.AGENT_RUNTIME_BASE_URL || appEnv.APP_URL || 'http://localhost:3010';
+ return {
+ callbackUrl: urlJoin(baseUrl, DEVICE_TOOL_COMPLETION_PATH),
+ toolCallId,
+ ttlMs: ASYNC_SHELL_TIMEOUT_MS + COMPLETION_TTL_SLACK_MS,
+ };
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.completion.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.completion.test.ts
new file mode 100644
index 00000000000..974bb814d3e
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/localSystem.completion.test.ts
@@ -0,0 +1,63 @@
+import { LocalSystemApiName } from '@lobechat/builtin-tool-local-system';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { type ToolExecutionContext } from '../../types';
+
+const mockExecuteToolCall = vi.fn(async () => ({ content: 'ok', success: true }));
+vi.mock('@/server/services/deviceGateway/authorizedToolCall', () => ({
+ executeAuthorizedDeviceToolCall: (_serverDB: unknown, ...args: unknown[]) =>
+ (mockExecuteToolCall as any)(...args),
+}));
+
+const { localSystemRuntime } = await import('../localSystem');
+
+const context = (overrides: Partial<ToolExecutionContext> = {}): ToolExecutionContext => ({
+ activeDeviceId: 'device-1',
+ operationId: 'op-1',
+ toolCallId: 'call-1',
+ toolManifestMap: {},
+ userId: 'user-1',
+ ...overrides,
+});
+
+const dispatchedParams = () => (mockExecuteToolCall.mock.calls[0] as unknown[])[0] as any;
+
+describe('localSystemRuntime late-completion registration', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('lets the device report a command result later', async () => {
+ const proxy = localSystemRuntime.factory(context()) as Record<string, (a: any) => any>;
+
+ await proxy[LocalSystemApiName.runCommand]({ command: 'sleep 600' });
+
+ expect(dispatchedParams().completion).toEqual({
+ callbackUrl: expect.stringMatching(/\/api\/agent\/device-tool-completion$/),
+ toolCallId: 'call-1',
+ // Outlives the server's own deadline, so the server β€” not the gateway β€”
+ // decides when the wait is over.
+ ttlMs: expect.any(Number),
+ });
+ expect(dispatchedParams().completion.ttlMs).toBeGreaterThan(30 * 60 * 1000);
+ });
+
+ it('registers nothing for a call that cannot outlive itself', async () => {
+ const proxy = localSystemRuntime.factory(context()) as Record<string, (a: any) => any>;
+
+ await proxy[LocalSystemApiName.readFile]({ path: 'a.txt' });
+
+ expect(dispatchedParams().completion).toBeUndefined();
+ });
+
+ it('registers nothing without a tool call id to correlate', async () => {
+ const proxy = localSystemRuntime.factory(context({ toolCallId: undefined })) as Record<
+ string,
+ (a: any) => any
+ >;
+
+ await proxy[LocalSystemApiName.runCommand]({ command: 'sleep 600' });
+
+ expect(dispatchedParams().completion).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
index 154e311017b..d975ce1f29e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/localSystem.ts
@@ -9,6 +9,7 @@ import {
awaitManagedDeviceForToolCall,
isDeviceUnreachableResult,
} from '@/server/services/deviceGateway/managedDeviceWake';
+import { buildShellCompletion } from '@/server/services/deviceGateway/toolCallCompletion';
import { buildDeviceLhEnv } from '@/server/services/toolExecution/preprocessLhCommand';
import { buildNoActiveDeviceResult, REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';
@@ -172,10 +173,18 @@ export const localSystemRuntime: ServerRuntimeRegistration = {
}
const deviceWorkspaceId = await getDeviceWorkspaceId();
+ // Only a command can outlive its call. The device may keep watching it
+ // and report the final result later, which lets the transport park the
+ // run instead of the model polling.
+ const completion =
+ api.name === LocalSystemApiName.runCommand
+ ? buildShellCompletion(context.toolCallId)
+ : undefined;
const execute = () =>
executeAuthorizedDeviceToolCall(
context.serverDB,
{
+ completion,
deviceId: context.activeDeviceId!,
operationId: context.operationId,
userId: context.userId!,
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index c0cf5b6c7c9..e76a6e35df7 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -613,6 +613,56 @@ describe('GatewayClient', () => {
});
});
+ describe('reportToolCallCompletion', () => {
+ const completion = {
+ operationId: 'op-1',
+ result: { content: 'done', success: true },
+ toolCallId: 'call-1',
+ };
+ const connectAndAuth = async () => {
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+ (client as any).handleMessage(JSON.stringify({ type: 'auth_success' }));
+ return (client as any).ws;
+ };
+ const ack = (status: string) =>
+ (client as any).handleMessage(
+ JSON.stringify({
+ ...completion,
+ result: undefined,
+ status,
+ type: 'tool_call_completion_ack',
+ }),
+ );
+
+ it('resolves with the gateway verdict for the same call', async () => {
+ const ws = await connectAndAuth();
+ const pending = client.reportToolCallCompletion(completion);
+
+ expect(JSON.parse(ws.send.mock.calls.at(-1)[0])).toEqual({
+ ...completion,
+ type: 'tool_call_completion',
+ });
+ ack('retry');
+
+ await expect(pending).resolves.toMatchObject({ status: 'retry', toolCallId: 'call-1' });
+ });
+
+ it('rejects when not connected, so the watcher keeps the result', async () => {
+ await expect(client.reportToolCallCompletion(completion)).rejects.toThrow('not connected');
+ });
+
+ it('rejects an in-flight report when the socket goes away', async () => {
+ await connectAndAuth();
+ const assertion = expect(client.reportToolCallCompletion(completion)).rejects.toThrow(
+ 'closed',
+ );
+
+ await client.disconnect();
+ await assertion;
+ });
+ });
+
describe('tunnel serving', () => {
it('forwards tunnel frames to the tunnel host', async () => {
client.connect();
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 39f94dc2ce2..e4bcde7459b 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -20,6 +20,8 @@ import type {
ServerMessage,
SystemInfoRequestMessage,
SystemInfoResponseMessage,
+ ToolCallCompletionAckMessage,
+ ToolCallCompletionMessage,
ToolCallRequestMessage,
ToolCallResponseMessage,
} from './types';
@@ -39,6 +41,7 @@ const MAX_MISSED_HEARTBEATS = 3; // Force reconnect after 3 missed acks
*/
const CONNECT_TIMEOUT = 15_000; // 15s
const METRICS_ACK_TIMEOUT_MS = 15_000;
+const COMPLETION_ACK_TIMEOUT_MS = 30_000;
/**
* Close reason the gateway sends when a newer socket with the same
* `connectionId` takes over. `connectionId` is persisted per install, so this
@@ -56,6 +59,9 @@ export interface GatewayClientLogger {
warn: (msg: string, ...args: unknown[]) => void;
}
+const completionAckKey = (operationId: string, toolCallId: string) =>
+ `${operationId}:${toolCallId}`;
+
const noopLogger: GatewayClientLogger = {
debug: () => {},
error: () => {},
@@ -123,6 +129,13 @@ export class GatewayClient extends EventEmitter {
string,
{ reject: (error: Error) => void; resolve: () => void }
>();
+ private pendingCompletionAcks = new Map<
+ string,
+ {
+ reject: (error: Error) => void;
+ resolve: (ack: Omit<ToolCallCompletionAckMessage, 'type'>) => void;
+ }
+ >();
private intentionalDisconnect = false;
/**
* When each socket abandoned mid-handshake was abandoned. Only such a socket
@@ -285,6 +298,40 @@ export class GatewayClient extends EventEmitter {
});
}
+ /**
+ * Send the late result of a call the device kept watching, and resolve with
+ * the gateway's verdict. Rejects when not connected, when the connection drops
+ * mid-flight, or when no ack arrives in time β€” the caller keeps the result and
+ * sends it again, which is safe because the server applies it at most once.
+ */
+ reportToolCallCompletion(
+ completion: Omit<ToolCallCompletionMessage, 'type'>,
+ ): Promise<Omit<ToolCallCompletionAckMessage, 'type'>> {
+ if (this.status !== 'connected' || this.ws?.readyState !== WebSocket.OPEN) {
+ return Promise.reject(new Error('Gateway not connected'));
+ }
+ const key = completionAckKey(completion.operationId, completion.toolCallId);
+ // A resend supersedes the attempt still waiting on this socket.
+ this.pendingCompletionAcks.get(key)?.reject(new Error('Superseded by a newer send'));
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pendingCompletionAcks.delete(key);
+ reject(new Error('Timed out waiting for tool_call_completion_ack'));
+ }, COMPLETION_ACK_TIMEOUT_MS);
+ this.pendingCompletionAcks.set(key, {
+ reject: (error) => {
+ clearTimeout(timer);
+ reject(error);
+ },
+ resolve: (ack) => {
+ clearTimeout(timer);
+ resolve(ack);
+ },
+ });
+ this.sendMessage({ ...completion, type: 'tool_call_completion' });
+ });
+ }
+
sendSystemInfoResponse(response: Omit<SystemInfoResponseMessage, 'type'>): void {
this.sendMessage({
...response,
@@ -466,6 +513,15 @@ export class GatewayClient extends EventEmitter {
break;
}
+ case 'tool_call_completion_ack': {
+ const { type: _type, ...ack } = message as ToolCallCompletionAckMessage;
+ const key = completionAckKey(ack.operationId, ack.toolCallId);
+ const pending = this.pendingCompletionAcks.get(key);
+ this.pendingCompletionAcks.delete(key);
+ pending?.resolve(ack);
+ break;
+ }
+
case 'device_metrics_ack': {
const pending = this.pendingMetricAcks.get(message.batchId);
this.pendingMetricAcks.delete(message.batchId);
@@ -663,6 +719,10 @@ export class GatewayClient extends EventEmitter {
pending.reject(new Error('Gateway connection closed'));
}
this.pendingMetricAcks.clear();
+ for (const pending of this.pendingCompletionAcks.values()) {
+ pending.reject(new Error('Gateway connection closed'));
+ }
+ this.pendingCompletionAcks.clear();
}
private closeWebSocket() {
diff --git a/packages/device-gateway-client/src/completionWatch.test.ts b/packages/device-gateway-client/src/completionWatch.test.ts
new file mode 100644
index 00000000000..5b3c612c444
--- /dev/null
+++ b/packages/device-gateway-client/src/completionWatch.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ resolveWatchableShell,
+ watchToolCallCompletion,
+ withCompletionWatch,
+} from './completionWatch';
+
+const request = {
+ completion: { toolCallId: 'call-1' },
+ operationId: 'op-1',
+ toolCall: { apiName: 'runCommand', arguments: '{}', identifier: 'lobe-local-system' },
+};
+
+const done = { content: 'Exit code: 0', state: { exitCode: 0, running: false }, success: true };
+
+describe('resolveWatchableShell', () => {
+ it('watches a command still running after its wait window', () => {
+ expect(
+ resolveWatchableShell(request, {
+ state: { commandId: 'sh-1', running: true },
+ success: true,
+ }),
+ ).toBe('sh-1');
+ });
+
+ it('watches a background spawn', () => {
+ expect(
+ resolveWatchableShell(request, {
+ state: { commandId: 'sh-1', isBackground: true },
+ success: true,
+ }),
+ ).toBe('sh-1');
+ });
+
+ it.each([
+ ['the server did not ask', { ...request, completion: undefined }, { running: true }],
+ ['the command already exited', request, { exitCode: 0, running: false }],
+ [
+ 'it is not runCommand',
+ { ...request, toolCall: { ...request.toolCall, apiName: 'readFile' } },
+ { running: true },
+ ],
+ [
+ 'it is an MCP call',
+ { ...request, toolCall: { ...request.toolCall, type: 'mcp' as const } },
+ { running: true },
+ ],
+ ])('does not watch when %s', (_label, req, state) => {
+ expect(
+ resolveWatchableShell(req as any, { state: { commandId: 'sh-1', ...state }, success: true }),
+ ).toBeUndefined();
+ });
+
+ it('marks the reply so the server may park', () => {
+ expect(
+ withCompletionWatch({ content: '', state: { commandId: 'sh-1' }, success: true }).state,
+ ).toEqual({ commandId: 'sh-1', completionWatch: true });
+ });
+});
+
+describe('watchToolCallCompletion', () => {
+ const sleep = vi.fn(async () => {});
+ const reporter = (statuses: string[]) => {
+ const reportToolCallCompletion = vi.fn(async () => {
+ const status = statuses.shift();
+ if (!status) throw new Error('Gateway not connected');
+ return { operationId: 'op-1', status, toolCallId: 'call-1' } as any;
+ });
+ return { off: vi.fn(), on: vi.fn(), reportToolCallCompletion };
+ };
+
+ it('observes until the command ends and reports its final result', async () => {
+ const observe = vi
+ .fn()
+ .mockResolvedValueOnce({ done: false, result: { content: '', success: true } })
+ .mockResolvedValueOnce({ done: true, result: done });
+ const r = reporter(['delivered']);
+
+ const status = await watchToolCallCompletion({
+ getReporter: () => r,
+ observe,
+ operationId: 'op-1',
+ sleep,
+ toolCallId: 'call-1',
+ });
+
+ expect(status).toBe('delivered');
+ expect(observe).toHaveBeenCalledTimes(2);
+ expect(r.reportToolCallCompletion).toHaveBeenCalledWith({
+ operationId: 'op-1',
+ result: done,
+ toolCallId: 'call-1',
+ });
+ });
+
+ it('resends after a retry verdict or a dropped connection', async () => {
+ const r = reporter(['retry']);
+ r.reportToolCallCompletion
+ .mockImplementationOnce(async () => ({ status: 'retry' }) as any)
+ .mockImplementationOnce(async () => {
+ throw new Error('Gateway not connected');
+ })
+ .mockImplementationOnce(async () => ({ status: 'delivered' }) as any);
+
+ const status = await watchToolCallCompletion({
+ getReporter: () => r,
+ observe: async () => ({ done: true, result: done }),
+ operationId: 'op-1',
+ sleep,
+ toolCallId: 'call-1',
+ });
+
+ expect(status).toBe('delivered');
+ expect(r.reportToolCallCompletion).toHaveBeenCalledTimes(3);
+ });
+
+ it('stops on a rejection', async () => {
+ const r = reporter(['rejected']);
+
+ await expect(
+ watchToolCallCompletion({
+ getReporter: () => r,
+ observe: async () => ({ done: true, result: done }),
+ operationId: 'op-1',
+ sleep,
+ toolCallId: 'call-1',
+ }),
+ ).resolves.toBe('rejected');
+ expect(r.reportToolCallCompletion).toHaveBeenCalledTimes(1);
+ });
+
+ it('reports an observation failure instead of going silent', async () => {
+ const r = reporter(['delivered']);
+
+ await watchToolCallCompletion({
+ getReporter: () => r,
+ observe: async () => {
+ throw new Error('shell runtime gone');
+ },
+ operationId: 'op-1',
+ sleep,
+ toolCallId: 'call-1',
+ });
+
+ expect(r.reportToolCallCompletion).toHaveBeenCalledWith(
+ expect.objectContaining({
+ result: expect.objectContaining({ error: 'shell runtime gone', success: false }),
+ }),
+ );
+ });
+
+ it('gives up once the result is older than the server would wait', async () => {
+ const now = vi.spyOn(Date, 'now');
+ now.mockReturnValueOnce(0).mockReturnValue(10_000);
+ const r = reporter([]);
+
+ const status = await watchToolCallCompletion({
+ getReporter: () => r,
+ maxAgeMs: 5000,
+ observe: async () => ({ done: true, result: done }),
+ operationId: 'op-1',
+ sleep,
+ toolCallId: 'call-1',
+ });
+
+ expect(status).toBe('expired');
+ now.mockRestore();
+ });
+});
diff --git a/packages/device-gateway-client/src/completionWatch.ts b/packages/device-gateway-client/src/completionWatch.ts
new file mode 100644
index 00000000000..8dbfc92923d
--- /dev/null
+++ b/packages/device-gateway-client/src/completionWatch.ts
@@ -0,0 +1,158 @@
+import type {
+ ToolCallCompletionAckMessage,
+ ToolCallCompletionMessage,
+ ToolCallRequestMessage,
+ ToolCallResponseMessage,
+} from './types';
+
+type ToolResult = ToolCallResponseMessage['result'];
+
+const LOCAL_SYSTEM_IDENTIFIER = 'lobe-local-system';
+
+/** Longest a device keeps a finished result it could not deliver. */
+export const DEFAULT_COMPLETION_MAX_AGE_MS = 2 * 60 * 60 * 1000;
+const INITIAL_RETRY_DELAY_MS = 5000;
+const MAX_RETRY_DELAY_MS = 60_000;
+
+interface ShellStateShape {
+ commandId?: unknown;
+ error?: unknown;
+ exitCode?: unknown;
+ isBackground?: unknown;
+ running?: unknown;
+}
+
+/**
+ * The shell a `runCommand` reply left running, when the server asked for a
+ * late result. Mirrors the server's park predicate: a background spawn or a
+ * foreground call that outlived its wait window, never a command that already
+ * has an exit code or failed to start.
+ */
+export const resolveWatchableShell = (
+ request: Pick<ToolCallRequestMessage, 'completion' | 'operationId' | 'toolCall'>,
+ result: Pick<ToolResult, 'state' | 'success'>,
+): string | undefined => {
+ if (!request.completion?.toolCallId || !request.operationId) return undefined;
+ if (request.toolCall.type === 'mcp') return undefined;
+ if (request.toolCall.identifier !== LOCAL_SYSTEM_IDENTIFIER) return undefined;
+ if (request.toolCall.apiName !== 'runCommand') return undefined;
+ if (result.success === false) return undefined;
+
+ const state = result.state as ShellStateShape | undefined;
+ if (!state || typeof state !== 'object') return undefined;
+ if (typeof state.commandId !== 'string' || !state.commandId) return undefined;
+ if (state.error) return undefined;
+ if (state.exitCode !== undefined && state.exitCode !== null) return undefined;
+ if (state.isBackground === true || state.running === true) return state.commandId;
+ return undefined;
+};
+
+/** Mark a reply so the server knows a late result will follow and may park. */
+export const withCompletionWatch = (result: ToolResult): ToolResult => ({
+ ...result,
+ state: { ...(result.state as object), completionWatch: true },
+});
+
+export interface CompletionReporter {
+ off: (event: 'connected', listener: () => void) => unknown;
+ on: (event: 'connected', listener: () => void) => unknown;
+ reportToolCallCompletion: (
+ completion: Omit<ToolCallCompletionMessage, 'type'>,
+ ) => Promise<Omit<ToolCallCompletionAckMessage, 'type'>>;
+}
+
+export interface WatchToolCallCompletionOptions {
+ /** Resolves with the gateway client to report through; re-read on every send. */
+ getReporter: () => CompletionReporter | null | undefined;
+ logger?: { info: (...args: any[]) => void; warn: (...args: any[]) => void };
+ maxAgeMs?: number;
+ /**
+ * Wait for the command and return its answer. `done: false` means the
+ * observation window closed while it was still running β€” observe again.
+ */
+ observe: () => Promise<{ done: boolean; result: ToolResult }>;
+ operationId: string;
+ /** Test seam for the retry delay. */
+ sleep?: (ms: number, wake: Promise<void>) => Promise<void>;
+ toolCallId: string;
+}
+
+const defaultSleep = (ms: number, wake: Promise<void>) =>
+ Promise.race([new Promise<void>((resolve) => setTimeout(resolve, ms)), wake]);
+
+/**
+ * Watch a command the device left running and deliver its final result.
+ *
+ * Observation is local (the device waits on its own process), so the wait costs
+ * the server nothing. Delivery retries with backoff β€” sooner when the gateway
+ * reconnects β€” until the gateway answers `delivered` or `rejected`, or the
+ * result is older than `maxAgeMs` (the server has timed the call out by then).
+ */
+export const watchToolCallCompletion = async ({
+ getReporter,
+ logger,
+ maxAgeMs = DEFAULT_COMPLETION_MAX_AGE_MS,
+ observe,
+ operationId,
+ sleep = defaultSleep,
+ toolCallId,
+}: WatchToolCallCompletionOptions): Promise<ToolCallCompletionAckMessage['status'] | 'expired'> => {
+ const startedAt = Date.now();
+
+ let result: ToolResult;
+ for (;;) {
+ let observed: { done: boolean; result: ToolResult };
+ try {
+ observed = await observe();
+ } catch (error) {
+ // The device can no longer tell what happened to the command (the shell
+ // was cleaned up, the runtime threw). Report that rather than nothing, so
+ // the run resumes with an error instead of waiting for its timeout.
+ const message = error instanceof Error ? error.message : String(error);
+ observed = {
+ done: true,
+ result: {
+ content: `Failed to observe the command: ${message}`,
+ error: message,
+ success: false,
+ },
+ };
+ }
+ if (observed.done) {
+ result = observed.result;
+ break;
+ }
+ if (Date.now() - startedAt > maxAgeMs) return 'expired';
+ }
+
+ let delay = INITIAL_RETRY_DELAY_MS;
+ for (;;) {
+ const reporter = getReporter();
+ if (reporter) {
+ try {
+ const ack = await reporter.reportToolCallCompletion({ operationId, result, toolCallId });
+ if (ack.status !== 'retry') {
+ logger?.info(`Completion for ${toolCallId} ${ack.status}`, ack.reason ?? '');
+ return ack.status;
+ }
+ logger?.warn(`Completion for ${toolCallId} not taken yet`, ack.reason ?? '');
+ } catch (error) {
+ logger?.warn(
+ `Completion for ${toolCallId} not sent`,
+ error instanceof Error ? error.message : String(error),
+ );
+ }
+ }
+
+ if (Date.now() - startedAt > maxAgeMs) return 'expired';
+
+ let onConnected: (() => void) | undefined;
+ const wake = new Promise<void>((resolve) => {
+ onConnected = resolve;
+ reporter?.on('connected', resolve);
+ });
+ await sleep(delay, wake);
+ if (onConnected) reporter?.off('connected', onConnected);
+ delay = Math.min(delay * 2, MAX_RETRY_DELAY_MS);
+ }
+};
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index da49ac2bb5c..d40f6d0e4bd 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -11,6 +11,7 @@ import type {
DeviceSystemInfo,
GatewayDevice,
GatewayMcpParams,
+ GatewayToolCallCompletion,
GatewayToolCallType,
GatewayTunnelRegistration,
} from './types';
@@ -151,6 +152,12 @@ export class GatewayHttpClient {
* knows; otherwise `resolveClientKinds` decides from the tool identifier.
*/
clientKinds?: DeviceClient[];
+ /**
+ * Lets the device deliver this call's final result later. The gateway
+ * keeps `callbackUrl` for `ttlMs` and posts the device's
+ * `tool_call_completion` there; the device only learns `toolCallId`.
+ */
+ completion?: GatewayToolCallCompletion;
deviceId?: string;
operationId?: string;
timeout?: number;
@@ -193,6 +200,7 @@ export class GatewayHttpClient {
private async postToolCall(
params: {
clientKinds?: DeviceClient[];
+ completion?: GatewayToolCallCompletion;
deviceId?: string;
operationId?: string;
timeout?: number;
@@ -223,6 +231,7 @@ export class GatewayHttpClient {
kind: 'tool',
type: toolCall.type ?? 'tool',
}),
+ completion: params.completion,
deviceId: params.deviceId,
operationId: params.operationId,
timeout: params.timeout,
diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.ts
index 3e4f78fd221..9af05b346a9 100644
--- a/packages/device-gateway-client/src/index.ts
+++ b/packages/device-gateway-client/src/index.ts
@@ -1,5 +1,12 @@
export type { GatewayClientLogger, GatewayClientOptions } from './client';
export { GatewayClient } from './client';
+export type { CompletionReporter, WatchToolCallCompletionOptions } from './completionWatch';
+export {
+ DEFAULT_COMPLETION_MAX_AGE_MS,
+ resolveWatchableShell,
+ watchToolCallCompletion,
+ withCompletionWatch,
+} from './completionWatch';
export type {
DeviceTransportFailure,
DeviceTransportOperation,
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 6c842d144dc..4d86a207be9 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -110,7 +110,35 @@ export interface DeviceMetricsMessage {
type: 'device_metrics';
}
+/**
+ * The late, final result of a tool call whose reply said the device would keep
+ * watching it (`state.completionWatch: true`). Keyed by the call's operation
+ * and tool call ids; the gateway forwards it only for a call the server
+ * registered for completion, and answers with a {@link ToolCallCompletionAckMessage}.
+ */
+export interface ToolCallCompletionMessage {
+ operationId: string;
+ result: ToolCallResponseMessage['result'];
+ toolCallId: string;
+ type: 'tool_call_completion';
+}
+
// Server β†’ Client
+/**
+ * - `delivered`: the server took the result; stop.
+ * - `rejected`: nobody wants it any more (expired, unknown, refused); stop.
+ * - `retry`: the server could not take it yet; send the same message again later.
+ */
+export type ToolCallCompletionAckStatus = 'delivered' | 'rejected' | 'retry';
+
+export interface ToolCallCompletionAckMessage {
+ operationId: string;
+ reason?: string;
+ status: ToolCallCompletionAckStatus;
+ toolCallId: string;
+ type: 'tool_call_completion_ack';
+}
+
export interface DeviceMetricsAckMessage {
accepted: number;
batchId: string;
@@ -175,7 +203,40 @@ export type GatewayMcpParams = GatewayMcpStdioParams | GatewayMcpHttpParams;
*/
export type GatewayToolCallType = 'tool' | 'mcp';
+/**
+ * Server β†’ gateway registration for a call's late result (see
+ * {@link ToolCallCompletionMessage}). The gateway posts the device's completion
+ * to `callbackUrl` with its service token, so only the server may set it.
+ */
+export interface GatewayToolCallCompletion {
+ callbackUrl: string;
+ toolCallId: string;
+ /** How long the gateway keeps the registration; later completions are rejected. */
+ ttlMs: number;
+}
+
+/**
+ * Gateway β†’ server body posted to {@link GatewayToolCallCompletion.callbackUrl}.
+ * `userId` / `workspaceId` are the principal the call was dispatched under.
+ */
+export interface GatewayToolCallCompletionCallback {
+ deviceId: string;
+ operationId: string;
+ result: ToolCallResponseMessage['result'];
+ toolCallId: string;
+ userId?: string;
+ workspaceId?: string;
+}
+
export interface ToolCallRequestMessage {
+ /**
+ * Present when the server can take this call's final result later, as a
+ * {@link ToolCallCompletionMessage}: a `runCommand` that outlives its wait
+ * window then parks the run instead of having the model poll. The device
+ * opts in per call by answering with `state.completionWatch: true`; a device
+ * that ignores the field keeps the old reply-only behaviour.
+ */
+ completion?: { toolCallId: string };
/** Operation that triggered the call, propagated by the gateway for tracing. */
operationId?: string;
requestId: string;
@@ -514,6 +575,7 @@ export type ClientMessage =
| MessageApiResponseMessage
| RpcResponseMessage
| SystemInfoResponseMessage
+ | ToolCallCompletionMessage
| ToolCallResponseMessage
| TunnelClientFrame;
export type ServerMessage =
@@ -526,6 +588,7 @@ export type ServerMessage =
| MessageApiRequestMessage
| RpcRequestMessage
| SystemInfoRequestMessage
+ | ToolCallCompletionAckMessage
| ToolCallRequestMessage
| TunnelServerFrame;
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index 87e2922588a..a1f09365d75 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -407,6 +407,7 @@ export abstract class ComputerRuntime {
isBackground: args.background || false,
output: r.output,
outputFiles,
+ running: r.running,
sandboxed: r.sandboxed,
stderr: r.stderr,
stdout: r.stdout,
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index 0a35e6a0a2e..19b86becebf 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -274,6 +274,14 @@ export interface RunCommandState {
stderr: { path: string; size: number; truncated: boolean };
stdout: { path: string; size: number; truncated: boolean };
};
+ /**
+ * Whether the command was still executing when the observation window closed.
+ *
+ * `exitCode === undefined` is not the same signal: a command killed by a
+ * signal never reports one. Callers that decide whether to keep waiting (the
+ * server's async-shell park, the client's completion watcher) read this.
+ */
+ running?: boolean;
/**
* Whether the device sandbox actually confined this command.
*