Spaces:
Running

File size: 13,876 Bytes
4822334
ea5a1e6
 
 
4822334
ea5a1e6
4822334
 
 
 
 
 
 
 
6acd609
 
4822334
 
 
 
 
 
6acd609
 
4822334
 
 
ea5a1e6
ea48014
796f85b
 
 
 
 
 
 
 
 
 
 
 
 
964bd64
 
 
796f85b
 
 
 
 
 
 
 
 
 
 
 
6acd609
 
 
 
 
 
 
 
796f85b
 
 
 
ea48014
 
796f85b
 
 
 
 
 
 
4822334
 
6acd609
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea5a1e6
 
 
 
 
4d76eb9
ea5a1e6
 
 
 
 
 
4d76eb9
ea5a1e6
 
4d76eb9
ea5a1e6
7237326
6acd609
4822334
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
'use strict';
// Ora's online service, on the user's own free Cloudflare account: Workers AI text models (drafts, coach,
// captions, insights) and FLUX.1-schnell pictures, over REST.
// The credentials are encrypted with Electron's safeStorage (the OS keychain) and only ever sent to Cloudflare.

const { safeStorage, net } = require('electron');
const fs = require('node:fs');
const path = require('node:path');


function createRemote(dataDir) {
    const FILE = path.join(dataDir, 'connections.json');
    const read = () => { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch { return {}; } };
    const write = v => { fs.mkdirSync(dataDir, { recursive: true }); fs.writeFileSync(FILE, JSON.stringify(v, null, 2), { mode: 0o600 }); };
    // smoke tests (PLAN_SMOKE, a throwaway user folder) keep test links unencrypted, so they never wait on a Keychain prompt
    const seal = text => !process.env.PLAN_SMOKE && safeStorage.isEncryptionAvailable() ? { enc: safeStorage.encryptString(text).toString('base64') } : { plain: text };
    const open = box => box && (box.enc ? safeStorage.decryptString(Buffer.from(box.enc, 'base64')) : box.plain);

    // ---- what the renderer may see (never the secrets) ----
    function status() {
        const c = read();
        return {
            cloudflare: c.cloudflare ? { connected: true, account: c.cloudflare.account.slice(0, 6) + '…', checked: c.cloudflare.checked || '' } : { connected: false },
            n8n: c.n8n ? { connected: true, host: c.n8n.host, accounts: c.n8n.accounts || {}, everOn: !!c.n8n.everOn, sheetLink: c.n8n.sheetLink || '', email: c.n8n.email || '', off: c.n8n.off || {}, checked: c.n8n.checked || '' } : { connected: false },
        };
    }

    // ---- Cloudflare Workers AI --------------------------------------------------------------------
    // FLUX.1-schnell over REST: { prompt, steps <= 8 } -> { result: { image: base64 JPEG 1024x1024 } }.
    // Free accounts get 10,000 Neurons a day (reset 00:00 UTC); one 1024x1024 image = 4 tiles x 4.8 + steps x 9.6.
    const CF = 'https://api.cloudflare.com/client/v4';
    const CF_MODEL = '@cf/black-forest-labs/flux-1-schnell';
    const cfNeurons = steps => 4 * 4.8 + steps * 9.6;
    async function cfCall(pathname, body) {
        const c = read().cloudflare;
        if (!c) throw new Error('Cloudflare is not connected.');
        const res = await net.fetch(`${CF}/accounts/${encodeURIComponent(c.account)}${pathname}`, {
            method: body ? 'POST' : 'GET', headers: { Authorization: `Bearer ${open(c.token)}`, 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined,
        });
        let j; try { j = await res.json(); } catch { j = {}; }
        if (res.status === 401 || res.status === 403) throw new Error('Cloudflare did not accept this token. It needs the "Workers AI" permission (Read is enough) for this account.');
        if (res.status === 429 || /neuron|quota|limit/i.test(JSON.stringify(j.errors || ''))) throw new Error('Cloudflare says today\'s free allowance is used up. It resets at 00:00 UTC.');
        const msg = (j.errors && j.errors[0] && j.errors[0].message) || '';
        if (/nsfw/i.test(msg)) throw new Error('Cloudflare\'s safety filter blocked this prompt as adult content, so no image was made. Change the wording and try again; harmless words like "nude" (as a colour), "bare" or "skin" can also trigger it.');
        if (!res.ok || j.success === false) throw new Error(`Cloudflare: ${msg || res.status}`);
        return j.result;
    }
    async function connectCloudflare(account, token) {
        account = String(account || '').trim(); token = String(token || '').trim();
        if (!/^[0-9a-f]{32}$/i.test(account)) throw new Error('The Account ID is 32 letters and numbers (Cloudflare dashboard › Workers AI › "Use REST API").');
        if (token.length < 20) throw new Error('Paste the API token you created with the Workers AI permission.');
        const c = read();
        c.cloudflare = { account, token: seal(token) };
        write(c);
        try { await cfCall('/ai/models/search?per_page=1'); return status(); }
        catch (e) { delete c.cloudflare; write(c); throw e; }
    }
    // Test: a free call that only works with a valid Account ID and token (no Neurons used)
    async function cfTest() {
        const c = read();
        if (!c.cloudflare) throw new Error('Cloudflare is not connected.');
        await cfCall('/ai/models/search?per_page=1');
        c.cloudflare.checked = new Date().toISOString(); write(c);
        return status();
    }
    async function runCloudflare(prompt, seed, steps, count, onImage, isCancelled) {
        const out = [];
        for (let i = 0; i < count; i++) {
            if (isCancelled()) break;
            // the model accepts only { prompt, steps } (a "seed" field is refused), so every image is a new variation
            const r = await cfCall(`/ai/run/${CF_MODEL}`, { prompt, steps });
            const buf = Buffer.from(r.image, 'base64');
            out.push(buf);
            onImage(i + 1, count);
        }
        return { images: out, neurons: out.length * cfNeurons(steps) };
    }

    function disconnect(which) { const c = read(); delete c[which]; write(c); return status(); }

    // ---- n8n (the learner's own n8n Cloud): Ora's automation listens at a webhook link; the link is the secret ----
    function n8nCheckUrl(url) {
        let u;
        try { u = new URL(String(url || '').trim()); } catch { throw new Error('Paste the whole link from n8n: it starts with https://'); }
        // PLAN_N8N_LOCAL (development): a local test n8n at http://localhost
        const local = process.env.PLAN_N8N_LOCAL && u.protocol === 'http:' && ['localhost', '127.0.0.1'].includes(u.hostname);
        if (u.protocol !== 'https:' && !local) throw new Error('The link must start with https://');
        if (/\/webhook-test\//.test(u.pathname)) throw new Error('This is the Test URL, which only works while n8n is listening. In n8n, double-click the first box (Ora: …) and copy the Production URL instead.');
        if (!/\/webhook\//.test(u.pathname)) throw new Error('This does not look like the link of Ora\'s automation. In n8n, double-click its first box (Ora: …) and copy the Production URL.');
        return u.toString();
    }
    // Sends JSON to the automation and returns its JSON answer, with n8n's errors in plain words
    async function n8nCall(body, url) {
        const target = url || open((read().n8n || {}).url);
        if (!target) throw new Error('n8n is not connected.');
        const ctrl = new AbortController(), t = setTimeout(() => ctrl.abort(), 30000);
        let res, text;
        try {
            // the learner's sheet and email go with every request, so they are typed once, in Ora, not in n8n
            const { sheetLink = '', email = '' } = read().n8n || {};
            res = await net.fetch(target, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...body, sheetLink, email }), signal: ctrl.signal });
            text = await res.text();
        } catch (e) {
            throw new Error(e.name === 'AbortError' ? 'n8n did not answer within 30 seconds. Try again in a moment.' : 'Cannot reach n8n. Check the internet connection and the link.');
        } finally { clearTimeout(t); }
        if (res.status === 404) throw new Error('n8n does not know this link. In n8n, make sure Ora\'s automation is published (switched on), then copy the Production URL of its first box (Ora: …) again.');
        if (res.status >= 500 && /problem executing|issues/i.test(text)) throw new Error('n8n could not run Ora\'s automation because a step is not finished. In n8n, finish the step you switched on (its account and sheet link), or switch it off again, then save.');
        if (!res.ok) throw new Error(`n8n answered with an error (${res.status}).`);
        let j; try { j = JSON.parse(text); } catch { j = null; }
        if (!j || j.ora !== 1) throw new Error('This link works, but it is not Ora\'s automation. Import Ora\'s automation file in n8n and use the link of its first box (Ora: …).');
        return j;
    }
    async function n8nTest(url) {
        const target = url ? n8nCheckUrl(url) : null;
        const j = await n8nCall({ action: 'test' }, target);
        const c = read();
        if (target) c.n8n = { url: seal(target), host: new URL(target).host };
        if (c.n8n) { c.n8n.accounts = j.accounts || {}; c.n8n.checked = new Date().toISOString(); if (Object.values(c.n8n.accounts).some(a => a && a.why && a.why !== 'off')) c.n8n.everOn = true; write(c); }
        return status();
    }
    async function n8nSend(posts) { return n8nCall({ action: 'posts', posts }); }
    // the Google Sheet's link (from the browser's address bar); empty clears it
    function n8nSetSheet(link) {
        const v = String(link || '').trim();
        if (v && !/^https:\/\/docs\.google\.com\/spreadsheets\/d\/[\w-]{20,}/.test(v)) throw new Error('Copy the whole link of your sheet from the address bar: it starts with https://docs.google.com/spreadsheets/d/');
        const c = read();
        if (!c.n8n) throw new Error('Connect n8n first.');
        c.n8n.sheetLink = v; write(c);
        return status();
    }
    // where reminders go (empty clears it)
    function n8nSetEmail(address) {
        const v = String(address || '').trim();
        if (v && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) throw new Error('Type your whole email address, like name@gmail.com');
        const c = read();
        if (!c.n8n) throw new Error('Connect n8n first.');
        c.n8n.email = v; write(c);
        return status();
    }
    // disconnect one account in Ora (Ora stops using it and forgets its sheet link or email), or use it again
    function n8nAccount(id, use) {
        if (!['sheets', 'gmail', 'linkedin'].includes(id)) throw new Error('bad account');
        const c = read();
        if (!c.n8n) throw new Error('Connect n8n first.');
        c.n8n.off = c.n8n.off || {};
        if (use) delete c.n8n.off[id];
        else {
            c.n8n.off[id] = true;
            if (id === 'sheets') delete c.n8n.sheetLink;
            if (id === 'gmail') delete c.n8n.email;
        }
        write(c);
        return status();
    }
    // one request per reminder: n8n answers at once, then waits until remindAt and emails it
    async function n8nRemind(r) { return n8nCall({ action: 'remind', remindAt: r.remindAt, subject: r.subject, text: r.text }); }
    // one request per LinkedIn post: n8n answers at once, waits until postAt, then posts the picture with its caption
    // Plan › Campaigns: delete the sheet rows with these IDs
    async function n8nUnlog(ids) { return n8nCall({ action: 'unlog', ids }); }
    // ends a waiting reminder or LinkedIn post early with { cancel: true } (its cancel link from n8n). Only n8n's own
    // waiting links are called, at the address of the connected n8n. One already sent (or gone) counts as done.
    async function n8nCancel(link) {
        const base = open((read().n8n || {}).url);
        if (!base) throw new Error('n8n is not connected.');
        let u; try { u = new URL(String(link)); } catch { return { gone: true }; }
        if (!/^\/webhook-waiting\/[\w-]+$/.test(u.pathname)) return { gone: true };
        const target = new URL(u.pathname + u.search, new URL(base).origin).toString();
        const ctrl = new AbortController(), t = setTimeout(() => ctrl.abort(), 20000);
        try {
            const res = await net.fetch(target, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ cancel: true }), signal: ctrl.signal });
            return res.ok ? { cancelled: true } : { gone: true };
        } catch { throw new Error('Cannot reach n8n. Check the internet connection.'); }
        finally { clearTimeout(t); }
    }
    async function n8nLinkedIn(p) { return n8nCall({ action: 'linkedin', postAt: p.postAt, caption: p.caption, image: p.image, fileName: p.fileName, mimeType: p.mimeType }); }

    // Text: the small Llama 3.1 8B (suggestions, captions, a few Neurons) or, with big, Llama 3.3 70B (drafts, coach,
    // insights: better writing, more Neurons), falling back to the 8B model; Llama 3.3 70B (planning, drafts, coaching: better writing, more Neurons); falls back to the 8B model
    // json: ask for Workers AI's JSON mode (valid JSON only), and plain text again if a model refuses that option.
    // A JSON answer can come back already parsed (the 70B model does this): it is turned back into text here.
    async function cfText(system, user, { big = false, maxTokens = 220, json = false } = {}) {
        const body = { messages: [{ role: 'system', content: system }, { role: 'user', content: user }], max_tokens: maxTokens, temperature: 0.6 };
        const asText = r => { const v = r && r.response; return typeof v === 'string' ? v.trim() : v && typeof v === 'object' ? JSON.stringify(v) : ''; };
        const fatal = e => /allowance|token|permission|safety/i.test(e.message);
        const run = async model => {
            if (json) { try { return asText(await cfCall(`/ai/run/${model}`, { ...body, response_format: { type: 'json_object' } })); } catch (e) { if (fatal(e)) throw e; } }
            return asText(await cfCall(`/ai/run/${model}`, body));
        };
        if (big) {
            try { return await run('@cf/meta/llama-3.3-70b-instruct-fp8-fast'); }
            catch (e) { if (fatal(e)) throw e; }
        }
        return run('@cf/meta/llama-3.1-8b-instruct');
    }
    return { status, connectCloudflare, cfTest, runCloudflare, cfText, cfNeurons, disconnect, n8nTest, n8nSend, n8nSetSheet, n8nSetEmail, n8nRemind, n8nAccount, n8nLinkedIn, n8nUnlog, n8nCancel };
}

module.exports = { createRemote };