← All Examples Example 11 / 12 Client Environment: Two-Plane Perimeter, Mycel Tracing & Credential Proxy
Prompt-First Example 11 · Durable Habitats · Decision D-11 · Perimeter + Proxy

Client Environment:
Perimeter & Zero-Secret Runtime

Separate a client-local perimeter gateway (Mycel LLM tracing + credential-injecting HTTP/MCP proxy + unified audit log) from a zero-secret DurableHabitat runtime.

File: examples/client-env/run.ts Recreate: pnpm run demo:client-env -- --smoke Packages: @umwelten/habitat @umwelten/mycel @umwelten/protocols @earendil-works/pi-durable
01 — The Prompt You Give Pi
“Split the single-container GaiaHost into a two-plane Client Environment (Decision D-11): a trusted perimeter-gateway running client-local @umwelten/mycel (LLM tracing + budget governance), a credential-injecting HTTP/MCP forward proxy that scrubs leaked secret tokens from responses and enforces host/method ACLs, and a unified SQLite audit ledger correlated by X-Client-Correlation-Id — paired with a zero-secret habitat-runtime running DurableHabitat.”
Paste directly into pi or your coding agent with @umwelten/* installed. 7 min walkthrough
02 — The Example That Gets Built

Live workspace source: examples/client-env/run.ts

Read directly from disk at site-build time — byte-for-byte identical to the typechecked script in this repo.

TypeScript examples/client-env/run.ts
pnpm run demo:client-env -- --smoke
1#!/usr/bin/env node
2/**
3 * Client Environment E2E Demo & Audit Workbench (`pnpm run demo:client-env`).
4 *
5 * Demonstrates rethinking GaiaHost into a two-plane Client Environment:
6 *   - Trusted `PerimeterGateway` (client-local Mycel LLM proxy/tracer + Hybrid
7 *     HTTP/MCP credential proxy + correlated Audit Ledger `traces.jsonl`)
8 *   - Untrusted zero-secret `HabitatRuntime` (`DurableHabitat` + SQLite +
9 *     Mounted R/O ontology repo)
10 *
11 * Run:
12 *   pnpm run demo:client-env
13 *   pnpm run demo:client-env -- --serve
14 */
15
16import assert from "node:assert/strict";
17import { randomBytes } from "node:crypto";
18import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
19import { tmpdir } from "node:os";
20import { join } from "node:path";
21import { parseArgs } from "node:util";
22import { startMockQuickBooksApi, startMockToolSupplier } from "./mock-upstreams.js";
23import { startClientPerimeter, type AuditSpan } from "./perimeter.js";
24import { startClientHabitatRuntime } from "./runtime.js";
25
26function printHelp(): void {
27  console.log(`Usage: pnpm run demo:client-env [-- [options]]
28
29Starts the two-plane Client Environment prototype:
30  - Trusted PerimeterGateway (client-local Mycel LLM proxy + Hybrid HTTP proxy + traces.jsonl)
31  - Zero-secret HabitatRuntime (QuickBooks DurableHabitat + Mounted R/O ontology)
32
33Options:
34  --smoke          Run all security, scrubbing, LLM tracing & correlation checks (default)
35  --serve          Run the live Warm Paper Audit & Trace UI at http://127.0.0.1:<port>
36  --port <port>    Port for --serve (default: 7450)
37  --help, -h       Show this help message`);
38}
39
40async function main(): Promise<void> {
41  const { values } = parseArgs({
42    args: process.argv.slice(2).filter((a) => a !== "--"),
43    options: {
44      smoke: { type: "boolean", default: false },
45      serve: { type: "boolean", default: false },
46      port: { type: "string", default: "7450" },
47      help: { type: "boolean", short: "h", default: false },
48    },
49    allowPositionals: true,
50  });
51
52  if (values.help) {
53    printHelp();
54    return;
55  }
56
57  const serveMode = values.serve && !values.smoke;
58  const port = Number(values.port);
59  if (!Number.isInteger(port) || port < 0 || port > 65535) {
60    throw new Error(`Invalid --port: ${values.port}`);
61  }
62
63  const tmpRoot = await mkdtemp(join(tmpdir(), "umwelten-client-env-"));
64  const auditDir = join(tmpRoot, "audit");
65  const habitatDir = join(tmpRoot, "habitats", "quickbooks-ops");
66  const ontologyDir = join(tmpRoot, "ontology");
67  await mkdir(ontologyDir, { recursive: true });
68  await writeFile(
69    join(ontologyDir, "GLOSSARY.md"),
70    "# Acme FinOps Ontology\n\n- **Overdue A/R**: Invoices >30 days past due excluding GL 6410 pass-throughs.\n",
71    "utf8",
72  );
73
74  // Vault secrets kept strictly on the Perimeter side — never passed to Runtime
75  const intuitSecret = `intuit-live-secret-${randomBytes(8).toString("hex")}`;
76  const habitatToken = `hab-scoped-${randomBytes(8).toString("hex")}`;
77
78  const qbo = await startMockQuickBooksApi(intuitSecret);
79  const supplier = await startMockToolSupplier();
80  const perimeter = await startClientPerimeter({
81    port: serveMode ? port : 0,
82    auditDir,
83    habitatToken,
84    supplierBaseUrl: supplier.baseUrl,
85    secrets: {
86      quickbooks_oauth_token: intuitSecret,
87    },
88    egressRoutes: {
89      quickbooks: {
90        baseUrl: qbo.baseUrl,
91        secretId: "quickbooks_oauth_token",
92        allowedMethods: ["GET"],
93        allowedPathPrefix: "/v3/company/",
94      },
95    },
96    forwardAllowlistHosts: [new URL(qbo.baseUrl).host],
97  });
98
99  const runtime = await startClientHabitatRuntime({
100    habitatId: "quickbooks-ops",
101    name: "QuickBooks FinOps Habitat",
102    description: "Read-only financial operations assistant grounded in Acme ontology.",
103    perimeterUrl: perimeter.url,
104    habitatToken,
105    workDir: habitatDir,
106    ontologyDir,
107  });
108
109  perimeter.setAskHandler(async ({ traceId, speakerId, prompt }) => {
110    const res = await runtime.askWithTrace({ traceId, speakerId, prompt });
111    return { text: res.text };
112  });
113
114  try {
115    if (serveMode) {
116      console.log(`\nClient Environment Audit Workbench running at ${perimeter.url}`);
117      console.log(`  Client-Local Mycel: ${perimeter.mycelUrl}`);
118      console.log(`  Audit Trace Ledger: ${perimeter.tracesFile}`);
119      console.log("  Press Ctrl+C to stop cleanly.\n");
120
121      await new Promise<void>((resolveStop) => {
122        const stop = () => resolveStop();
123        process.once("SIGINT", stop);
124        process.once("SIGTERM", stop);
125      });
126      return;
127    }
128
129    console.log("=== Client Environment Perimeter + Correlated Audit Smoke Test ===");
130    console.log(`Perimeter Gateway:  ${perimeter.url}`);
131    console.log(`Client-Local Mycel: ${perimeter.mycelUrl}`);
132
133    // 1. Validate rendered Warm Paper UI HTML + JS syntax
134    const uiRes = await fetch(`${perimeter.url}/`);
135    assert.equal(uiRes.status, 200);
136    const uiHtml = await uiRes.text();
137    const scriptMatch = uiHtml.match(/<script>([\s\S]*?)<\/script>/);
138    assert.ok(scriptMatch, "Expected inline script in workbench HTML");
139    assert.ok(!scriptMatch[1].includes("</"), "Disallowed </ inside inline script");
140    new Function(scriptMatch[1]);
141    console.log("1. PASS Warm Paper Audit UI HTML + inline JS syntax valid");
142
143    // 2. Unauthenticated egress call must fail closed (401)
144    const unauthRes = await fetch(
145      `${perimeter.url}/egress/quickbooks/v3/company/acme/reports/AgedReceivables`,
146    );
147    assert.equal(unauthRes.status, 401);
148    console.log("2. PASS Unauthenticated egress request rejected (HTTP 401)");
149
150    // 3. Forbidden DELETE method must be blocked by perimeter ACL (403) before touching QBO
151    const reqCountBeforeDelete = qbo.requests.length;
152    const deniedRes = await fetch(
153      `${perimeter.url}/egress/quickbooks/v3/company/acme/invoice/1042`,
154      {
155        method: "DELETE",
156        headers: {
157          authorization: `Bearer ${habitatToken}`,
158          "x-trace-id": "tr-acl-test",
159          "x-habitat-id": "quickbooks-ops",
160          "x-speaker-id": "adversary",
161        },
162      },
163    );
164    assert.equal(deniedRes.status, 403);
165    assert.equal(
166      qbo.requests.length,
167      reqCountBeforeDelete,
168      "Forbidden DELETE must never reach upstream QuickBooks",
169    );
170    console.log("3. PASS Destructive DELETE blocked at perimeter ACL (HTTP 403, 0 upstream hits)");
171
172    // 4. Secret scrubber must redact upstream secret echo
173    const echoRes = await fetch(
174      `${perimeter.url}/egress/quickbooks/v3/company/acme/echo-auth`,
175      {
176        headers: {
177          authorization: `Bearer ${habitatToken}`,
178          "x-trace-id": "tr-scrub-test",
179          "x-habitat-id": "quickbooks-ops",
180          "x-speaker-id": "[email protected]",
181        },
182      },
183    );
184    assert.equal(echoRes.status, 200);
185    const echoText = await echoRes.text();
186    assert.ok(!echoText.includes(intuitSecret), "Raw Intuit secret leaked past scrubber!");
187    assert.ok(echoText.includes("[REDACTED_VAULT_SECRET]"), "Expected redaction marker");
188    console.log("4. PASS Secret scrubber redacted upstream echoed token");
189
190    // 5. Forward proxy allowlist rejects arbitrary non-allowlisted internet host
191    const fwdDenied = await fetch(`${perimeter.url}/forward-check`, {
192      method: "POST",
193      headers: {
194        "content-type": "application/json",
195        authorization: `Bearer ${habitatToken}`,
196        "x-trace-id": "tr-fwd-test",
197        "x-habitat-id": "quickbooks-ops",
198        "x-speaker-id": "[email protected]",
199      },
200      body: JSON.stringify({ targetUrl: "https://exfiltrate.invalid/steal", method: "POST" }),
201    });
202    assert.equal(fwdDenied.status, 403);
203    console.log("5. PASS Forward proxy allowlist blocked non-approved host (HTTP 403)");
204
205    // 6. Full traced ask: Zero-secret Habitat -> Perimeter LLM (Mycel) -> Perimeter QBO Tool -> Mycel Synthesis
206    const traceId = "tr-qbo-run-1";
207    const askRes = await fetch(`${perimeter.url}/api/ask`, {
208      method: "POST",
209      headers: { "content-type": "application/json" },
210      body: JSON.stringify({
211        traceId,
212        speakerId: "[email protected]",
213        prompt: "What are our overdue receivables in QuickBooks right now?",
214      }),
215    });
216    assert.equal(askRes.status, 200);
217    const askBody = (await askRes.json()) as { traceId: string; text: string };
218    assert.ok(
219      askBody.text.includes("$24,450"),
220      `Expected synthesized QBO total in answer, got: ${askBody.text}`,
221    );
222    assert.ok(!askBody.text.includes(intuitSecret), "Secret found in assistant answer!");
223    console.log(`6. PASS Multi-turn traced QBO answer -> "${askBody.text}"`);
224
225    // 7. Inspect traces.jsonl for correlated traceId spans + Mycel micro-dollars + zero leaked secrets
226    const rawTraces = await readFile(perimeter.tracesFile, "utf8");
227    assert.ok(!rawTraces.includes(intuitSecret), "Traces file must never store upstream secret values");
228    const spans = rawTraces
229      .trim()
230      .split("\n")
231      .map((line) => JSON.parse(line) as AuditSpan);
232    const runSpans = spans.filter((s) => s.traceId === traceId);
233    const llmSpans = runSpans.filter((s) => s.kind === "llm.completion");
234    const httpSpans = runSpans.filter((s) => s.kind === "http.egress");
235    const inboundSpans = runSpans.filter((s) => s.kind === "a2a.inbound");
236
237    assert.ok(llmSpans.length >= 2, `Expected >=2 LLM spans for tool turn + answer, got ${llmSpans.length}`);
238    assert.ok(httpSpans.length >= 1, "Expected >=1 QuickBooks HTTP egress span");
239    assert.equal(inboundSpans.length, 1, "Expected 1 inbound trace root span");
240    assert.ok(
241      llmSpans.every((s) => (s.chargeMicroDollars ?? 0) > 0),
242      "Expected positive integer Mycel micro-dollar charges on LLM spans",
243    );
244    console.log(
245      `7. PASS Audit ledger correlated ${runSpans.length} spans under ${traceId} ` +
246        `(${llmSpans.length} Mycel LLM + ${httpSpans.length} QuickBooks HTTP + ${inboundSpans.length} inbound)`,
247    );
248    console.log("\nALL CLIENT ENVIRONMENT CHECKS PASSED.");
249  } finally {
250    await runtime.close();
251    await perimeter.close();
252    await supplier.close();
253    await qbo.close();
254    await rm(tmpRoot, { recursive: true, force: true });
255  }
256}
257
258main().catch((err) => {
259  console.error("\nClient Environment demo failed:", err);
260  process.exit(1);
261});
03 — Captured Execution Telemetry

