diff --git a/apps/api/src/studio/c0mpute.ts b/apps/api/src/studio/c0mpute.ts index dd4929b..6b92746 100644 --- a/apps/api/src/studio/c0mpute.ts +++ b/apps/api/src/studio/c0mpute.ts @@ -7,8 +7,12 @@ * email, so nobody can claim an account by typing an address. * - plan charges (/api/v1/billing/charge, kind "social.plan"): a 30-day plan * taken from their compute balance, idempotent on our key. - * - AI writing (/v1/chat/completions, model "auto"): drafts run on the c0mpute - * network and are billed to their balance at c0mpute's own rates. + * - AI writing (/api/v1/ai/text): drafts run on the c0mpute network first and + * are billed to their balance at the network's rates. When no node starts + * writing within about 20 seconds, c0mpute has OpenAI or Anthropic write it + * (@profullstack/ai-providers on c0mpute.com, where the paid keys live) and + * charges their balance 2x that provider's list-price cost, idempotent on + * our idem_key. The answer says which provider wrote it and what was charged. * * Every call takes `fetchImpl` so tests never touch the network. */ @@ -126,20 +130,30 @@ export async function charge( return { error: String(err.message ?? `c0mpute billing answered ${r.status}`), status: r.status >= 500 ? 503 : 400 }; } -/** One completion on the c0mpute network, billed to the person. */ -export async function complete(cfg: C0mputeConfig, token: string, system: string, user: string, maxTokens = 900): Promise { - const r = await (cfg.fetchImpl ?? fetch)(`${cfg.base}/v1/chat/completions`, { +export interface Written { + text: string; + /** "c0mpute", or the paid fallback that wrote it ("openai", "anthropic"). */ + provider: string; + model: string; + /** network: the c0mpute network billed its tokens. fallback: charged 2x the provider's list-price cost. */ + billed: { by: "network" | "fallback"; costUsd: number; chargedUsd: number; line: string | null }; +} + +/** One completion: c0mpute first, a paid fallback when the network is too slow; billed to the person either way. */ +export async function complete(cfg: C0mputeConfig, token: string, system: string, user: string, opts: { maxTokens?: number; idemKey?: string } = {}): Promise { + const r = await (cfg.fetchImpl ?? fetch)(`${cfg.base}/api/v1/ai/text`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify({ - model: "auto", - max_tokens: maxTokens, + max_tokens: opts.maxTokens ?? 900, messages: [ { role: "system", content: system }, { role: "user", content: user }, ], + app: "myna-studio", + ...(opts.idemKey ? { idem_key: opts.idemKey } : {}), }), - signal: AbortSignal.timeout(180_000), + signal: AbortSignal.timeout(300_000), }); const data = (await r.json().catch(() => ({}))) as Record; if (r.status === 402) throw new Error("Your c0mpute balance is empty. Top it up to keep writing with AI."); @@ -148,8 +162,18 @@ export async function complete(cfg: C0mputeConfig, token: string, system: string const msg = typeof err === "string" ? err : String(err?.message ?? `c0mpute answered ${r.status}`); throw new Error(msg); } - const choices = data.choices as Array<{ message?: { content?: string } }> | undefined; - const text = choices?.[0]?.message?.content ?? ""; + const text = typeof data.text === "string" ? data.text : ""; if (!text.trim()) throw new Error("c0mpute returned an empty draft; try again."); - return text.trim(); + const billed = (data.billed ?? {}) as Record; + return { + text: text.trim(), + provider: typeof data.provider === "string" ? data.provider : "c0mpute", + model: typeof data.model === "string" ? data.model : "auto", + billed: { + by: billed.by === "fallback" ? "fallback" : "network", + costUsd: Number(billed.cost_usd) || 0, + chargedUsd: Number(billed.charged_usd) || 0, + line: typeof billed.line === "string" ? billed.line : null, + }, + }; } diff --git a/apps/api/src/studio/routes.ts b/apps/api/src/studio/routes.ts index 7521be5..2c65575 100644 --- a/apps/api/src/studio/routes.ts +++ b/apps/api/src/studio/routes.ts @@ -347,7 +347,12 @@ ws.delete( ws.get("/analytics", route(async (c) => ({ analytics: await store.analytics(c.get("m").workspace.id, Math.min(90, Math.max(1, Number(c.req.query("days") ?? 30) || 30))) }))); ws.post("/analytics/refresh", route(async (c) => ({ refreshed: await refreshStats(c.get("m").workspace.id, c.get("key")) }))); -/** AI writer: drafts on the c0mpute network, billed to the signed-in person's balance at c0mpute's rates. */ +/** + * AI writer: drafts on the c0mpute network first, billed to the signed-in + * person's balance at the network's rates; when no node starts in time c0mpute + * has OpenAI or Anthropic write them and charges 2x that provider's cost. The + * answer says who wrote it. + */ ws.post( "/ai/write", route(async (c) => { @@ -365,13 +370,13 @@ ws.post( const system = "You write social media posts for a small business or an independent creator. Plain, specific, no hype, no emoji unless asked, no em dashes, no hashtags unless asked. Each draft must stand on its own. Answer with exactly three drafts separated by a line containing only ---. No preamble, no numbering, no commentary."; const prompt = `What the post is about:\n${brief}\n\n${tone ? `Tone: ${tone}\n` : ""}${limits.length ? `It goes to: ${limits.join("; ")}. Keep every draft under the smallest limit.\n` : ""}`; - const text = await c0.complete(cfg(), tokenOf(c as unknown as Context), system, prompt); - const drafts = text + const written = await c0.complete(cfg(), tokenOf(c as unknown as Context), system, prompt, { idemKey: `studio-${m.workspace.id}-${randomId()}`.slice(0, 100) }); + const drafts = written.text .split(/\n\s*-{3,}\s*\n/) .map((d) => d.trim().replace(/—/g, ", ")) .filter(Boolean) .slice(0, 3); - return { drafts }; + return { drafts, provider: written.provider, model: written.model, billed: written.billed }; }), ); diff --git a/apps/api/test/studio.test.ts b/apps/api/test/studio.test.ts index 0a1427a..1d0783c 100644 --- a/apps/api/test/studio.test.ts +++ b/apps/api/test/studio.test.ts @@ -169,12 +169,23 @@ describe("c0mpute client", () => { await expect(c0.me(dead, "t")).rejects.toBeInstanceOf(c0.C0mputeAuthError); }); - test("AI writing calls the c0mpute chat API with model auto", async () => { + test("AI writing calls c0mpute's c0mpute-first AI endpoint and reports who wrote it", async () => { const seen: Array<{ url: string; init?: RequestInit }> = []; - const cfg = { ...c0.c0mputeConfig({}), fetchImpl: fake(200, { choices: [{ message: { content: "one\n---\ntwo" } }] }, seen) }; - expect(await c0.complete(cfg, "t", "sys", "user")).toBe("one\n---\ntwo"); - expect(seen[0]!.url).toBe("https://c0mpute.com/v1/chat/completions"); - expect(JSON.parse(String(seen[0]!.init!.body)).model).toBe("auto"); + const cfg = { ...c0.c0mputeConfig({}), fetchImpl: fake(200, { text: "one\n---\ntwo", provider: "c0mpute", model: "qwen3:4b", billed: { by: "network", cost_usd: 0, charged_usd: 0, line: null } }, seen) }; + const w = await c0.complete(cfg, "t", "sys", "user", { idemKey: "studio-w1-x" }); + expect(w).toEqual({ text: "one\n---\ntwo", provider: "c0mpute", model: "qwen3:4b", billed: { by: "network", costUsd: 0, chargedUsd: 0, line: null } }); + expect(seen[0]!.url).toBe("https://c0mpute.com/api/v1/ai/text"); + const sent = JSON.parse(String(seen[0]!.init!.body)); + expect(sent).toMatchObject({ app: "myna-studio", idem_key: "studio-w1-x", max_tokens: 900 }); + expect(sent.messages.map((m: { role: string }) => m.role)).toEqual(["system", "user"]); + }); + + test("a fallback draft carries the provider and the 2x charge", async () => { + const line = "fallback: anthropic claude-haiku-5-5, 1500 tokens (1000 in, 500 out) at list price, $0.000350"; + const cfg = { ...c0.c0mputeConfig({}), fetchImpl: fake(200, { text: "a", provider: "anthropic", model: "claude-haiku-5-5", billed: { by: "fallback", cost_usd: 0.00035, charged_usd: 0.0007, line } }) }; + expect(await c0.complete(cfg, "t", "sys", "user")).toMatchObject({ provider: "anthropic", billed: { by: "fallback", costUsd: 0.00035, chargedUsd: 0.0007, line } }); + const broke = { ...c0.c0mputeConfig({}), fetchImpl: fake(402, { error: { code: "insufficient_balance", message: "top up" } }) }; + await expect(c0.complete(broke, "t", "s", "u")).rejects.toThrow("balance is empty"); }); }); diff --git a/apps/cli/package.json b/apps/cli/package.json index 99368a5..9592d7c 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "@profullstack/myna", - "version": "0.57.0", + "version": "0.58.0", "description": "A terminal social media manager. Log in, compose, schedule and post to every network from one TUI.", "license": "MIT", "type": "module", diff --git a/apps/web/assets/studio.js b/apps/web/assets/studio.js index 546e3c7..4e1f76b 100644 --- a/apps/web/assets/studio.js +++ b/apps/web/assets/studio.js @@ -368,7 +368,14 @@ function openComposer(post, day) { try { const nets = [...new Set(state.channels.filter((c) => picked.has(c.id)).map((c) => c.network))]; const r = await wsApi("/ai/write", { method: "POST", body: { brief: brief.value || text.value, tone: tone.value, networks: nets } }); - aiOut.replaceChildren(...r.drafts.map((d) => h("div", { class: "draft" }, d, h("div", {}, h("button", { type: "button", onclick: () => ((text.value = d), update()) }, "Use this"))))); + const by = + r.billed && r.billed.by === "fallback" + ? `Written by ${r.provider} ${r.model} (the c0mpute network was busy); $${Number(r.billed.chargedUsd).toFixed(6)} charged to your c0mpute balance (2x its cost).` + : `Written on the c0mpute network${r.model ? ` (${r.model})` : ""}; billed at network rates.`; + aiOut.replaceChildren( + h("p", { class: "muted small" }, by), + ...r.drafts.map((d) => h("div", { class: "draft" }, d, h("div", {}, h("button", { type: "button", onclick: () => ((text.value = d), update()) }, "Use this")))), + ); } catch (e) { aiOut.replaceChildren(h("p", { class: "notice" }, e.message), e.message.includes("balance") ? h("a", { href: `${state.me.c0mputeUrl}/checkout`, target: "_blank", rel: "noopener" }, "Top up your c0mpute balance") : null); } finally { @@ -376,7 +383,7 @@ function openComposer(post, day) { } }, }, "Write 3 drafts with AI"); - const ai = readOnly ? null : h("div", { class: "ai" }, h("b", {}, "AI writer"), h("p", { class: "muted small" }, "Runs on the c0mpute network, billed per draft to your c0mpute balance at network rates."), h("div", { class: "row" }, h("div", { class: "grow" }, brief), h("div", { class: "grow" }, tone), aiBtn), aiOut); + const ai = readOnly ? null : h("div", { class: "ai" }, h("b", {}, "AI writer"), h("p", { class: "muted small" }, "Runs on the c0mpute network, billed per draft to your c0mpute balance at network rates. If the network is busy, OpenAI or Anthropic writes it and you pay 2x their cost; each answer says which."), h("div", { class: "row" }, h("div", { class: "grow" }, brief), h("div", { class: "grow" }, tone), aiBtn), aiOut); const err = h("p", { class: "notice", hidden: true }); const save = (mode) => async () => { diff --git a/bun.lock b/bun.lock index a484b9b..d81ba50 100644 --- a/bun.lock +++ b/bun.lock @@ -27,7 +27,7 @@ }, "apps/cli": { "name": "@profullstack/myna", - "version": "0.57.0", + "version": "0.58.0", "bin": { "myna": "./bin/myna.mjs", }, @@ -62,7 +62,7 @@ }, "packages/core": { "name": "@profullstack/myna-core", - "version": "0.57.0", + "version": "0.58.0", "dependencies": { "@anthropic-ai/sdk": "^0.123.0", "@profullstack/ai-providers": "^0.3.1", @@ -86,7 +86,7 @@ }, "packages/mcp": { "name": "@profullstack/myna-mcp", - "version": "0.57.0", + "version": "0.58.0", "bin": { "myna-mcp": "./src/server.ts", }, diff --git a/docs/studio.md b/docs/studio.md index f787bba..62c3f8f 100644 --- a/docs/studio.md +++ b/docs/studio.md @@ -11,7 +11,10 @@ Sign-in is "Sign in with c0mpute" (CoinPay underneath; accounts are keyed on the never an email). Plans are 30 days each, bought from the workspace owner's c0mpute balance through c0mpute's app-charge route (kind `social.plan`), and nothing renews by itself: Free (3 channels, 30 posts a month), Creator $9, Team $19 (approvals, 10 seats), Agency $49 (100 channels). AI -drafts run on the c0mpute network and are billed per use to the person's balance. +drafts run on the c0mpute network first (c0mpute.com `/api/v1/ai/text`) and are billed per use to the person's +balance; when no node starts writing within about 20 seconds, c0mpute has OpenAI or Anthropic write them +(`@profullstack/ai-providers`, paid keys in c0mpute's vault) and charges the balance 2x that provider's list-price +cost (Infernet usage kind `ai.fallback`, idempotent per draft). The writer says which provider wrote each answer. Server settings: `DATABASE_URL`, `MYNA_STUDIO_KEY` (64 hex characters; seals channel credentials), optionally `MYNA_STUDIO_ORIGINS`, `MYNA_STUDIO_C0MPUTE_URL`, `MYNA_STUDIO_C0MPUTE_CLIENT_ID`, diff --git a/packages/core/package.json b/packages/core/package.json index 144b3c0..e1de70a 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@profullstack/myna-core", - "version": "0.57.0", + "version": "0.58.0", "description": "Network adapters, credential vault, scheduling and the AI writer behind myna.", "license": "MIT", "type": "module", diff --git a/packages/core/src/version.ts b/packages/core/src/version.ts index 9e2a96e..48a541c 100644 --- a/packages/core/src/version.ts +++ b/packages/core/src/version.ts @@ -6,4 +6,4 @@ * binary reporting the wrong version, and nothing would fail. A test asserts * this matches the package.json it is published under. */ -export const VERSION = "0.57.0"; +export const VERSION = "0.58.0"; diff --git a/packages/mcp/package.json b/packages/mcp/package.json index 04b0668..0fb994d 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "@profullstack/myna-mcp", - "version": "0.57.0", + "version": "0.58.0", "description": "MCP server for myna. Lets an agent post, schedule and read across every connected social account.", "license": "MIT", "type": "module",