Skip to content

(MOT-3962) Hide internal worker plumbing from engine::functions::list - #474

Merged
andersonleal merged 2 commits into
mainfrom
andersonleal/mot-3962-hide-internal-worker-plumbing-from-enginefunctionslist
Jul 10, 2026
Merged

(MOT-3962) Hide internal worker plumbing from engine::functions::list#474
andersonleal merged 2 commits into
mainfrom
andersonleal/mot-3962-hide-internal-worker-plumbing-from-enginefunctionslist

Conversation

@andersonleal

@andersonleal andersonleal commented Jul 10, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • engine::functions::list is the candidate universe harness's LLM tool-discovery pulls from, and it was returning every internal orchestration/config-reload/write-path function unfiltered — router::chat, session::store::*, provider::*::stream, harness::send/turn/stop, console browser watch handlers, etc. — even though most of it is already denied to agents in iii-permissions.yaml. Discovery and authorization were two separate gates; this closes the discovery one too (defense-in-depth).
  • Tags ~94 non-agent-facing registrations across 10 workers with metadata.internal = true, the field engine::functions::list already checks (engine/src/workers/engine_fn/mod.rs in ../iii) to hide tagged functions by default. Registrations stay fully callable by id — only discovery is hidden. Full per-worker breakdown in the linked ticket.
  • console gets two extra layers: the browser SDK's client.on() now defaults new registrations to internal (console/web/src/lib/iii-client.ts), and the WS proxy stamps metadata.internal = true onto any registerfunction frame passing through it (console/src/proxy.rs) so a stale/cached SPA bundle can't leak a registration.
  • Out of scope: engine builtins in ../iii (state::set/update/delete, stream::*, iii::durable::publish, iii::queue::*, configuration::*, worker::*) — same fix, different repo.

Test plan

  • cargo check on all 12 touched Rust crates
  • cargo fmt --check on all 12 touched Rust crates
  • py_compile on scrapling's guidance.py
  • tsc --noEmit on console/web
  • llm-router cargo test --test schemas (4 passed)
  • context-manager cargo test --test schemas (4 passed)
  • harness cargo test surface/functions subsets (49 passed)
  • session-manager cargo test --tests (66 passed)
  • console cargo test --lib proxy (8 passed, 3 new)
  • Manual: restart affected workers + reload console tab, confirm engine::functions::list no longer returns the tagged ids

MOT-3962: https://linear.app/motia/issue/MOT-3962/hide-internal-worker-plumbing-from-enginefunctionslist

Summary by CodeRabbit

  • New Features

    • Internal platform functions are now identified and excluded from standard function discovery.
    • Browser-registered handlers are automatically marked as internal while preserving custom registration options.
    • Internal metadata is consistently applied across configuration, session, provider, router, harness, and system functions.
  • Bug Fixes

    • Improved handling of registration messages, including existing metadata, malformed payloads, and unrelated messages.

engine::functions::list is the candidate universe harness's LLM
tool-discovery pulls from. It returned every internal orchestration,
config-reload, and write-path function unfiltered — router::chat,
session::store::*, provider::*::stream, harness::send/turn/stop,
console browser watch handlers, and more — even though most of it is
already denied to agents in iii-permissions.yaml. Discovery and
authorization were two separate gates; this closes the discovery one
too.

Tags ~94 non-agent-facing registrations across 10 workers with
metadata.internal = true, the field engine::functions::list already
checks to hide tagged functions by default. Registrations stay fully
callable by id — only discovery is hidden.

console gets two extra layers: the browser SDK's client.on() now
defaults new registrations to internal, and the WS proxy stamps
metadata.internal = true onto any registerfunction frame passing
through it, so a stale/cached SPA bundle can't leak a registration.
@vercel

vercel Bot commented Jul 10, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
workers Ready Ready Preview, Comment Jul 10, 2026 9:35pm
workers-tech-spec Ready Ready Preview, Comment Jul 10, 2026 9:35pm

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

skill-check — worker

0 verified, 41 skipped (no docs/).

Layer Result
structure
vale
ai
render

Four for four. Nicely done.

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The change marks internal control-plane, router, provider, session, and hook registrations with metadata.internal = true. Browser registrations gain optional SDK options, and the console proxy stamps browser-to-engine registerfunction messages while preserving unsupported or unrelated messages.

Changes

Internal registration visibility

