Skip to content

feat(desktop): bridge the JIT knowledge-ledger tools into the agent runtime - #12397

Merged
Git-on-my-level merged 1 commit into
mainfrom
feat/desktop-jit-knowledge-tool-bridge
Aug 29, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
feat/desktop-jit-knowledge-tool-bridge

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Why

Verified live on 2026-08-29: a desktop request to save a playbook was routed to a
background agent that wrote the playbook to the filesystem, because the desktop
agent's tool registry (desktop/macos/agent/src/runtime/omi-tool-manifest.ts +
desktop-tool-policy.ts) has no verbs for the backend's JIT-gated knowledge
ledger. The backend already serves these tools via GET /v1/agent/tools and
POST /v1/agent/execute-tool (backend/routers/agent_tools.py), gated per-uid
by resolve_jit_rollout (backend/utils/retrieval/agentic.py /
JIT_ONLY_TOOL_NAMES), and the generated Swift client
(OmiApi.generated.swift) already has the endpoints — nothing called them yet.

This PR bridges the seven tools into the desktop runtime so "save a playbook",
"watch for X", and "that's no longer true" route to the ledger instead of a
generic filesystem/task path.

The seven tools

  • Read (allowed, no approval): search_knowledge, read_playbook,
    search_historical_facts, get_entity_timeline_tool
  • Write (requires user approval): save_playbook, create_standing_trigger,
    close_fact

Schemas and descriptions are drawn from
backend/utils/retrieval/tools/knowledge_ledger_tools.py and
knowledge_ledger_write_tools.py, condensed for desktop use. Manifest prompt
guidance steers durable facts/corrections, playbook saves, standing-watch
requests, and fact closures to the ledger tools instead of create_memory or
a filesystem document (added cross-link bullets on create_memory and
search_knowledge).

Dispatch