Captured stdout from running pnpm run demo:client-env -- --smoke

Captured Run Output pnpm run demo:client-env -- --smoke
=== Client Environment Perimeter + Correlated Audit Smoke Test ===
Perimeter Gateway:  http://127.0.0.1:61455
Client-Local Mycel: http://127.0.0.1:61453
1. PASS Warm Paper Audit UI HTML + inline JS syntax valid
2. PASS Unauthenticated egress request rejected (HTTP 401)
3. PASS Destructive DELETE blocked at perimeter ACL (HTTP 403, 0 upstream hits)
4. PASS Secret scrubber redacted upstream echoed token
5. PASS Forward proxy allowlist blocked non-approved host (HTTP 403)
6. PASS Multi-turn traced QBO answer -> "QuickBooks Aged Receivables shows $24,450 overdue across Acme Holdings LLC ($16,600) and Northwind Co ($7,850), with $27,700 current ($52,150 total A/R)."
7. PASS Audit ledger correlated 4 spans under tr-qbo-run-1 (2 Mycel LLM + 1 QuickBooks HTTP + 1 inbound)

ALL CLIENT ENVIRONMENT CHECKS PASSED.
04 — How & Why This Extends Pi

Architectural notes

Per Decision D-11, client-owned deployments separate cognition from secrets and governance: LLM calls stream through a client-local Mycel perimeter while external REST and MCP calls pass through a host-allowlisted HTTP/MCP proxy that injects short-lived credentials and scrubs echoed tokens before responses return to the agent.