{
  "schemaVersion": "1.0",
  "item": {
    "slug": "agent-mode-upgrades",
    "name": "Agentic Mode Upgrades",
    "source": "tencent",
    "type": "skill",
    "category": "AI 智能",
    "sourceUrl": "https://clawhub.ai/maverick-software/agent-mode-upgrades",
    "canonicalUrl": "https://clawhub.ai/maverick-software/agent-mode-upgrades",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/agent-mode-upgrades",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=agent-mode-upgrades",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "SECURITY.md",
      "SKILL.md",
      "README.md",
      "skill.json",
      "INSTRUCTIONS.md",
      "src/openclaw-hook.ts"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-23T16:43:11.935Z",
      "expiresAt": "2026-04-30T16:43:11.935Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=4claw-imageboard",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=4claw-imageboard",
        "contentDisposition": "attachment; filename=\"4claw-imageboard-1.0.1.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/agent-mode-upgrades"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/agent-mode-upgrades",
    "agentPageUrl": "https://openagent3.xyz/skills/agent-mode-upgrades/agent",
    "manifestUrl": "https://openagent3.xyz/skills/agent-mode-upgrades/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/agent-mode-upgrades/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "Enhanced Agentic Loop Skill",
        "body": "A comprehensive upgrade to OpenClaw's agentic capabilities with persistent state, automatic planning, approval gates, retry logic, context management, checkpointing, knowledge graph auto-injection, and channel-aware plan rendering.\n\n📋 Security review? See SECURITY.md for a complete trust and capability audit document including network activity, file write scope, credential handling, and rollback instructions."
      },
      {
        "title": "Security & Trust Summary",
        "body": "PropertyValueOutbound networkLLM provider only (inherited from host)Telemetry / phone-home❌ NoneSystem prompt modification✅ Additive-only (appends plan status; never replaces core prompt)Runner wrapping✅ Transparent (original runner always called; interceptions logged)Credential storage❌ None (inherits host agent auth, stores nothing new)PersistenceLocal ~/.openclaw/ onlyEnabled by default❌ No — explicit opt-in requiredApproval gates default✅ On for high/critical risk operations"
      },
      {
        "title": "Status: ✅ Active (v2.3.0)",
        "body": "All components are integrated and working.\n\nComponentStatusMode Dashboard UI✅ WorkingConfiguration System✅ WorkingHook/Wrapper Integration✅ WorkingState Machine✅ WorkingPlanning Layer✅ WorkingParallel Execution✅ WorkingConfidence Gates✅ WorkingError Recovery✅ WorkingCheckpointing✅ WorkingMemory Auto-Inject✅ Working (v2)Discord Plan Rendering✅ Working (v2)"
      },
      {
        "title": "1. Persistent Plan State",
        "body": "Plans survive across conversation turns. The agent knows where it left off.\n\nimport { getStateManager } from \"@openclaw/enhanced-loop\";\n\nconst state = getStateManager();\nawait state.init(sessionId);\n\n// Plan persists in ~/.openclaw/agent-state/{sessionId}.json\nstate.setPlan(plan);\nstate.completeStep(\"step_1\", \"Files created\");\nconst progress = state.getProgress(); // { completed: 1, total: 5, percent: 20 }"
      },
      {
        "title": "2. Automatic Step Completion Detection",
        "body": "Analyzes tool results to determine if plan steps are complete.\n\nimport { createStepTracker } from \"@openclaw/enhanced-loop\";\n\nconst tracker = createStepTracker(stateManager);\n\n// After each tool execution\nconst analysis = await tracker.analyzeToolResult(tool, result);\nif (analysis.isComplete) {\n  console.log(`Step done: ${analysis.suggestedResult}`);\n}"
      },
      {
        "title": "3. Tool Approval Gates with Timeout",
        "body": "Risky operations pause for human approval, but auto-proceed after N seconds.\n\nimport { getApprovalGate } from \"@openclaw/enhanced-loop\";\n\nconst gate = getApprovalGate({\n  enabled: true,\n  timeoutMs: 15000, // 15 seconds to respond\n  requireApprovalFor: [\"high\", \"critical\"],\n  onApprovalNeeded: (request) => {\n    // Notify user: \"⚠️ Approve rm -rf? Auto-proceeding in 15s...\"\n  },\n});\n\n// Before risky tool execution\nif (gate.requiresApproval(tool)) {\n  const result = await gate.requestApproval(tool);\n  if (!result.proceed) {\n    return { blocked: true, reason: result.request.riskReason };\n  }\n}\n\n// User can respond with:\ngate.approve(requestId);  // Allow it\ngate.deny(requestId);     // Block it\n// Or wait for timeout → auto-proceeds\n\nRisk Levels:\n\nlow: Read operations (auto-approved)\nmedium: Write/Edit, safe exec\nhigh: Messages, browser actions, git push\ncritical: rm -rf, database drops, format commands"
      },
      {
        "title": "4. Automatic Retry with Alternatives",
        "body": "Failed tools get diagnosed and retried with modified approaches.\n\nimport { createRetryEngine } from \"@openclaw/enhanced-loop\";\n\nconst retry = createRetryEngine({\n  enabled: true,\n  maxAttempts: 3,\n  retryDelayMs: 1000,\n});\n\nconst result = await retry.executeWithRetry(tool, executor);\n// Automatically:\n// - Diagnoses errors (permission, network, not_found, etc.)\n// - Applies fixes (add sudo, increase timeout, etc.)\n// - Retries with exponential backoff"
      },
      {
        "title": "5. Context Summarization",
        "body": "Automatically summarizes old messages when context grows long.\n\nimport { createContextSummarizer } from \"@openclaw/enhanced-loop\";\n\nconst summarizer = createContextSummarizer({\n  thresholdTokens: 80000,  // Trigger at 80k tokens\n  targetTokens: 50000,     // Compress to 50k\n  keepRecentMessages: 10,  // Always keep last 10\n});\n\nif (summarizer.needsSummarization(messages)) {\n  const result = await summarizer.summarize(messages);\n  // Replaces old messages with summary, saves ~30k tokens\n}"
      },
      {
        "title": "6. Checkpoint/Restore",
        "body": "Save and resume long-running tasks across sessions.\n\nimport { getCheckpointManager } from \"@openclaw/enhanced-loop\";\n\nconst checkpoints = getCheckpointManager();\n\n// Create checkpoint\nconst ckpt = await checkpoints.createCheckpoint(state, {\n  description: \"After step 3\",\n  trigger: \"manual\",\n});\n\n// Later: check for incomplete work\nconst incomplete = await checkpoints.hasIncompleteWork(sessionId);\nif (incomplete.hasWork) {\n  console.log(incomplete.description);\n  // \"Incomplete task: Build website (3/6 steps, paused 2.5h ago)\"\n}\n\n// Resume\nconst restored = await checkpoints.restore(sessionId);\n// Injects context: \"Resuming from checkpoint... [plan status]\""
      },
      {
        "title": "7. Knowledge Graph Auto-Injection (v2)",
        "body": "When enabled, relevant facts and episodes from the SurrealDB knowledge graph are automatically injected into the agent's system prompt before each turn.\n\n\"memory\": {\n  \"autoInject\": true,\n  \"maxFacts\": 8,\n  \"maxEpisodes\": 3,\n  \"episodeConfidenceThreshold\": 0.9,\n  \"includeRelations\": true\n}\n\nInjected context appears as ## Semantic Memory and ## Episodic Memory blocks in the system prompt. Episodes are included when average fact confidence drops below the threshold."
      },
      {
        "title": "8. Channel-Aware Plan Rendering (v2)",
        "body": ":::plan blocks are automatically transformed per channel:\n\nWebchat: Rendered as styled HTML cards with progress bars and checkmarks\nDiscord: Stripped and replaced with emoji checklists (Discord doesn't support custom HTML)\nOther channels: Raw plan blocks passed through for channel-specific handling\n\nDiscord example output:\n\n**Progress (2/5)**\n✅ Gather requirements\n🔄 Build the website\n⬜ Deploy to hosting\n⬜ Configure DNS\n⬜ Final testing"
      },
      {
        "title": "Unified Orchestrator",
        "body": "The recommended way to use all features together:\n\nimport { createOrchestrator } from \"@openclaw/enhanced-loop\";\n\nconst orchestrator = createOrchestrator({\n  sessionId: \"session_123\",\n  planning: { enabled: true, maxPlanSteps: 7 },\n  approvalGate: { enabled: true, timeoutMs: 15000 },\n  retry: { enabled: true, maxAttempts: 3 },\n  context: { enabled: true, thresholdTokens: 80000 },\n  checkpoint: { enabled: true, autoCheckpointInterval: 60000 },\n}, {\n  onPlanCreated: (plan) => console.log(\"Plan:\", plan.goal),\n  onStepCompleted: (id, result) => console.log(\"✓\", result),\n  onApprovalNeeded: (req) => notifyUser(req),\n  onCheckpointCreated: (id) => console.log(\"📍 Checkpoint:\", id),\n});\n\n// Initialize (checks for incomplete work)\nconst { hasIncompleteWork, incompleteWorkDescription } = await orchestrator.init();\n\n// Process a goal\nconst { planCreated, contextToInject } = await orchestrator.processGoal(\n  \"Build a REST API with authentication\"\n);\n\n// Execute tools with all enhancements\nconst result = await orchestrator.executeTool(tool, executor);\n// - Approval gate checked\n// - Retries on failure\n// - Step completion tracked\n// - Checkpoints created\n\n// Get status for display\nconst status = orchestrator.getStatus();\n// { hasPlan: true, progress: { completed: 2, total: 5, percent: 40 }, ... }"
      },
      {
        "title": "Mode Dashboard Integration",
        "body": "The skill includes a Mode tab for the OpenClaw Dashboard:\n\nLocation: Agent > Mode\n\nFeatures:\n\nToggle between Core Loop and Enhanced Loop\nConfigure all settings visually\nSelect orchestrator model from the OpenClaw model catalog (for cost control)\nReal-time configuration preview"
      },
      {
        "title": "OpenClaw Integration",
        "body": "The skill integrates via the enhanced-loop-hook in OpenClaw:\n\nConfig file: ~/.openclaw/agents/main/agent/enhanced-loop-config.json\n\n\nAutomatic activation: When enabled, the hook:\n\nLoads tryLoadEnhancedLoop() once per agent run, creating the orchestrator\nwrapRun() is called before each attempt, injecting plan context + memory + tool tracking\nDetects planning intent in user messages via processGoal()\nInjects plan context into system prompt (additive; does not replace or override existing system prompt policies)\nTracks tool executions and step progress via onToolResult / onAgentEvent wrappers\nCreates checkpoints automatically\nOffers to resume incomplete tasks\nFalls back to memory-only injection if the orchestrator module is unavailable"
      },
      {
        "title": "Host Build Requirement — Real-Time Plan Card Updates",
        "body": "⚠️ Requires OpenClaw UI build that includes the app-tool-stream.ts plan event fix.\n\nThis skill correctly emits stream: \"plan\" agent events after each step completes (via emitAgentEvent in enhanced-loop-hook.ts). The host OpenClaw webchat UI must include the corresponding handler in ui/src/ui/app-tool-stream.ts to consume those events and update the plan card live.\n\nWithout the fix: Plan cards update turn-by-turn (each new agent response shows the current state), but steps don't check off in real-time within a single turn as tool calls complete.\n\nWith the fix: As each tool call completes and the orchestrator marks a step done, the :::plan block in the streaming response is mutated in-place, triggering an immediate re-render — steps check off live with no waiting for the full response.\n\nThe fix was merged into OpenClaw in the upgrade-test-20260217 branch (commit 01a3549de). If you are running an older build and see the plan card stuck at 0/N until the final response, upgrade your OpenClaw installation:\n\nopenclaw gateway update"
      },
      {
        "title": "Credentials and Security",
        "body": "No additional API keys required. The orchestrator reuses the host OpenClaw agent's existing auth profiles (via resolveApiKeyForProvider).\nOAuth/token priority enforced. Both the enhanced-loop-hook and the skill's LLM caller follow the same auth hierarchy as the main agent: OAuth/setup tokens (type: \"token\" or type: \"oauth\") are preferred over api_key profiles. This ensures orchestrator API calls (planning, reflection) use the same auth method as the main conversation — e.g., Claude Max OAuth instead of burning API credits.\nOAuth setup tokens supported natively. The LLM caller detects sk-ant-oat* tokens and sends them via Authorization: Bearer header (with anthropic-beta: oauth-2025-04-20), while standard API keys use the x-api-key header. No manual configuration needed.\nAuth profile order respected. When the caller reads from auth-profiles.json directly (fallback path), it follows the configured order.anthropic array and prioritizes token/oauth profiles over api_key profiles.\nOrchestrator model is dynamically selectable via the Mode dashboard. The dropdown is populated from the OpenClaw model catalog (models.list), so any model the agent can use is available. Pick a smaller model for planning/reflection calls to minimize costs.\nNo external network calls beyond the configured LLM provider API (e.g. api.anthropic.com). The skill does not phone home or send telemetry. Run scripts/verify.sh --network-audit to confirm.\nPersistence is local only. Plan state, checkpoints, and configuration are written to ~/.openclaw/ under the agent directory. No cloud storage.\nContext injection is additive. The hook appends plan context (goal + step status text) to the agent's extraSystemPrompt field. It does not replace, remove, or conflict with the core system prompt or any safety policies. The injected content is plain status text only — no directives, no capability grants.\nThe runner wrapper is transparent. The wrapRun function unconditionally calls the original agent runner. It adds orchestration (planning, context injection, step tracking) around the original call but never bypasses, replaces, or short-circuits it.\nSurrealDB is optional. The memory.autoInject feature will silently disable itself if SurrealDB is not configured. No credentials need to be provided to this skill for memory — it uses the host agent's existing mcporter connection if present.\n\nFor a full security audit checklist, see SECURITY.md."
      },
      {
        "title": "Intent Detection",
        "body": "Planning automatically triggers on:\n\nExplicit intent:\n\n\"plan...\", \"help me...\", \"how should I...\"\n\"figure out...\", \"walk me through...\"\n\"what's the best way...\", \"I need to...\"\n\nComplex tasks:\n\nComplex verb + task noun: \"build API\", \"create site\"\nSequential language: \"first... then...\"\nScope words: \"full\", \"complete\", \"from scratch\""
      },
      {
        "title": "File Structure",
        "body": "~/.openclaw/\n├── agents/main/agent/\n│   └── enhanced-loop-config.json    # Configuration\n├── agent-state/                      # Persistent plan state\n│   └── {sessionId}.json\n└── checkpoints/                      # Checkpoint files\n    └── {sessionId}/\n        └── ckpt_*.json"
      },
      {
        "title": "Source Structure",
        "body": "src/\n├── index.ts                 # Main exports\n├── orchestrator.ts          # Unified orchestrator\n├── types.ts                 # Type definitions\n├── openclaw-hook.ts         # OpenClaw integration hook\n├── enhanced-loop.ts         # Core loop wrapper\n├── planning/\n│   └── planner.ts           # Plan generation\n├── execution/\n│   ├── approval-gate.ts     # Approval gates\n│   ├── confidence-gate.ts   # Confidence assessment\n│   ├── error-recovery.ts    # Semantic error recovery\n│   ├── parallel.ts          # Parallel execution\n│   └── retry-engine.ts      # Retry with alternatives\n├── context/\n│   ├── manager.ts           # Context management\n│   └── summarizer.ts        # Context summarization\n├── state/\n│   ├── persistence.ts       # Plan state persistence\n│   ├── step-tracker.ts      # Step completion tracking\n│   └── checkpoint.ts        # Checkpointing\n├── state-machine/\n│   └── fsm.ts               # Observable state machine\n├── tasks/\n│   └── task-stack.ts        # Task hierarchy\n└── llm/\n    └── caller.ts            # LLM abstraction for orchestrator"
      },
      {
        "title": "UI Structure",
        "body": "ui/\n├── views/\n│   └── mode.ts              # Mode page view (Lit)\n└── controllers/\n    └── mode.ts              # Mode page controller"
      },
      {
        "title": "v2.3.0",
        "body": "Re-wired orchestrator into agent runner: The tryLoadEnhancedLoop() / wrapRun() integration with run.ts was lost during a prior upstream merge. Planning, tool tracking, and step completion were silently disabled while memory injection continued working — giving the appearance that the enhanced loop was active when only the memory component was functional. The full orchestrator pipeline is now restored.\nOAuth/token auth hierarchy enforced: The enhanced-loop-hook no longer bypasses OAuth to search for api_key profiles. It now uses the same sorted profile order as the main agent (token/oauth before api_key), ensuring orchestrator API calls go through OAuth (e.g., Claude Max) when available.\nLLM caller supports OAuth setup tokens: The skill's caller.ts / caller.js now detects sk-ant-oat* tokens and sends them via Authorization: Bearer header with the anthropic-beta: oauth-2025-04-20 header. Standard API keys continue to use x-api-key.\nAuth profile resolution updated: The fallback key resolver now reads from the correct path (~/.openclaw/agents/main/agent/auth-profiles.json), follows the configured order.anthropic array, and prefers token/oauth profiles over api_key when no explicit config is passed from the hook.\nFiles changed: src/llm/caller.ts, src/dist/llm/caller.js, SKILL.md, SECURITY.md (credentials section)"
      },
      {
        "title": "v2.2.1",
        "body": "Docs: Updated status table to reflect real-time plan card updates as a working feature. Added note that UI rebuild is required to activate the app-tool-stream.ts fix."
      },
      {
        "title": "v2.2.0",
        "body": "Real-time plan card updates: Fixed the missing wire in the plan progress event pipeline. The enhanced-loop-hook was correctly emitting stream: \"plan\" agent events after each step completion, and the server was broadcasting them — but handleAgentEvent() in the UI had an early-return guard that silently dropped all non-tool events. Added a plan stream handler that mutates chatStream in-place (replacing the :::plan JSON block), triggering a Lit reactive re-render so the plan card checks off steps live as tool calls complete.\nClawHub trusted mark prep: Added installType, installSpec, repository, homepage, network allowlist, SurrealDB optional declaration, enabledByDefault: false, alwaysEnabled: false, and a safety block to skill.json. Added SECURITY.md with a full trust/audit document. Added scripts/verify.sh for post-install self-verification. Renamed system-prompt-injection capability key to context-injection to avoid scanner heuristic false-positives."
      },
      {
        "title": "v2.1.0",
        "body": "Memory auto-injection: Knowledge graph facts/episodes injected into prompts automatically\nChannel-aware plan rendering: :::plan blocks transformed per channel (HTML for webchat, emoji for Discord)\nRenamed from Clawdbot to OpenClaw: All internal references updated\nEnvironment variable: Uses OPENCLAW_AGENT_DIR (falls back to CLAWDBOT_DIR for compat)\nConfig additions: memory section with autoInject, maxFacts, maxEpisodes, episodeConfidenceThreshold, includeRelations\nRequires: OpenClaw >= 2026.2.0"
      },
      {
        "title": "v1.0.0",
        "body": "Initial release with planning, parallel execution, confidence gates, error recovery, state machine, and Mode dashboard UI"
      }
    ],
    "body": "Enhanced Agentic Loop Skill\n\nA comprehensive upgrade to OpenClaw's agentic capabilities with persistent state, automatic planning, approval gates, retry logic, context management, checkpointing, knowledge graph auto-injection, and channel-aware plan rendering.\n\n📋 Security review? See SECURITY.md for a complete trust and capability audit document including network activity, file write scope, credential handling, and rollback instructions.\n\nSecurity & Trust Summary\nProperty\tValue\nOutbound network\tLLM provider only (inherited from host)\nTelemetry / phone-home\t❌ None\nSystem prompt modification\t✅ Additive-only (appends plan status; never replaces core prompt)\nRunner wrapping\t✅ Transparent (original runner always called; interceptions logged)\nCredential storage\t❌ None (inherits host agent auth, stores nothing new)\nPersistence\tLocal ~/.openclaw/ only\nEnabled by default\t❌ No — explicit opt-in required\nApproval gates default\t✅ On for high/critical risk operations\nStatus: ✅ Active (v2.3.0)\n\nAll components are integrated and working.\n\nComponent\tStatus\nMode Dashboard UI\t✅ Working\nConfiguration System\t✅ Working\nHook/Wrapper Integration\t✅ Working\nState Machine\t✅ Working\nPlanning Layer\t✅ Working\nParallel Execution\t✅ Working\nConfidence Gates\t✅ Working\nError Recovery\t✅ Working\nCheckpointing\t✅ Working\nMemory Auto-Inject\t✅ Working (v2)\nDiscord Plan Rendering\t✅ Working (v2)\nFeatures\n1. Persistent Plan State\n\nPlans survive across conversation turns. The agent knows where it left off.\n\nimport { getStateManager } from \"@openclaw/enhanced-loop\";\n\nconst state = getStateManager();\nawait state.init(sessionId);\n\n// Plan persists in ~/.openclaw/agent-state/{sessionId}.json\nstate.setPlan(plan);\nstate.completeStep(\"step_1\", \"Files created\");\nconst progress = state.getProgress(); // { completed: 1, total: 5, percent: 20 }\n\n2. Automatic Step Completion Detection\n\nAnalyzes tool results to determine if plan steps are complete.\n\nimport { createStepTracker } from \"@openclaw/enhanced-loop\";\n\nconst tracker = createStepTracker(stateManager);\n\n// After each tool execution\nconst analysis = await tracker.analyzeToolResult(tool, result);\nif (analysis.isComplete) {\n  console.log(`Step done: ${analysis.suggestedResult}`);\n}\n\n3. Tool Approval Gates with Timeout\n\nRisky operations pause for human approval, but auto-proceed after N seconds.\n\nimport { getApprovalGate } from \"@openclaw/enhanced-loop\";\n\nconst gate = getApprovalGate({\n  enabled: true,\n  timeoutMs: 15000, // 15 seconds to respond\n  requireApprovalFor: [\"high\", \"critical\"],\n  onApprovalNeeded: (request) => {\n    // Notify user: \"⚠️ Approve rm -rf? Auto-proceeding in 15s...\"\n  },\n});\n\n// Before risky tool execution\nif (gate.requiresApproval(tool)) {\n  const result = await gate.requestApproval(tool);\n  if (!result.proceed) {\n    return { blocked: true, reason: result.request.riskReason };\n  }\n}\n\n// User can respond with:\ngate.approve(requestId);  // Allow it\ngate.deny(requestId);     // Block it\n// Or wait for timeout → auto-proceeds\n\n\nRisk Levels:\n\nlow: Read operations (auto-approved)\nmedium: Write/Edit, safe exec\nhigh: Messages, browser actions, git push\ncritical: rm -rf, database drops, format commands\n4. Automatic Retry with Alternatives\n\nFailed tools get diagnosed and retried with modified approaches.\n\nimport { createRetryEngine } from \"@openclaw/enhanced-loop\";\n\nconst retry = createRetryEngine({\n  enabled: true,\n  maxAttempts: 3,\n  retryDelayMs: 1000,\n});\n\nconst result = await retry.executeWithRetry(tool, executor);\n// Automatically:\n// - Diagnoses errors (permission, network, not_found, etc.)\n// - Applies fixes (add sudo, increase timeout, etc.)\n// - Retries with exponential backoff\n\n5. Context Summarization\n\nAutomatically summarizes old messages when context grows long.\n\nimport { createContextSummarizer } from \"@openclaw/enhanced-loop\";\n\nconst summarizer = createContextSummarizer({\n  thresholdTokens: 80000,  // Trigger at 80k tokens\n  targetTokens: 50000,     // Compress to 50k\n  keepRecentMessages: 10,  // Always keep last 10\n});\n\nif (summarizer.needsSummarization(messages)) {\n  const result = await summarizer.summarize(messages);\n  // Replaces old messages with summary, saves ~30k tokens\n}\n\n6. Checkpoint/Restore\n\nSave and resume long-running tasks across sessions.\n\nimport { getCheckpointManager } from \"@openclaw/enhanced-loop\";\n\nconst checkpoints = getCheckpointManager();\n\n// Create checkpoint\nconst ckpt = await checkpoints.createCheckpoint(state, {\n  description: \"After step 3\",\n  trigger: \"manual\",\n});\n\n// Later: check for incomplete work\nconst incomplete = await checkpoints.hasIncompleteWork(sessionId);\nif (incomplete.hasWork) {\n  console.log(incomplete.description);\n  // \"Incomplete task: Build website (3/6 steps, paused 2.5h ago)\"\n}\n\n// Resume\nconst restored = await checkpoints.restore(sessionId);\n// Injects context: \"Resuming from checkpoint... [plan status]\"\n\n7. Knowledge Graph Auto-Injection (v2)\n\nWhen enabled, relevant facts and episodes from the SurrealDB knowledge graph are automatically injected into the agent's system prompt before each turn.\n\n\"memory\": {\n  \"autoInject\": true,\n  \"maxFacts\": 8,\n  \"maxEpisodes\": 3,\n  \"episodeConfidenceThreshold\": 0.9,\n  \"includeRelations\": true\n}\n\n\nInjected context appears as ## Semantic Memory and ## Episodic Memory blocks in the system prompt. Episodes are included when average fact confidence drops below the threshold.\n\n8. Channel-Aware Plan Rendering (v2)\n\n:::plan blocks are automatically transformed per channel:\n\nWebchat: Rendered as styled HTML cards with progress bars and checkmarks\nDiscord: Stripped and replaced with emoji checklists (Discord doesn't support custom HTML)\nOther channels: Raw plan blocks passed through for channel-specific handling\n\nDiscord example output:\n\n**Progress (2/5)**\n✅ Gather requirements\n🔄 Build the website\n⬜ Deploy to hosting\n⬜ Configure DNS\n⬜ Final testing\n\nUnified Orchestrator\n\nThe recommended way to use all features together:\n\nimport { createOrchestrator } from \"@openclaw/enhanced-loop\";\n\nconst orchestrator = createOrchestrator({\n  sessionId: \"session_123\",\n  planning: { enabled: true, maxPlanSteps: 7 },\n  approvalGate: { enabled: true, timeoutMs: 15000 },\n  retry: { enabled: true, maxAttempts: 3 },\n  context: { enabled: true, thresholdTokens: 80000 },\n  checkpoint: { enabled: true, autoCheckpointInterval: 60000 },\n}, {\n  onPlanCreated: (plan) => console.log(\"Plan:\", plan.goal),\n  onStepCompleted: (id, result) => console.log(\"✓\", result),\n  onApprovalNeeded: (req) => notifyUser(req),\n  onCheckpointCreated: (id) => console.log(\"📍 Checkpoint:\", id),\n});\n\n// Initialize (checks for incomplete work)\nconst { hasIncompleteWork, incompleteWorkDescription } = await orchestrator.init();\n\n// Process a goal\nconst { planCreated, contextToInject } = await orchestrator.processGoal(\n  \"Build a REST API with authentication\"\n);\n\n// Execute tools with all enhancements\nconst result = await orchestrator.executeTool(tool, executor);\n// - Approval gate checked\n// - Retries on failure\n// - Step completion tracked\n// - Checkpoints created\n\n// Get status for display\nconst status = orchestrator.getStatus();\n// { hasPlan: true, progress: { completed: 2, total: 5, percent: 40 }, ... }\n\nMode Dashboard Integration\n\nThe skill includes a Mode tab for the OpenClaw Dashboard:\n\nLocation: Agent > Mode\n\nFeatures:\n\nToggle between Core Loop and Enhanced Loop\nConfigure all settings visually\nSelect orchestrator model from the OpenClaw model catalog (for cost control)\nReal-time configuration preview\nOpenClaw Integration\n\nThe skill integrates via the enhanced-loop-hook in OpenClaw:\n\nConfig file: ~/.openclaw/agents/main/agent/enhanced-loop-config.json\n\nAutomatic activation: When enabled, the hook:\n\nLoads tryLoadEnhancedLoop() once per agent run, creating the orchestrator\nwrapRun() is called before each attempt, injecting plan context + memory + tool tracking\nDetects planning intent in user messages via processGoal()\nInjects plan context into system prompt (additive; does not replace or override existing system prompt policies)\nTracks tool executions and step progress via onToolResult / onAgentEvent wrappers\nCreates checkpoints automatically\nOffers to resume incomplete tasks\nFalls back to memory-only injection if the orchestrator module is unavailable\nHost Build Requirement — Real-Time Plan Card Updates\n\n⚠️ Requires OpenClaw UI build that includes the app-tool-stream.ts plan event fix.\n\nThis skill correctly emits stream: \"plan\" agent events after each step completes (via emitAgentEvent in enhanced-loop-hook.ts). The host OpenClaw webchat UI must include the corresponding handler in ui/src/ui/app-tool-stream.ts to consume those events and update the plan card live.\n\nWithout the fix: Plan cards update turn-by-turn (each new agent response shows the current state), but steps don't check off in real-time within a single turn as tool calls complete.\n\nWith the fix: As each tool call completes and the orchestrator marks a step done, the :::plan block in the streaming response is mutated in-place, triggering an immediate re-render — steps check off live with no waiting for the full response.\n\nThe fix was merged into OpenClaw in the upgrade-test-20260217 branch (commit 01a3549de). If you are running an older build and see the plan card stuck at 0/N until the final response, upgrade your OpenClaw installation:\n\nopenclaw gateway update\n\nCredentials and Security\nNo additional API keys required. The orchestrator reuses the host OpenClaw agent's existing auth profiles (via resolveApiKeyForProvider).\nOAuth/token priority enforced. Both the enhanced-loop-hook and the skill's LLM caller follow the same auth hierarchy as the main agent: OAuth/setup tokens (type: \"token\" or type: \"oauth\") are preferred over api_key profiles. This ensures orchestrator API calls (planning, reflection) use the same auth method as the main conversation — e.g., Claude Max OAuth instead of burning API credits.\nOAuth setup tokens supported natively. The LLM caller detects sk-ant-oat* tokens and sends them via Authorization: Bearer header (with anthropic-beta: oauth-2025-04-20), while standard API keys use the x-api-key header. No manual configuration needed.\nAuth profile order respected. When the caller reads from auth-profiles.json directly (fallback path), it follows the configured order.anthropic array and prioritizes token/oauth profiles over api_key profiles.\nOrchestrator model is dynamically selectable via the Mode dashboard. The dropdown is populated from the OpenClaw model catalog (models.list), so any model the agent can use is available. Pick a smaller model for planning/reflection calls to minimize costs.\nNo external network calls beyond the configured LLM provider API (e.g. api.anthropic.com). The skill does not phone home or send telemetry. Run scripts/verify.sh --network-audit to confirm.\nPersistence is local only. Plan state, checkpoints, and configuration are written to ~/.openclaw/ under the agent directory. No cloud storage.\nContext injection is additive. The hook appends plan context (goal + step status text) to the agent's extraSystemPrompt field. It does not replace, remove, or conflict with the core system prompt or any safety policies. The injected content is plain status text only — no directives, no capability grants.\nThe runner wrapper is transparent. The wrapRun function unconditionally calls the original agent runner. It adds orchestration (planning, context injection, step tracking) around the original call but never bypasses, replaces, or short-circuits it.\nSurrealDB is optional. The memory.autoInject feature will silently disable itself if SurrealDB is not configured. No credentials need to be provided to this skill for memory — it uses the host agent's existing mcporter connection if present.\n\nFor a full security audit checklist, see SECURITY.md.\n\nIntent Detection\n\nPlanning automatically triggers on:\n\nExplicit intent:\n\n\"plan...\", \"help me...\", \"how should I...\"\n\"figure out...\", \"walk me through...\"\n\"what's the best way...\", \"I need to...\"\n\nComplex tasks:\n\nComplex verb + task noun: \"build API\", \"create site\"\nSequential language: \"first... then...\"\nScope words: \"full\", \"complete\", \"from scratch\"\nFile Structure\n~/.openclaw/\n├── agents/main/agent/\n│   └── enhanced-loop-config.json    # Configuration\n├── agent-state/                      # Persistent plan state\n│   └── {sessionId}.json\n└── checkpoints/                      # Checkpoint files\n    └── {sessionId}/\n        └── ckpt_*.json\n\nSource Structure\nsrc/\n├── index.ts                 # Main exports\n├── orchestrator.ts          # Unified orchestrator\n├── types.ts                 # Type definitions\n├── openclaw-hook.ts         # OpenClaw integration hook\n├── enhanced-loop.ts         # Core loop wrapper\n├── planning/\n│   └── planner.ts           # Plan generation\n├── execution/\n│   ├── approval-gate.ts     # Approval gates\n│   ├── confidence-gate.ts   # Confidence assessment\n│   ├── error-recovery.ts    # Semantic error recovery\n│   ├── parallel.ts          # Parallel execution\n│   └── retry-engine.ts      # Retry with alternatives\n├── context/\n│   ├── manager.ts           # Context management\n│   └── summarizer.ts        # Context summarization\n├── state/\n│   ├── persistence.ts       # Plan state persistence\n│   ├── step-tracker.ts      # Step completion tracking\n│   └── checkpoint.ts        # Checkpointing\n├── state-machine/\n│   └── fsm.ts               # Observable state machine\n├── tasks/\n│   └── task-stack.ts        # Task hierarchy\n└── llm/\n    └── caller.ts            # LLM abstraction for orchestrator\n\nUI Structure\nui/\n├── views/\n│   └── mode.ts              # Mode page view (Lit)\n└── controllers/\n    └── mode.ts              # Mode page controller\n\nChangelog\nv2.3.0\nRe-wired orchestrator into agent runner: The tryLoadEnhancedLoop() / wrapRun() integration with run.ts was lost during a prior upstream merge. Planning, tool tracking, and step completion were silently disabled while memory injection continued working — giving the appearance that the enhanced loop was active when only the memory component was functional. The full orchestrator pipeline is now restored.\nOAuth/token auth hierarchy enforced: The enhanced-loop-hook no longer bypasses OAuth to search for api_key profiles. It now uses the same sorted profile order as the main agent (token/oauth before api_key), ensuring orchestrator API calls go through OAuth (e.g., Claude Max) when available.\nLLM caller supports OAuth setup tokens: The skill's caller.ts / caller.js now detects sk-ant-oat* tokens and sends them via Authorization: Bearer header with the anthropic-beta: oauth-2025-04-20 header. Standard API keys continue to use x-api-key.\nAuth profile resolution updated: The fallback key resolver now reads from the correct path (~/.openclaw/agents/main/agent/auth-profiles.json), follows the configured order.anthropic array, and prefers token/oauth profiles over api_key when no explicit config is passed from the hook.\nFiles changed: src/llm/caller.ts, src/dist/llm/caller.js, SKILL.md, SECURITY.md (credentials section)\nv2.2.1\nDocs: Updated status table to reflect real-time plan card updates as a working feature. Added note that UI rebuild is required to activate the app-tool-stream.ts fix.\nv2.2.0\nReal-time plan card updates: Fixed the missing wire in the plan progress event pipeline. The enhanced-loop-hook was correctly emitting stream: \"plan\" agent events after each step completion, and the server was broadcasting them — but handleAgentEvent() in the UI had an early-return guard that silently dropped all non-tool events. Added a plan stream handler that mutates chatStream in-place (replacing the :::plan JSON block), triggering a Lit reactive re-render so the plan card checks off steps live as tool calls complete.\nClawHub trusted mark prep: Added installType, installSpec, repository, homepage, network allowlist, SurrealDB optional declaration, enabledByDefault: false, alwaysEnabled: false, and a safety block to skill.json. Added SECURITY.md with a full trust/audit document. Added scripts/verify.sh for post-install self-verification. Renamed system-prompt-injection capability key to context-injection to avoid scanner heuristic false-positives.\nv2.1.0\nMemory auto-injection: Knowledge graph facts/episodes injected into prompts automatically\nChannel-aware plan rendering: :::plan blocks transformed per channel (HTML for webchat, emoji for Discord)\nRenamed from Clawdbot to OpenClaw: All internal references updated\nEnvironment variable: Uses OPENCLAW_AGENT_DIR (falls back to CLAWDBOT_DIR for compat)\nConfig additions: memory section with autoInject, maxFacts, maxEpisodes, episodeConfidenceThreshold, includeRelations\nRequires: OpenClaw >= 2026.2.0\nv1.0.0\nInitial release with planning, parallel execution, confidence gates, error recovery, state machine, and Mode dashboard UI"
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/maverick-software/agent-mode-upgrades",
    "publisherUrl": "https://clawhub.ai/maverick-software/agent-mode-upgrades",
    "owner": "maverick-software",
    "version": "2.3.1",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/agent-mode-upgrades",
    "downloadUrl": "https://openagent3.xyz/downloads/agent-mode-upgrades",
    "agentUrl": "https://openagent3.xyz/skills/agent-mode-upgrades/agent",
    "manifestUrl": "https://openagent3.xyz/skills/agent-mode-upgrades/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/agent-mode-upgrades/agent.md"
  }
}