Skip to content

[plugin sdk] Consolidate workflow seams and fixtures#73384

Closed
100yenadmin wants to merge 97 commits intoopenclaw:mainfrom
electricsheephq:feature/plugin-sdk-workflow-followups-consolidated
Closed

[plugin sdk] Consolidate workflow seams and fixtures#73384
100yenadmin wants to merge 97 commits intoopenclaw:mainfrom
electricsheephq:feature/plugin-sdk-workflow-followups-consolidated

Conversation

@100yenadmin
Copy link
Copy Markdown
Contributor

@100yenadmin 100yenadmin commented Apr 28, 2026

Summary

This PR consolidates the implementation/test follow-up work that was stacked behind the now-merged generic host-hook foundation in #72287. Docs split update: the large host-hook recipe page/nav/glossary work has been moved to the separate docs-only PR #74853, so this PR now carries implementation, tests, generated protocol/API baselines, and QA hardening only (~4,542 additions / 151 deletions across 68 files).

Feature / LOC Breakdown

Approximate line counts from the current consolidated diff against main (after #72287 merged). These are grouped by original follow-up PR / feature area so maintainers can review the stack by purpose, not just by file list. Production counts include generated client/API model updates where they are part of the shipped protocol surface; test counts include contract fixtures and QA/CI hardening tests; docs counts include recipe docs, nav, glossary, and the generated SDK API baseline hash.

Feature / original PR Production LOC Tests / fixtures LOC Docs LOC Total diff Files What it adds
#72383 workflow seams + hardening ~1,413 ~1,034 0 ~2,447 / -40 38 Session actions, host-mediated attachments, scheduled turns, finalize retry, workflow validation, Gateway protocol/client models, cleanup hardening, and contract coverage.
#72384 advanced workflow fixtures ~205 ~604 0 ~809 / -0 2 Executable fixture plugins for approval, policy gate, background monitor, artifact reply, and retry archetypes.
#72333 host-hook recipes/docs 0 0 moved to #74853 ~2,680 / -0 3 Maintainer/plugin-author recipe page, diagrams, examples, docs nav entry, and glossary entry now isolated in the docs-only PR.
Consolidation + QA/CI stabilization ~15 ~31 0 ~46 / -3 10 Scope-stable QA gateway RPC helper coverage, parity scenario stabilization, startup/security test determinism, and small support-file adjustments needed to keep exact-head CI reliable.
Current #73384 total after docs split implementation + generated protocol/API focused contract/fixture/QA coverage 0 large prose docs ~4,542 / -151 68 One current implementation PR replacing stale stacked follow-ups while preserving reviewable feature slices and extensive tests.

#72287 has merged, so keeping the remaining work split across three stale/stacked PRs now creates more review churn than clarity. This replacement keeps the original commit-level review slices, but presents them as one follow-up PR based on current main, with the implementation and executable fixture proofs here and the docs/examples isolated in #74853.

Process note: this stack went through roughly two days of GPT-5.5/Codex-assisted hardening plus maintainer, bot, and adversarial review loops. The earlier follow-ups were repeatedly tested, fixed, and restacked. Consolidating them now is meant to stop the hardening loop from scattering new feedback across stale PR diffs while preserving the original detail and review evidence.

This remains generic plugin SDK work. It does not add Plan Mode product code, prompts, /plan behavior, Telegram-specific behavior, or product-specific UI. #71676 remains a parity oracle only; #71731 is the RFC context.

Relationship To The Merged Foundation

flowchart TD
  RFC["RFC #71731: plugin host-hook capability requirements"] --> Foundation["#72287 merged: generic host-hook foundation"]
  Oracle["#71676 parity oracle: required entry-point classes"] --> Foundation
  Foundation --> ThisPR["This consolidated follow-up PR"]
  ThisPR --> Workflow["Workflow seams: session actions, attachments, scheduling, finalize retry"]
  ThisPR --> Fixtures["Advanced contract fixtures: approval, policy, monitor, artifact, retry"]
  ThisPR -.-> Docs["#74853 docs PR: recipes and examples map"]
Loading

#72287 established the generic host-hook foundation: session extension storage/projection, queued injections, trusted tool policies, tool metadata, control UI descriptors, lifecycle/event subscriptions, run-context helpers, scheduler ownership cleanup, Gateway schemas, and SDK exports.

This PR builds on that merged foundation with host-mediated workflow affordances that real plugins need after they can register hooks:

  • Let plugins define typed session actions and return validated action results.
  • Let plugins send session-bound attachments through host-owned outbound delivery.
  • Let plugins schedule future session turns through existing cron-compatible scheduler plumbing.
  • Let plugins request bounded agent-finalize retries without owning runner internals.
  • Add adversarial fixtures that prove the seams compose safely.
  • Keep the large docs recipes split to [docs][plugin sdk] Split host-hook recipes from workflow follow-ups #74853 so this PR stays focused on code, tests, and generated API/protocol evidence.

Why Consolidate Now

The old PRs were useful while #72287 was still unmerged because they separated foundation, workflow, proof fixtures, and docs. After #72287 merged, that split became counterproductive:

This branch is the current comparison surface. The old PRs should be closed after this PR is opened and linked.

Review Order

The commits intentionally preserve the old review slices. Suggested review order:

  1. Workflow seam commits, starting at feat(plugin-sdk): add workflow host seams.
  2. Hardening commits for validation, cron compatibility, cleanup, lazy imports, and schema normalization.
  3. Fixture commits, starting at test(plugin-sdk): add advanced workflow fixtures.
  4. Consolidation/support commits:
    • chore(plugin-sdk): refresh consolidated API baseline
    • chore(plugin-sdk): refresh rebased API baseline
    • test(security): isolate windows acl os mock

The former docs/recipe commit group is now isolated in #74853.

Runtime Architecture

sequenceDiagram
  participant Plugin
  participant Registry as Plugin registry
  participant Gateway as Gateway method
  participant Runner as Agent runner
  participant Cron as Existing cron scheduler
  participant Outbound as Host outbound delivery

  Plugin->>Registry: registerSessionAction(...)
  Plugin->>Registry: sendSessionAttachment(...)
  Plugin->>Registry: scheduleSessionTurn(...)
  Plugin->>Registry: before_agent_finalize retry hook

  Gateway->>Registry: plugins.sessionAction(name, input)
  Registry->>Registry: validate action id, input, output, failure shape
  Registry-->>Gateway: typed success/failure reply

  Runner->>Registry: agent lifecycle / event payloads
  Registry->>Plugin: scoped event subscriptions
  Plugin->>Registry: setRunContext / enqueueNextTurnInjection

  Plugin->>Registry: scheduleSessionTurn(session, when, text)
  Registry->>Cron: cron-compatible scheduled job payload
  Cron-->>Runner: future session turn

  Plugin->>Registry: sendSessionAttachment(...)
  Registry->>Outbound: lazy host-owned delivery path
  Outbound-->>Gateway: session-bound attachment delivery
Loading

What Future Plugins Can Now Do

flowchart LR
  Hooks["Merged #72287 host hooks"] --> Workflow["This PR workflow seams"]
  Workflow --> Deploy["Deploy approver plugin"]
  Workflow --> Budget["Budget guard plugin"]
  Workflow --> SLA["SLA / incident watcher plugin"]
  Workflow --> Artifact["Artifact responder plugin"]
  Workflow --> Review["Review concierge plugin"]
  Workflow --> Wizard["Setup wizard plugin"]
  Workflow --> Monitor["Background monitor plugin"]

  Deploy --> A1["Session action + continueAgent + scoped command"]
  Budget --> A2["Trusted policy + session state + typed denial"]
  SLA --> A3["Scheduled turn + agent events + run context"]
  Artifact --> A4["Attachment send + tool metadata + action result"]
  Review --> A5["Finalize retry + queued injection + event subscription"]
  Wizard --> A6["Control descriptor + session action + persisted extension"]
  Monitor --> A7["Cron-compatible schedule + lifecycle cleanup"]
Loading

Examples that are intentionally generic, not Plan Mode-specific:

  • Deploy approver: registers a deploy.approve action, requires operator approval scope, stores the pending deployment in plugin-owned session state, and uses continueAgent after an approval action.
  • Budget guard: registers trusted tool policy reads and blocks expensive tools when plugin-owned budget state is exhausted, with a typed denial instead of a thrown internal error.
  • SLA watcher: subscribes to agent/session events, schedules a future session turn if a deadline is missed, and cleans scheduled jobs when the plugin/session is disabled or deleted.
  • Artifact responder: sends session-bound files through host outbound delivery after a plugin tool produces a report, bundle, or review artifact.
  • Review concierge: uses finalize retry and queued injection priority to ask the agent to repair a reply before the host finalizes delivery.
  • Setup wizard: registers a control UI descriptor plus session actions so a UI can present plugin-defined setup state without arbitrary browser JS.

SDK And Gateway Surface Added In This PR

SDK / plugin API

  • Session actions: plugins can register typed session actions that are invoked through the host rather than through ad hoc commands.
  • Outbound attachment helper: plugins can ask the host to send a session-bound attachment without importing channel/runtime internals.
  • Scheduled session turns: plugins can schedule future session turns through the existing cron-compatible host scheduler.
  • Finalize retry support: plugins can request a bounded retry before a reply is finalized.
  • Priority on queued next-turn injections: queued injections can express priority while still being validated by the host.
  • Workflow hook config defaults: plugin workflow hook config is captured with safe defaults and validation.
  • Runtime context helpers remain from [plugin sdk] Add generic plugin host-hook contracts #72287 and are exercised here in workflow scenarios.

Gateway / protocol

  • Adds typed protocol support for plugin session actions and typed action errors.
  • Normalizes workflow Gateway outputs so clients see deterministic success/failure shapes.
  • Updates generated Swift Gateway models for the additive protocol surface.
  • Preserves closed-schema behavior: invalid or oversized plugin data is rejected or skipped instead of leaking arbitrary payloads into host paths.

Runner / agent lifecycle

  • Agent finalize retry requests are preserved long enough for bounded retry evaluation.
  • CLI prompt preparation stays lazy when no prompt-consuming hooks are present.
  • Workflow caches and runtime context are cleaned by host-owned cleanup paths.

Scheduler / cron

  • Scheduled session turns are host-mediated over existing cron access.
  • Runtime-only scheduled turns are preserved on plugin restart/reload.
  • Cleanup exclusions are keyed by owner/job id so stale cleanup cannot delete another plugin's jobs.
  • Default cron delivery mode is omitted because the cron payload schema is closed.

Docs / recipes

The large recipe page, docs navigation entry, and glossary entry were split to #74853. This PR keeps the implementation/tests/generated API surface only.

File-Group Changelog

SDK/API

  • src/plugins/host-hooks.ts: expands the generic hook types with workflow action, outbound, scheduler, and retry concepts.
  • src/plugins/types.ts: exposes additive plugin API types for workflow seams.
  • src/plugin-sdk/core.ts, src/plugin-sdk/plugin-entry.ts, src/plugin-sdk/plugin-test-api.ts: project the new SDK methods into public plugin entry/test surfaces.
  • docs/.generated/plugin-sdk-api-baseline.sha256: regenerated after the consolidated API surface was verified.

Registry/runtime

  • src/plugins/registry.ts: captures workflow registrations, validates schemas, dispatches session actions, and wires cleanup.
  • src/plugins/registry-types.ts, src/plugins/captured-registration.ts, src/plugins/runtime-state.ts: add durable capture/runtime typing for workflow hooks.
  • src/plugins/host-hook-runtime.ts, src/plugins/host-hook-state.ts, src/plugins/host-hook-cleanup.ts: scope run context, side effects, lifecycle cleanup, and scheduler ownership cleanup.
  • src/plugins/runtime.ts, src/plugins/registry-empty.ts: keep empty registries and runtime state compatible with the new surface.

Workflow bridge

  • src/plugins/host-hook-workflow.ts: centralizes session action dispatch, attachment delivery, scheduled turn registration, and workflow helper behavior.
  • src/agents/harness/lifecycle-hook-helpers.ts: factors finalize retry helper behavior so retry is bounded and testable.
  • src/agents/pi-embedded-runner/run.ts: integrates finalize retry requests into the runner path.
  • src/agents/cli-runner/prepare.ts: keeps prompt prep lazy when no prompt-consuming hooks are present.

Gateway/protocol

  • src/gateway/server-methods/plugin-host-hooks.ts: adds Gateway methods for plugin workflow/session action calls.
  • src/gateway/server-methods-list.ts, src/gateway/method-scopes.ts: wires method registration and scope metadata.
  • src/gateway/protocol/schema/plugins.ts, src/gateway/protocol/schema/protocol-schemas.ts, src/gateway/protocol/schema/types.ts, src/gateway/protocol/index.ts: adds typed schemas and exported protocol entries.
  • apps/macos/Sources/OpenClawProtocol/GatewayModels.swift and apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift: generated client model updates for the additive protocol surface.

Policy/catalog hardening touched by workflow seams

  • src/plugins/trusted-tool-policy.ts: keeps policy parameter handling plain-object guarded and compatible with workflow use.
  • src/agents/pi-tools.before-tool-call.integration.e2e.test.ts: retains coverage around intentional policy blocks as blocked results rather than generic tool execution failures.

Contract tests and fixtures

  • src/plugins/contracts/host-hooks.contract.test.ts: expands contract coverage for workflow registration, validation, cleanup, scheduling, queued injection priority, side effects, and Gateway normalization.
  • src/plugins/contracts/advanced-workflow-fixtures.ts: adds reusable fixture plugin archetypes.
  • src/plugins/contracts/advanced-workflow-fixtures.contract.test.ts: proves approval, policy gate, background monitor, artifact reply, and finalize retry flows through executable fixtures.
  • src/agents/harness/lifecycle-hook-helpers.test.ts: verifies bounded finalize retry semantics.

CI stabilization

  • src/security/windows-acl.test.ts: adds explicit module reset before importing the Windows ACL module under test. This is not part of the plugin SDK surface; it keeps the broad core-unit-fast-support CI shard deterministic after current main started caching node:os before this test mock in the full shard.

Docs

Hook Hardening Matrix

Area Before After Why it matters
Session action schemas Registration/runtime could accept malformed shapes too late Registration and dispatch validate action ids, params, result, and failure objects Bad plugin data cannot crash Gateway or leak arbitrary payloads
Action failure results Failure payloads were not consistently typed Typed plugin-action error fields are exposed in protocol schemas Clients can distinguish validation denial from plugin failure
Scheduler payloads Default delivery and unsupported payload fields could violate cron schema Scheduled turn jobs omit default delivery and stay cron-compatible Existing scheduler stays generic; no Plan Mode nudge logic
Scheduler cleanup Cleanup could be too broad for owner/job overlaps Cleanup exclusions are keyed by plugin owner and job id Stale cleanup cannot delete newer or unrelated jobs
Restart semantics Runtime-only jobs risked accidental cleanup on reload Runtime scheduled turns are preserved on restart/reload, cleaned on disable/reset/delete Reload is safe; destructive lifecycle operations still clean plugin state
Side effects Tests could trigger real scheduler/outbound side effects Side effects are gated by runtime config and lazy imports Unit/contract tests stay deterministic
Queued injections Priority shape was not explicitly validated Priority is typed and invalid values are rejected Prompt prep cannot be destabilized by malformed persisted queue entries
Event streams Plugin event subscription payloads needed runtime validation Workflow event/action schemas are enforced Bad stream lists or event payloads fail closed
Metadata/policy params Policy params could accept non-plain-object shapes Params are plain-object guarded Defends policy evaluation paths from malformed plugin input
Docs examples Examples referenced old stack boundaries and optional session keys unsafely Examples guard session-bound calls and reference the consolidated landing shape Maintainers and plugin authors get accurate copy-pasteable guidance

Before / After Examples

Scheduled turns stay cron-compatible

Before, a plugin schedule helper could produce payloads with default delivery metadata that the closed cron schema did not accept.

After, scheduled session turns only send cron-compatible fields:

api.scheduleSessionTurn({
  sessionKey,
  text: "Check whether the deployment window is still blocked.",
  runAt: new Date(Date.now() + 15 * 60_000).toISOString(),
});

Session action validation fails deterministically

Before, malformed action outputs could surface as generic runtime failures.

After, invalid action registration or invalid action results are rejected through typed plugin-action errors:

api.registerSessionAction({
  id: "deploy.approve",
  inputSchema: {
    type: "object",
    properties: { deploymentId: { type: "string" } },
    required: ["deploymentId"],
    additionalProperties: false,
  },
  async handler(ctx, input) {
    return {
      ok: true,
      reply: `Approved ${input.deploymentId}`,
      continueAgent: true,
    };
  },
});

Scheduler cleanup is owner-safe

Before, stale cleanup could be too broad when old and new scheduler records shared job ids.

After, cleanup exclusions are keyed by owner and job id. A plugin reload can preserve its active jobs, while disable/reset/delete still removes plugin-owned scheduled state.

Finalize retry is bounded

Before, a plugin that wanted to repair a final reply had no generic host-mediated finalize retry seam.

After, workflow plugins can request a bounded retry through the finalize hook path, and the helper tests prove retries clear their budget rather than looping indefinitely.

Example Plugin Shapes

Deploy approval plugin

api.registerSessionExtension({
  namespace: "deployApproval",
  description: "Pending deployment approvals for this session",
});

api.registerSessionAction({
  id: "deploy.approve",
  inputSchema: {
    type: "object",
    properties: { deploymentId: { type: "string" } },
    required: ["deploymentId"],
    additionalProperties: false,
  },
  async handler(ctx, input) {
    await api.enqueueNextTurnInjection({
      sessionKey: ctx.sessionKey,
      text: `Deployment ${input.deploymentId} was approved. Continue the release checklist.`,
      priority: "high",
    });
    return { ok: true, reply: "Approved.", continueAgent: true };
  },
});

Budget guard plugin

api.registerTrustedToolPolicy({
  id: "budget.guard",
  description: "Block expensive tools when the session budget is exhausted",
  async evaluate(ctx) {
    const budget = await api.getRunContext(ctx.runId, "budget.remainingUsd");
    if (typeof budget === "number" && budget <= 0) {
      return { block: true, reason: "Session budget exhausted" };
    }
    return { allow: true };
  },
});

SLA watcher plugin

api.registerAgentEventSubscription({
  streams: ["agent.lifecycle", "agent.tool"],
  async handler(event) {
    if (event.type === "agent.lifecycle" && event.name === "turn.started") {
      await api.scheduleSessionTurn({
        sessionKey: event.sessionKey,
        runAt: new Date(Date.now() + 30 * 60_000).toISOString(),
        text: "SLA watcher: check whether this incident still needs escalation.",
      });
    }
  },
});

Artifact responder plugin

api.registerSessionAction({
  id: "review.sendArtifact",
  inputSchema: {
    type: "object",
    properties: { path: { type: "string" }, label: { type: "string" } },
    required: ["path", "label"],
    additionalProperties: false,
  },
  async handler(ctx, input) {
    await api.sendSessionAttachment({
      sessionKey: ctx.sessionKey,
      path: input.path,
      label: input.label,
    });
    return { ok: true, reply: `Sent ${input.label}.` };
  },
});

Removed Or Refactored Code

No Plan Mode product code is added here. No Plan Mode prompts, /plan command behavior, Telegram routing, local installer patches, arbitrary browser JS, or Plan Mode-specific UI cards are introduced.

Refactors/removals are limited to keeping the generic workflow surface production-safe:

  • Scheduled turn payload metadata was narrowed so the helper emits only fields accepted by the existing cron schema. Risk: plugin authors cannot depend on a default delivery string. Mitigation: docs and tests show the omitted-default form.
  • Runtime workflow side effects are lazy/gated by config. Risk: code paths become more indirect. Mitigation: contract tests exercise both registered behavior and no-side-effect fixture behavior.
  • Workflow helper logic is centralized in src/plugins/host-hook-workflow.ts rather than scattering session action, attachment, and scheduling paths through Gateway/runner code. Risk: one module carries more responsibility. Mitigation: focused contract tests cover validation and output normalization.
  • Finalize retry helper behavior is factored into src/agents/harness/lifecycle-hook-helpers.ts to make bounded retry explicit. Risk: runner integration changes. Mitigation: lifecycle helper tests and host-hook contract coverage.
  • Docs examples removed the core-tool metadata pattern from the earlier docs review because metadata projection is plugin-owned. Risk: less broad-looking example. Mitigation: examples now match the actual contract and avoid implying plugins can rewrite core-owned catalog entries.

Validation

Local validation on this consolidated branch:

pnpm test src/plugins/contracts/host-hooks.contract.test.ts src/plugins/contracts/advanced-workflow-fixtures.contract.test.ts src/agents/pi-tools.before-tool-call.integration.e2e.test.ts src/auto-reply/reply/commands-plugin.test.ts
# passed: 2 plugin contract files / 55 tests, 1 auto-reply file / 4 tests, 1 e2e file / 10 tests

pnpm docs:list
# passed

pnpm plugin-sdk:api:check
# passed after regenerating docs/.generated/plugin-sdk-api-baseline.sha256

pnpm tsgo:all
# passed

pnpm lint
# passed

pnpm check:architecture
# passed: import cycles, madge cycles, deprecated internal config API guard

pnpm check:changed
# passed

pnpm build
# passed

git diff --check upstream/main...HEAD
# passed

OPENCLAW_VITEST_MAX_WORKERS=2 OPENCLAW_VITEST_SHARD_NAME=core-unit-fast-support pnpm exec node scripts/test-projects.mjs test/vitest/vitest.unit-fast.config.ts test/vitest/vitest.unit-support.config.ts
# passed: 887 unit-fast files, 7911 tests

Maintainer Checklist

Rollback: revert this PR. No DB migration is expected. The surfaces are additive; plugin-owned state and scheduled jobs are host-owned and cleanup/ignore paths are covered by the foundation plus this follow-up.

Issue / RFC Linkage

@clawsweeper
Copy link
Copy Markdown
Contributor

clawsweeper Bot commented Apr 28, 2026

Codex review: needs changes before merge.

What this changes:

The PR adds generic Plugin SDK workflow host seams, Gateway plugins.sessionAction protocol handling, scheduler/attachment/finalize-retry helpers, generated client/API baselines, contract fixtures, and QA hardening.

Required change before merge:

A narrow automated repair can add the missing changelog entry; broader API approval and unresolved CI failures still need normal maintainer review after that mechanical fix.

Security review:

Security review cleared: Dedicated security review found no concrete security or supply-chain regression in the diff; sensitive paths such as workflow dispatch, attachments, scheduler cleanup, CI, lockfile, and generated clients were inspected.

Review findings:

  • [P3] Add the required changelog entry — src/plugins/types.ts:2510-2533
Review details

Best possible solution:

Add the missing release-note entry, resolve the exact-head CI failures, and continue reviewing this PR as the implementation vehicle for the generic workflow layer while keeping the recipe documentation in the separate docs PR.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a feature PR, but the current-main comparison is high-confidence: current main lacks the workflow SDK methods and plugins.sessionAction, while the PR head adds them. The remaining review finding is reproducible by the PR file list excluding CHANGELOG.md.

Is this the best way to solve the issue?

Yes for the architecture direction: additive Plugin SDK/Gateway seams with contract fixtures are the maintainable path for this workflow surface. No for merge-readiness as-is because repo policy still requires a changelog entry and exact-head CI must be green.

Full review comments:

  • [P3] Add the required changelog entry — src/plugins/types.ts:2510-2533
    This PR adds user-facing Plugin SDK and Gateway workflow APIs, but the diff does not update CHANGELOG.md. Repo policy requires user-facing feature changes to add a single-line entry under Unreleased with contributor credit, so release notes will miss this SDK surface unless the changelog is added before merge.
    Confidence: 0.94

Overall correctness: patch is correct
Overall confidence: 0.78

Acceptance criteria:

  • git diff --check
  • pnpm docs:list
  • pnpm check:changed in Testbox after the branch repair because the full PR touches public SDK, Gateway protocol, generated clients, and test surfaces

What I checked:

  • Current main lacks workflow SDK methods: OpenClawPluginApi on current main has agent event subscriptions, run context, and scheduler job registration, but not emitAgentEvent, scheduleSessionTurn, sendSessionAttachment, or registerSessionAction. (src/plugins/types.ts:2493, 4eec2843cd0c)
  • Current main lacks session-action Gateway dispatch: Current main's plugin host hook handlers expose only plugins.uiDescriptors; there is no plugins.sessionAction handler. (src/gateway/server-methods/plugin-host-hooks.ts:10, 4eec2843cd0c)
  • PR head adds workflow SDK methods: The PR head adds emitAgentEvent, scheduleSessionTurn, sendSessionAttachment, and registerSessionAction to the plugin API type. (src/plugins/types.ts:2510, b7fc58c28894)
  • PR head adds Gateway session action handler: The PR head adds an async plugins.sessionAction handler with param validation, registry lookup, scope enforcement, schema validation, typed success/failure responses, and sanitized exception handling. (src/gateway/server-methods/plugin-host-hooks.ts:52, b7fc58c28894)
  • Earlier runtime-deps blocker appears repaired: Latest head only adds the install-capable compatibility key when the request itself is installBundledRuntimeDeps:false, so explicit install requests no longer match skip-runtime-deps registries by this path. (src/plugins/loader.ts:988, b7fc58c28894)
  • Earlier finalize-retry blocker appears repaired: Latest head normalizes retry instructions and selects the first non-empty retry when merging multiple before_agent_finalize revise results. (src/plugins/hooks.ts:324, b7fc58c28894)

Likely related people:

  • 100yenadmin: Authored the merged generic host-hook foundation commit on current main and this PR builds directly on that Plugin SDK/Gateway surface. (role: introduced behavior / adjacent owner; confidence: high; commits: 1adaa28dc86b; files: src/plugins/types.ts, src/plugins/host-hooks.ts, src/plugins/registry.ts)
  • vincentkoc: Recent current-main history includes the before-agent-finalize hook and related plugin/runtime work that this PR extends with bounded finalize retry semantics. (role: adjacent hook/runtime maintainer; confidence: medium; commits: f3accc753cf2, 1d61862adb0d, 4c675216f1ce; files: src/agents/harness/lifecycle-hook-helpers.ts, src/plugins/registry.ts, .github/workflows/parity-gate.yml)
  • steipete: Recent current-main commits touch plugin runtime dependency staging, plugin path resolution, release validation, and parity-gate workflow behavior adjacent to this PR's loader and CI surfaces. (role: recent maintainer / adjacent owner; confidence: medium; commits: 8cf724a381a3, 5138d3f8b6ba, cc7a20998250; files: src/plugins/types.ts, src/plugins/registry.ts, .github/workflows/parity-gate.yml)

Remaining risk / open question:

  • Exact-head CI is not green: check-lint and checks-fast-bundled failed, while parity and security-high checks were still in progress at inspection time.
  • The PR changes a broad public Plugin SDK, Gateway protocol, generated Swift model, workflow, and QA surface, so maintainer API review is still needed even after the mechanical changelog fix.
  • The check-run metadata did not include failure logs in the inspected API output, so the root cause of the red CI jobs remains unresolved.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 4eec2843cd0c.

@100yenadmin 100yenadmin force-pushed the feature/plugin-sdk-workflow-followups-consolidated branch from d0e45df to db15c9c Compare April 28, 2026 07:52
@100yenadmin 100yenadmin marked this pull request as ready for review April 28, 2026 07:53
Copilot AI review requested due to automatic review settings April 28, 2026 07:53
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented Apr 28, 2026

Greptile Summary

This consolidated PR builds workflow seams on top of the already-merged #72287 host-hook foundation: typed session actions (with JSON Schema validation and scope enforcement), host-mediated outbound attachments, cron-compatible scheduled session turns, bounded finalize retries, and priority-sorted next-turn injection queues. The implementation is well-hardened — schema validation fails closed, cleanup is keyed by owner+jobId to prevent cross-plugin interference, and finalize retry budgets are bounded and cleared per-run. The only nit is three split import declarations from the same module in prepare.ts.

Confidence Score: 4/5

Safe to merge; changes are additive, well-tested, and only carry a minor style nit.

All findings are P2. The PR is thoroughly tested with contract tests covering validation, cleanup, scheduling, and finalize retry semantics. No logic errors, security issues, or correctness problems were found in the Gateway handler, cleanup paths, or retry budget logic.

No files require special attention beyond the import style nit in src/agents/cli-runner/prepare.ts.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/cli-runner/prepare.ts
Line: 35-37

Comment:
**Duplicate imports from the same module**

Three separate import declarations reference `"../pi-embedded-runner/run/attempt.prompt-helpers.js"`. These should be collapsed into a single import to follow the module-import style used everywhere else in the file.

```suggestion
import {
  forgetPromptBuildDrainCacheForRun,
  resolvePromptBuildHookResult,
  resolveAttemptPrependSystemContext,
} from "../pi-embedded-runner/run/attempt.prompt-helpers.js";
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "chore(plugin-sdk): refresh rebased API b..." | Re-trigger Greptile

Comment thread src/agents/cli-runner/prepare.ts Outdated
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR consolidates the post-#72287 plugin host-hook follow-ups by landing workflow seams (session actions, outbound attachments, scheduling, finalize-retry), executable fixture proofs, and the companion docs/recipes together on current main.

Changes:

  • Add workflow-oriented Plugin SDK seams: session action dispatch (Gateway method), host-mediated session scheduling, outbound session attachments, and plugin-attributed agent event emission.
  • Harden host runtime behavior: prioritized next-turn injections, trusted policy session-state reads, bounded finalize-retry budgeting, and safer scheduler cleanup semantics.
  • Expand contract tests/fixtures and publish a large recipes doc, plus regenerated protocol/Swift models and SDK API baseline.

Reviewed changes

Copilot reviewed 42 out of 42 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/plugins/types.ts Exports new workflow seam types and adds SDK methods to OpenClawPluginApi.
src/plugins/trusted-tool-policy.ts Adds plain-object guarding for param rewrites and injects getSessionExtension into trusted policy context.
src/plugins/runtime.ts Moves agent-event bridge unsubscribe tracking into global registry state.
src/plugins/runtime-state.ts Extends RegistryState to store agent event unsubscribe handle.
src/plugins/registry.ts Registers session actions, wires workflow helpers (emit event / schedule turn / send attachment), validates session-action JSON schema.
src/plugins/registry-types.ts Adds sessionActions registry typing.
src/plugins/registry-empty.ts Initializes sessionActions array in empty registry.
src/plugins/host-hooks.ts Introduces workflow types: session actions, attachments, scheduling, and agent event emit params/results.
src/plugins/host-hook-workflow.ts Implements host-mediated workflow helpers (emit events, attachments via outbound, schedule session turns via cron).
src/plugins/host-hook-turn-types.ts Adds priority to next-turn injections.
src/plugins/host-hook-state.ts Validates/persists injection priority, sorts by priority then time, adds sync session-extension read helper, defaults config sourcing.
src/plugins/host-hook-runtime.ts Adds bounded wait for terminal event handlers, improves scheduler cleanup exclusions and preserve semantics.
src/plugins/host-hook-cleanup.ts Extends cleanup to also remove runtime-only scheduler jobs while avoiding registry-owned duplicates.
src/plugins/hooks.ts Adds hook-runner context mapping (inject getSessionExtension) and propagates finalize-retry metadata through result merging.
src/plugins/hook-types.ts Extends before_agent_finalize result with structured retry request; extends tool context with optional getSessionExtension.
src/plugins/contracts/host-hooks.contract.test.ts Adds contract coverage for session actions, workflow failures being non-fatal, bounded terminal cleanup wait, priority validation, and scheduler cleanup edge cases.
src/plugins/contracts/advanced-workflow-fixtures.ts Adds reusable “realistic archetype” fixture plugin registrations that exercise composed seams.
src/plugins/contracts/advanced-workflow-fixtures.contract.test.ts End-to-end fixture proofs across approval/action dispatch, policy gates, scheduling + cleanup, attachments, and bounded finalize retry.
src/plugins/captured-registration.ts Captures new workflow registrations in the test capture harness (actions, scheduling, attachments, event emit).
src/plugins/api-builder.ts Adds no-op wiring for new SDK methods when not provided by host.
src/plugin-sdk/plugin-test-api.ts Updates test API stub with new workflow methods.
src/plugin-sdk/plugin-entry.ts Re-exports new workflow types from the SDK entry surface.
src/plugin-sdk/core.ts Re-exports new workflow types from SDK core.
src/gateway/server-methods/plugin-host-hooks.ts Adds plugins.sessionAction Gateway method with schema validation and typed success/failure responses.
src/gateway/server-methods-list.ts Registers plugins.sessionAction in the server method list.
src/gateway/protocol/schema/types.ts Adds protocol types for session-action params/result.
src/gateway/protocol/schema/protocol-schemas.ts Registers new session-action schemas in protocol schema map.
src/gateway/protocol/schema/plugins.ts Defines JSON-value schema for plugin payloads, extends UI descriptor schema, and adds session-action schemas.
src/gateway/protocol/index.ts Adds AJV validator for PluginsSessionActionParams and exports schema.
src/gateway/method-scopes.ts Adds plugins.sessionAction under write-scoped methods.
src/config/sessions/types.ts Persists optional injection priority in session store type.
src/agents/pi-tools.before-tool-call.integration.e2e.test.ts Loosens assertion to expect.objectContaining(...) for tool context shape.
src/agents/pi-embedded-runner/run.ts Clears finalize-retry budget on run end alongside other per-run caches.
src/agents/harness/lifecycle-hook-helpers.ts Implements bounded finalize-retry budgeting keyed by run/idempotency, with pruning and explicit clearing.
src/agents/harness/lifecycle-hook-helpers.test.ts Adds tests verifying finalize-retry budget clearing by run id.
src/agents/cli-runner/prepare.ts Avoids loading transcript messages unless needed by hooks; ensures prompt-drain cache cleanup in finally.
docs/plugins/host-hooks-examples.md Publishes consolidated host-hook recipes/examples page.
docs/docs.json Adds the new recipes page to docs navigation.
docs/.i18n/glossary.zh-CN.json Adds glossary entries for the new recipes page labels.
docs/.generated/plugin-sdk-api-baseline.sha256 Updates SDK API baseline checksums.
apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift Regenerates Swift models for descriptor fields + session-action RPC types.
apps/macos/Sources/OpenClawProtocol/GatewayModels.swift Regenerates Swift models for descriptor fields + session-action RPC types.

Comment thread src/gateway/server-methods/plugin-host-hooks.ts
Comment thread src/plugins/host-hook-workflow.ts
Comment thread src/plugins/host-hooks.ts
Comment thread src/plugins/host-hooks.ts
@100yenadmin 100yenadmin requested a review from a team as a code owner April 28, 2026 08:00
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: db15c9c0bb

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/plugins/registry.ts Outdated
Comment thread src/plugins/registry.ts Outdated
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 44 out of 44 changed files in this pull request and generated 3 comments.

Comment thread docs/plugins/host-hooks-examples.md Outdated
Comment thread docs/plugins/host-hooks-examples.md Outdated
Comment thread docs/plugins/host-hooks-examples.md Outdated
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2d6fe5ebed

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/plugins/host-hook-workflow.ts
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 45 out of 45 changed files in this pull request and generated 4 comments.

Comment thread src/plugins/host-hook-workflow.ts
Comment thread src/plugins/host-hook-workflow.ts
Comment thread src/gateway/server-methods/plugin-host-hooks.ts Outdated
Comment thread src/plugins/trusted-tool-policy.ts
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 45 out of 45 changed files in this pull request and generated no new comments.

@100yenadmin 100yenadmin requested a review from Copilot April 28, 2026 08:48
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 97f73f9c26

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/plugins/loader.ts Outdated
@100yenadmin
Copy link
Copy Markdown
Contributor Author

Closing this consolidated stack in favor of individual hook/seam PRs. The code has been through hardening, but the combined PR became too large and brittle against fast-moving upstream main plugin sprint leading to messy additional debugging. Splitting it back into focused fresh-main PRs should reduce reviewer load, isolate CI failures, and make each generic SDK seam independently mergeable even if main shifts.

@100yenadmin
Copy link
Copy Markdown
Contributor Author

Closing this consolidated stack in favor of individual hook/seam PRs. The code has been through hardening, but the combined PR became too large and brittle against fast-moving upstream main. Splitting it into focused fresh-main PRs should reduce reviewer load, isolate CI failures, and make each generic SDK seam independently mergeable.

Replacement slices opened so far:

  1. [plugin sdk] Add session action gateway protocol #75578 — Session actions + Gateway protocol
  2. [plugin sdk] Add host-mediated session attachments #75581 — Host-mediated attachments
  3. [plugin sdk] Add scheduled session turns #75588 — Scheduled turns + cleanup
  4. [plugin sdk] Harden finalize retry and run context cleanup #75600 — Finalize retry + run context lifecycle
  5. [plugin sdk] Derive tool target paths for hooks #75605 — Tool-derived path facts
  6. [plugin sdk] Project session extension slots #75609 — SessionEntry slot projection

The advanced workflow fixture slice should be filed after these seams land on main; opening it now from fresh main would fail before the public seams exist, while stacking or duplicating those seams would recreate the brittle consolidated PR this split is replacing.

Docs remain split in #74853; foundation remains merged #72287.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: macos App: macos app: web-ui App: web-ui cli CLI command changes docs Improvements or additions to documentation extensions: qa-lab gateway Gateway runtime scripts Repository scripts size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants