@muxoai/sdk 1.3.0 → 1.4.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.
Files changed (76) hide show
  1. package/.agents/plugins/marketplace.json +2 -2
  2. package/.claude-plugin/marketplace.json +19 -4
  3. package/.codex/config.toml +9 -2
  4. package/ARCHITECTURE.md +16 -6
  5. package/README.md +69 -24
  6. package/dist/clerk.d.ts +35 -0
  7. package/dist/clerk.js +201 -0
  8. package/dist/cli.js +1677 -103
  9. package/dist/composio-catalog.d.ts +234 -0
  10. package/dist/composio-catalog.js +1894 -0
  11. package/dist/config.d.ts +16 -0
  12. package/dist/config.js +27 -1
  13. package/dist/durable-workflow.d.ts +112 -0
  14. package/dist/durable-workflow.js +284 -0
  15. package/dist/engine.d.ts +377 -6
  16. package/dist/engine.js +1919 -94
  17. package/dist/index.d.ts +3 -0
  18. package/dist/index.js +3 -0
  19. package/dist/mcp-schema.d.ts +286 -0
  20. package/dist/mcp-schema.js +2580 -0
  21. package/dist/mcp.d.ts +2 -25
  22. package/dist/mcp.js +1008 -507
  23. package/dist/memory-graph.d.ts +45 -0
  24. package/dist/memory-graph.js +293 -0
  25. package/dist/nl.js +214 -35
  26. package/dist/oauth.d.ts +32 -0
  27. package/dist/oauth.js +134 -0
  28. package/dist/oss-suite.d.ts +217 -0
  29. package/dist/oss-suite.js +836 -0
  30. package/dist/policy.d.ts +190 -0
  31. package/dist/policy.js +1597 -0
  32. package/dist/providers/composio-instant.d.ts +4 -0
  33. package/dist/providers/composio-instant.js +890 -535
  34. package/dist/providers/composio-sdk.d.ts +126 -5
  35. package/dist/providers/composio-sdk.js +902 -79
  36. package/dist/providers/microsoft-governance.d.ts +89 -3
  37. package/dist/providers/microsoft-governance.js +673 -26
  38. package/dist/providers/stripe-billing.d.ts +42 -0
  39. package/dist/providers/stripe-billing.js +244 -5
  40. package/dist/providers/stripe-projects.d.ts +459 -4
  41. package/dist/providers/stripe-projects.js +2674 -122
  42. package/dist/providers/supermemory.d.ts +102 -6
  43. package/dist/providers/supermemory.js +609 -55
  44. package/dist/provisioning-managed.d.ts +50 -0
  45. package/dist/provisioning-managed.js +155 -0
  46. package/dist/sdk.d.ts +728 -7
  47. package/dist/sdk.js +539 -10
  48. package/dist/server.js +2744 -321
  49. package/dist/store.d.ts +138 -6
  50. package/dist/store.js +932 -58
  51. package/dist/types.d.ts +330 -4
  52. package/dist/ui/console-html.d.ts +62 -0
  53. package/dist/ui/console-html.js +3742 -2228
  54. package/dist/ui/design-tokens.d.ts +177 -0
  55. package/dist/ui/design-tokens.js +210 -0
  56. package/dist/version.d.ts +1 -0
  57. package/dist/version.js +1 -0
  58. package/package.json +6 -5
  59. package/plugins/muxo/.app.json +1 -1
  60. package/plugins/muxo/.claude-plugin/plugin.json +3 -3
  61. package/plugins/muxo/.codex-plugin/plugin.json +19 -10
  62. package/plugins/muxo/.cursor-plugin/plugin.json +30 -0
  63. package/plugins/muxo/.mcp.json +1 -33
  64. package/plugins/muxo/assets/logo.png +0 -0
  65. package/plugins/muxo/hooks/session-start.sh +16 -4
  66. package/plugins/muxo/hooks/user-prompt-submit.sh +14 -1
  67. package/plugins/muxo/mcp.json +0 -10
  68. package/plugins/muxo/plugin.json +65 -8
  69. package/plugins/muxo/skills/muxo/SKILL.md +142 -14
  70. package/plugins/muxo/skills/muxo/agents/openai.yaml +12 -0
  71. package/plugins/muxo/skills/muxo/references/cli.md +9 -3
  72. package/plugins/muxo/skills/muxo/references/mcp.md +22 -10
  73. package/plugins/muxo/skills/muxo-activity-summary/SKILL.md +81 -0
  74. package/plugins/muxo/skills/setup/SKILL.md +17 -3
  75. package/plugins/muxo/skills/setup/agents/openai.yaml +12 -0
  76. package/src/catalogues/stripe-projects-catalog.json +140 -0