Mirrors the existing backend-RAG tools' pattern exactly — swiftTool /
chatToolExecutor in the manifest, dispatched through
ChatToolExecutor.executeUnchecked. Unlike get_conversations /
search_memories / etc., these seven have no bespoke typed /v1/tools/*
route on the backend — they share one generic contract,
POST /v1/agent/execute-tool with {tool_name, params}. So instead of seven
typed wrappers, ChatToolExecutor.executeAgentLedgerTool calls one new
generic APIClient.executeAgentTool (APIClient+Tools.swift), which reuses
the app's existing owner-bound post(...) transport (auth headers, owner
checks) against the endpoint the generated client already exposes.

Spec deviation, flagged as requested: the task description says the
backend contract is {tool_name, arguments}. The actual backend Pydantic
model (ExecuteToolRequest in agent_tools.py) is {tool_name, params}. I
implemented against the real backend contract (params), not the prompt's
paraphrase.

Gating

Client gating is UX only — backend/routers/agent_tools.py independently
re-checks resolve_jit_rollout on every execute-tool call and 404s an
ungated tool regardless of what the client advertised.

The TS runtime has no existing access to the JIT rollout decision
(JITProactivityFlags / JITProactivityRuntime live entirely on the Swift
side, e.g. ProactiveAssistants/Core/JITProactivityRuntime.swift; nothing in
desktop/macos/agent/src references it). Per the task's fallback instruction,
I added a new manifest capability flag, jitKnowledgeToolsEnabled, plumbed
through the runtime the same way the existing screenContext /
onboardingOnly conditions are:

  • QueryMessage.jitKnowledgeToolsEnabled (new optional per-turn field,
    protocol.ts)
  • → McpServerBuildContext.jitKnowledgeToolsEnabled (jsonl-transport.ts),
    and into run metadata (metadata.jitKnowledgeToolsEnabled), mirroring the
    existing reasoningEffort field exactly
  • → OMI_JIT_KNOWLEDGE_TOOLS_ENABLED env var into the omi-tools MCP
    subprocess (index.ts → omi-tools-stdio.ts), mirroring
    OMI_SCREEN_CONTEXT
  • → RunToolCapabilityBroker's persisted-run projection context
    (run-tool-capability.ts), so the authorized-invocation allowlist doesn't
    diverge from what's advertised
  • → new jitKnowledgeToolsEnabled condition in
    isToolAvailableForContext (omi-tool-manifest.ts), applied to all seven
    tools via piAndStdio("jitKnowledgeToolsEnabled")

Swift now actually populates this flag, so the gate is live, not inert.
AgentRuntimeProcess.query(...) (Chat/AgentRuntimeProcess.swift) already
receives the caller's RuntimeOwnerAuthorizationSnapshot on every query. It
now awaits ProactiveLaneClient.shared.jitProactivityFlags(authorizationSnapshot:)
— the exact same client-observable rollout signal JITProactivityRuntime
already reads for the ambient/planned proactive lanes (GET /v1/jit/rollout-decision, server-cached 15s–15min per the response's own
cache_ttl_seconds, so this is a cache hit on every query except the first
after login/TTL expiry) — before building the wire message, and sets
jitKnowledgeToolsEnabled from a new pure helper in a new extension file,
Chat/AgentRuntimeProcess+JITKnowledgeToolsGate.swift
(AgentRuntimeProcess.jitKnowledgeToolsEnabled(from:); the gate logic lives
in its own file rather than the base AgentRuntimeProcess.swift specifically
to respect that file's desktop-agent-runtime-convergence-ratchet line cap,
mirroring the existing AgentRuntimeProcess+BackendRouting.swift /
+ChatFirstJournal.swift extraction convention):

static func jitKnowledgeToolsEnabled(from flags: JITProactivityFlags) -> Bool {
  flags.effective == .enabled
}

This admits only the server's own effective == .enabled verdict — the same
authority JITProactivityFlags.permitsNewLane treats as owning admission,
never re-derived from the raw rollout/kill_switch pair. Any transport,
decode, or owner-authorization-race failure inside jitProactivityFlags
already resolves to .effective == .unknown (fail-closed), which this helper
maps to false. queryWireMessage only emits the wire key when true
(if jitKnowledgeToolsEnabled { message["jitKnowledgeToolsEnabled"] = true }),
matching how the TS side already treats an absent field as false.

Net effect: an enrolled account (server effective: "enabled") now actually
sees and can use the seven tools in chat; everyone else — disabled, unknown,
or any error — sees the pre-existing behavior, unchanged.

Policy

  • Reads added to LOCAL_READ_TOOLS → desktop.context.local_read bundle,
    approvalPolicy: "allow" (matches get_conversations / search_memories
    convention for authenticated backend reads).
  • The three write verbs mutate the same backend memory/knowledge-ledger
    store as create_memory, so they share its desktop.memories.write
    bundle (new LEDGER_WRITE_TOOLS set) rather than inventing a new bundle.
    approvalPolicy is derived automatically from the localWrite annotation
    → "user_approval", matching the existing write/sensitive convention.

Tests

desktop/macos/agent/tests/:

  • omi-tool-manifest.test.ts — manifest entry validity (executor, surfaces,
    latency, read/write annotations), schema shape per backend contract,
    fail-closed-by-default gating, gating-on advertising, prompt-guidance
    cross-links.
  • desktop-tool-policy.test.ts — reads decision allow, writes decision
    dispatch_required/user_approval (same as create_memory), denial when
    the memory-write bundle isn't selected.
  • jsonl-transport.test.ts — the per-turn jitKnowledgeToolsEnabled flag
    reaches both the MCP-build context and persisted run metadata correctly on
    and off.
  • run-tool-capability.test.ts — the authorized-invocation allowlist
    excludes the ledger tools by default and includes them (and authorizes a
    search_knowledge call) once the run's admitted metadata carries the gate.
  • Regenerated tests/fixtures/tool-manifest.json via
    scripts/generate-tool-surfaces.mjs (also regenerates the two touched
    generated Swift files, GeneratedToolCapabilities.swift /
    GeneratedToolExecutors.swift).

desktop/macos/Desktop/Tests/KernelContractWireTests.swift:

  • testQueryWireOmitsJitKnowledgeToolsFlagByDefaultAndCarriesItOnlyWhenTrue —
    the wire key is absent by default and when explicitly false, present
    (true) only when the gate is on.
  • testJitKnowledgeToolsGateAdmitsOnlyTheServersEnabledVerdictAndFailsClosedOtherwise
    — jitKnowledgeToolsEnabled(from:) is true only for
    effective == .enabled; false for an explicit effective == .disabled
    (even with a permissive raw rollout/kill-switch pair), for
    effective == .unknown (the fail-closed shape of any transport/decode/
    owner-race error), and for the older-server-compatibility default where
    effective is omitted entirely.

The effective-verdict derivation itself (enabled/disabled/unknown from
the raw HTTP response, TTL caching, fail-closed on error) was already covered
by the pre-existing ProactiveLaneClientTests.swift (24 tests, unchanged,
still green) — this PR adds the new mapping from that verdict into the query
wire message on top of it.

Verbatim results

npm run build (tsc): clean, no errors.

npm test (vitest): 707 passed, 0 failed (59 test files) — up from 695
passed before this change (12 new tests added).

node --experimental-strip-types scripts/generate-tool-surfaces.mjs --check:
generate-tool-surfaces: all outputs match (--check)

xcrun swift build -c debug --package-path Desktop: Build complete!
(both the initial dispatch-layer build and the follow-up gating-wiring build
succeeded; only a pre-existing unrelated libwebp linker version warning).

./scripts/dev-feedback.py --once swift 'ChatToolExecutor': 44 tests, 0
failures
.

./scripts/dev-feedback.py --once swift 'AgentRuntimeProcessTests': 71
tests, 0 failures
.

./scripts/dev-feedback.py --once swift 'KernelContractWireTests': 17
tests, 0 failures
(15 pre-existing + 2 new).

./scripts/dev-feedback.py --once swift 'ProactiveLaneClientTests': 24
tests, 0 failures
(unchanged — confirms the gating wiring didn't disturb the
existing rollout-decision coverage).

./scripts/agent-logic-harness.sh --cross-surface-smoke: Harness passed
on both rounds.

./scripts/swiftlint-wrapper.sh lint (full repo scope, includes every
touched file): 0 violations, 0 serious.

./scripts/swift-format-wrapper.sh lint on every hand-edited Swift file:
clean (exit 0).

Product invariants affected

  • INV-AGENT-*
  • INV-CHAT-1

Both are cited because this PR touches desktop/macos/agent/src/runtime/**
and ChatToolExecutor.swift. No violation: the seven new tools are ordinary
authenticated backend RAG-style dispatch (same shape as get_conversations /
search_memories), gated through the existing capability/allowlist and
approval-policy machinery rather than a new authority path; they do not touch
session/run/attempt identity, execution-role authorization, or the kernel
transcript store.

Line-count exceptions

Line-Count-Exception: desktop/macos/Desktop/Sources/Providers/ChatToolExecutor.swift | 3457 -> 3497 | Adds one generic dispatch case (7 enum cases routed to one function) plus the executeAgentLedgerTool passthrough for the 7 new JIT knowledge-ledger tools, mirroring the existing executeBackendTool pattern in the same file; this is the file every other backend-tool dispatch case already lives in, so splitting it is a separate refactor out of scope for this bridge PR.

Line-Count-Exception: desktop/macos/Desktop/Sources/Chat/AgentRuntimeProcess.swift | 4376 -> 4387 | Adds a one-line call into the new AgentRuntimeProcess+JITKnowledgeToolsGate.swift extension (gate logic lives there to respect this file's own convergence-ratchet cap) plus one new parameter on the existing queryWireMessage builder, the single call site that already sends every other query field.

Not ready for merge

Draft PR — gating is now live end-to-end (see above), but this stays a draft
per the task's instructions pending human review before marking ready.

…untime

Route the seven backend JIT-gated knowledge-ledger tools (search_knowledge,
read_playbook, search_historical_facts, get_entity_timeline_tool,
save_playbook, create_standing_trigger, close_fact) into the desktop agent
runtime as remote-dispatch tools, so requests like "save a playbook" or
"watch for X" reach the ledger verbs instead of a generic filesystem/task
path.

- Manifest entries mirror the existing backend-RAG tools' swiftTool/
  chatToolExecutor pattern; the three write verbs require user approval
  and reads are allowed, following desktop-tool-policy.ts convention.
- Client-side gating is a jitKnowledgeToolsEnabled projection-context flag,
  plumbed the same way screenContext/onboarding already are (QueryMessage
  -> McpServerBuildContext -> env var / persisted run metadata). It is now
  live: AgentRuntimeProcess.query awaits the same cached JIT rollout
  decision (ProactiveLaneClient.jitProactivityFlags, GET
  /v1/jit/rollout-decision) that JITProactivityRuntime already reads for
  the ambient/planned proactive lanes, and admits only the server's own
  effective == .enabled verdict, failing closed on any error. The backend
  independently re-checks entitlement on every /v1/agent/execute-tool call
  regardless.
- ChatToolExecutor dispatches all seven through one new generic
  APIClient.executeAgentTool wrapper against POST /v1/agent/execute-tool
  ({tool_name, params}), reusing the already-generated Swift client's
  endpoint instead of adding bespoke per-tool routes.

Co-Authored-By: Claude Fable 5 <[email protected]>
@Git-on-my-level
Git-on-my-level force-pushed the feat/desktop-jit-knowledge-tool-bridge branch from 6c636d3 to e8b69e7 Compare August 29, 2026 21:05
@Git-on-my-level
Git-on-my-level marked this pull request as ready for review August 29, 2026 22:10
@Git-on-my-level
Git-on-my-level merged commit d0769fd into main Aug 29, 2026
32 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/desktop-jit-knowledge-tool-bridge branch August 29, 2026 22:10
Git-on-my-level added a commit that referenced this pull request Aug 31, 2026
## What changed and why

Bind JIT admission on every GCP `dev` evaluator (GKE listen, Cloud Run
listen, maintenance), then make first-open, ledger writes,
empty-watchlist suppress, drain, and public-docs hygiene correct before
flipping `jit-processing-v1` to 100% of Omi Beta / TestFlight.
Empty-extraction 500s already landed in #12410. Production `api.omi.me`
PostHog is unchanged.

## Product invariants affected

- INV-AGENT-*
- INV-DATA-1
- INV-MEM-1
- INV-MEM-4
- INV-TASK-2

## How it was verified

- `backend/.venv/bin/python -m pytest
backend/tests/unit/test_backend_runtime_env_validator.py
backend/tests/unit/test_conversation_jit_processing.py
backend/tests/unit/test_first_open_effect_resume.py` — 131 passed after
rebase onto `origin/main`.
- `python3 .github/scripts/check_agent_doc_references.py` and
`check_agents_md_lean.py` — OK.
- `python3 backend/deploy/compose_runtime_env.py` — generated
`runtime_env.yaml` matches overlays (dev TZ recon on, prod off).
- Did not deploy to GCP `dev` or flip PostHog in this PR. After merge:
probe a non-allowlist Beta UID, then operators flip `jit-processing-v1`
to 100% on the **dev** PostHog project only. Keep the two-UID allowlist
until soak.

## Tests

- Runtime-env compose requires PostHog +
`OMI_FIRESTORE_DATA_PLANE_PROJECT` on listen/maintenance.
- `force_process=True` still defers folders/apps when rollout admits;
`bypass_jit_first_open` is the explicit reprocess hatch.
- Empty folders initialize then assign; first-open never
`complete('folder_assignment')` on a skip.
- Ledger writes use the data-plane client; unknown preference slots stay
unslotted.
- macOS/Windows: complete empty watchlist suppresses; incomplete
snapshot consumes the visit; Insight stays gated.
- Cron skips `writer_mode=ledger` dreaming; sweep continues after one
unknown slot.

## Failure class (fixes)

Failure-Class: FC-rollout-flag-absent-from-a-cohost-of-its-code-path

Enabling `jit-processing-v1` while GKE/Cloud Run listen and maintenance
lacked `POSTHOG_PROJECT_API_KEY` (and GKE listen lacked the data-plane
overlay) would have produced two behaviours for the same UID: Cloud Run
chat/sync admitted, listen finalized as `configuration_missing`.

## Test plan

After merge, deploy this PR to GCP `dev`. Probe a **non-allowlist** Beta
UID:

1. `GET /v1/jit/rollout-decision` on desktop-backend and Cloud Run
`backend` → same `effective=enabled` once the flag is on for that UID
(PostHog override before 100% is fine).
2. Live-finalize via GKE listen: logs are not `configuration_missing`;
first-open attaches.
3. Kill-switch drill on **dev** PostHog, including allowlist, then off.
4. Chat `create_standing_trigger` appears on Mac **and** Windows
snapshots.
5. Empty ledger: no ambient nano/full; Windows does not run Insight.
6. Empty extraction conversation is 200.

Then flip `jit-processing-v1` to 100% on the **dev** PostHog project.
Watch writer_mode drain; do not claim extraction is off until `ledger`
is the majority. Keep the two-UID allowlist until soak.

Windows TestFlight floor is builds that include #12381 / #12391 /
#12397; older apps keep the legacy loop and cannot be remotely disabled.

## Line-count exceptions

Oversized files grew by the JIT admission/sweep patches; splitting them
is out of scope for this Beta-readiness PR.

Line-Count-Exception: backend/routers/conversations.py | 1955 -> 1956 |
pass bypass_jit_first_open through create/finalize without splitting the
router
Line-Count-Exception:
backend/utils/conversations/process_conversation.py | 2561 -> 2572 | add
bypass_jit_first_open so force_process stays a lazy-desktop hatch, not a
JIT bypass
Line-Count-Exception: backend/utils/memory/canonical_memory_adapter.py |
3491 -> 3496 | keep empty replace_conversation_source a no-op after
#12410 rebase
Line-Count-Exception: backend/utils/memory/daily_memory_sweep.py | 4994
-> 5008 | unknown-slot ValueError skips that candidate instead of
aborting the day
Line-Count-Exception: backend/utils/sync/pipeline.py | 2527 -> 2528 |
reprocess path sets bypass_jit_first_open


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/12452?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
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