Repository navigation
feat(desktop): bridge the JIT knowledge-ledger tools into the agent runtime - #12397
Merged
Merged
Conversation
…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
force-pushed
the
feat/desktop-jit-knowledge-tool-bridge
branch
from
August 29, 2026 21:05
6c636d3 to
e8b69e7
Compare
Git-on-my-level
marked this pull request as ready for review
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. -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 knowledgeledger. The backend already serves these tools via
GET /v1/agent/toolsandPOST /v1/agent/execute-tool(backend/routers/agent_tools.py), gated per-uidby
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
search_knowledge,read_playbook,search_historical_facts,get_entity_timeline_toolsave_playbook,create_standing_trigger,close_factSchemas and descriptions are drawn from
backend/utils/retrieval/tools/knowledge_ledger_tools.pyandknowledge_ledger_write_tools.py, condensed for desktop use. Manifest promptguidance steers durable facts/corrections, playbook saves, standing-watch
requests, and fact closures to the ledger tools instead of
create_memoryora filesystem document (added cross-link bullets on
create_memoryandsearch_knowledge).Dispatch
Mirrors the existing backend-RAG tools' pattern exactly —
swiftTool/chatToolExecutorin the manifest, dispatched throughChatToolExecutor.executeUnchecked. Unlikeget_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-toolwith{tool_name, params}. So instead of seventyped wrappers,
ChatToolExecutor.executeAgentLedgerToolcalls one newgeneric
APIClient.executeAgentTool(APIClient+Tools.swift), which reusesthe app's existing owner-bound
post(...)transport (auth headers, ownerchecks) 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 Pydanticmodel (
ExecuteToolRequestinagent_tools.py) is{tool_name, params}. Iimplemented against the real backend contract (
params), not the prompt'sparaphrase.
Gating
Client gating is UX only —
backend/routers/agent_tools.pyindependentlyre-checks
resolve_jit_rollouton everyexecute-toolcall and 404s anungated tool regardless of what the client advertised.
The TS runtime has no existing access to the JIT rollout decision
(
JITProactivityFlags/JITProactivityRuntimelive entirely on the Swiftside, e.g.
ProactiveAssistants/Core/JITProactivityRuntime.swift; nothing indesktop/macos/agent/srcreferences it). Per the task's fallback instruction,I added a new manifest capability flag,
jitKnowledgeToolsEnabled, plumbedthrough the runtime the same way the existing
screenContext/onboardingOnlyconditions are:QueryMessage.jitKnowledgeToolsEnabled(new optional per-turn field,protocol.ts)McpServerBuildContext.jitKnowledgeToolsEnabled(jsonl-transport.ts),and into run metadata (
metadata.jitKnowledgeToolsEnabled), mirroring theexisting
reasoningEffortfield exactlyOMI_JIT_KNOWLEDGE_TOOLS_ENABLEDenv var into theomi-toolsMCPsubprocess (
index.ts→omi-tools-stdio.ts), mirroringOMI_SCREEN_CONTEXTRunToolCapabilityBroker's persisted-run projection context(
run-tool-capability.ts), so the authorized-invocation allowlist doesn'tdiverge from what's advertised
jitKnowledgeToolsEnabledcondition inisToolAvailableForContext(omi-tool-manifest.ts), applied to all seventools via
piAndStdio("jitKnowledgeToolsEnabled")Swift now actually populates this flag, so the gate is live, not inert.
AgentRuntimeProcess.query(...)(Chat/AgentRuntimeProcess.swift) alreadyreceives the caller's
RuntimeOwnerAuthorizationSnapshoton every query. Itnow awaits
ProactiveLaneClient.shared.jitProactivityFlags(authorizationSnapshot:)— the exact same client-observable rollout signal
JITProactivityRuntimealready reads for the ambient/planned proactive lanes (
GET /v1/jit/rollout-decision, server-cached 15s–15min per the response's owncache_ttl_seconds, so this is a cache hit on every query except the firstafter login/TTL expiry) — before building the wire message, and sets
jitKnowledgeToolsEnabledfrom a new pure helper in a new extension file,Chat/AgentRuntimeProcess+JITKnowledgeToolsGate.swift(
AgentRuntimeProcess.jitKnowledgeToolsEnabled(from:); the gate logic livesin its own file rather than the base
AgentRuntimeProcess.swiftspecificallyto respect that file's
desktop-agent-runtime-convergence-ratchetline cap,mirroring the existing
AgentRuntimeProcess+BackendRouting.swift/+ChatFirstJournal.swiftextraction convention):This admits only the server's own
effective == .enabledverdict — the sameauthority
JITProactivityFlags.permitsNewLanetreats as owning admission,never re-derived from the raw
rollout/kill_switchpair. Any transport,decode, or owner-authorization-race failure inside
jitProactivityFlagsalready resolves to
.effective == .unknown(fail-closed), which this helpermaps to
false.queryWireMessageonly 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 actuallysees and can use the seven tools in chat; everyone else — disabled, unknown,
or any error — sees the pre-existing behavior, unchanged.
Policy
LOCAL_READ_TOOLS→desktop.context.local_readbundle,approvalPolicy: "allow"(matchesget_conversations/search_memoriesconvention for authenticated backend reads).
store as
create_memory, so they share itsdesktop.memories.writebundle (new
LEDGER_WRITE_TOOLSset) rather than inventing a new bundle.approvalPolicyis derived automatically from thelocalWriteannotation→
"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 decisionallow, writes decisiondispatch_required/user_approval(same ascreate_memory), denial whenthe memory-write bundle isn't selected.
jsonl-transport.test.ts— the per-turnjitKnowledgeToolsEnabledflagreaches both the MCP-build context and persisted run metadata correctly on
and off.
run-tool-capability.test.ts— the authorized-invocation allowlistexcludes the ledger tools by default and includes them (and authorizes a
search_knowledgecall) once the run's admitted metadata carries the gate.tests/fixtures/tool-manifest.jsonviascripts/generate-tool-surfaces.mjs(also regenerates the two touchedgenerated 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:)istrueonly foreffective == .enabled;falsefor an expliciteffective == .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
effectiveis omitted entirely.The
effective-verdict derivation itself (enabled/disabled/unknownfromthe 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 695passed 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, 0failures.
./scripts/dev-feedback.py --once swift 'AgentRuntimeProcessTests': 71tests, 0 failures.
./scripts/dev-feedback.py --once swift 'KernelContractWireTests': 17tests, 0 failures (15 pre-existing + 2 new).
./scripts/dev-feedback.py --once swift 'ProactiveLaneClientTests': 24tests, 0 failures (unchanged — confirms the gating wiring didn't disturb the
existing rollout-decision coverage).
./scripts/agent-logic-harness.sh --cross-surface-smoke: Harness passedon both rounds.
./scripts/swiftlint-wrapper.sh lint(full repo scope, includes everytouched file): 0 violations, 0 serious.
./scripts/swift-format-wrapper.sh linton every hand-edited Swift file:clean (exit 0).
Product invariants affected
Both are cited because this PR touches
desktop/macos/agent/src/runtime/**and
ChatToolExecutor.swift. No violation: the seven new tools are ordinaryauthenticated backend RAG-style dispatch (same shape as
get_conversations/search_memories), gated through the existing capability/allowlist andapproval-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
executeAgentLedgerToolpassthrough for the 7 new JIT knowledge-ledger tools, mirroring the existingexecuteBackendToolpattern 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.