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.

πŸ› fix(skills): surface cloud-sandbox fallback in exec APIs when the bound device is offline (#16759)

YuTengjingda9cb3d82836
diff --git a/.agents/skills/agent-tracing/SKILL.md b/.agents/skills/agent-tracing/SKILL.md
index 36d2bd2c221..b17b66b2179 100644
--- a/.agents/skills/agent-tracing/SKILL.md
+++ b/.agents/skills/agent-tracing/SKILL.md
@@ -1,6 +1,6 @@
---
name: agent-tracing
-description: 'Agent tracing CLI for execution snapshots. Use for agent-tracing, traces, snapshots, LLM call inspection, context engine data, agent step analysis, or execution debugging.'
+description: 'Agent tracing CLI for execution snapshots. Use for agent-tracing, traces, snapshots, LLM call inspection, context engine data, agent step analysis, execution debugging, or pulling remote/production traces ("ζ‹‰ηΊΏδΈŠ tracing") by operation id.'
user-invocable: false
---
@@ -41,8 +41,37 @@ packages/agent-tracing/
- Completed snapshots: `.agent-tracing/{ISO-timestamp}_{traceId-short}.json`
- Latest symlink: `.agent-tracing/latest.json`
- In-progress partials: `.agent-tracing/_partial/{operationId}.json`
+- Downloaded remote snapshots: `.agent-tracing/_remote/{operationId}.json`
- `FileSnapshotStore` resolves from `process.cwd()` β€” **run CLI from the repo root**
+## Remote Traces (Production / Staging)
+
+Server deployments also upload completed snapshots to object storage (zstd-compressed; the key is stored in `agent_operations.trace_s3_key`). `agent-tracing inspect <operationId>` transparently downloads, decompresses, and caches them β€” no manual S3 access needed.
+
+1. **Find the operation id** from a business id (users usually hand you a topic id):
+
+ ```sql
+ SELECT id, trace_s3_key FROM agent_operations WHERE topic_id = 'tpc_xxx';
+ ```
+
+ `trace_s3_key IS NULL` means no snapshot was recorded; a non-null key can still 404 in storage (retention/TTL).
+
+2. **Configure the base URL** β€” the bucket's public domain plus the `/agent-traces` prefix β€” either way:
+
+ - env var: `TRACING_BASE_URL=https://<bucket-public-domain>/agent-traces`
+ - file: `.agent-tracing/.env` in the repo root containing the same `TRACING_BASE_URL=...` line
+
+ The deployment-specific value is private to each deployment and intentionally not recorded in this repo.
+
+3. **Inspect by operation id** β€” auto-detected by the `op_..._agt_..._tpc_...` shape; the snapshot is cached to `.agent-tracing/_remote/<opId>.json` and every `inspect` flag works the same as for local traces:
+
+ ```bash
+ agent-tracing inspect op_xxx_agt_xxx_tpc_xxx_xxxx # step tree of a production run
+ agent-tracing inspect op_xxx_agt_xxx_tpc_xxx_xxxx -T # tool injection (enabledToolIds, manifests)
+ ```
+
+Implementation: `packages/agent-tracing/src/store/remote-store.ts` (URL is built from the operation id as `{base}/{agentId}/{topicId}/{opId}.json.zst`).
+
## CLI Commands
All commands run from the **repo root**:
@@ -112,7 +141,7 @@ agent-tracing partial clean
| `--step <n>` | `-s` | Target a specific step | β€” |
| `--messages` | `-m` | Messages context (CE input β†’ params β†’ LLM payload) | β€” |
| `--tools` | `-t` | Tool calls & results (what agent invoked) | β€” |
-| `--events` | `-e` | Raw events (llm_start, llm_result, etc.) | β€” |
+| `--events` | `-e` | Raw events (llm\_start, llm\_result, etc.) | β€” |
| `--context` | `-c` | Runtime context & payload (raw) | β€” |
| `--system-role` | `-r` | Full system role content | 0 |
| `--env` | | Environment context | 0 |
@@ -168,12 +197,7 @@ interface ExecutionSnapshot {
startedAt: number;
completedAt?: number;
completionReason?:
- | 'done'
- | 'error'
- | 'interrupted'
- | 'max_steps'
- | 'cost_limit'
- | 'waiting_for_human';
+ 'done' | 'error' | 'interrupted' | 'max_steps' | 'cost_limit' | 'waiting_for_human';
totalSteps: number;
totalTokens: number;
totalCost: number;
diff --git a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
index a4b0ed626c6..f9ccd196ff5 100644
--- a/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
+++ b/apps/server/src/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts
@@ -6,6 +6,7 @@ import { LobeAgentApiName, LobeAgentManifest } from '@lobechat/builtin-tool-lobe
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { MemoryManifest } from '@lobechat/builtin-tool-memory';
import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
+import { SkillsApiName, SkillsManifest } from '@lobechat/builtin-tool-skills';
import { WebBrowsingManifest } from '@lobechat/builtin-tool-web-browsing';
import { builtinTools } from '@lobechat/builtin-tools';
import { ToolsEngine } from '@lobechat/context-engine';
@@ -319,6 +320,34 @@ describe('createServerAgentToolsEngine', () => {
expect(lobeAgent?.api.map((a) => a.name)).not.toContain(LobeAgentApiName.callSubAgent);
});
+ it('rewrites lobe-skills exec descriptions when manifestContext.executionEnv is device-unrouted', () => {
+ const context = createMockContext();
+ const engine = createServerAgentToolsEngine(context, {
+ agentConfig: { plugins: [] },
+ manifestContext: {
+ executionEnv: 'device-unrouted',
+ executionEnvUnroutedReason: 'bound-device-offline',
+ },
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ });
+
+ const result = engine.generateToolsDetailed({
+ model: 'deepseek-chat',
+ provider: 'deepseek',
+ toolIds: [],
+ });
+
+ // lobe-skills is always-on, so the resolved manifest is what the model sees.
+ const skills = result.enabledManifests.find((m) => m.identifier === SkillsManifest.identifier);
+ const runCommand = skills?.api.find((a) => a.name === SkillsApiName.runCommand);
+ expect(runCommand?.description).toContain('local device but it is offline');
+ // without a manifest context the static description has no offline warning
+ expect(
+ SkillsManifest.api.find((a) => a.name === SkillsApiName.runCommand)?.description,
+ ).not.toContain('offline');
+ });
+
it('hides lobe-agent callSubAgent inside a group run (scope=group)', () => {
const context = createMockContext();
const engine = createServerAgentToolsEngine(context, {
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index a76e6969586..bea7b471268 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -2492,6 +2492,22 @@ export class AiAgentService {
executionPlan.kind,
activeDeviceId ?? 'none',
);
+ // A device-targeted run that could not be routed silently degrades exec
+ // (lobe-skills runCommand/execScript) to the cloud sandbox. Surface it as
+ // a structured warn β€” `bound-device-offline` with a requestedDeviceId is
+ // the desktop "local device" pick whose gateway connection dropped, and
+ // this log is the breadcrumb for diagnosing WHY the device was judged
+ // offline (lazy WS connect vs getScopedOnlineDevices failing silently).
+ if (executionPlan.kind === 'device-unrouted') {
+ console.warn('[AiAgentService] device-unrouted: exec degrades to cloud sandbox', {
+ boundDeviceId,
+ onlineDeviceCount: onlineDevices.length,
+ reason: executionPlan.reason,
+ requestedDeviceId,
+ topicId,
+ userId: this.userId,
+ });
+ }
// Resolve the operation's group context ONCE here and snapshot it into op
// metadata below β€” the per-step context engine reads it back without a DB
@@ -2556,7 +2572,14 @@ export class AiAgentService {
// lobe-agent drops `callSubAgent` so the model can't recurse into nested
// sub-agents (which the runtime rejects, looping until the inactivity
// watchdog kills the op). Mirrors the frontend `createAgentToolsEngine`.
+ // `executionEnv` mirrors the resolved plan so exec-capable tools
+ // (lobe-skills) can state where their commands actually run β€” most
+ // importantly the `device-unrouted` degradation, where the user picked
+ // a local device that is offline and exec silently lands in the sandbox.
manifestContext: {
+ executionEnv: executionPlan.kind,
+ executionEnvUnroutedReason:
+ executionPlan.kind === 'device-unrouted' ? executionPlan.reason : undefined,
isSubAgent: appContext?.isSubAgent,
scope: appContext?.scope ?? undefined,
},
diff --git a/packages/builtin-skills/src/agent-browser/content.ts b/packages/builtin-skills/src/agent-browser/content.ts
index b80b619f319..0ab7bb80acd 100644
--- a/packages/builtin-skills/src/agent-browser/content.ts
+++ b/packages/builtin-skills/src/agent-browser/content.ts
@@ -3,7 +3,7 @@ export const systemPrompt = `<agent_browser_guides>
\`agent-browser\` is a fast browser automation CLI for AI agents β€” drives Chrome/Chromium via CDP and serves accessibility-tree snapshots with compact \`@eN\` element refs (so you act on the page in a few hundred tokens, not raw HTML).
-LobeHub desktop bundles \`agent-browser\` natively β€” no install needed. Outside LobeHub, install with \`npm i -g agent-browser\` (or \`brew install agent-browser\` / \`cargo install agent-browser\`), then run \`agent-browser install\` once to fetch the bundled Chrome.
+LobeHub desktop bundles \`agent-browser\` natively β€” no install needed. \`agent-browser\` lives on the user's device: when \`lobe-local-system\` runCommand is available, run all \`agent-browser\` commands through it β€” never through the skills exec APIs (their cloud sandbox has no browser and no \`agent-browser\` binary). Outside LobeHub, install with \`npm i -g agent-browser\` (or \`brew install agent-browser\` / \`cargo install agent-browser\`), then run \`agent-browser install\` once to fetch the bundled Chrome.
## The core loop
@@ -16,6 +16,8 @@ agent-browser snapshot -i # 4. re-snapshot after any page change
Refs become **stale on every page change** (click that navigates, form submit, dynamic re-render, dialog open). Always re-snapshot before the next ref interaction.
+When the task is done, run \`agent-browser close\` and quit any Chrome you launched for CDP β€” browsers opened for the task otherwise stay on the user's machine.
+
## Dynamic pages & anti-bot escalation
When scraping dynamic or anti-bot pages, escalate from cheap to heavy and stop at the first rung that yields real content:
@@ -24,7 +26,7 @@ When scraping dynamic or anti-bot pages, escalate from cheap to heavy and stop a
2. **Empty body, verification page, or obfuscated JS** β†’ the page needs a real JS run: \`agent-browser open <url>\`, \`agent-browser wait --load networkidle\`, then \`agent-browser read\` (or \`snapshot\`).
3. **Still blocked** (anti-bot that fingerprints headless Chrome) β†’ connect to a real browser: launch Chrome with \`--remote-debugging-port=9222\` (Chrome 136+ also requires a separate \`--user-data-dir\`), then drive it with \`agent-browser --cdp 9222 <command>\` β€” a real browser fingerprint usually passes in one go.
-Discipline: the crux of anti-bot checks is "did a real browser execute the JS", so the closer to a human environment, the easier it passes. Verify you actually got content with \`agent-browser eval "document.body.innerText.length"\` (0 means blocked). Dump large output to a file first, then \`grep\`/\`head\` it. Close the debug-port browser session when done.
+Discipline: the crux of anti-bot checks is "did a real browser execute the JS", so the closer to a human environment, the easier it passes. Verify you actually got content with \`agent-browser eval "document.body.innerText.length"\` (0 means blocked). Dump large output to a file first, then \`grep\`/\`head\` it.
## Discovering everything else
diff --git a/packages/builtin-tool-activator/src/systemRole.ts b/packages/builtin-tool-activator/src/systemRole.ts
index a3562a969c4..5fd754a917e 100644
--- a/packages/builtin-tool-activator/src/systemRole.ts
+++ b/packages/builtin-tool-activator/src/systemRole.ts
@@ -83,15 +83,14 @@ export const systemPrompt = `You have access to a Tools Activator that allows yo
**Important:**
- Never ask users to paste API keys directly in chat β€” always use \`lobe-creds\` to store them securely
-- \`lobe-creds\` works together with \`lobe-cloud-sandbox\` for secure credential injection
-**Credential Usage by Runtime:**
+**Credential Usage by Runtime (sandbox mode: {{sandbox_enabled}}):**
-In cloud sandbox (\`injectCredsToSandbox\` available):
+When sandbox mode is true (\`lobe-cloud-sandbox\` present, \`injectCredsToSandbox\` available):
- Environment-based credentials (oauth, kv-env, kv-header) β†’ \`~/.creds/env\` β€” use \`runCommand\` with \`bash -c "source ~/.creds/env && your_command"\`
- File-based credentials β†’ \`~/.creds/files/{key}/{filename}\` β€” use file path directly in your code
-On desktop/local (no sandbox, \`injectCredsToSandbox\` NOT available):
+When sandbox mode is false (\`lobe-cloud-sandbox\` does not exist in this session β€” do not look for it or offer to activate it):
- Use \`getPlaintextCred\` to retrieve values, then pass as inline env vars in \`runCommand\`
- Example: \`runCommand({ command: "GITHUB_TOKEN='xxx' gh repo list" })\`
- File credentials: use \`getPlaintextCred\` to get the file path from the response state
diff --git a/packages/builtin-tool-skills/src/index.ts b/packages/builtin-tool-skills/src/index.ts
index ebac11ed0ba..446eb4e654e 100644
--- a/packages/builtin-tool-skills/src/index.ts
+++ b/packages/builtin-tool-skills/src/index.ts
@@ -1,4 +1,5 @@
export { SkillsManifest } from './manifest';
+export { resolveSkillsManifest } from './resolveManifest';
export { systemPrompt } from './systemRole';
export {
type ActivateSkillParams,
diff --git a/packages/builtin-tool-skills/src/resolveManifest.test.ts b/packages/builtin-tool-skills/src/resolveManifest.test.ts
new file mode 100644
index 00000000000..08528f77c1e
--- /dev/null
+++ b/packages/builtin-tool-skills/src/resolveManifest.test.ts
@@ -0,0 +1,136 @@
+import { describe, expect, it } from 'vitest';
+
+import { SkillsManifest } from './manifest';
+import { resolveSkillsManifest } from './resolveManifest';
+import { systemPrompt } from './systemRole';
+import { SkillsApiName } from './types';
+
+const EXEC_APIS = [SkillsApiName.runCommand, SkillsApiName.execScript, SkillsApiName.exportFile];
+const NON_EXEC_APIS = [SkillsApiName.activateSkill, SkillsApiName.readReference];
+
+const apiByName = (
+ manifest: { api: { description: string; humanIntervention?: unknown; name: string }[] },
+ name: string,
+) => manifest.api.find((a) => a.name === name)!;
+
+describe('resolveSkillsManifest', () => {
+ it('returns the static manifest reference when no executionEnv is set', () => {
+ expect(resolveSkillsManifest({})).toBe(SkillsManifest);
+ expect(resolveSkillsManifest({ isSubAgent: true, scope: 'main' })).toBe(SkillsManifest);
+ });
+
+ it.each(['local', 'none'] as const)(
+ 'returns the static manifest reference for executionEnv %s',
+ (executionEnv) => {
+ expect(resolveSkillsManifest({ executionEnv })).toBe(SkillsManifest);
+ },
+ );
+
+ it('prefixes exec APIs with the fallback framing when a device is online', () => {
+ const result = resolveSkillsManifest({ executionEnv: 'device' })!;
+
+ for (const name of EXEC_APIS) {
+ const description = apiByName(result, name).description;
+ expect(description).toMatch(/^Fallback execution environment: an isolated cloud sandbox/);
+ expect(description).toContain('GITHUB_TOKEN');
+ // the original mechanics stay after the preamble
+ expect(description).toContain(apiByName(SkillsManifest, name).description);
+ }
+ // cross-tool arbitration rides the tool systemRole, not the descriptions
+ expect(result.systemRole).toContain(systemPrompt);
+ expect(result.systemRole).toContain(
+ 'Default shell execution to `lobe-local-system` runCommand',
+ );
+ });
+
+ it.each(['bound-device-offline', 'no-online-device'] as const)(
+ 'warns about the offline device when device-unrouted for %s',
+ (executionEnvUnroutedReason) => {
+ const result = resolveSkillsManifest({
+ executionEnv: 'device-unrouted',
+ executionEnvUnroutedReason,
+ })!;
+
+ for (const name of EXEC_APIS) {
+ const description = apiByName(result, name).description;
+ expect(description).toMatch(/^Fallback execution environment: an isolated cloud sandbox/);
+ expect(description).toContain('local device but it is offline');
+ }
+ // the offline fact rides the tool systemRole into the prompt
+ expect(result.systemRole).toContain(systemPrompt);
+ expect(result.systemRole).toContain(
+ 'Bound device offline; shell commands execute in the cloud sandbox this run.',
+ );
+ },
+ );
+
+ it.each(['no-bound-device', 'ambiguous-online-devices'] as const)(
+ 'steers toward device selection when device-unrouted for %s',
+ (executionEnvUnroutedReason) => {
+ const result = resolveSkillsManifest({
+ executionEnv: 'device-unrouted',
+ executionEnvUnroutedReason,
+ })!;
+
+ for (const name of EXEC_APIS) {
+ const description = apiByName(result, name).description;
+ expect(description).toMatch(/^Fallback execution environment: an isolated cloud sandbox/);
+ expect(description).toContain('No local device is selected yet');
+ expect(description).not.toContain('offline');
+ }
+ expect(result.systemRole).toContain(systemPrompt);
+ expect(result.systemRole).toContain('select a device via the remote-device tool');
+ expect(result.systemRole).not.toContain('Bound device offline');
+ },
+ );
+
+ it('keeps reason-neutral wording when device-unrouted has no reason', () => {
+ const result = resolveSkillsManifest({ executionEnv: 'device-unrouted' })!;
+
+ for (const name of EXEC_APIS) {
+ const description = apiByName(result, name).description;
+ expect(description).toContain('no device is routed this run');
+ expect(description).not.toContain('offline');
+ }
+ expect(result.systemRole).toContain(
+ 'No local device is routed; shell commands execute in the cloud sandbox this run.',
+ );
+ });
+
+ it('clarifies the sandbox location for an explicit sandbox target', () => {
+ const result = resolveSkillsManifest({ executionEnv: 'sandbox' })!;
+
+ for (const name of EXEC_APIS) {
+ const description = apiByName(result, name).description;
+ expect(description).toMatch(
+ /^Execution environment: an isolated cloud sandbox, not the user's machine\./,
+ );
+ }
+ expect(result.systemRole).toBe(systemPrompt);
+ });
+
+ it.each(['device', 'device-unrouted', 'sandbox'] as const)(
+ 'keeps non-exec APIs, api shape, and humanIntervention intact for %s',
+ (executionEnv) => {
+ const result = resolveSkillsManifest({ executionEnv })!;
+
+ expect(result.api.map((a) => a.name)).toEqual(SkillsManifest.api.map((a) => a.name));
+ for (const name of NON_EXEC_APIS) {
+ expect(apiByName(result, name)).toBe(apiByName(SkillsManifest, name));
+ }
+ for (const name of [SkillsApiName.runCommand, SkillsApiName.execScript]) {
+ expect(apiByName(result, name).humanIntervention).toBe('required');
+ }
+ expect(result.identifier).toBe(SkillsManifest.identifier);
+ },
+ );
+
+ it('does not mutate the static manifest', () => {
+ const staticDescriptions = SkillsManifest.api.map((a) => a.description);
+
+ resolveSkillsManifest({ executionEnv: 'device-unrouted' });
+
+ expect(SkillsManifest.api.map((a) => a.description)).toEqual(staticDescriptions);
+ expect(SkillsManifest.systemRole).toBe(systemPrompt);
+ });
+});
diff --git a/packages/builtin-tool-skills/src/resolveManifest.ts b/packages/builtin-tool-skills/src/resolveManifest.ts
new file mode 100644
index 00000000000..03bea38a30b
--- /dev/null
+++ b/packages/builtin-tool-skills/src/resolveManifest.ts
@@ -0,0 +1,125 @@
+import type { BuiltinManifestResolver, BuiltinToolResolveContext } from '@lobechat/types';
+
+import { SkillsManifest } from './manifest';
+import { SkillsApiName } from './types';
+
+/**
+ * The exec-class APIs whose runtime is the server-side cloud sandbox
+ * (`apps/server/.../serverRuntimes/skills.ts`), regardless of the run's
+ * execution target. Their static descriptions never say where they run, so a
+ * desktop user who picked "local device" can have commands silently land in
+ * the sandbox β€” most damagingly when the bound device is judged offline and
+ * `lobe-local-system` is not injected at all (plan kind `device-unrouted`).
+ */
+const EXEC_API_NAMES = new Set<string>([
+ SkillsApiName.execScript,
+ SkillsApiName.exportFile,
+ SkillsApiName.runCommand,
+]);
+
+/**
+ * Per-environment description preambles for the exec-class APIs. Descriptions
+ * carry tool semantics only (where it runs, what credentials it has);
+ * cross-tool arbitration lives in `EXEC_ENV_FACTS`.
+ *
+ * - `device`: a local device is online β€” the sandbox is the FALLBACK.
+ * Credential fact: `injectCredsToSandbox` only injects into the sandbox;
+ * devices deliberately get nothing.
+ * - `device-unrouted`: the user chose local-device execution but no device is
+ * routed this run β€” the model must disclose that instead of silently
+ * running machine-specific commands in the sandbox. Wording varies by
+ * unrouted reason (see `resolveUnroutedTexts`).
+ * - `sandbox`: explicit sandbox target β€” current semantics, just made
+ * unambiguous that it is not the user's machine.
+ *
+ * `local` / `none` (and no context) keep the static manifest untouched.
+ */
+const EXEC_ENV_PREAMBLES: Partial<
+ Record<NonNullable<BuiltinToolResolveContext['executionEnv']>, string>
+> = {
+ 'device':
+ "Fallback execution environment: an isolated cloud sandbox, not the user's machine (LobeHub-managed credentials injected, e.g. `GITHUB_TOKEN`).",
+ 'device-unrouted':
+ 'Fallback execution environment: an isolated cloud sandbox. The user chose local-device execution but no device is routed this run β€” say so before running commands that assume their machine.',
+ 'sandbox': "Execution environment: an isolated cloud sandbox, not the user's machine.",
+};
+
+/**
+ * Environment facts appended to the tool systemRole. Cross-tool arbitration
+ * (which runCommand to default to) belongs here, not in the API descriptions:
+ * descriptions get skimmed once the tool list is long, and a "prefer the
+ * other tool" rule written on the tool NOT to pick is read too late β€” only
+ * when the model is already considering it.
+ */
+const EXEC_ENV_FACTS: Partial<
+ Record<NonNullable<BuiltinToolResolveContext['executionEnv']>, string>
+> = {
+ 'device':
+ 'A local device is online. Default shell execution to `lobe-local-system` runCommand; use the skills exec APIs only when the local run lacks a required tool, the task needs LobeHub-managed credentials, or the task needs isolation.',
+ 'device-unrouted':
+ 'No local device is routed; shell commands execute in the cloud sandbox this run.',
+};
+
+/**
+ * `device-unrouted` covers four reasons (`ExecutionPlanUnroutedReason`) that
+ * split into two truths: the device the user counts on is OFFLINE
+ * (`bound-device-offline` / `no-online-device`), vs a device is still
+ * SELECTABLE (`no-bound-device` / `ambiguous-online-devices` β€” the
+ * remote-device picker is active, so the prompt must steer toward selecting
+ * one rather than declaring the device dead). Reason absent β†’ keep the
+ * neutral defaults above, which are true for all four.
+ */
+const resolveUnroutedTexts = (
+ reason: BuiltinToolResolveContext['executionEnvUnroutedReason'],
+): { fact?: string; preamble?: string } => {
+ switch (reason) {
+ case 'bound-device-offline':
+ case 'no-online-device': {
+ return {
+ fact: 'Bound device offline; shell commands execute in the cloud sandbox this run.',
+ preamble:
+ 'Fallback execution environment: an isolated cloud sandbox. The user chose their local device but it is offline β€” say so before running commands that assume their machine.',
+ };
+ }
+ case 'ambiguous-online-devices':
+ case 'no-bound-device': {
+ return {
+ fact: "No local device is selected yet (devices may be online). If the task needs the user's machine, select a device via the remote-device tool first; until then, shell commands execute in the cloud sandbox.",
+ preamble:
+ "Fallback execution environment: an isolated cloud sandbox. No local device is selected yet β€” if the task needs the user's machine, select an online device first instead of running machine-specific commands here.",
+ };
+ }
+ default: {
+ return {};
+ }
+ }
+};
+
+/**
+ * Context-aware manifest for the lobe-skills tool: prefixes the exec-class API
+ * descriptions with where they actually run, derived from the resolved
+ * execution plan (see `BuiltinToolResolveContext.executionEnv`).
+ */
+export const resolveSkillsManifest: BuiltinManifestResolver = (context) => {
+ const basePreamble = context.executionEnv && EXEC_ENV_PREAMBLES[context.executionEnv];
+ if (!basePreamble) return SkillsManifest;
+
+ const unrouted =
+ context.executionEnv === 'device-unrouted'
+ ? resolveUnroutedTexts(context.executionEnvUnroutedReason)
+ : {};
+ const preamble = unrouted.preamble ?? basePreamble;
+ const fact = unrouted.fact ?? (context.executionEnv && EXEC_ENV_FACTS[context.executionEnv]);
+
+ return {
+ ...SkillsManifest,
+ api: SkillsManifest.api.map((api) =>
+ EXEC_API_NAMES.has(api.name)
+ ? { ...api, description: `${preamble} ${api.description}` }
+ : api,
+ ),
+ ...(fact && {
+ systemRole: `${SkillsManifest.systemRole}\n<execution_environment>\n${fact}\n</execution_environment>\n`,
+ }),
+ };
+};
diff --git a/packages/builtin-tool-skills/src/systemRole.ts b/packages/builtin-tool-skills/src/systemRole.ts
index 5360430c3ac..f7477753c45 100644
--- a/packages/builtin-tool-skills/src/systemRole.ts
+++ b/packages/builtin-tool-skills/src/systemRole.ts
@@ -31,6 +31,7 @@ export const systemPrompt = `You have access to a Skills tool that can activate
- **runCommand**: Call this to execute shell commands in the cloud sandbox
- Use for general CLI commands, platform tools (e.g., \`lh\` CLI), and ad-hoc operations
+ - If \`lobe-local-system\` runCommand is also available, default shell execution to it β€” use this sandbox runCommand only when the task needs LobeHub-managed credentials, isolation, or a tool missing on the local device
- Provide the command to execute and a clear description of what it does
- Returns the command output (stdout/stderr) and exit code
- Requires user confirmation before execution
@@ -52,7 +53,7 @@ export const systemPrompt = `You have access to a Skills tool that can activate
<runcommand_vs_execscript>
**When to use runCommand vs execScript:**
-- **runCommand (Default for most commands)**:
+- **runCommand (default of the two)**:
- Use for general shell commands and CLI tools (e.g., \`lh kb list\`, \`npm install\`)
- Use for platform tool commands (LobeHub CLI, etc.)
- No skill context needed β€” just provide the command
diff --git a/packages/builtin-tool-web-browsing/src/systemRole.ts b/packages/builtin-tool-web-browsing/src/systemRole.ts
index 9ac015e9628..e3e7025cb02 100644
--- a/packages/builtin-tool-web-browsing/src/systemRole.ts
+++ b/packages/builtin-tool-web-browsing/src/systemRole.ts
@@ -114,8 +114,7 @@ Our search service is a metasearch engine with automatic engine selection. Provi
2. Consider trying alternative categories or query terms.
3. If the search was language-specific and failed (especially for technical, scientific, or non-regional topics), try rewriting the query or searching again using English.
4. If needed, explain the issue to the user and suggest alternative search terms or strategies.
-- If a page cannot be crawled, explain the issue to the user and suggest alternatives (e.g., trying a different source from search results).
-- If a crawled page returns an empty body, a verification/challenge page, or mostly obfuscated JavaScript, the page requires a real browser to execute its JS β€” do NOT keep retrying with different queries or sources. When the agent-browser skill is available, activate it and re-fetch the page with headless Chrome instead.
+- If a crawl fails (error, timeout, blocked) or returns an empty body, a verification/challenge page, or mostly obfuscated JavaScript, the page needs a real browser β€” do NOT keep retrying with different queries or sources. When the agent-browser skill is available, activate it and re-fetch the page with it. Exception: a definitively dead link (HTTP 404/410, non-existent domain) won't open in a browser either β€” skip escalation and try a different source. When in doubt, escalate: anti-bot walls often masquerade as timeouts or generic errors. Only when no browser path exists, explain the issue to the user and suggest alternatives (e.g., trying a different source from search results).
- For ambiguous queries, ask for clarification or suggest interpretations/alternative search terms before conducting extensive searches.
- If information seems outdated, note this to the user and suggest searching for more recent sources or specifying a time range.
</error_handling>
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 62e061fff78..4f205dfe2de 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -25,7 +25,7 @@ import { RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import { selfFeedbackIntentManifest } from '@lobechat/builtin-tool-self-iteration';
import { SkillMaintainerManifest } from '@lobechat/builtin-tool-skill-maintainer';
import { SkillStoreManifest } from '@lobechat/builtin-tool-skill-store';
-import { SkillsManifest } from '@lobechat/builtin-tool-skills';
+import { resolveSkillsManifest, SkillsManifest } from '@lobechat/builtin-tool-skills';
import { TaskManifest } from '@lobechat/builtin-tool-task';
import { TopicReferenceManifest } from '@lobechat/builtin-tool-topic-reference';
import { UserInteractionManifest } from '@lobechat/builtin-tool-user-interaction';
@@ -169,6 +169,10 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
hidden: true,
identifier: SkillsManifest.identifier,
manifest: SkillsManifest,
+ // Context-aware: prefixes exec-class API descriptions with the run's
+ // actual execution environment (cloud sandbox as fallback / offline
+ // degradation), so the model never assumes they run on the user's machine.
+ resolveManifest: resolveSkillsManifest,
type: 'builtin',
},
{
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 0d96e4785c3..8c338b731d4 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -172,6 +172,10 @@ export class GatewayClient extends EventEmitter {
}
async disconnect(): Promise<void> {
+ // Explicit log so a permanent stop (e.g. the auth_failed path calls
+ // disconnect()) is provable from logs instead of inferred from the
+ // absence of later reconnect lines.
+ this.logger.info('Intentional disconnect; auto-reconnect disabled');
this.intentionalDisconnect = true;
this.cleanup();
this.setStatus('disconnected');
@@ -270,10 +274,27 @@ export class GatewayClient extends EventEmitter {
return `${wsProtocol}://${host}/ws?${params.toString()}`;
}
+ /**
+ * Best-effort JWT `exp` readout for auth logs. Internal backoff/heartbeat
+ * reconnects reuse `this.token`, so whether the token was already expired
+ * at auth time is the deciding fact when diagnosing auth failures from
+ * logs. Never logs the token itself.
+ */
+ private describeTokenExpiry(): string {
+ try {
+ const payload = JSON.parse(Buffer.from(this.token.split('.')[1], 'base64url').toString());
+ if (typeof payload.exp !== 'number') return 'token exp: none';
+ const expired = Date.now() >= payload.exp * 1000;
+ return `token exp: ${new Date(payload.exp * 1000).toISOString()}${expired ? ' (EXPIRED)' : ''}`;
+ } catch {
+ return 'token exp: unparsable';
+ }
+ }
+
// ─── WebSocket Event Handlers ───
private handleOpen = () => {
- this.logger.info('WebSocket connected, sending auth...');
+ this.logger.info(`WebSocket connected, sending auth... (${this.describeTokenExpiry()})`);
this.reconnectDelay = INITIAL_RECONNECT_DELAY;
this.setStatus('authenticating');
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 113fd25d251..050cfef75f7 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -125,8 +125,7 @@ export const DynamicInterventionConfigSchema = z.object({
* Extended human intervention config that supports dynamic evaluation
*/
export type ExtendedHumanInterventionConfig =
- | HumanInterventionConfig
- | { dynamic: DynamicInterventionConfig };
+ HumanInterventionConfig | { dynamic: DynamicInterventionConfig };
export const ExtendedHumanInterventionConfigSchema = z.union([
HumanInterventionConfigSchema,
@@ -246,6 +245,25 @@ export const BuiltinToolManifestSchema = z.object({
* more tools migrate their context-based trimming here.
*/
export interface BuiltinToolResolveContext {
+ /**
+ * Where this run executes, mirroring the resolved `ExecutionPlan.kind`
+ * (`device` / `device-unrouted` / `sandbox` / `none`) plus `local` for the
+ * desktop in-process engine. Lets exec-capable tools (e.g. lobe-skills)
+ * rewrite their API descriptions per environment β€” most notably
+ * `device-unrouted`, where the user picked their local device but it is
+ * offline and commands silently fall back to the cloud sandbox. Kept as a
+ * plain union to avoid coupling the tool layer to the execution-plan types.
+ */
+ executionEnv?: 'device' | 'device-unrouted' | 'local' | 'none' | 'sandbox';
+ /**
+ * Why a `device-unrouted` plan failed to route, mirroring
+ * `ExecutionPlanUnroutedReason` (`src/helpers/executionTarget.ts`). Only set
+ * when `executionEnv` is `device-unrouted`. Offline reasons and
+ * still-selectable reasons (unbound / several devices online, where the
+ * remote-device picker is active) need different prompt wording.
+ */
+ executionEnvUnroutedReason?:
+ 'ambiguous-online-devices' | 'bound-device-offline' | 'no-bound-device' | 'no-online-device';
/**
* True when running inside a sub-agent execution. A nested sub-agent must not
* be able to dispatch further sub-agents.