continuum-engine-client 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client-kernel.js CHANGED
@@ -6,19 +6,32 @@
6
6
  * Purpose: Middleware for safely and easily invoking the ASI-OPEX Engine's dedicated API.
7
7
  * Developers can validate in the terminal (.ask) and integrate into their own systems (.query).
8
8
  */
9
+ const DriveMcpClient = require("./mcp-drive");
10
+
9
11
  class ContinuumClient {
10
12
  /**
11
13
  * @param {string} endpointUrl - Dedicated API endpoint URL issued post-purchase
12
14
  * @param {string} authHeaderName - Dedicated header name specified post-purchase (Zero-Trust)
13
15
  * @param {string} continuumToken - Dedicated access credential purchased for $60 (Continuum Token)
14
- * @param {string} docId - (Optional) Google Docs ID for external cooling (sync) of conversation history
16
+ * @param {string|Object|null} storageOption - (Optional)
17
+ * - null: Pure Stateless Mode (zero retention anywhere)
18
+ * - Object: Client-Side Google Drive MCP Config ({ clientId, clientSecret, fileId, fileName })
19
+ * - string: Legacy Google Docs ID for external cooling (sync)
15
20
  */
16
- constructor(endpointUrl, authHeaderName, continuumToken, docId = null) {
21
+ constructor(endpointUrl, authHeaderName, continuumToken, storageOption = null) {
17
22
  this.endpointUrl = endpointUrl;
18
23
  this.authHeaderName = authHeaderName;
19
24
  this.continuumToken = continuumToken;
20
- this.docId = docId;
21
25
  this.sessionId = `session_${Date.now()}`;
26
+
27
+ if (storageOption && typeof storageOption === "object") {
28
+ // Enforce pure Stateless execution on Continuum backend; sync strictly client-side via MCP
29
+ this.docId = null;
30
+ this.mcpDrive = new DriveMcpClient(storageOption);
31
+ } else {
32
+ this.docId = storageOption;
33
+ this.mcpDrive = null;
34
+ }
22
35
  }
23
36
 
24
37
  /**
@@ -73,6 +86,19 @@ class ContinuumClient {
73
86
  return;
74
87
  }
75
88
 
89
+ if (this.mcpDrive) {
90
+ try {
91
+ process.stdout.write("🔐 Syncing history directly to your Google Drive via MCP...\n");
92
+ data.mcp_sync = await this.mcpDrive.syncInferenceLog({
93
+ sessionId: this.sessionId,
94
+ prompt: message,
95
+ data,
96
+ });
97
+ } catch (mcpErr) {
98
+ console.error(`⚠️ Client-Side MCP Sync Warning: ${mcpErr.message}`);
99
+ }
100
+ }
101
+
76
102
  this._renderResponse(data);
77
103
  } catch (error) {
78
104
  clearInterval(interval);
@@ -111,6 +137,14 @@ class ContinuumClient {
111
137
  );
112
138
  }
113
139
 
140
+ if (this.mcpDrive) {
141
+ data.mcp_sync = await this.mcpDrive.syncInferenceLog({
142
+ sessionId: this.sessionId,
143
+ prompt: message,
144
+ data,
145
+ });
146
+ }
147
+
114
148
  return data;
115
149
  }
116
150
 
@@ -124,6 +158,7 @@ class ContinuumClient {
124
158
  remaining_requests,
125
159
  finops_report,
126
160
  doc_id,
161
+ mcp_sync,
127
162
  } = data;
128
163
 
129
164
  console.log("\n==================================================");
@@ -140,7 +175,15 @@ class ContinuumClient {
140
175
  console.log("--------------------------------------------------");
141
176
  }
142
177
 
143
- if (doc_id) {
178
+ if (mcp_sync && mcp_sync.synced) {
179
+ console.log(
180
+ `🛡️ [ZERO-TRUST MCP SYNC] Saved directly to your Google Drive (${mcp_sync.mode}: ${mcp_sync.fileId})`
181
+ );
182
+ if (mcp_sync.viewUrl) {
183
+ console.log(` 👉 ${mcp_sync.viewUrl}`);
184
+ }
185
+ console.log("--------------------------------------------------");
186
+ } else if (doc_id) {
144
187
  console.log(
145
188
  `📝 [STATE STORAGE] History successfully synced to your private document.`
146
189
  );
package/mcp-drive.js ADDED
@@ -0,0 +1,425 @@
1
+ // mcp-drive.js
2
+ /**
3
+ * ============================================================================
4
+ * Continuum Engine - Zero-Trust Google Drive MCP Adapter (Route A)
5
+ * ============================================================================
6
+ * Hardened per IETF RFC 8252 (Section 7.3 & 8.3) & OAuth 2.1:
7
+ * - Strict loopback literal binding (`127.0.0.1` only; never `0.0.0.0` or `localhost`)
8
+ * - High ephemeral-adjacent callback port (`53682`) to avoid `:3000` dev-server collisions
9
+ * - Mandatory PKCE (`S256`) + cryptographic CSRF `state` verification
10
+ * - Single-shot socket auto-destruction with strict 120s timeout
11
+ */
12
+ const fs = require("node:fs/promises");
13
+ const path = require("node:path");
14
+ const http = require("node:http");
15
+ const crypto = require("node:crypto");
16
+ const readline = require("node:readline/promises");
17
+
18
+ const DEFAULT_MCP_URL = "https://drivemcp.googleapis.com/mcp/v1";
19
+ const DEFAULT_REDIRECT_URI = "http://127.0.0.1:53682/callback";
20
+ const DRIVE_FILE_SCOPE = "https://www.googleapis.com/auth/drive.file";
21
+ const AUTH_TIMEOUT_MS = 120_000;
22
+
23
+ class DriveMcpClient {
24
+ /**
25
+ * @param {Object} config
26
+ * @param {string} config.clientId - Google OAuth 2.0 Client ID (AI-powered agent enabled)
27
+ * @param {string} config.clientSecret - Google OAuth 2.0 Client Secret
28
+ * @param {string} [config.fileId] - Optional existing Drive File ID created by this client
29
+ * @param {string} [config.fileName] - Log file name created on first sync
30
+ * @param {string} [config.tokenPath] - Local path to cache OAuth refresh token & fileId (0600)
31
+ * @param {string} [config.redirectUri] - Must use explicit loopback IP `127.0.0.1`
32
+ */
33
+ constructor(config = {}) {
34
+ this.clientId = config.clientId || process.env.GOOGLE_OAUTH_CLIENT_ID;
35
+ this.clientSecret = config.clientSecret || process.env.GOOGLE_OAUTH_CLIENT_SECRET;
36
+ this.fileId = config.fileId || process.env.CONTINUUM_DRIVE_FILE_ID || null;
37
+ this.fileName = config.fileName || "Continuum_Inference_Log.txt";
38
+ this.redirectUri = config.redirectUri || DEFAULT_REDIRECT_URI;
39
+ this.mcpUrl = config.mcpUrl || DEFAULT_MCP_URL;
40
+ this.tokenPath =
41
+ config.tokenPath || path.resolve(process.cwd(), ".continuum_mcp_token.json");
42
+ this.mcpSessionId = null;
43
+ this.initialized = false;
44
+
45
+ const parsedRedirect = new URL(this.redirectUri);
46
+ if (parsedRedirect.hostname !== "127.0.0.1") {
47
+ throw new Error(
48
+ `Zero-Trust Policy Violation: redirectUri must bind strictly to 127.0.0.1 (got "${parsedRedirect.hostname}").`
49
+ );
50
+ }
51
+ }
52
+
53
+ async _loadLocalState() {
54
+ try {
55
+ return JSON.parse(await fs.readFile(this.tokenPath, "utf8"));
56
+ } catch {
57
+ return {};
58
+ }
59
+ }
60
+
61
+ async _saveLocalState(patch) {
62
+ const current = await this._loadLocalState();
63
+ const merged = { ...current, ...patch, updatedAt: new Date().toISOString() };
64
+ await fs.writeFile(this.tokenPath, JSON.stringify(merged, null, 2), {
65
+ encoding: "utf8",
66
+ mode: 0o600,
67
+ });
68
+ return merged;
69
+ }
70
+
71
+ _extractCode(rawInput, expectedState) {
72
+ const trimmed = (rawInput || "").trim();
73
+ try {
74
+ const parsed = new URL(trimmed);
75
+ const returnedState = parsed.searchParams.get("state");
76
+ if (returnedState && returnedState !== expectedState) {
77
+ throw new Error("OAuth CSRF state mismatch detected.");
78
+ }
79
+ const code = parsed.searchParams.get("code");
80
+ if (code) return code;
81
+ } catch (err) {
82
+ if (err.message.includes("CSRF")) throw err;
83
+ }
84
+ const match = trimmed.match(/[?&]code=([^&\s]+)/);
85
+ if (match) return decodeURIComponent(match[1]);
86
+ return trimmed;
87
+ }
88
+
89
+ async _obtainAuthCode(authUrl, expectedState) {
90
+ const ac = new AbortController();
91
+ const redirectObj = new URL(this.redirectUri);
92
+ const port = Number(redirectObj.port) || 53682;
93
+ const callbackPath = redirectObj.pathname || "/callback";
94
+ let server;
95
+ let timeoutId;
96
+
97
+ const timeoutPromise = new Promise((_, reject) => {
98
+ timeoutId = setTimeout(() => {
99
+ reject(new Error("OAuth loopback listener timed out after 120 seconds."));
100
+ }, AUTH_TIMEOUT_MS);
101
+ });
102
+
103
+ const serverPromise = new Promise((resolve) => {
104
+ server = http.createServer((req, res) => {
105
+ res.setHeader("Connection", "close");
106
+ res.setHeader("Cache-Control", "no-store");
107
+ res.setHeader(
108
+ "Content-Security-Policy",
109
+ "default-src 'none'; style-src 'unsafe-inline'"
110
+ );
111
+
112
+ if (req.method !== "GET") {
113
+ res.writeHead(405);
114
+ res.end();
115
+ return;
116
+ }
117
+
118
+ try {
119
+ const reqUrl = new URL(req.url, `http://127.0.0.1:${port}`);
120
+ if (reqUrl.pathname !== callbackPath) {
121
+ res.writeHead(404);
122
+ res.end();
123
+ return;
124
+ }
125
+
126
+ const code = reqUrl.searchParams.get("code");
127
+ const returnedState = reqUrl.searchParams.get("state");
128
+
129
+ if (!code || returnedState !== expectedState) {
130
+ res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" });
131
+ res.end("Forbidden: Invalid OAuth state or missing authorization code.");
132
+ return;
133
+ }
134
+
135
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
136
+ res.end(
137
+ "<h2>Continuum Engine: Zero-Trust Drive MCP Authorized</h2>" +
138
+ "<p>PKCE &amp; state verified on 127.0.0.1 loopback. You may close this tab.</p>"
139
+ );
140
+ resolve(code);
141
+ } catch {
142
+ res.writeHead(400);
143
+ res.end();
144
+ }
145
+ });
146
+
147
+ server.on("error", (err) => {
148
+ console.warn(
149
+ ` ℹ️ Loopback port 127.0.0.1:${port} unavailable (${err.code}); use manual URL paste below.`
150
+ );
151
+ });
152
+
153
+ // Strictly bind to IPv4 loopback interface (lo) ONLY — never 0.0.0.0
154
+ server.listen(port, "127.0.0.1");
155
+ });
156
+
157
+ console.log("\n🔐 [Google Drive MCP] Initial OAuth 2.0 + PKCE consent required.");
158
+ console.log(`👉 Open this URL in your browser:\n\n${authUrl}\n`);
159
+ console.log(
160
+ ` * Loopback socket bound strictly to 127.0.0.1:${port} (auto-closes in 120s).\n` +
161
+ " * Remote / SSH / Cloud Shell: Paste the redirected URL below.\n"
162
+ );
163
+
164
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
165
+ const manualPromise = rl
166
+ .question("Paste redirected URL (if running remotely): ", { signal: ac.signal })
167
+ .then((ans) => this._extractCode(ans, expectedState))
168
+ .catch((err) => {
169
+ if (err.name === "AbortError") return new Promise(() => {});
170
+ throw err;
171
+ });
172
+
173
+ try {
174
+ return await Promise.race([serverPromise, manualPromise, timeoutPromise]);
175
+ } finally {
176
+ clearTimeout(timeoutId);
177
+ ac.abort();
178
+ rl.close();
179
+ if (server) {
180
+ server.closeAllConnections?.();
181
+ server.close();
182
+ }
183
+ }
184
+ }
185
+
186
+ async getAccessToken() {
187
+ if (!this.clientId || !this.clientSecret) {
188
+ throw new Error(
189
+ "Missing Google OAuth credentials (`clientId` / `clientSecret`)."
190
+ );
191
+ }
192
+
193
+ const state = await this._loadLocalState();
194
+ if (!this.fileId && state.fileId) {
195
+ this.fileId = state.fileId;
196
+ }
197
+
198
+ if (state.refresh_token) {
199
+ const refreshRes = await fetch("https://oauth2.googleapis.com/token", {
200
+ method: "POST",
201
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
202
+ body: new URLSearchParams({
203
+ client_id: this.clientId,
204
+ client_secret: this.clientSecret,
205
+ refresh_token: state.refresh_token,
206
+ grant_type: "refresh_token",
207
+ }),
208
+ });
209
+ const refreshData = await refreshRes.json();
210
+ if (refreshRes.ok && refreshData.access_token) {
211
+ return refreshData.access_token;
212
+ }
213
+ }
214
+
215
+ // RFC 7636 PKCE (S256) + CSRF State generation
216
+ const codeVerifier = crypto.randomBytes(32).toString("base64url");
217
+ const codeChallenge = crypto
218
+ .createHash("sha256")
219
+ .update(codeVerifier)
220
+ .digest("base64url");
221
+ const oauthState = crypto.randomBytes(24).toString("hex");
222
+
223
+ const authUrl = new URL("https://accounts.google.com/o/oauth2/v2/auth");
224
+ authUrl.searchParams.set("client_id", this.clientId);
225
+ authUrl.searchParams.set("redirect_uri", this.redirectUri);
226
+ authUrl.searchParams.set("response_type", "code");
227
+ authUrl.searchParams.set("scope", DRIVE_FILE_SCOPE);
228
+ authUrl.searchParams.set("access_type", "offline");
229
+ authUrl.searchParams.set("prompt", "consent");
230
+ authUrl.searchParams.set("state", oauthState);
231
+ authUrl.searchParams.set("code_challenge", codeChallenge);
232
+ authUrl.searchParams.set("code_challenge_method", "S256");
233
+
234
+ const code = await this._obtainAuthCode(authUrl.toString(), oauthState);
235
+
236
+ const tokenRes = await fetch("https://oauth2.googleapis.com/token", {
237
+ method: "POST",
238
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
239
+ body: new URLSearchParams({
240
+ code,
241
+ client_id: this.clientId,
242
+ client_secret: this.clientSecret,
243
+ redirect_uri: this.redirectUri,
244
+ grant_type: "authorization_code",
245
+ code_verifier: codeVerifier,
246
+ }),
247
+ });
248
+ const tokenData = await tokenRes.json();
249
+ if (!tokenRes.ok || !tokenData.access_token) {
250
+ throw new Error(
251
+ `OAuth token exchange failed: ${tokenData.error_description || tokenData.error || tokenRes.status}`
252
+ );
253
+ }
254
+
255
+ if (tokenData.refresh_token) {
256
+ await this._saveLocalState({ refresh_token: tokenData.refresh_token });
257
+ }
258
+ return tokenData.access_token;
259
+ }
260
+
261
+ async _rpc(accessToken, method, params = {}) {
262
+ const headers = {
263
+ Authorization: `Bearer ${accessToken}`,
264
+ "Content-Type": "application/json",
265
+ Accept: "application/json, text/event-stream",
266
+ };
267
+ if (this.mcpSessionId) {
268
+ headers["Mcp-Session-Id"] = this.mcpSessionId;
269
+ }
270
+
271
+ const res = await fetch(this.mcpUrl, {
272
+ method: "POST",
273
+ headers,
274
+ body: JSON.stringify({
275
+ jsonrpc: "2.0",
276
+ id: Date.now(),
277
+ method,
278
+ params,
279
+ }),
280
+ });
281
+
282
+ const sid = res.headers.get("mcp-session-id");
283
+ if (sid) this.mcpSessionId = sid;
284
+
285
+ const raw = await res.text();
286
+ let payload;
287
+ if ((res.headers.get("content-type") || "").includes("text/event-stream")) {
288
+ const dataLines = raw
289
+ .split("\n")
290
+ .filter((line) => line.startsWith("data:"))
291
+ .map((line) => line.slice(5).trim())
292
+ .filter(Boolean);
293
+ payload = JSON.parse(dataLines[dataLines.length - 1] || "{}");
294
+ } else {
295
+ payload = JSON.parse(raw || "{}");
296
+ }
297
+
298
+ if (!res.ok || payload.error) {
299
+ throw new Error(
300
+ `MCP HTTP/RPC Error (${res.status}): ${JSON.stringify(payload.error || raw)}`
301
+ );
302
+ }
303
+ if (payload.result?.isError) {
304
+ const msg = payload.result?.content?.[0]?.text || "Unknown MCP tool error";
305
+ throw new Error(`Drive MCP Tool Error: ${msg}`);
306
+ }
307
+ return payload.result;
308
+ }
309
+
310
+ async _ensureInitialized(accessToken) {
311
+ if (this.initialized) return;
312
+ await this._rpc(accessToken, "initialize", {
313
+ protocolVersion: "2024-11-05",
314
+ capabilities: {},
315
+ clientInfo: { name: "continuum-engine-client", version: "1.0.0" },
316
+ });
317
+ this.initialized = true;
318
+ }
319
+
320
+ async callTool(accessToken, name, args = {}) {
321
+ await this._ensureInitialized(accessToken);
322
+ const result = await this._rpc(accessToken, "tools/call", {
323
+ name,
324
+ arguments: args,
325
+ });
326
+ if (result?.structuredContent) return result.structuredContent;
327
+ const text = result?.content?.[0]?.text;
328
+ if (text) {
329
+ try {
330
+ return JSON.parse(text);
331
+ } catch {
332
+ return { rawText: text };
333
+ }
334
+ }
335
+ return result;
336
+ }
337
+
338
+ _formatEntry({ sessionId, prompt, data }) {
339
+ const timestamp = new Date().toISOString();
340
+ const br = data?.finops_report?.breakdown || {};
341
+ const lines = [
342
+ "============================================================",
343
+ `[${timestamp}] Session: ${sessionId}`,
344
+ "------------------------------------------------------------",
345
+ `[PROMPT]\n${prompt}`,
346
+ "------------------------------------------------------------",
347
+ `[AI RESPONSE]\n${data?.ai_response || ""}`,
348
+ ];
349
+
350
+ if (Array.isArray(data?.source_urls) && data.source_urls.length > 0) {
351
+ lines.push("------------------------------------------------------------");
352
+ lines.push("[VERIFIED SOURCES]");
353
+ data.source_urls.forEach((s, i) => {
354
+ lines.push(` ${i + 1}. ${s.title || "Source"} - ${s.uri || ""}`);
355
+ });
356
+ }
357
+
358
+ if (data?.finops_report) {
359
+ lines.push("------------------------------------------------------------");
360
+ lines.push(
361
+ `[FINOPS TELEMETRY] Input: ${br.t_input_optimized ?? 0} | ` +
362
+ `Grounding: ${br.t_grounding_dynamic ?? 0} | ` +
363
+ `Output: ${br.t_output_generated ?? 0} | ` +
364
+ `Saved: ${data.finops_report.tokens_saved ?? 0} | ` +
365
+ `Net Billed: ${data.finops_report.billed_tokens ?? 0} | ` +
366
+ `Quota Remaining: ${data.remaining_requests ?? "N/A"}`
367
+ );
368
+ }
369
+ lines.push("============================================================");
370
+ return lines.join("\n");
371
+ }
372
+
373
+ async syncInferenceLog({ sessionId, prompt, data }) {
374
+ const accessToken = await this.getAccessToken();
375
+ const entryText = this._formatEntry({ sessionId, prompt, data });
376
+
377
+ if (this.fileId) {
378
+ try {
379
+ const readRes = await this.callTool(accessToken, "read_file_content", {
380
+ fileId: this.fileId,
381
+ });
382
+ const existing = (readRes?.fileContent || "").trim();
383
+ const combined = existing ? `${existing}\n\n${entryText}` : entryText;
384
+
385
+ const revRes = await this.callTool(accessToken, "upload_file_revision", {
386
+ fileId: this.fileId,
387
+ contentMimeType: "text/plain",
388
+ textContent: combined,
389
+ });
390
+
391
+ return {
392
+ synced: true,
393
+ mode: "updated",
394
+ fileId: this.fileId,
395
+ viewUrl: readRes?.viewUrl || null,
396
+ modifiedTime: revRes?.modifiedTime || new Date().toISOString(),
397
+ };
398
+ } catch {
399
+ this.fileId = null;
400
+ }
401
+ }
402
+
403
+ const created = await this.callTool(accessToken, "create_file", {
404
+ title: this.fileName,
405
+ contentMimeType: "text/plain",
406
+ disableConversionToGoogleType: true,
407
+ textContent: entryText,
408
+ });
409
+
410
+ this.fileId = created?.id || null;
411
+ if (this.fileId) {
412
+ await this._saveLocalState({ fileId: this.fileId });
413
+ }
414
+
415
+ return {
416
+ synced: true,
417
+ mode: "created",
418
+ fileId: this.fileId,
419
+ viewUrl: created?.viewUrl || null,
420
+ modifiedTime: created?.modifiedTime || new Date().toISOString(),
421
+ };
422
+ }
423
+ }
424
+
425
+ module.exports = DriveMcpClient;
package/package.json CHANGED
@@ -1,8 +1,17 @@
1
1
  {
2
2
  "name": "continuum-engine-client",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "Cut LLM runaway token costs by up to 82% at the edge. Zero-Trust FinOps routing middleware & BYOD state controller for Gemini / Vertex AI.",
5
5
  "main": "client-kernel.js",
6
+ "files": [
7
+ "client-kernel.js",
8
+ "mcp-drive.js",
9
+ "run_simulator.js",
10
+ "README.md"
11
+ ],
12
+ "engines": {
13
+ "node": ">=18.0.0"
14
+ },
6
15
  "author": "individual-app-developers-cmck",
7
16
  "license": "MIT",
8
17
  "repository": {
@@ -17,6 +26,7 @@
17
26
  "rag",
18
27
  "llm-gateway",
19
28
  "token-optimization",
20
- "bff"
29
+ "bff",
30
+ "mcp"
21
31
  ]
22
- }
32
+ }