@@ -0,0 +1,836 @@
1
+ /**
2
+ * Unified Open-Source & Commercial Enterprise Suite (Runtime-Agnostic: Node.js + Cloudflare Workers):
3
+ * 1. AWS Cedar & Open Policy Agent (OPA / Rego) Policy-as-Code Compiler & Evaluator
4
+ * 2. OpenTelemetry (OTel GenAI / MCP Semantic Conventions) OTLP JSON & Langfuse Trace Exporter
5
+ * 3. Turnkey Commercial Business Saga Playbooks (backed by Temporal-compatible DurableWorkflows)
6
+ * 4. FinOps & Commercial ROI Unit-Economics Analytics
7
+ */
8
+ import { describePolicyInPlainEnglish, evaluateParameterPolicyRules, formatHumanFriendlyExplanation, simulatePolicyEvaluation, } from "./policy.js";
9
+ export function compileWorkspacePolicyToCedarAndRego(policy, workspace) {
10
+ const statements = [];
11
+ const regoDenyBlocks = [];
12
+ const regoReviewBlocks = [];
13
+ // 1. Baseline Ring & Workspace Permit Statement
14
+ const maxRing = typeof policy.executionRing === "number" ? policy.executionRing : 2;
15
+ statements.push({
16
+ id: "muxo-base-ring-permit",
17
+ effect: "permit",
18
+ description: `Allow authenticated workspace agents operating within Ring ${maxRing} or higher privilege`,
19
+ statement: [
20
+ `@id("muxo-base-ring-permit")`,
21
+ `permit (`,
22
+ ` principal is Muxo::Agent,`,
23
+ ` action,`,
24
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
25
+ `) when {`,
26
+ ` context.agentRing <= ${maxRing} || context.requiredRing >= ${maxRing}`,
27
+ `};`,
28
+ ].join("\n"),
29
+ });
30
+ // 2. Kill Switch Forbid Statement
31
+ statements.push({
32
+ id: "muxo-kill-switch-forbid",
33
+ effect: "forbid",
34
+ description: "Emergency kill switch blocks all non-exempt tool executions when active",
35
+ statement: [
36
+ `@id("muxo-kill-switch-forbid")`,
37
+ `forbid (`,
38
+ ` principal,`,
39
+ ` action,`,
40
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
41
+ `) when {`,
42
+ ` context.killSwitchActive == true`,
43
+ `};`,
44
+ ].join("\n"),
45
+ });
46
+ regoDenyBlocks.push(`deny contains "Workspace emergency kill switch is active" if {\n input.context.killSwitchActive == true\n}`);
47
+ // 3. Destructive SQL Guard
48
+ if (policy.blockDestructiveSql !== false) {
49
+ statements.push({
50
+ id: "muxo-destructive-sql-forbid",
51
+ effect: "forbid",
52
+ description: "Block DROP TABLE, TRUNCATE, and unscoped DELETE SQL statements",
53
+ statement: [
54
+ `@id("muxo-destructive-sql-forbid")`,
55
+ `forbid (`,
56
+ ` principal,`,
57
+ ` action,`,
58
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
59
+ `) when {`,
60
+ ` context.hasDestructiveSql == true`,
61
+ `};`,
62
+ ].join("\n"),
63
+ });
64
+ regoDenyBlocks.push(`deny contains "Destructive SQL (DROP/TRUNCATE/DELETE without WHERE) is blocked by policy" if {\n input.context.hasDestructiveSql == true\n}`);
65
+ }
66
+ // 4. Max Credits Per Run Cap
67
+ if (typeof policy.maxCreditsPerRun === "number" && policy.maxCreditsPerRun >= 0) {
68
+ statements.push({
69
+ id: "muxo-credit-budget-forbid",
70
+ effect: "forbid",
71
+ description: `Block single tool runs exceeding ${policy.maxCreditsPerRun} credits`,
72
+ statement: [
73
+ `@id("muxo-credit-budget-forbid")`,
74
+ `forbid (`,
75
+ ` principal,`,
76
+ ` action,`,
77
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
78
+ `) when {`,
79
+ ` context.creditCost > ${policy.maxCreditsPerRun}`,
80
+ `};`,
81
+ ].join("\n"),
82
+ });
83
+ regoDenyBlocks.push(`deny contains sprintf("Credit cost %v exceeds maxCreditsPerRun (%v)", [input.context.creditCost, ${policy.maxCreditsPerRun}]) if {\n input.context.creditCost > ${policy.maxCreditsPerRun}\n}`);
84
+ }
85
+ // 5. Blocked Tool Slugs
86
+ const blockedSlugs = Array.isArray(policy.blockedToolSlugs)
87
+ ? policy.blockedToolSlugs
88
+ : [];
89
+ if (blockedSlugs.length > 0) {
90
+ const actionList = blockedSlugs
91
+ .map((s) => `Muxo::Action::"${s}"`)
92
+ .join(", ");
93
+ statements.push({
94
+ id: "muxo-blocked-tools-forbid",
95
+ effect: "forbid",
96
+ description: `Explicitly blocked tools or prefixes (${blockedSlugs.join(", ")})`,
97
+ statement: [
98
+ `@id("muxo-blocked-tools-forbid")`,
99
+ `forbid (`,
100
+ ` principal,`,
101
+ ` action in [${actionList}],`,
102
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
103
+ `);`,
104
+ ].join("\n"),
105
+ });
106
+ regoDenyBlocks.push(`deny contains sprintf("Tool %v is in blockedToolSlugs", [input.action]) if {\n some blocked in ${JSON.stringify(blockedSlugs)}\n startswith(input.action, trim_suffix(blocked, "*"))\n}`);
107
+ }
108
+ // 6. Lane Guards (Instant Wallet & Provisioning)
109
+ if (policy.allowInstantWallet === false || policy.allowProvisioning === false) {
110
+ const allowedLanes = ["composio_sdk"];
111
+ if (policy.allowInstantWallet !== false)
112
+ allowedLanes.push("composio_instant");
113
+ if (policy.allowProvisioning !== false)
114
+ allowedLanes.push("stripe_projects");
115
+ const lanesLiteral = allowedLanes.map((l) => `"${l}"`).join(", ");
116
+ statements.push({
117
+ id: "muxo-allowed-lanes-forbid",
118
+ effect: "forbid",
119
+ description: `Restrict execution to allowed provider lanes (${allowedLanes.join(", ")})`,
120
+ statement: [
121
+ `@id("muxo-allowed-lanes-forbid")`,
122
+ `forbid (`,
123
+ ` principal,`,
124
+ ` action,`,
125
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
126
+ `) unless {`,
127
+ ` [${lanesLiteral}].contains(context.lane)`,
128
+ `};`,
129
+ ].join("\n"),
130
+ });
131
+ }
132
+ // 7. Parameter-Level Policy Rules
133
+ const paramRules = Array.isArray(policy.parameterRules)
134
+ ? policy.parameterRules
135
+ : [];
136
+ paramRules.forEach((rule, idx) => {
137
+ const ruleId = `muxo-param-rule-${idx + 1}-${rule.parameter.replace(/[^a-zA-Z0-9_-]/g, "-")}`;
138
+ const effect = rule.action === "allow" || rule.action === "auto_approve"
139
+ ? "permit"
140
+ : "forbid";
141
+ statements.push({
142
+ id: ruleId,
143
+ effect,
144
+ description: rule.description ||
145
+ `Parameter guardrail on ${rule.toolPattern || "*"}.${rule.parameter} (${rule.operator})`,
146
+ statement: [
147
+ `@id("${ruleId}")`,
148
+ `@effect("${rule.action}")`,
149
+ `${effect} (`,
150
+ ` principal,`,
151
+ ` action,`,
152
+ ` resource in Muxo::Workspace::"${workspace.slug}"`,
153
+ `) when {`,
154
+ ` context.toolMatches_${idx + 1} == true && context.paramComplies_${idx + 1} == false`,
155
+ `};`,
156
+ ].join("\n"),
157
+ });
158
+ });
159
+ // 8. Risk-Lane Approval Requirements in OPA Rego
160
+ const approvalRisks = Array.isArray(policy.requireApprovalFor)
161
+ ? policy.requireApprovalFor
162
+ : [];
163
+ if (approvalRisks.length > 0) {
164
+ regoReviewBlocks.push(`require_approval contains sprintf("Risk lane '%v' requires human approval", [input.context.riskLevel]) if {\n some r in ${JSON.stringify(approvalRisks)}\n input.context.riskLevel == r\n}`);
165
+ }
166
+ const cedarPolicyText = [
167
+ `// ============================================================================`,
168
+ `// Muxo Policy-as-Code (AWS Cedar 4.x) — Workspace: ${workspace.name} (${workspace.slug})`,
169
+ `// Auto-compiled from active Muxo GovernancePolicy & Plain-English Guardrails`,
170
+ `// ============================================================================`,
171
+ ``,
172
+ ...statements.map((s) => `// ${s.description}\n${s.statement}\n`),
173
+ ].join("\n");
174
+ const regoText = [
175
+ `# ============================================================================`,
176
+ `# Muxo Policy-as-Code (Open Policy Agent Rego v1) — Workspace: ${workspace.name}`,
177
+ `# ============================================================================`,
178
+ `package muxo.authz`,
179
+ `import rego.v1`,
180
+ ``,
181
+ `default allow := false`,
182
+ `default decision := "deny"`,
183
+ ``,
184
+ `allow if {`,
185
+ ` count(deny) == 0`,
186
+ ` count(require_approval) == 0`,
187
+ `}`,
188
+ ``,
189
+ `decision := "allow" if { allow }`,
190
+ `decision := "review" if { count(deny) == 0; count(require_approval) > 0 }`,
191
+ ``,
192
+ ...regoDenyBlocks,
193
+ ...regoReviewBlocks,
194
+ ].join("\n");
195
+ const plainEnglish = describePolicyInPlainEnglish(policy);
196
+ const headline = `Compiled ${statements.length} AWS Cedar statements and ${regoDenyBlocks.length + regoReviewBlocks.length} OPA Rego rules for ${workspace.name}.`;
197
+ const explanation = formatHumanFriendlyExplanation({
198
+ headline,
199
+ nonTechnical: `${headline} Active guardrails: ${plainEnglish.rules.join(" · ")}.`,
200
+ technical: `workspace=${workspace.id} | cedarStatements=${statements.length} | opaRules=${regoDenyBlocks.length + regoReviewBlocks.length}`,
201
+ policy,
202
+ });
203
+ return {
204
+ workspaceId: workspace.id,
205
+ workspaceSlug: workspace.slug,
206
+ generatedAt: new Date().toISOString(),
207
+ engines: ["aws-cedar-4.x", "open-policy-agent-rego-v1"],
208
+ cedarSchemaVersion: "4.0",
209
+ cedarPolicyText,
210
+ opaRegoText: regoText,
211
+ statements,
212
+ cedar: {
213
+ schemaNamespace: "Muxo",
214
+ statementsCount: statements.length,
215
+ policyText: cedarPolicyText,
216
+ statements,
217
+ },
218
+ opa: {
219
+ packageName: "muxo.authz",
220
+ rulesCount: regoDenyBlocks.length + regoReviewBlocks.length,
221
+ regoText,
222
+ },
223
+ plainEnglishSummary: plainEnglish.rules,
224
+ explanation,
225
+ };
226
+ }
227
+ export function evaluateCedarAndOpaPolicy(params) {
228
+ const compiledBundle = compileWorkspacePolicyToCedarAndRego(params.policy, params.workspace);
229
+ const sim = simulatePolicyEvaluation({
230
+ policy: params.policy,
231
+ toolSlug: params.toolSlug,
232
+ riskLevel: params.riskLevel,
233
+ creditCost: params.creditCost,
234
+ lane: params.lane,
235
+ input: params.input || {},
236
+ });
237
+ const determiningPolicies = [];
238
+ const denyReasons = [];
239
+ const reviewReasons = [];
240
+ if (params.policy.killSwitchActive) {
241
+ determiningPolicies.push("muxo-kill-switch-forbid");
242
+ denyReasons.push("Workspace emergency kill switch is active");
243
+ }
244
+ const serializedInput = JSON.stringify(params.input || {});
245
+ const hasDestructiveSql = /\b(DROP\s+TABLE|DROP\s+DATABASE|TRUNCATE\s+TABLE|DELETE\s+FROM\s+[a-zA-Z0-9_."`]+\s*(?:;|$))/i.test(serializedInput);
246
+ if (params.policy.blockDestructiveSql !== false && hasDestructiveSql) {
247
+ determiningPolicies.push("muxo-destructive-sql-forbid");
248
+ denyReasons.push("Destructive SQL (DROP/TRUNCATE/DELETE without WHERE) is blocked by policy");
249
+ }
250
+ if (typeof params.policy.maxCreditsPerRun === "number" &&
251
+ sim.creditCost > params.policy.maxCreditsPerRun) {
252
+ determiningPolicies.push("muxo-credit-budget-forbid");
253
+ denyReasons.push(`Credit cost ${sim.creditCost} exceeds maxCreditsPerRun (${params.policy.maxCreditsPerRun})`);
254
+ }
255
+ const paramEval = evaluateParameterPolicyRules({
256
+ policy: params.policy,
257
+ toolSlug: params.toolSlug,
258
+ input: params.input || {},
259
+ });
260
+ if (!paramEval.allowed) {
261
+ determiningPolicies.push("muxo-param-rule-1");
262
+ denyReasons.push(paramEval.reason || "Parameter policy rule blocked execution");
263
+ }
264
+ else if (paramEval.action === "require_approval") {
265
+ determiningPolicies.push("muxo-param-rule-1");
266
+ reviewReasons.push(paramEval.reason || "Parameter policy rule requires human approval");
267
+ }
268
+ const normalizedDecision = denyReasons.length > 0 || sim.decision === "blocked"
269
+ ? "deny"
270
+ : reviewReasons.length > 0 || sim.decision === "pending_approval"
271
+ ? "require_approval"
272
+ : "allow";
273
+ if (normalizedDecision === "deny" && denyReasons.length === 0) {
274
+ determiningPolicies.push("muxo-blocked-tools-forbid");
275
+ denyReasons.push(sim.reasons.join("; ") || "Denied by workspace policy");
276
+ }
277
+ else if (normalizedDecision === "require_approval" &&
278
+ reviewReasons.length === 0) {
279
+ determiningPolicies.push("muxo-base-ring-permit");
280
+ reviewReasons.push(sim.reasons.join("; ") ||
281
+ `Risk level '${sim.riskLevel}' requires human approval`);
282
+ }
283
+ else if (normalizedDecision === "allow") {
284
+ determiningPolicies.push("muxo-base-ring-permit");
285
+ }
286
+ const upperDecision = normalizedDecision === "allow"
287
+ ? "ALLOW"
288
+ : normalizedDecision === "require_approval"
289
+ ? "REQUIRE_APPROVAL"
290
+ : "DENY";
291
+ return {
292
+ workspaceId: params.workspace.id,
293
+ toolSlug: params.toolSlug,
294
+ riskLevel: sim.riskLevel,
295
+ creditCost: sim.creditCost,
296
+ allowed: normalizedDecision === "allow",
297
+ decision: upperDecision,
298
+ policyDecision: normalizedDecision,
299
+ cedarResult: {
300
+ decision: normalizedDecision === "allow" ? "ALLOW" : "DENY",
301
+ determiningPolicies,
302
+ errors: [],
303
+ },
304
+ opaResult: {
305
+ allow: normalizedDecision === "allow",
306
+ decision: normalizedDecision === "allow"
307
+ ? "allow"
308
+ : normalizedDecision === "require_approval"
309
+ ? "review"
310
+ : "deny",
311
+ denyReasons,
312
+ reviewReasons,
313
+ },
314
+ matchedStatements: determiningPolicies,
315
+ remediationForLlm: sim.remediationForLlm,
316
+ compiledBundle,
317
+ };
318
+ }
319
+ // ============================================================================
320
+ // 2. OPENTELEMETRY (OTel GenAI / MCP CONVENTIONS) & LANGFUSE TRACE EXPORTER
321
+ // ============================================================================
322
+ function deterministicHex(seed, length) {
323
+ let h1 = 0xdeadbeef ^ seed.length;
324
+ let h2 = 0x41c6ce57 ^ seed.length;
325
+ for (let i = 0; i < seed.length; i++) {
326
+ const ch = seed.charCodeAt(i);
327
+ h1 = Math.imul(h1 ^ ch, 2654435761);
328
+ h2 = Math.imul(h2 ^ ch, 1597334677);
329
+ }
330
+ let out = "";
331
+ let round = 0;
332
+ while (out.length < length) {
333
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
334
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
335
+ out += ((h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0"));
336
+ round++;
337
+ h1 ^= round;
338
+ }
339
+ return out.slice(0, length);
340
+ }
341
+ export function buildOtelTraceExport(params) {
342
+ const receiptByRunId = new Map();
343
+ for (const r of params.receipts) {
344
+ receiptByRunId.set(r.runId, r);
345
+ }
346
+ const nowIso = new Date().toISOString();
347
+ const spans = [];
348
+ const langfuseBatch = [];
349
+ const sourceRuns = params.runs.length > 0
350
+ ? params.runs.slice(0, 25)
351
+ : [
352
+ {
353
+ id: `run_telemetry_${params.workspace.slug}`,
354
+ planId: `plan_telemetry_${params.workspace.slug}`,
355
+ workspaceId: params.workspace.id,
356
+ actorId: "agent:muxo",
357
+ toolSlug: "instant.dns.lookup",
358
+ lane: "composio_instant",
359
+ riskLevel: "read",
360
+ status: "succeeded",
361
+ input: { domain: "muxo.ai" },
362
+ output: { ok: true },
363
+ error: null,
364
+ actionsMetered: 1,
365
+ creditsMetered: 1,
366
+ durationMs: 18,
367
+ receiptId: `rcpt_telemetry_${params.workspace.slug}`,
368
+ startedAt: nowIso,
369
+ completedAt: nowIso,
370
+ },
371
+ ];
372
+ for (const run of sourceRuns) {
373
+ const receipt = receiptByRunId.get(run.id);
374
+ const traceId = deterministicHex(`trace:${params.workspace.id}:${run.planId}:${run.id}`, 32);
375
+ const planSpanId = deterministicHex(`plan:${run.planId}`, 16);
376
+ const execSpanId = deterministicHex(`exec:${run.id}`, 16);
377
+ const startMs = Date.parse(run.startedAt) || Date.now();
378
+ const durationMs = Math.max(1, Number(run.durationMs || 25));
379
+ const endMs = (Date.parse(run.completedAt || "") || startMs + durationMs);
380
+ const traceparent = `00-${traceId}-${execSpanId}-01`;
381
+ const attributes = [
382
+ { key: "gen_ai.system", value: { stringValue: "muxo" } },
383
+ { key: "gen_ai.operation.name", value: { stringValue: "execute_tool" } },
384
+ { key: "gen_ai.tool.name", value: { stringValue: run.toolSlug } },
385
+ { key: "gen_ai.tool.call.id", value: { stringValue: run.id } },
386
+ { key: "mcp.method.name", value: { stringValue: "tools/call" } },
387
+ { key: "muxo.workspace.id", value: { stringValue: params.workspace.id } },
388
+ { key: "muxo.workspace.slug", value: { stringValue: params.workspace.slug } },
389
+ { key: "muxo.plan.id", value: { stringValue: run.planId } },
390
+ { key: "muxo.lane", value: { stringValue: run.lane } },
391
+ { key: "muxo.risk_level", value: { stringValue: run.riskLevel } },
392
+ { key: "muxo.credits.metered", value: { intValue: run.creditsMetered } },
393
+ {
394
+ key: "muxo.receipt.id",
395
+ value: { stringValue: receipt?.id || run.receiptId || "pending" },
396
+ },
397
+ {
398
+ key: "muxo.receipt.verified",
399
+ value: { boolValue: Boolean(receipt?.signature) },
400
+ },
401
+ ];
402
+ if (receipt?.decisionRecord?.agentDid) {
403
+ attributes.push({
404
+ key: "muxo.governance.agent_did",
405
+ value: { stringValue: receipt.decisionRecord.agentDid },
406
+ });
407
+ }
408
+ spans.push({
409
+ traceId,
410
+ spanId: execSpanId,
411
+ parentSpanId: planSpanId,
412
+ traceparent,
413
+ name: `muxo.execute ${run.toolSlug}`,
414
+ kind: "SPAN_KIND_SERVER",
415
+ startTimeUnixNano: `${BigInt(startMs) * 1000000n}`,
416
+ endTimeUnixNano: `${BigInt(endMs) * 1000000n}`,
417
+ status: {
418
+ code: run.status === "succeeded" ? "STATUS_CODE_OK" : "STATUS_CODE_ERROR",
419
+ ...(run.error ? { message: run.error } : {}),
420
+ },
421
+ attributes,
422
+ });
423
+ langfuseBatch.push({
424
+ id: `lf_trace_${run.id}`,
425
+ type: "trace-create",
426
+ timestamp: run.startedAt,
427
+ body: {
428
+ id: traceId,
429
+ name: `muxo:${run.toolSlug}`,
430
+ userId: run.actorId,
431
+ sessionId: params.workspace.slug,
432
+ metadata: {
433
+ workspaceId: params.workspace.id,
434
+ planId: run.planId,
435
+ runId: run.id,
436
+ receiptId: receipt?.id || run.receiptId,
437
+ lane: run.lane,
438
+ riskLevel: run.riskLevel,
439
+ creditsMetered: run.creditsMetered,
440
+ },
441
+ tags: ["muxo", run.lane, run.riskLevel, run.status],
442
+ },
443
+ });
444
+ }
445
+ const w3cSample = spans[0]?.traceparent ||
446
+ `00-${deterministicHex(params.workspace.id, 32)}-${deterministicHex(params.workspace.slug, 16)}-01`;
447
+ const resourceSpans = [
448
+ {
449
+ resource: {
450
+ attributes: [
451
+ { key: "service.name", value: { stringValue: "muxo-agent-runtime" } },
452
+ {
453
+ key: "service.version",
454
+ value: { stringValue: params.version || "1.4.3" },
455
+ },
456
+ {
457
+ key: "muxo.workspace.id",
458
+ value: { stringValue: params.workspace.id },
459
+ },
460
+ {
461
+ key: "muxo.workspace.tier",
462
+ value: { stringValue: params.workspace.tier },
463
+ },
464
+ ],
465
+ },
466
+ scopeSpans: [
467
+ {
468
+ scope: {
469
+ name: "@muxoai/otel-genai-mcp-tracer",
470
+ version: params.version || "1.4.3",
471
+ },
472
+ spans,
473
+ },
474
+ ],
475
+ },
476
+ ];
477
+ return {
478
+ workspaceId: params.workspace.id,
479
+ workspaceSlug: params.workspace.slug,
480
+ exportedAt: nowIso,
481
+ protocol: "OTLP/HTTP-JSON-v1",
482
+ semanticConventions: ["gen_ai.1.29.0", "mcp.2026-07-28", "muxo.governance.v5"],
483
+ w3cTraceParent: w3cSample,
484
+ w3cTraceContextSample: w3cSample,
485
+ spansCount: spans.length,
486
+ otlpPayload: { resourceSpans },
487
+ resourceSpans,
488
+ langfuseBatch,
489
+ };
490
+ }
491
+ export const MUXO_COMMERCIAL_PLAYBOOKS = [
492
+ {
493
+ slug: "fullstack-cloud-bootstrap",
494
+ name: "Full-Stack Cloud Database & Secret Vault Bootstrap",
495
+ persona: "Engineering & DevOps",
496
+ summary: "Provisions a live cloud database (Neon Postgres / Turso SQLite), reveals and seals AES-256-GCM credentials in the Muxo Vault, and records topology in the Graphiti Bi-Temporal Knowledge Graph with automatic Saga rollback.",
497
+ commercialValue: "Replaces 45 minutes of manual cloud account setup, IAM key copying, and .env distribution with a single governed, rollback-safe call.",
498
+ estimatedMinutesSaved: 45,
499
+ creditCost: 5,
500
+ defaultProvider: "neon",
501
+ defaultServiceRef: "postgres",
502
+ steps: [
503
+ {
504
+ name: "verify_workspace_policy_and_cedar_guardrails",
505
+ toolSlug: "governance.cedar.evaluate",
506
+ primitive: "step.do",
507
+ description: "Validate workspace ring permissions and Cedar/OPA guardrails before cloud provisioning",
508
+ },
509
+ {
510
+ name: "provision_cloud_database_resource",
511
+ toolSlug: "resource.neon.postgres",
512
+ primitive: "step.do",
513
+ compensationAction: "resource.neon.remove",
514
+ description: "Provision serverless Postgres database via Stripe Projects v2 API",
515
+ },
516
+ {
517
+ name: "reveal_and_seal_vault_credentials",
518
+ toolSlug: "vault.seal_access_configuration",
519
+ primitive: "step.do",
520
+ compensationAction: "vault.revoke_secrets",
521
+ description: "Encrypt DATABASE_URL in per-workspace AES-256-GCM secret vault",
522
+ },
523
+ {
524
+ name: "record_bitemporal_knowledge_graph_topology",
525
+ toolSlug: "memory.graph.record_fact",
526
+ primitive: "step.do",
527
+ compensationAction: "memory.graph.retire_fact",
528
+ description: "Commit active database topology edge into Graphiti bi-temporal knowledge graph",
529
+ },
530
+ ],
531
+ },
532
+ {
533
+ slug: "competitor-seo-growth-brief",
534
+ name: "Technical SEO Audit, Web Crawl & Episodic Growth Benchmark",
535
+ persona: "Marketing & Growth",
536
+ summary: "Audits target domain technical SEO, scrapes top pages, synthesizes market intelligence, and stores a timestamped Graphiti episodic snapshot for week-over-week comparison.",
537
+ commercialValue: "Automates recurring agency-grade SEO & market intelligence audits with zero OAuth setup.",
538
+ estimatedMinutesSaved: 60,
539
+ creditCost: 3,
540
+ defaultProvider: "firecrawl",
541
+ defaultServiceRef: "seo_audit",
542
+ steps: [
543
+ {
544
+ name: "execute_technical_seo_audit",
545
+ toolSlug: "instant.seo.audit",
546
+ primitive: "step.do",
547
+ description: "Run technical SEO, metadata, and structured-data audit on target URL",
548
+ },
549
+ {
550
+ name: "scrape_and_extract_landing_copy",
551
+ toolSlug: "instant.web.scrape",
552
+ primitive: "step.do",
553
+ description: "Extract clean markdown content and headings from primary landing page",
554
+ },
555
+ {
556
+ name: "record_episodic_seo_benchmark_fact",
557
+ toolSlug: "memory.graph.record_fact",
558
+ primitive: "step.do",
559
+ compensationAction: "memory.graph.retire_fact",
560
+ description: "Store dated SEO score in Graphiti bi-temporal graph for point-in-time delta tracking",
561
+ },
562
+ ],
563
+ },
564
+ {
565
+ slug: "incident-containment-audit",
566
+ name: "Zero-Trust Security Scan, Cedar Compliance & WORM Evidence Bundle",
567
+ persona: "SecOps & Compliance",
568
+ summary: "Scans workspace context for prompt injection, verifies Ed25519 receipt chain integrity, compiles AWS Cedar / OPA compliance policies, and exports an OTLP + WORM audit bundle.",
569
+ commercialValue: "Produces SOC2 / ISO-27001 ready cryptographic agent execution evidence and OpenTelemetry traces in one command.",
570
+ estimatedMinutesSaved: 90,
571
+ creditCost: 2,
572
+ defaultProvider: "muxo",
573
+ defaultServiceRef: "compliance_audit",
574
+ steps: [
575
+ {
576
+ name: "scan_workspace_context_for_poisoning",
577
+ toolSlug: "governance.context_poisoning.scan",
578
+ primitive: "step.do",
579
+ description: "Scan workspace memories and active defaults for prompt injection or secret exfiltration",
580
+ },
581
+ {
582
+ name: "compile_and_verify_cedar_opa_policies",
583
+ toolSlug: "governance.cedar.compile",
584
+ primitive: "step.do",
585
+ description: "Compile workspace guardrails into formal AWS Cedar & OPA Rego policy statements",
586
+ },
587
+ {
588
+ name: "export_worm_and_opentelemetry_bundle",
589
+ toolSlug: "telemetry.otlp.export",
590
+ primitive: "step.do",
591
+ description: "Generate signed SHA-256 Merkle chain + OTLP GenAI trace bundle",
592
+ },
593
+ ],
594
+ },
595
+ {
596
+ slug: "customer-release-readiness",
597
+ name: "Release Readiness & Infrastructure Health Gate",
598
+ persona: "Product & Founders",
599
+ summary: "Gathers repository pulse, checks provisioned cloud infrastructure health, validates budget runway, and issues a signed Ed25519 release readiness receipt.",
600
+ commercialValue: "Gives founders and product leads an instant, verifiable go/no-go release check across code, cloud, and budget.",
601
+ estimatedMinutesSaved: 35,
602
+ creditCost: 2,
603
+ defaultProvider: "github",
604
+ defaultServiceRef: "release_gate",
605
+ steps: [
606
+ {
607
+ name: "inspect_repository_release_intel",
608
+ toolSlug: "instant.github.repo_intel",
609
+ primitive: "step.do",
610
+ description: "Fetch repository activity, open blockers, and release metadata",
611
+ },
612
+ {
613
+ name: "verify_cloud_infrastructure_topology",
614
+ toolSlug: "resource.projects.status",
615
+ primitive: "step.do",
616
+ description: "Check active Stripe Projects databases and cloud services",
617
+ },
618
+ {
619
+ name: "record_release_readiness_episode",
620
+ toolSlug: "memory.graph.record_fact",
621
+ primitive: "step.do",
622
+ compensationAction: "memory.graph.retire_fact",
623
+ description: "Record release readiness milestone in Graphiti bi-temporal knowledge graph",
624
+ },
625
+ ],
626
+ },
627
+ ];
628
+ export function getCommercialPlaybook(slug) {
629
+ const normalized = String(slug || "")
630
+ .trim()
631
+ .toLowerCase();
632
+ return (MUXO_COMMERCIAL_PLAYBOOKS.find((p) => p.slug === normalized) || null);
633
+ }
634
+ export function buildPlaybookSagaExecution(params) {
635
+ const now = new Date().toISOString();
636
+ const provider = String(params.input?.provider || params.playbook.defaultProvider).toLowerCase();
637
+ const serviceRef = String(params.input?.serviceRef ||
638
+ params.input?.target ||
639
+ params.playbook.defaultServiceRef).toLowerCase();
640
+ const resourceId = `res_pb_${provider}_${params.id.slice(-8)}`;
641
+ const history = [];
642
+ const compensations = [];
643
+ const steps = [];
644
+ history.push({
645
+ eventId: 1,
646
+ eventTime: now,
647
+ eventType: "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED",
648
+ taskQueue: "muxo-commercial-playbook-saga-queue",
649
+ attributes: {
650
+ playbookSlug: params.playbook.slug,
651
+ workflowId: params.id,
652
+ workspaceId: params.workspaceId,
653
+ input: params.input || {},
654
+ },
655
+ });
656
+ for (const s of params.playbook.steps) {
657
+ const stepOutput = {
658
+ toolSlug: s.toolSlug,
659
+ status: "completed",
660
+ provider,
661
+ serviceRef,
662
+ ...(params.input || {}),
663
+ };
664
+ steps.push({
665
+ name: s.name,
666
+ primitive: s.primitive,
667
+ status: "completed",
668
+ output: stepOutput,
669
+ completedAt: now,
670
+ compensationAction: s.compensationAction,
671
+ });
672
+ history.push({
673
+ eventId: history.length + 1,
674
+ eventTime: now,
675
+ eventType: "EVENT_TYPE_ACTIVITY_TASK_COMPLETED",
676
+ taskQueue: "muxo-commercial-playbook-saga-queue",
677
+ attributes: {
678
+ activityName: s.name,
679
+ toolSlug: s.toolSlug,
680
+ result: stepOutput,
681
+ },
682
+ });
683
+ if (s.compensationAction) {
684
+ compensations.push({
685
+ stepName: s.name,
686
+ compensationAction: s.compensationAction,
687
+ status: "registered",
688
+ description: `Rollback ${s.name} via ${s.compensationAction}`,
689
+ });
690
+ }
691
+ }
692
+ history.push({
693
+ eventId: history.length + 1,
694
+ eventTime: now,
695
+ eventType: "EVENT_TYPE_WORKFLOW_EXECUTION_COMPLETED",
696
+ taskQueue: "muxo-commercial-playbook-saga-queue",
697
+ attributes: {
698
+ playbookSlug: params.playbook.slug,
699
+ workflowId: params.id,
700
+ estimatedMinutesSaved: params.playbook.estimatedMinutesSaved,
701
+ },
702
+ });
703
+ const workflow = {
704
+ id: params.id,
705
+ runId: `run_${params.id}`,
706
+ workspaceId: params.workspaceId,
707
+ workflowType: "commercial_playbook_saga",
708
+ playbookSlug: params.playbook.slug,
709
+ status: "completed",
710
+ provider,
711
+ serviceRef,
712
+ resourceId,
713
+ steps,
714
+ compensations,
715
+ signals: [],
716
+ temporalEventHistory: history,
717
+ rollbackReason: null,
718
+ createdAt: now,
719
+ updatedAt: now,
720
+ };
721
+ return {
722
+ playbook: params.playbook,
723
+ workflow,
724
+ temporalFact: {
725
+ subject: `workspace:${params.workspaceSlug}`,
726
+ predicate: `EXECUTED_PLAYBOOK_${params.playbook.slug.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`,
727
+ object: `resource:${provider}:${serviceRef}`,
728
+ summary: `Executed commercial saga playbook '${params.playbook.name}' (${params.playbook.slug}) targeting ${provider}/${serviceRef}`,
729
+ episodeId: workflow.runId,
730
+ },
731
+ };
732
+ }
733
+ export function buildCommercialRoiReport(params) {
734
+ const ws = params.workspace;
735
+ const laneBreakdown = {
736
+ composio_instant: { runsCount: 0, creditsConsumed: 0, estimatedMinutesSaved: 0 },
737
+ composio_sdk: { runsCount: 0, creditsConsumed: 0, estimatedMinutesSaved: 0 },
738
+ stripe_projects: { runsCount: 0, creditsConsumed: 0, estimatedMinutesSaved: 0 },
739
+ };
740
+ let succeededRunsCount = 0;
741
+ let byokZeroCreditRunsCount = 0;
742
+ let managedFundedRunsCount = 0;
743
+ let totalCreditsConsumed = 0;
744
+ for (const run of params.runs) {
745
+ const lane = run.lane in laneBreakdown ? run.lane : "composio_instant";
746
+ const mins = lane === "stripe_projects"
747
+ ? 30
748
+ : lane === "composio_sdk"
749
+ ? 12
750
+ : 5;
751
+ laneBreakdown[lane].runsCount += 1;
752
+ laneBreakdown[lane].creditsConsumed += run.creditsMetered || 0;
753
+ laneBreakdown[lane].estimatedMinutesSaved += mins;
754
+ totalCreditsConsumed += run.creditsMetered || 0;
755
+ if (run.status === "succeeded")
756
+ succeededRunsCount += 1;
757
+ if ((run.creditsMetered || 0) === 0) {
758
+ byokZeroCreditRunsCount += 1;
759
+ }
760
+ else {
761
+ managedFundedRunsCount += 1;
762
+ }
763
+ }
764
+ const configuredByokProviders = params.byokKeys
765
+ .filter((k) => k.configured)
766
+ .map((k) => k.provider);
767
+ const byokCreditsSaved = byokZeroCreditRunsCount * 2;
768
+ const byokDollarsSavedUsd = Number((byokCreditsSaved * 0.02).toFixed(2));
769
+ const baseMinutesSaved = Object.values(laneBreakdown).reduce((acc, l) => acc + l.estimatedMinutesSaved, 0) +
770
+ params.resources.length * 30 +
771
+ Math.min(20, params.temporalFacts.length) * 3;
772
+ const estimatedEngineeringMinutesSaved = Math.max(15, baseMinutesSaved);
773
+ const estimatedEngineeringHoursSaved = Number((estimatedEngineeringMinutesSaved / 60).toFixed(2));
774
+ const estimatedLaborValueSavedUsd = Number((estimatedEngineeringHoursSaved * 120).toFixed(2));
775
+ const rejectedPlansCount = (params.plans || []).filter((p) => p.approvalStatus === "rejected" || p.decisionRecord?.decision === "deny").length;
776
+ const recommendations = [];
777
+ if (!configuredByokProviders.includes("composio")) {
778
+ recommendations.push({
779
+ id: "enable-composio-byok",
780
+ category: "byok_savings",
781
+ title: "Enable 0-Credit BYOK for Connected Apps & Instant Tools",
782
+ impact: "Save 100% of Muxo runtime credits on app.* and instant.* executions by linking your own Composio key.",
783
+ actionCommand: "muxo byok set composio",
784
+ });
785
+ }
786
+ if (params.resources.length === 0) {
787
+ recommendations.push({
788
+ id: "run-cloud-bootstrap-playbook",
789
+ category: "playbook_automation",
790
+ title: "Launch Turnkey Full-Stack Cloud Bootstrap Playbook",
791
+ impact: "Provision a production Postgres/SQLite database and seal Vault credentials in 1 call (~45 mins saved).",
792
+ actionCommand: "muxo playbooks run fullstack-cloud-bootstrap",
793
+ });
794
+ }
795
+ recommendations.push({
796
+ id: "export-cedar-otel-compliance",
797
+ category: "governance_safety",
798
+ title: "Export AWS Cedar Policy-as-Code & OpenTelemetry Trace Bundle",
799
+ impact: "Stream W3C OTLP traces to Langfuse/Datadog and verify formal Cedar guardrails.",
800
+ actionCommand: "muxo governance cedar && muxo telemetry",
801
+ });
802
+ const headline = `Commercial ROI (${ws.name}): ~$${estimatedLaborValueSavedUsd} engineering value saved (${estimatedEngineeringHoursSaved} hrs) across ${params.runs.length} governed run${params.runs.length === 1 ? "" : "s"} and ${params.resources.length} provisioned cloud resource${params.resources.length === 1 ? "" : "s"}.`;
803
+ const explanation = formatHumanFriendlyExplanation({
804
+ headline,
805
+ nonTechnical: `${headline} Active credit balance: ${ws.creditsBalance} credits (${byokZeroCreditRunsCount} zero-credit BYOK runs).`,
806
+ technical: `workspace=${ws.id} | creditsBalance=${ws.creditsBalance} | runs=${params.runs.length} | hoursSaved=${estimatedEngineeringHoursSaved} | laborValueUsd=${estimatedLaborValueSavedUsd} | byokProviders=[${configuredByokProviders.join(",")}]`,
807
+ policy: ws.policy,
808
+ });
809
+ return {
810
+ workspaceId: ws.id,
811
+ workspaceSlug: ws.slug,
812
+ workspaceName: ws.name,
813
+ tier: ws.tier,
814
+ generatedAt: new Date().toISOString(),
815
+ unitEconomics: {
816
+ creditsBalance: ws.creditsBalance,
817
+ totalRunsAnalyzed: params.runs.length,
818
+ succeededRunsCount,
819
+ byokZeroCreditRunsCount,
820
+ managedFundedRunsCount,
821
+ totalCreditsConsumed,
822
+ byokCreditsSaved,
823
+ byokDollarsSavedUsd,
824
+ estimatedEngineeringMinutesSaved,
825
+ estimatedEngineeringHoursSaved,
826
+ estimatedLaborValueSavedUsd,
827
+ preventedPolicyViolationsCount: rejectedPlansCount,
828
+ activeCloudResourcesCount: params.resources.length,
829
+ activeBiTemporalFactsCount: params.temporalFacts.filter((f) => !f.validTo).length,
830
+ configuredByokProviders,
831
+ },
832
+ laneBreakdown,
833
+ recommendations,
834
+ explanation,
835
+ };
836
+ }