Layer / File(s) Summary
Browser registration stamping
console/src/proxy.rs, console/web/src/lib/iii-client.ts
The SDK accepts registration options, while the proxy recognizes and stamps browser-originated registerfunction messages with internal metadata and tests the supported and rejected inputs.
Shared registration helpers
context-manager/src/functions/mod.rs, harness/src/functions/mod.rs, session-manager/src/functions/mod.rs
Context, harness, and session registration helpers assign internal visibility per function while retaining typed handlers and existing wiring.
Service control registrations
console/src/functions/mod.rs, */src/configuration.rs, harness/src/subscriptions/*, iii-directory/src/*, scrapling/src/*, shell/src/*, web/src/*, session-manager/src/functions/store_protocol.rs
Internal metadata is added to service configuration, status, hook, directory, notification, shell, web, and raw session-store registrations.
Router and provider registrations
llm-router/src/register.rs, provider-*/src/register.rs
Router and provider stream, refresh, readiness, routing, and configuration registrations are marked internal.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant IiiClient
  participant ConsoleProxy
  participant IiiEngine
  Browser->>IiiClient: register handler with options
  IiiClient->>ConsoleProxy: send registerfunction message
  ConsoleProxy->>ConsoleProxy: stamp metadata.internal
  ConsoleProxy->>IiiEngine: forward stamped message
Loading

Poem

I’m a rabbit with metadata bright,
Hiding control functions from catalog sight.
Through proxy and handlers, the flags gently flow,
Router and providers now clearly know.
Hop, hop—internal registrations glow!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: hiding internal worker plumbing from engine::functions::list.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch andersonleal/mot-3962-hide-internal-worker-plumbing-from-enginefunctionslist

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
harness/src/functions/mod.rs (1)

114-142: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consolidate register_internal into register with an internal: bool parameter.

register_internal duplicates the entire body of register solely to append .metadata(...). The context-manager crate in this same PR already solved this by adding internal: bool to its register helper and conditionally applying metadata. Adopting the same pattern here eliminates ~15 lines of duplicated code and keeps the two crates consistent.

♻️ Proposed refactor: replace `register_internal` with an `internal` flag on `register`

Remove register_internal and add internal: bool to the existing register function (not shown, near line 90):

 fn register<Req, Resp, F, Fut>(
     iii: &Arc<IIIClient>,
     deps: &Arc<Deps>,
     id: &str,
     description: &str,
+    internal: bool,
     handler: F,
 ) where
     Req: DeserializeOwned + JsonSchema + Send + 'static,
     Resp: Serialize + JsonSchema + Send + 'static,
     F: Fn(Arc<Deps>, Req) -> Fut + Send + Sync + Clone + 'static,
     Fut: Future<Output = Result<Resp, HarnessError>> + Send + 'static,
 {
     let deps = deps.clone();
-    iii.register_function(
-        id,
-        RegisterFunction::new_async(move |req: Req| {
-            let deps = deps.clone();
-            let handler = handler.clone();
-            async move { handler(deps, req).await.map_err(Error::from) }
-        })
-        .description(description),
-    );
+    let reg = RegisterFunction::new_async(move |req: Req| {
+        let deps = deps.clone();
+        let handler = handler.clone();
+        async move { handler(deps, req).await.map_err(Error::from) }
+    })
+    .description(description);
+    let reg = if internal {
+        reg.metadata(serde_json::json!({ "internal": true }))
+    } else {
+        reg
+    };
+    iii.register_function(id, reg);
 }

Then delete register_internal (lines 114–141) and update call sites:

-    register_internal(iii, deps, SEND_ID, SEND_DESC, |d, r| async move {
+    register(iii, deps, SEND_ID, SEND_DESC, true, |d, r| async move {
         send::handle(&d, r).await
     });
-    register(iii, deps, SPAWN_ID, SPAWN_DESC, |d, r| async move {
+    register(iii, deps, SPAWN_ID, SPAWN_DESC, false, |d, r| async move {
         spawn::handle(&d, r).await
     });

Apply the same true/false argument to every register_internalregister call site in register_all.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@harness/src/functions/mod.rs` around lines 114 - 142, Consolidate the
duplicated register_internal helper into register by adding an internal: bool
parameter to register and conditionally applying the internal metadata when
true. Remove register_internal, then update every call in register_all to use
register with true for previously internal registrations and false for normal
registrations, preserving existing behavior and descriptions.
provider-anthropic/src/register.rs (1)

132-163: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider extracting a local internal_meta() helper for consistency with llm-router.

The inline json!({ "internal": true }) is repeated 3× in this file and identically across all 5 provider crates (15 total occurrences). llm-router already uses an internal_meta() helper for the same pattern. A local helper in each provider crate would improve consistency and centralize future metadata changes.

♻️ Suggested helper extraction
+fn internal_meta() -> serde_json::Value {
+    json!({ "internal": true })
+}
+
 // ...
 iii.register_function(
     surface::STREAM_ID,
     RegisterFunction::new_async_with_bad_request(
         make_stream(iii.clone(), http.clone()),
         invalid_request_from_serde,
     )
     .description(surface::STREAM_DESC)
-    .metadata(json!({ "internal": true })),
+    .metadata(internal_meta()),
 );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@provider-anthropic/src/register.rs` around lines 132 - 163, Extract a local
internal_meta() helper in the provider module returning the shared internal
metadata object, then replace all three inline json!({ "internal": true })
expressions in the function registrations, including STREAM_ID,
REFRESH_MODELS_ID, and ON_ROUTER_READY_ID. Apply the same helper pattern
consistently across the other provider crates.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@console/web/src/lib/iii-client.ts`:
- Around line 155-162: Preserve the default internal metadata when callers
provide metadata through options. In the handler registration block using
sdk.registerFunction, merge options.metadata with { internal: true } after
spreading options, ensuring caller metadata cannot overwrite the internal flag
while retaining other metadata fields.

---

Nitpick comments:
In `@harness/src/functions/mod.rs`:
- Around line 114-142: Consolidate the duplicated register_internal helper into
register by adding an internal: bool parameter to register and conditionally
applying the internal metadata when true. Remove register_internal, then update
every call in register_all to use register with true for previously internal
registrations and false for normal registrations, preserving existing behavior
and descriptions.

In `@provider-anthropic/src/register.rs`:
- Around line 132-163: Extract a local internal_meta() helper in the provider
module returning the shared internal metadata object, then replace all three
inline json!({ "internal": true }) expressions in the function registrations,
including STREAM_ID, REFRESH_MODELS_ID, and ON_ROUTER_READY_ID. Apply the same
helper pattern consistently across the other provider crates.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0eec7339-dc51-4311-a7f3-6101ebd5fe19

📥 Commits

Reviewing files that changed from the base of the PR and between 1e52245 and c0e48d0.

📒 Files selected for processing (25)
  • console/src/functions/mod.rs
  • console/src/proxy.rs
  • console/web/src/lib/iii-client.ts
  • context-manager/src/configuration.rs
  • context-manager/src/functions/mod.rs
  • harness/src/configuration.rs
  • harness/src/functions/mod.rs
  • harness/src/subscriptions/notify_agent.rs
  • iii-directory/src/configuration.rs
  • iii-directory/src/main.rs
  • llm-router/src/register.rs
  • provider-anthropic/src/register.rs
  • provider-openai-codex/src/register.rs
  • provider-openai/src/register.rs
  • provider-xai/src/configuration.rs
  • provider-xai/src/register.rs
  • provider-zai/src/register.rs
  • scrapling/src/guidance.py
  • session-manager/src/configuration.rs
  • session-manager/src/functions/mod.rs
  • session-manager/src/functions/store_protocol.rs
  • shell/src/configuration.rs
  • shell/src/main.rs
  • web/src/configuration.rs
  • web/src/functions/mod.rs

Comment on lines +155 to +162
// Every handler registered here is a browser-local console plumbing fn
// (traces, sessions, worktree events, ...) — none are meant for other
// workers (e.g. harness) to discover, so default them out of
// `engine::functions::list`. Callers can still override via `options`.
const ref = sdk.registerFunction(id, wrapped, {
metadata: { internal: true },
...options,
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Shallow spread drops internal: true when caller provides metadata in options.

{ metadata: { internal: true }, ...options } performs a shallow merge. If a caller passes options containing any metadata property, the entire default { internal: true } is replaced — not deep-merged. A caller adding { metadata: { custom: "x" } } would unintentionally lose the internal flag.

The proxy stamping in console/src/proxy.rs provides defense-in-depth, so the practical risk is low. But if you want the SPA default to be robust on its own, consider deep-merging or documenting that callers must include internal: true when passing metadata.

♻️ Optional: deep-merge metadata to preserve the default
     const ref = sdk.registerFunction(id, wrapped, {
-      metadata: { internal: true },
-      ...options,
+      ...options,
+      metadata: { internal: true, ...options?.metadata },
     })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Every handler registered here is a browser-local console plumbing fn
// (traces, sessions, worktree events, ...) — none are meant for other
// workers (e.g. harness) to discover, so default them out of
// `engine::functions::list`. Callers can still override via `options`.
const ref = sdk.registerFunction(id, wrapped, {
metadata: { internal: true },
...options,
})
// Every handler registered here is a browser-local console plumbing fn
// (traces, sessions, worktree events, ...) — none are meant for other
// workers (e.g. harness) to discover, so default them out of
// `engine::functions::list`. Callers can still override via `options`.
const ref = sdk.registerFunction(id, wrapped, {
...options,
metadata: { internal: true, ...options?.metadata },
})
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@console/web/src/lib/iii-client.ts` around lines 155 - 162, Preserve the
default internal metadata when callers provide metadata through options. In the
handler registration block using sdk.registerFunction, merge options.metadata
with { internal: true } after spreading options, ensuring caller metadata cannot
overwrite the internal flag while retaining other metadata fields.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant